OXYGENHUB
# 93e7f1d9ef1c oxygen / crates / oxy-core / src / repo / tests.rs
185.4 KiB · Rust · last changed Delete bookmarks on a remote: oxy push REMOTE --delete NAME 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()).unwrap();
2488
    assert_eq!(r.old, key_a);
2489
    let key_a2 = r.new;
2490
    assert_eq!(a.identity(&key_a2).unwrap().delegates, vec![key_b]);
2491
    assert_eq!(
2492
        a.identity(&key_a2).unwrap().ed25519_pk,
2493
        a.identity(&key_a).unwrap().ed25519_pk
2494
    );
2495
    assert!(a.delegate_add(id_b.clone()).is_err(), "already a delegate");
2496
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2497
    write(&root.join("a"), "a.txt", b"a3\n");
2498
    let h3 = a.commit("three", &[]).unwrap();
2499
    assert!(
2500
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2501
        "the same secret signs under the new KeyId"
2502
    );
2503
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2504
    a.set_user_config("core.sign", "seal").unwrap();
2505
    write(&root.join("a"), "a.txt", b"a4\n");
2506
    let h4 = a.commit("four", &[]).unwrap();
2507
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2508
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2509
    a.store()
2510
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2511
        .unwrap();
2512
    assert!(
2513
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2514
    );
2515
    a.set_user_config("core.sign", "change").unwrap();
2516
    // Withdrawing the delegation re-issues the identity again.
2517
    let r = a.delegate_remove(&key_b).unwrap();
2518
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2519
    assert!(a.delegate_remove(&key_b).is_err());
2520
    let key_a3 = r.new;
2521
    let res = a.push("origin", false).unwrap();
2522
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2523
2524
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2525
    // both applied under the old threshold of 1. A grant then needs Bob too.
2526
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2527
    assert!(a.policy_root_add(id_b.clone()).is_err());
2528
    assert!(a.policy_set_threshold(3).is_err());
2529
    assert!(a.policy_set_threshold(2).unwrap().applied);
2530
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2531
    b.pull("origin").unwrap();
2532
    assert_eq!(
2533
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2534
        2
2535
    );
2536
    let mut c = Repo::init(&root.join("c"))
2537
        .unwrap()
2538
        .with_home(root.join("home-c"));
2539
    let (key_c, id_c) = c
2540
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2541
        .unwrap();
2542
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2543
    let proposal = a.policy_grant(id_c, None).unwrap();
2544
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2545
    assert_eq!(proposal.policy.serial, serial_before + 1);
2546
    assert_eq!(
2547
        a.current_policy().unwrap().unwrap().1.policy.serial,
2548
        serial_before,
2549
        "a proposal changes nothing yet"
2550
    );
2551
    // Bob signs the proposal, handed over as a file, and it applies for him.
2552
    let bytes = proposal.signed().encode();
2553
    let signed = b
2554
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2555
        .unwrap();
2556
    assert!(signed.applied && signed.sigs.len() == 2);
2557
    assert!(b
2558
        .current_policy()
2559
        .unwrap()
2560
        .unwrap()
2561
        .1
2562
        .policy
2563
        .authorizes(&key_c, "main"));
2564
    assert!(
2565
        b.policy_sign(signed.signed()).is_err(),
2566
        "a stale proposal is refused"
2567
    );
2568
    // Bob publishes it and Ada picks it up.
2569
    assert!(b
2570
        .push("origin", false)
2571
        .unwrap()
2572
        .iter()
2573
        .any(|x| x.name == "policy" && x.ok));
2574
    a.pull("origin").unwrap();
2575
    assert_eq!(
2576
        a.current_policy().unwrap().unwrap().1.policy.serial,
2577
        serial_before + 1
2578
    );
2579
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2580
    assert!(a.policy_revoke(&key_a3).is_err());
2581
    let u = a
2582
        .revoke_identity(&key_c, "left the project")
2583
        .unwrap()
2584
        .unwrap();
2585
    assert!(!u.applied);
2586
    assert!(a.is_revoked(&key_c).unwrap());
2587
    assert!(!b.is_revoked(&key_c).unwrap());
2588
    let u = b.policy_sign(u.signed()).unwrap();
2589
    assert!(u.applied && u.policy.is_revoked(&key_c));
2590
    assert!(b.is_revoked(&key_c).unwrap());
2591
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2592
    assert!(
2593
        b.policy_revoke(&key_a3).is_err(),
2594
        "would leave one root for a threshold of 2"
2595
    );
2596
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2597
    let key_c_own = c.config.author_key.unwrap();
2598
    assert!(c
2599
        .revoke_identity(&key_c_own, "lost laptop")
2600
        .unwrap()
2601
        .is_none());
2602
    assert!(c.is_revoked(&key_c_own).unwrap());
2603
    assert_eq!(key_c_own, key_c);
2604
}
2605
2606
#[test]
2607
fn renames_are_detected_and_tracked_as_moves() {
2608
    hermetic();
2609
    let dir = tempfile::tempdir().unwrap();
2610
    let root = dir.path();
2611
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2612
    write(
2613
        root,
2614
        "src/old.rs",
2615
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2616
    );
2617
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2618
    write(root, "tiny.txt", b"x\n");
2619
    let h1 = repo.commit("base", &[]).unwrap();
2620
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2621
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2622
2623
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2624
    // that shares nothing with the removed file.
2625
    fs::remove_file(root.join("src/old.rs")).unwrap();
2626
    write(
2627
        root,
2628
        "lib/new.rs",
2629
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2630
    );
2631
    fs::remove_file(root.join("img.bin")).unwrap();
2632
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2633
    fs::remove_file(root.join("tiny.txt")).unwrap();
2634
    write(root, "other.txt", b"completely different\n");
2635
    let snap = repo.snapshot("status").unwrap();
2636
    let statuses: Vec<(&str, ChangeStatus)> = snap
2637
        .statuses
2638
        .iter()
2639
        .map(|s| (s.path.as_str(), s.status))
2640
        .collect();
2641
    assert_eq!(
2642
        statuses,
2643
        vec![
2644
            ("assets/img.bin", ChangeStatus::Renamed),
2645
            ("lib/new.rs", ChangeStatus::Renamed),
2646
            ("other.txt", ChangeStatus::Added),
2647
            ("src", ChangeStatus::Removed),
2648
            ("tiny.txt", ChangeStatus::Removed)
2649
        ]
2650
    );
2651
    let h2 = repo.commit("move things", &[]).unwrap();
2652
    let c = repo.store().get_change(&h2).unwrap();
2653
    let moves: Vec<_> = c
2654
        .tree_ops
2655
        .iter()
2656
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2657
        .collect();
2658
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
2659
    assert!(c.tree_ops.iter().any(
2660
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2661
    ));
2662
    assert!(c.tree_ops.iter().any(
2663
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2664
    ));
2665
    let snap = repo.load_state(&[h2]).unwrap().materialize();
2666
    assert_eq!(
2667
        snap.files["lib/new.rs"].node, node_old,
2668
        "the node survives the rename"
2669
    );
2670
    assert!(
2671
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2672
    );
2673
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
2674
    assert!(render_change(
2675
        &c,
2676
        &repo.load_state(&[h1]).unwrap(),
2677
        &repo.load_state(&[h1]).unwrap().materialize()
2678
    )
2679
    .contains("R "));
2680
    // A fresh checkout reproduces the tree.
2681
    let other = tempfile::tempdir().unwrap();
2682
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
2683
    assert_eq!(
2684
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2685
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2686
    );
2687
    assert!(!other.path().join("src").exists());
2688
    assert!(!clone.snapshot("status").unwrap().changed);
2689
    // Similarity is line based, byte weighted.
2690
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2691
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2692
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2693
    assert_eq!(similarity(b"", b"x\n"), 0);
2694
}
2695
2696
#[test]
2697
fn git_fetch_and_push_round_trip() {
2698
    hermetic();
2699
    if std::process::Command::new("git")
2700
        .arg("--version")
2701
        .output()
2702
        .is_err()
2703
    {
2704
        eprintln!("git not installed; skipping");
2705
        return;
2706
    }
2707
    let dir = tempfile::tempdir().unwrap();
2708
    let root = dir.path();
2709
    let git_in = |d: &Path, args: &[&str]| -> String {
2710
        let out = std::process::Command::new("git")
2711
            .arg("-C")
2712
            .arg(d)
2713
            .args([
2714
                "-c",
2715
                "user.name=Grace",
2716
                "-c",
2717
                "[email protected]",
2718
                "-c",
2719
                "commit.gpgsign=false",
2720
            ])
2721
            .args(args)
2722
            .output()
2723
            .unwrap();
2724
        assert!(
2725
            out.status.success(),
2726
            "git {args:?}: {}",
2727
            String::from_utf8_lossy(&out.stderr)
2728
        );
2729
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2730
    };
2731
    // A bare "remote" and a work tree that pushes to it.
2732
    let remote = root.join("remote.git");
2733
    fs::create_dir_all(&remote).unwrap();
2734
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2735
    let work = root.join("work");
2736
    git_in(
2737
        root,
2738
        &[
2739
            "clone",
2740
            "-q",
2741
            remote.to_str().unwrap(),
2742
            work.to_str().unwrap(),
2743
        ],
2744
    );
2745
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2746
    write(&work, "README.md", b"# Project\n");
2747
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2748
    git_in(&work, &["add", "."]);
2749
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2750
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2751
    git_in(&work, &["commit", "-q", "-am", "second"]);
2752
    git_in(&work, &["push", "-q", "origin", "main"]);
2753
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2754
2755
    // Fetch into a fresh oxy repository.
2756
    let o = root.join("oxy");
2757
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
2758
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2759
        .unwrap();
2760
    let url = remote.to_string_lossy().to_string();
2761
    let r = repo.git_fetch(&url, "main").unwrap();
2762
    assert_eq!((r.commits, r.heads), (2, 1));
2763
    assert_eq!(
2764
        fs::read(o.join("src/lib.rs")).unwrap(),
2765
        b"pub fn a() {}\npub fn b() {}\n"
2766
    );
2767
    assert!(!repo.snapshot("status").unwrap().changed);
2768
    assert_eq!(
2769
        repo.git_fetch(&url, "main").unwrap().commits,
2770
        0,
2771
        "nothing new"
2772
    );
2773
2774
    // An oxy change, pushed back: one commit on top of the Git tip.
2775
    write(
2776
        &o,
2777
        "src/lib.rs",
2778
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2779
    );
2780
    write(&o, "NOTES.md", b"from oxy\n");
2781
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2782
    let r = repo.git_push(&url, "main").unwrap();
2783
    assert_eq!(r.exported, 1, "{r:?}");
2784
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2785
    assert_eq!(
2786
        git_in(&work, &["log", "--format=%s", "main"]),
2787
        "add c and notes\nsecond\ninitial"
2788
    );
2789
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2790
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2791
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
2792
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2793
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2794
    assert_eq!(
2795
        repo.git_push(&url, "main").unwrap().exported,
2796
        0,
2797
        "already pushed"
2798
    );
2799
2800
    // Git moves on; pushing without fetching is refused, fetching brings
2801
    // the commit in and the working copy follows.
2802
    write(&work, "README.md", b"# Project\n\nMore.\n");
2803
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2804
    git_in(&work, &["push", "-q", "origin", "main"]);
2805
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
2806
    assert!(repo
2807
        .git_push(&url, "main")
2808
        .unwrap_err()
2809
        .to_string()
2810
        .contains("fetch"));
2811
    let r = repo.git_fetch(&url, "main").unwrap();
2812
    assert_eq!(
2813
        (r.commits, r.heads),
2814
        (1, 2),
2815
        "the Git change and the oxy change commute"
2816
    );
2817
    assert_eq!(
2818
        fs::read(o.join("README.md")).unwrap(),
2819
        b"# Project\n\nMore.\n"
2820
    );
2821
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2822
    assert!(!repo.snapshot("status").unwrap().changed);
2823
    // Another oxy change pushes on top of Git's newest commit.
2824
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2825
    repo.commit("notes again", &[]).unwrap();
2826
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2827
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2828
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
2829
    assert_eq!(
2830
        fs::read(work.join("NOTES.md")).unwrap(),
2831
        b"from oxy\nagain\n"
2832
    );
2833
    assert_eq!(
2834
        git_in(&work, &["log", "--format=%s", "main"])
2835
            .lines()
2836
            .count(),
2837
        5
2838
    );
2839
}
2840
2841
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2842
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2843
#[test]
2844
#[ignore]
2845
fn bench_one_gibibyte_file() {
2846
    hermetic();
2847
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2848
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2849
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2850
        None => tempfile::tempdir().unwrap(),
2851
    };
2852
    let root = dir.path();
2853
    let repo = Repo::init(&root.join("r"))
2854
        .unwrap()
2855
        .with_home(root.join("home"));
2856
    let size = 1usize << 30;
2857
    let mut data = vec![0u8; size];
2858
    let mut x = 0x9e3779b97f4a7c15u64;
2859
    for chunk in data.chunks_mut(8) {
2860
        x ^= x << 13;
2861
        x ^= x >> 7;
2862
        x ^= x << 17;
2863
        let b = x.to_le_bytes();
2864
        chunk.copy_from_slice(&b[..chunk.len()]);
2865
    }
2866
    let t = std::time::Instant::now();
2867
    write(&root.join("r"), "big.bin", &data);
2868
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
2869
    let t = std::time::Instant::now();
2870
    let h = repo.commit("big", &[]).unwrap();
2871
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
2872
    let t = std::time::Instant::now();
2873
    assert!(!repo.snapshot("status").unwrap().changed);
2874
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
2875
    let t = std::time::Instant::now();
2876
    let objects = repo.store().list().unwrap().len();
2877
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
2878
    let t = std::time::Instant::now();
2879
    let g = repo.gc(true).unwrap();
2880
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
2881
    let t = std::time::Instant::now();
2882
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
2883
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
2884
    let t = std::time::Instant::now();
2885
    let back = fs::read(root.join("c/big.bin")).unwrap();
2886
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
2887
    eprintln!("read back and verify: {:.2?}", t.elapsed());
2888
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
2889
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
2890
    eprintln!(
2891
        "store size: {:.1} MiB for 1 GiB of data",
2892
        store_bytes as f64 / (1024.0 * 1024.0)
2893
    );
2894
}
2895
2896
fn walkdir_size(p: &Path) -> u64 {
2897
    let mut total = 0;
2898
    if let Ok(rd) = fs::read_dir(p) {
2899
        for e in rd.flatten() {
2900
            let path = e.path();
2901
            if path.is_dir() {
2902
                total += walkdir_size(&path);
2903
            } else if let Ok(m) = fs::metadata(&path) {
2904
                total += m.len();
2905
            }
2906
        }
2907
    }
2908
    total
2909
}
2910
2911
/// An opaque file whose size and mtime match the manifest is not read on
2912
/// the next snapshot: its blob comes from the manifest's stat cache.
2913
#[cfg(unix)]
2914
#[test]
2915
fn stat_cache_skips_reading_unchanged_opaque_files() {
2916
    use std::os::unix::fs::PermissionsExt;
2917
    hermetic();
2918
    let dir = tempfile::tempdir().unwrap();
2919
    let root = dir.path();
2920
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2921
    let mut big = vec![0u8; 300 * 1024];
2922
    for (i, b) in big.iter_mut().enumerate() {
2923
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
2924
    }
2925
    big[0] = 0;
2926
    write(root, "big.bin", &big);
2927
    write(root, "a.txt", b"text\n");
2928
    let h1 = repo.commit("base", &[]).unwrap();
2929
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
2930
    assert!(
2931
        m.entries["big.bin"].blob.is_some(),
2932
        "opaque files record their blob"
2933
    );
2934
    assert!(m.entries["a.txt"].blob.is_none());
2935
    let blob = m.entries["big.bin"].blob.unwrap();
2936
    assert!(repo.store().has(&blob));
2937
2938
    // Files modified within two seconds of the manifest are racy and still
2939
    // read; age the file so the cache applies, then snapshot to record it.
2940
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
2941
    fs::File::options()
2942
        .write(true)
2943
        .open(root.join("big.bin"))
2944
        .unwrap()
2945
        .set_modified(old)
2946
        .unwrap();
2947
    assert!(!repo.snapshot("status").unwrap().changed);
2948
    // Now the file cannot be read at all; the snapshot succeeds without it.
2949
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
2950
    let snap = repo.snapshot("status").unwrap();
2951
    assert!(
2952
        !snap.changed && snap.statuses.is_empty(),
2953
        "{:?}",
2954
        snap.statuses
2955
    );
2956
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
2957
    // A real change (new mtime, new content) is seen and committed correctly.
2958
    let mut big2 = big.clone();
2959
    big2[10] ^= 0xff;
2960
    write(root, "big.bin", &big2);
2961
    let snap = repo.snapshot("status").unwrap();
2962
    assert_eq!(
2963
        snap.statuses
2964
            .iter()
2965
            .map(|s| (s.path.as_str(), s.status))
2966
            .collect::<Vec<_>>(),
2967
        vec![("big.bin", ChangeStatus::Modified)]
2968
    );
2969
    let h2 = repo.commit("edit", &[]).unwrap();
2970
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
2971
    assert_eq!(
2972
        files["big.bin"].content,
2973
        FileContent::Opaque {
2974
            blobs: vec![Repo::blob_ref(&big2)]
2975
        }
2976
    );
2977
    // Checkout writes a manifest with blobs too, so the next status is cached.
2978
    repo.checkout(&[h1], false, "checkout").unwrap();
2979
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
2980
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
2981
    assert!(!repo.snapshot("status").unwrap().changed);
2982
}
2983
2984
#[test]
2985
fn status_json_lists_conflicts_with_contributors() {
2986
    hermetic();
2987
    let dir = tempfile::tempdir().unwrap();
2988
    let root = dir.path();
2989
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2990
    write(root, "a.txt", b"one\n");
2991
    let h1 = repo.commit("base", &[]).unwrap();
2992
    write(root, "a.txt", b"one\nleft\n");
2993
    let ha = repo.commit("left", &[]).unwrap();
2994
    repo.checkout(&[h1], true, "checkout").unwrap();
2995
    write(root, "a.txt", b"one\nright\n");
2996
    let hb = repo.commit("right", &[]).unwrap();
2997
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
2998
    let snap = repo.snapshot("status").unwrap();
2999
    assert!(snap.base_snapshot.is_conflicted());
3000
    let json = repo.status_json(&snap).unwrap();
3001
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3002
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3003
    assert!(json.contains("\"conflicted\":true"), "{json}");
3004
    assert!(
3005
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3006
        "{json}"
3007
    );
3008
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3009
    assert!(json.contains("\"resolved\":false"), "{json}");
3010
    assert!(json.starts_with('{') && json.ends_with('}'));
3011
    // Resolve and the report says so; a clean copy has no conflicts.
3012
    write(root, "a.txt", b"one\nleft\nright\n");
3013
    let snap = repo.snapshot("status").unwrap();
3014
    let json = repo.status_json(&snap).unwrap();
3015
    assert!(json.contains("\"resolved\":true"), "{json}");
3016
    repo.commit("resolve", &[]).unwrap();
3017
    let snap = repo.snapshot("status").unwrap();
3018
    let json = repo.status_json(&snap).unwrap();
3019
    assert!(
3020
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3021
        "{json}"
3022
    );
3023
}
3024
3025
#[test]
3026
fn ignore_rules_do_not_untrack_files() {
3027
    hermetic();
3028
    let dir = tempfile::tempdir().unwrap();
3029
    let root = dir.path();
3030
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3031
    write(root, "src.c", b"int x;\n");
3032
    write(root, "build/out.o", b"\0obj");
3033
    write(root, "sub/keep.log", b"keep\n");
3034
    write(root, "sub/junk.log", b"junk\n");
3035
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3036
    let snap = repo.snapshot("status").unwrap();
3037
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3038
    assert_eq!(
3039
        added,
3040
        vec![".oxyignore", "src.c", "sub/keep.log"],
3041
        "anchored, glob, and negated rules"
3042
    );
3043
    let h1 = repo.commit("base", &[]).unwrap();
3044
    // Ignoring a tracked file changes nothing about it.
3045
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3046
    let snap = repo.snapshot("status").unwrap();
3047
    assert_eq!(
3048
        snap.statuses
3049
            .iter()
3050
            .map(|s| s.path.as_str())
3051
            .collect::<Vec<_>>(),
3052
        vec![".oxyignore"]
3053
    );
3054
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3055
    assert!(repo
3056
        .load_state(&[h2])
3057
        .unwrap()
3058
        .materialize()
3059
        .files
3060
        .contains_key("src.c"));
3061
    // Its edits are still seen, by status and by the prompt.
3062
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3063
    write(root, "src.c", b"int x, y;\n");
3064
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3065
    let snap = repo.snapshot("status").unwrap();
3066
    assert_eq!(
3067
        snap.statuses
3068
            .iter()
3069
            .map(|s| (s.path.as_str(), s.status))
3070
            .collect::<Vec<_>>(),
3071
        vec![("src.c", ChangeStatus::Modified)]
3072
    );
3073
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3074
    assert!(
3075
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3076
    );
3077
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3078
    fs::remove_file(root.join("src.c")).unwrap();
3079
    let snap = repo.snapshot("status").unwrap();
3080
    assert_eq!(
3081
        snap.statuses
3082
            .iter()
3083
            .map(|s| (s.path.as_str(), s.status))
3084
            .collect::<Vec<_>>(),
3085
        vec![("src.c", ChangeStatus::Removed)]
3086
    );
3087
    repo.checkout(&[h3], true, "checkout").unwrap();
3088
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3089
    assert!(!repo.snapshot("status").unwrap().changed);
3090
    let _ = h1;
3091
}
3092
3093
#[test]
3094
fn split_works_on_non_heads_by_node() {
3095
    hermetic();
3096
    let dir = tempfile::tempdir().unwrap();
3097
    let root = dir.path();
3098
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3099
    write(root, "a.txt", b"one\n");
3100
    write(root, "junk/x.lock", b"lock\n");
3101
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3102
    write(root, "a.txt", b"one\ntwo\n");
3103
    let h2 = repo.commit("more work", &[]).unwrap();
3104
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3105
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3106
    // h1 is not a head: split it by node.
3107
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3108
    assert_ne!(h1b, h1);
3109
    assert_eq!(
3110
        repo.store().get_change(&h1b).unwrap().change_id,
3111
        id1,
3112
        "the rest keeps the ChangeId"
3113
    );
3114
    let junk = repo.store().get_change(&hj).unwrap();
3115
    assert!(junk.tree_ops.iter().all(
3116
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3117
    ));
3118
    let heads = repo.bookmark_heads().unwrap();
3119
    assert!(
3120
        heads.contains(&hj),
3121
        "the split-off part is a head of its own"
3122
    );
3123
    let snap = repo.load_state(&heads).unwrap().materialize();
3124
    assert!(
3125
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3126
        "the dependent was rewritten onto the new hash"
3127
    );
3128
    assert!(snap.files.contains_key("junk/x.lock"));
3129
    let h2b = heads
3130
        .iter()
3131
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3132
        .copied()
3133
        .unwrap();
3134
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3135
    assert!(!repo.snapshot("status").unwrap().changed);
3136
    // Abandoning the split-off head removes the junk from history.
3137
    repo.abandon(&hj).unwrap();
3138
    let heads = repo.bookmark_heads().unwrap();
3139
    let snap = repo.load_state(&heads).unwrap().materialize();
3140
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3141
    assert!(snap.files.contains_key("a.txt"));
3142
    // A dependent that touches the split-off paths blocks the split.
3143
    write(root, "junk/y.lock", b"y\n");
3144
    let hb = repo.commit("junk base", &[]).unwrap();
3145
    write(root, "junk/y.lock", b"yy\n");
3146
    write(root, "b.txt", b"b\n");
3147
    repo.commit("touches junk", &[]).unwrap();
3148
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3149
    assert!(err.contains("depends on the split-off paths"), "{err}");
3150
}
3151
3152
#[test]
3153
fn bookmarks_switch_merge_and_push() {
3154
    hermetic();
3155
    let dir = tempfile::tempdir().unwrap();
3156
    let root = dir.path();
3157
    let origin = Repo::init(&root.join("origin")).unwrap();
3158
    let url = root.join("origin").to_string_lossy().to_string();
3159
    let mut repo = Repo::clone(&url, &root.join("r"))
3160
        .unwrap()
3161
        .with_home(root.join("home"));
3162
    let r = root.join("r");
3163
    write(&r, "a.txt", b"a\n");
3164
    let h_a = repo.commit("a", &[]).unwrap();
3165
    assert!(repo.push("origin", false).unwrap()[0].ok);
3166
3167
    // A bookmark at the working copy's base, then work on it.
3168
    assert!(repo.bookmark_create("bad name..", None).is_err());
3169
    assert!(repo.bookmark_create("-x", None).is_err());
3170
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3171
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3172
    repo.bookmark_switch("feature", false).unwrap();
3173
    assert_eq!(repo.config.bookmark, "feature");
3174
    write(&r, "a.txt", b"a\nb\n");
3175
    write(&r, "b.txt", b"b\n");
3176
    let h_b = repo.commit("b on feature", &[]).unwrap();
3177
    assert_eq!(
3178
        repo.bookmark_heads().unwrap(),
3179
        vec![h_b],
3180
        "b edits a.txt, so it depends on a"
3181
    );
3182
    assert_eq!(
3183
        repo.resolve_heads("main").unwrap(),
3184
        vec![h_a],
3185
        "main is untouched"
3186
    );
3187
    assert_eq!(
3188
        repo.resolve_change("feature").unwrap(),
3189
        h_b,
3190
        "a one-head bookmark names its change"
3191
    );
3192
    // Reopening keeps the workspace's bookmark.
3193
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3194
    assert_eq!(reopened.config.bookmark, "feature");
3195
    // Back to main: b.txt goes away; work there.
3196
    repo.bookmark_switch("main", false).unwrap();
3197
    assert!(!r.join("b.txt").exists());
3198
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3199
    write(&r, "c.txt", b"c\n");
3200
    let h_c = repo.commit("c on main", &[]).unwrap();
3201
    let list = repo.bookmarks().unwrap();
3202
    assert_eq!(
3203
        list.iter()
3204
            .map(|b| (b.name.as_str(), b.current))
3205
            .collect::<Vec<_>>(),
3206
        vec![("feature", false), ("main", true)]
3207
    );
3208
    assert_eq!(
3209
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3210
        Some(1),
3211
        "c is not on origin yet"
3212
    );
3213
    // Merge feature into main: the union, both heads, no merge change.
3214
    let m = repo.merge("feature").unwrap();
3215
    assert!(m.changed && m.checked_out);
3216
    let mut want = vec![h_b, h_c];
3217
    want.sort();
3218
    assert_eq!(m.heads, want);
3219
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3220
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3221
    assert!(repo.merge("main").is_err());
3222
    // The other bookmark can be pushed by name and appears at origin.
3223
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3224
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3225
    assert!(repo.push("origin", false).unwrap()[0].ok);
3226
    assert_eq!(
3227
        repo.bookmarks()
3228
            .unwrap()
3229
            .iter()
3230
            .find(|b| b.name == "main")
3231
            .unwrap()
3232
            .ahead,
3233
        Some(0)
3234
    );
3235
    // A second workspace inherits the current bookmark and can switch independently.
3236
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3237
    assert_eq!(ws.config.bookmark, "main");
3238
    let mut ws = ws;
3239
    ws.bookmark_switch("feature", false).unwrap();
3240
    assert_eq!(
3241
        Repo::open(&r).unwrap().config.bookmark,
3242
        "main",
3243
        "the first workspace is unaffected"
3244
    );
3245
    assert!(
3246
        repo.bookmark_delete("feature").is_err(),
3247
        "current bookmark of another workspace"
3248
    );
3249
    ws.bookmark_switch("main", false).unwrap();
3250
    // Set and delete.
3251
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3252
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3253
    repo.bookmark_delete("feature").unwrap();
3254
    assert!(repo.resolve_heads("feature").is_err());
3255
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3256
    assert!(
3257
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3258
        "changes of a deleted bookmark remain"
3259
    );
3260
}
3261
3262
#[test]
3263
fn oxygen_subrepos_pin_follow_and_update() {
3264
    hermetic();
3265
    let dir = tempfile::tempdir().unwrap();
3266
    let root = dir.path();
3267
    // A library repository with two commits, and a bare-ish origin for it.
3268
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3269
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3270
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3271
        .unwrap()
3272
        .with_home(root.join("home"));
3273
    write(&root.join("lib"), "lib.txt", b"v1\n");
3274
    let l1 = lib.commit("lib v1", &[]).unwrap();
3275
    assert!(lib.push("origin", false).unwrap()[0].ok);
3276
    let _ = lib_origin;
3277
3278
    // The application (a clone of its own origin) adds it as a subrepo.
3279
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3280
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3281
    let _ = app_origin;
3282
    let app_dir = root.join("app");
3283
    let app = Repo::clone(&app_url, &app_dir)
3284
        .unwrap()
3285
        .with_home(root.join("home"));
3286
    write(&app_dir, "main.txt", b"app\n");
3287
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3288
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3289
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3290
    let snap = app.snapshot("status").unwrap();
3291
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3292
    assert_eq!(
3293
        paths,
3294
        vec![".oxymodules", "libs/lib", "main.txt"],
3295
        "the nested files are not walked"
3296
    );
3297
    let a1 = app.commit("app with lib", &[]).unwrap();
3298
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3299
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3300
    assert!(!files.contains_key("libs/lib/lib.txt"));
3301
    assert!(!app.snapshot("status").unwrap().changed);
3302
    let subs = app.subrepos().unwrap();
3303
    assert_eq!(subs.len(), 1);
3304
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3305
3306
    // Advance the nested repository: the parent sees a modified pin.
3307
    let nested = Repo::open(&app_dir.join("libs/lib"))
3308
        .unwrap()
3309
        .with_home(root.join("home"));
3310
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3311
    let l2 = nested.commit("lib v2", &[]).unwrap();
3312
    assert!(nested.push("origin", false).unwrap()[0].ok);
3313
    let snap = app.snapshot("status").unwrap();
3314
    assert_eq!(
3315
        snap.statuses
3316
            .iter()
3317
            .map(|s| (s.path.as_str(), s.status))
3318
            .collect::<Vec<_>>(),
3319
        vec![("libs/lib", ChangeStatus::Modified)]
3320
    );
3321
    let a2 = app.commit("bump lib", &[]).unwrap();
3322
    // Checking out the older app state moves the nested repository back.
3323
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3324
    assert!(r.notes.is_empty(), "{:?}", r.notes);
3325
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3326
    assert_eq!(
3327
        Repo::open(&app_dir.join("libs/lib"))
3328
            .unwrap()
3329
            .bookmark_heads()
3330
            .unwrap(),
3331
        vec![l1]
3332
    );
3333
    assert!(!app.snapshot("status").unwrap().changed);
3334
    // A dirty nested repository is left alone and reported.
3335
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3336
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3337
    assert!(
3338
        r.notes.iter().any(|n| n.contains("uncommitted")),
3339
        "{:?}",
3340
        r.notes
3341
    );
3342
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3343
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3344
    let r = app.submodule_update(false, &[]).unwrap();
3345
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3346
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3347
    let _ = l2;
3348
3349
    // A fresh clone of the app has the pin but no nested repository until update --init.
3350
    assert!(app.push("origin", false).unwrap()[0].ok);
3351
    let clone_dir = root.join("app-clone");
3352
    let clone = Repo::clone(&app_url, &clone_dir)
3353
        .unwrap()
3354
        .with_home(root.join("home"));
3355
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3356
    assert_eq!(
3357
        clone.submodule_update(false, &[]).unwrap(),
3358
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3359
    );
3360
    assert_eq!(
3361
        clone.submodule_update(true, &[]).unwrap(),
3362
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3363
    );
3364
    assert_eq!(
3365
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3366
        b"v2\n"
3367
    );
3368
    assert!(!clone.snapshot("status").unwrap().changed);
3369
    // Removing the subrepo leaves the directory and drops the node.
3370
    clone.submodule_remove("libs/lib").unwrap();
3371
    let snap = clone.snapshot("status").unwrap();
3372
    assert!(
3373
        snap.statuses
3374
            .iter()
3375
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3376
        "{:?}",
3377
        snap.statuses
3378
    );
3379
    let c = clone.commit("drop lib", &[]).unwrap();
3380
    assert!(!clone
3381
        .load_state(&[c])
3382
        .unwrap()
3383
        .materialize()
3384
        .files
3385
        .contains_key("libs/lib"));
3386
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3387
    assert!(
3388
        !clone.snapshot("status").unwrap().changed,
3389
        "an unregistered nested repository is ignored"
3390
    );
3391
}
3392
3393
#[test]
3394
fn git_submodules_import_and_export_as_gitlinks() {
3395
    hermetic();
3396
    if std::process::Command::new("git")
3397
        .arg("--version")
3398
        .output()
3399
        .is_err()
3400
    {
3401
        eprintln!("git not installed; skipping");
3402
        return;
3403
    }
3404
    let dir = tempfile::tempdir().unwrap();
3405
    let root = dir.path();
3406
    let git_in = |d: &Path, args: &[&str]| -> String {
3407
        let out = std::process::Command::new("git")
3408
            .arg("-C")
3409
            .arg(d)
3410
            .args([
3411
                "-c",
3412
                "user.name=Grace",
3413
                "-c",
3414
                "[email protected]",
3415
                "-c",
3416
                "commit.gpgsign=false",
3417
                "-c",
3418
                "protocol.file.allow=always",
3419
            ])
3420
            .args(args)
3421
            .output()
3422
            .unwrap();
3423
        assert!(
3424
            out.status.success(),
3425
            "git {args:?}: {}",
3426
            String::from_utf8_lossy(&out.stderr)
3427
        );
3428
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3429
    };
3430
    let sub = root.join("sub");
3431
    fs::create_dir_all(&sub).unwrap();
3432
    git_in(&sub, &["init", "-q", "-b", "main"]);
3433
    write(&sub, "s.txt", b"sub\n");
3434
    git_in(&sub, &["add", "."]);
3435
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3436
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3437
    let g = root.join("main.git");
3438
    fs::create_dir_all(&g).unwrap();
3439
    git_in(&g, &["init", "-q", "-b", "main"]);
3440
    write(&g, "README.md", b"# app\n");
3441
    git_in(&g, &["add", "."]);
3442
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3443
    git_in(
3444
        &g,
3445
        &[
3446
            "submodule",
3447
            "add",
3448
            "-q",
3449
            sub.to_str().unwrap(),
3450
            "vendor/sub",
3451
        ],
3452
    );
3453
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3454
3455
    let dest = root.join("oxy");
3456
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3457
    let rep = repo.import_git(&g, "main").unwrap();
3458
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3459
    let files = repo
3460
        .load_state(&repo.bookmark_heads().unwrap())
3461
        .unwrap()
3462
        .materialize()
3463
        .files;
3464
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3465
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3466
        panic!()
3467
    };
3468
    assert_eq!(
3469
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3470
        crate::subrepo::Pin::Git {
3471
            sha: sub_sha.clone(),
3472
            branch: "HEAD".into()
3473
        }
3474
    );
3475
    let modules =
3476
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3477
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3478
    assert!(modules.entries["vendor/sub"].git);
3479
    assert!(
3480
        files.contains_key(".gitmodules"),
3481
        "the Git file is kept for round trips"
3482
    );
3483
    assert!(
3484
        !dest.join("vendor/sub/.git").exists(),
3485
        "not cloned until update --init"
3486
    );
3487
    assert!(!repo.snapshot("status").unwrap().changed);
3488
    // update --init clones it at the pinned commit; status is unchanged.
3489
    assert_eq!(
3490
        repo.submodule_update(true, &[]).unwrap(),
3491
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3492
    );
3493
    assert_eq!(
3494
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3495
        sub_sha
3496
    );
3497
    assert!(!repo.snapshot("status").unwrap().changed);
3498
    // Export writes the gitlink and .gitmodules back.
3499
    let mirror = root.join("mirror.git");
3500
    let rep = repo.git_export(&mirror).unwrap();
3501
    assert_eq!(rep.skipped_subrepos, 0);
3502
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3503
    assert!(
3504
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3505
        "{ls}"
3506
    );
3507
    assert_eq!(
3508
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3509
        ".gitmodules\nREADME.md\nvendor"
3510
    );
3511
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3512
    assert_eq!(
3513
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3514
        orig_tree,
3515
        "tree round trip"
3516
    );
3517
}
3518
3519
#[test]
3520
fn partial_commits_by_path_and_by_hunk() {
3521
    hermetic();
3522
    let dir = tempfile::tempdir().unwrap();
3523
    let root = dir.path();
3524
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3525
    write(root, "a.txt", b"1\n2\n3\n");
3526
    write(root, "b.txt", b"b\n");
3527
    let h0 = repo.commit("base", &[]).unwrap();
3528
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3529
    write(root, "b.txt", b"b\nbb\n");
3530
    write(root, "c.txt", b"c\n");
3531
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3532
    let h1 = repo
3533
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3534
        .unwrap();
3535
    let c1 = repo.store().get_change(&h1).unwrap();
3536
    assert!(
3537
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3538
        "{:?}",
3539
        c1.tree_ops
3540
    );
3541
    assert_eq!(c1.deps, vec![h0]);
3542
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3543
    assert!(
3544
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3545
    );
3546
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3547
    assert!(!files.contains_key("c.txt"));
3548
    let snap = repo.snapshot("status").unwrap();
3549
    assert_eq!(
3550
        snap.statuses
3551
            .iter()
3552
            .map(|s| (s.path.as_str(), s.status))
3553
            .collect::<Vec<_>>(),
3554
        vec![
3555
            ("b.txt", ChangeStatus::Modified),
3556
            ("c.txt", ChangeStatus::Added)
3557
        ]
3558
    );
3559
    assert_eq!(
3560
        fs::read(root.join("b.txt")).unwrap(),
3561
        b"b\nbb\n",
3562
        "disk untouched"
3563
    );
3564
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3565
    let (_, hunks) = repo.hunks().unwrap();
3566
    let b_hunk = hunks
3567
        .iter()
3568
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3569
        .unwrap()
3570
        .index;
3571
    let h2 = repo
3572
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3573
        .unwrap();
3574
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3575
    assert!(
3576
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3577
    );
3578
    assert!(!files.contains_key("c.txt"));
3579
    let snap = repo.snapshot("status").unwrap();
3580
    assert_eq!(
3581
        snap.statuses
3582
            .iter()
3583
            .map(|s| s.path.as_str())
3584
            .collect::<Vec<_>>(),
3585
        vec!["c.txt"]
3586
    );
3587
    // Choosing only the content hunk of a file in a new directory pulls in
3588
    // the directory and file additions it needs.
3589
    write(root, "d/e.txt", b"e\n");
3590
    let (_, hunks) = repo.hunks().unwrap();
3591
    let e_insert = hunks
3592
        .iter()
3593
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3594
        .unwrap()
3595
        .index;
3596
    let h3 = repo
3597
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3598
        .unwrap();
3599
    let c3 = repo.store().get_change(&h3).unwrap();
3600
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3601
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3602
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3603
    // Choosing a new file's addition hunk brings its content along.
3604
    write(root, "f/g.txt", b"g\n");
3605
    let (_, hunks) = repo.hunks().unwrap();
3606
    let g_add = hunks
3607
        .iter()
3608
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3609
        .unwrap()
3610
        .index;
3611
    let h4 = repo
3612
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3613
        .unwrap();
3614
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
3615
    assert!(
3616
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3617
    );
3618
    assert!(!repo
3619
        .snapshot("status")
3620
        .unwrap()
3621
        .statuses
3622
        .iter()
3623
        .any(|s| s.path == "f/g.txt"));
3624
    // Everything left commits normally; the working copy is then clean.
3625
    repo.commit("the rest", &[]).unwrap();
3626
    assert!(!repo.snapshot("status").unwrap().changed);
3627
    let files = repo
3628
        .load_state(&repo.bookmark_heads().unwrap())
3629
        .unwrap()
3630
        .materialize()
3631
        .files;
3632
    assert!(files.contains_key("c.txt"));
3633
}
3634
3635
#[test]
3636
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3637
    hermetic();
3638
    let dir = tempfile::tempdir().unwrap();
3639
    let root = dir.path();
3640
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3641
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3642
        .unwrap();
3643
    write(root, "a.txt", b"one\n");
3644
    let h1 = repo.commit("first", &[]).unwrap();
3645
    write(root, "a.txt", b"one\ntwo\n");
3646
    let h2 = repo.commit("second", &[]).unwrap();
3647
    let b = repo.blame("a.txt").unwrap();
3648
    assert_eq!(
3649
        b.iter()
3650
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3651
            .collect::<Vec<_>>(),
3652
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3653
    );
3654
    assert!(b.iter().all(|l| l.author == "Ada"));
3655
    assert_eq!(
3656
        b[0].change_id,
3657
        repo.store().get_change(&h1).unwrap().change_id
3658
    );
3659
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3660
    repo.commit("rename", &[]).unwrap();
3661
    let b = repo.blame("b.txt").unwrap();
3662
    assert_eq!(
3663
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3664
        vec![h1, h2],
3665
        "the node survives the rename"
3666
    );
3667
    assert!(repo.blame("a.txt").is_err());
3668
}
3669
3670
#[test]
3671
fn bisect_finds_the_first_bad_change() {
3672
    hermetic();
3673
    let dir = tempfile::tempdir().unwrap();
3674
    let root = dir.path();
3675
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3676
    let mut content = String::new();
3677
    let mut hashes = Vec::new();
3678
    for i in 1..=8 {
3679
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3680
        write(root, "f.txt", content.as_bytes());
3681
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3682
    }
3683
    // Each step appends after the previous line, so the chain is linear.
3684
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3685
    repo.bisect_start().unwrap();
3686
    assert!(matches!(
3687
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3688
        BisectStep::NeedMarks { good: 1, bad: 0 }
3689
    ));
3690
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3691
    assert!(
3692
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3693
        "{step:?}"
3694
    );
3695
    // Automated: bad when the bug line is present.
3696
    let step = repo
3697
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3698
        .unwrap();
3699
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3700
    assert_eq!(
3701
        repo.bisect_status().unwrap(),
3702
        Some(BisectStep::Found { culprit: hashes[4] })
3703
    );
3704
    repo.bisect_reset().unwrap();
3705
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3706
    assert!(repo.bisect_status().unwrap().is_none());
3707
    assert!(!repo.snapshot("status").unwrap().changed);
3708
    // Manual marks and a skip.
3709
    repo.bisect_start().unwrap();
3710
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3711
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3712
    let mut skipped_once = false;
3713
    let mut guard = 0;
3714
    while let BisectStep::Testing { .. } = step {
3715
        guard += 1;
3716
        assert!(guard < 20);
3717
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3718
        if !skipped_once && text.contains("line 6") {
3719
            // An untestable state away from the boundary: the search routes around it.
3720
            skipped_once = true;
3721
            step = repo.bisect_mark(None, &[]).unwrap();
3722
            continue;
3723
        }
3724
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3725
    }
3726
    assert!(skipped_once);
3727
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3728
    repo.bisect_reset().unwrap();
3729
    // Skipping the culprit itself leaves it among the candidates reported.
3730
    repo.bisect_start().unwrap();
3731
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3732
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3733
    let mut guard = 0;
3734
    while let BisectStep::Testing { heads, .. } = &step {
3735
        guard += 1;
3736
        assert!(guard < 20);
3737
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3738
        let is_culprit_state =
3739
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3740
        step = if is_culprit_state {
3741
            repo.bisect_mark(None, &[]).unwrap()
3742
        } else {
3743
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3744
        };
3745
    }
3746
    match step {
3747
        BisectStep::Inconclusive { candidates } => assert!(
3748
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3749
            "{candidates:?}"
3750
        ),
3751
        other => panic!("{other:?}"),
3752
    }
3753
    repo.bisect_reset().unwrap();
3754
}
3755
3756
#[test]
3757
fn squash_folds_a_change_into_its_dependency() {
3758
    hermetic();
3759
    let dir = tempfile::tempdir().unwrap();
3760
    let root = dir.path();
3761
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3762
    write(root, "a.txt", b"1\n");
3763
    let a = repo.commit("A", &[]).unwrap();
3764
    write(root, "a.txt", b"1\n2\n");
3765
    let c = repo.commit("C", &[]).unwrap();
3766
    write(root, "a.txt", b"1\n2\n3\n");
3767
    let e = repo.commit("E", &[]).unwrap();
3768
    write(root, "b.txt", b"b\n");
3769
    let b = repo.commit("B", &[]).unwrap();
3770
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3771
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3772
    // E depends on C which A lacks: refused, naming it.
3773
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3774
    assert!(err.contains(&c.short(12)), "{err}");
3775
    // C into A: A' has both, C is gone, E follows and still reads the same.
3776
    let a2 = repo.squash(&c, &a).unwrap();
3777
    let a2c = repo.store().get_change(&a2).unwrap();
3778
    assert_eq!(a2c.change_id, id_a);
3779
    assert!(a2c.deps.is_empty());
3780
    let heads = repo.bookmark_heads().unwrap();
3781
    let st = repo.load_state(&heads).unwrap();
3782
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
3783
    let e2 = st
3784
        .changes()
3785
        .find(|(_, m)| m.change_id == id_e)
3786
        .map(|(h, _)| *h)
3787
        .unwrap();
3788
    assert_eq!(
3789
        repo.store().get_change(&e2).unwrap().deps,
3790
        vec![a2],
3791
        "E now depends on A' alone"
3792
    );
3793
    let files = st.materialize().files;
3794
    assert!(
3795
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3796
    );
3797
    assert!(files.contains_key("b.txt"));
3798
    assert!(st.contains(&b));
3799
    assert!(!repo.snapshot("status").unwrap().changed);
3800
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3801
    // Undo restores the three original changes.
3802
    repo.undo().unwrap();
3803
    repo.undo().unwrap();
3804
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3805
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3806
}
3807
3808
#[test]
3809
fn rebase_re_expresses_a_change_against_another_base() {
3810
    hermetic();
3811
    let dir = tempfile::tempdir().unwrap();
3812
    let root = dir.path();
3813
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3814
    write(root, "a.txt", b"1\n2\n");
3815
    let a = repo.commit("A", &[]).unwrap();
3816
    write(root, "a.txt", b"1\n2\n3\n");
3817
    let c = repo.commit("C: append 3", &[]).unwrap();
3818
    write(root, "a.txt", b"1\n2\n3\n4\n");
3819
    let e = repo.commit("E: append 4", &[]).unwrap();
3820
    // A different base: A plus a change that prepends a line.
3821
    repo.checkout(&[a], true, "checkout").unwrap();
3822
    write(root, "a.txt", b"0\n1\n2\n");
3823
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3824
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3825
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3826
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3827
    let c2 = repo.rebase(&c, &[d]).unwrap();
3828
    let c2c = repo.store().get_change(&c2).unwrap();
3829
    assert_eq!(c2c.change_id, id_c);
3830
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3831
    let heads = repo.bookmark_heads().unwrap();
3832
    let st = repo.load_state(&heads).unwrap();
3833
    assert!(!st.contains(&c) && st.contains(&d));
3834
    let e2 = st
3835
        .changes()
3836
        .find(|(_, m)| m.change_id == id_e)
3837
        .map(|(h, _)| *h)
3838
        .unwrap();
3839
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
3840
    assert!(
3841
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3842
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3843
    );
3844
    let files = st.materialize().files;
3845
    assert!(
3846
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3847
        "{:?}",
3848
        files["a.txt"].content
3849
    );
3850
    assert!(!files["a.txt"].is_conflicted());
3851
    // Rebasing onto a state that already contains the change is refused.
3852
    assert!(repo.rebase(&c2, &[c2]).is_err());
3853
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
3854
    assert!(
3855
        err.contains("lacks dependencies"),
3856
        "E needs C, which D's state does not have: {err}"
3857
    );
3858
}
3859
3860
#[test]
3861
fn unsigned_tags_keep_their_message() {
3862
    hermetic();
3863
    let dir = tempfile::tempdir().unwrap();
3864
    let root = dir.path();
3865
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3866
    write(root, "a.txt", b"a\n");
3867
    repo.commit("a", &[]).unwrap();
3868
    assert!(repo.secret_key().unwrap().is_none());
3869
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
3870
        .unwrap();
3871
    let tags = repo.tags().unwrap();
3872
    assert_eq!(
3873
        (
3874
            tags[0].name.as_str(),
3875
            tags[0].message.as_str(),
3876
            tags[0].signer.as_deref()
3877
        ),
3878
        ("v1", "first release", None)
3879
    );
3880
    assert!(
3881
        repo.tag_refs().unwrap()[0].attestation.is_none(),
3882
        "an unsigned attestation is not advertised"
3883
    );
3884
}
3885
3886
#[test]
3887
fn fsck_passes_a_sound_repository_and_names_each_fault() {
3888
    hermetic();
3889
    let dir = tempfile::tempdir().unwrap();
3890
    let root = dir.path();
3891
    let origin_path = root.join("origin");
3892
    let origin = Repo::init(&origin_path).unwrap();
3893
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
3894
        .unwrap()
3895
        .with_home(root.join("home-a"));
3896
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
3897
        .unwrap();
3898
    write(&root.join("a"), "f.txt", b"one\n");
3899
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
3900
    let h1 = a.commit("first", &[]).unwrap();
3901
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
3902
    let h2 = a.commit("second", &[]).unwrap();
3903
    a.tag_create("v1", &[h2], "first release").unwrap();
3904
    a.checkpoint().unwrap();
3905
    assert!(a.push("origin", false).unwrap()[0].ok);
3906
3907
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
3908
    for repo in [&a, &origin] {
3909
        let rep = repo.fsck().unwrap();
3910
        assert_eq!(rep.problems, vec![], "{rep:?}");
3911
        // The two commits, plus the working copy's change in `a`.
3912
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
3913
        assert!(rep.ops > 1 && rep.objects > 5);
3914
    }
3915
    assert!(origin.fsck().unwrap().attestations >= 1);
3916
3917
    // A flipped byte in a stored object is corruption, named by hash.
3918
    let c1 = a.store().path_for(&h1);
3919
    let pristine = fs::read(&c1).unwrap();
3920
    let mut bytes = pristine.clone();
3921
    *bytes.last_mut().unwrap() ^= 1;
3922
    fs::write(&c1, &bytes).unwrap();
3923
    let rep = a.fsck().unwrap();
3924
    assert!(rep.errors() >= 1);
3925
    assert!(
3926
        rep.problems
3927
            .iter()
3928
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
3929
        "{rep:?}"
3930
    );
3931
    fs::write(&c1, &pristine).unwrap();
3932
    assert_eq!(a.fsck().unwrap().errors(), 0);
3933
3934
    // A missing change is named with what needed it.
3935
    fs::remove_file(&c1).unwrap();
3936
    let rep = a.fsck().unwrap();
3937
    assert!(
3938
        rep.problems.iter().any(|p| p.severity == Severity::Error
3939
            && p.object == Some(h1)
3940
            && p.what.contains("change missing, needed by change")),
3941
        "{rep:?}"
3942
    );
3943
    fs::write(&c1, &pristine).unwrap();
3944
3945
    // A missing blob is an error in a full clone.
3946
    let c2 = a.store().get_change(&h1).unwrap();
3947
    let blob = c2
3948
        .edits
3949
        .iter()
3950
        .find_map(|e| match e {
3951
            Edit::Replace { new: Some(b), .. } => Some(*b),
3952
            _ => None,
3953
        })
3954
        .expect("the binary file is a blob");
3955
    let bp = a.store().path_for(&blob);
3956
    let blob_bytes = fs::read(&bp).unwrap();
3957
    fs::remove_file(&bp).unwrap();
3958
    let rep = a.fsck().unwrap();
3959
    assert!(
3960
        rep.problems
3961
            .iter()
3962
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
3963
        "{rep:?}"
3964
    );
3965
    fs::write(&bp, &blob_bytes).unwrap();
3966
3967
    // A broken op log head is reported, not a crash.
3968
    let head = root.join("a/.oxy/ops/head");
3969
    let saved = fs::read(&head).unwrap();
3970
    fs::write(&head, b"not a hash").unwrap();
3971
    let rep = a.fsck().unwrap();
3972
    assert!(
3973
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
3974
        "{rep:?}"
3975
    );
3976
    fs::write(&head, saved).unwrap();
3977
    assert_eq!(a.fsck().unwrap().problems, vec![]);
3978
}
3979
3980
/// Copy a directory tree (for restoring a pristine repository).
3981
fn copy_tree(from: &Path, to: &Path) {
3982
    fs::create_dir_all(to).unwrap();
3983
    for e in fs::read_dir(from).unwrap() {
3984
        let e = e.unwrap();
3985
        let target = to.join(e.file_name());
3986
        if e.file_type().unwrap().is_dir() {
3987
            copy_tree(&e.path(), &target);
3988
        } else {
3989
            fs::copy(e.path(), &target).unwrap();
3990
        }
3991
    }
3992
}
3993
3994
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
3995
/// would, and check that both repositories still open, pass `fsck`, and
3996
/// accept the same operation again.
3997
#[test]
3998
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
3999
    use crate::durable::failpoint;
4000
    hermetic();
4001
    let dir = tempfile::tempdir().unwrap();
4002
    let pristine = dir.path().join("pristine");
4003
    let origin_path = pristine.join("origin");
4004
    Repo::init(&origin_path).unwrap();
4005
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4006
        .unwrap()
4007
        .with_home(dir.path().join("home"));
4008
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4009
        .unwrap();
4010
    write(&pristine.join("a"), "f.txt", b"one\n");
4011
    a.commit("first", &[]).unwrap();
4012
    assert!(a.push("origin", false).unwrap()[0].ok);
4013
    drop(a);
4014
4015
    type Op = fn(&Repo) -> Result<()>;
4016
    let edit_and_commit: Op = |r| {
4017
        write(r.root(), "f.txt", b"one\ntwo\n");
4018
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4019
        r.commit("second", &[]).map(|_| ())
4020
    };
4021
    let push: Op = |r| {
4022
        let res = r.push("origin", false)?;
4023
        if res.iter().all(|x| x.ok) {
4024
            Ok(())
4025
        } else {
4026
            Err(RepoError::Msg(format!("{res:?}")))
4027
        }
4028
    };
4029
4030
    for (name, prepare, op) in [
4031
        ("commit", None, edit_and_commit),
4032
        ("push", Some(edit_and_commit), push),
4033
    ] {
4034
        let mut steps = 0;
4035
        for n in 1.. {
4036
            let run = dir.path().join(format!("{name}-{n}"));
4037
            copy_tree(&pristine, &run);
4038
            // Clones record their remote by path; point it at this copy.
4039
            let open = |p: &Path| {
4040
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4041
                r.config
4042
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4043
                    .unwrap();
4044
                r.save_config().unwrap();
4045
                r
4046
            };
4047
            let a = open(&run.join("a"));
4048
            if let Some(prep) = prepare {
4049
                prep(&a).unwrap();
4050
            }
4051
            failpoint::crash_after(n);
4052
            let outcome = op(&a);
4053
            let crashed = failpoint::disarm();
4054
            drop(a);
4055
            if !crashed {
4056
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4057
                steps = n - 1;
4058
                break;
4059
            }
4060
            assert!(
4061
                outcome.is_err(),
4062
                "{name}: a crash at step {n} was swallowed"
4063
            );
4064
            for repo in ["a", "origin"] {
4065
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4066
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4067
                });
4068
                let rep = r.fsck().unwrap();
4069
                assert_eq!(
4070
                    rep.errors(),
4071
                    0,
4072
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4073
                    rep.problems
4074
                );
4075
            }
4076
            // The interrupted operation can simply be run again.
4077
            let a = open(&run.join("a"));
4078
            // A crash after the commit point leaves the commit done.
4079
            let landed = a
4080
                .bookmark_heads()
4081
                .unwrap()
4082
                .iter()
4083
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4084
            let again = match (name, landed) {
4085
                ("commit", true) => Ok(()),
4086
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4087
                _ => op(&a),
4088
            };
4089
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4090
            assert_eq!(a.fsck().unwrap().errors(), 0);
4091
            fs::remove_dir_all(&run).unwrap();
4092
        }
4093
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4094
    }
4095
}
4096
4097
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4098
/// running at the same time lose nothing: every commit ends up on the
4099
/// bookmark, locally and on the remote, and the repository passes fsck.
4100
#[test]
4101
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4102
    hermetic();
4103
    let dir = tempfile::tempdir().unwrap();
4104
    let root = dir.path();
4105
    let origin = root.join("origin");
4106
    Repo::init_bare_unbound(&origin).unwrap();
4107
    let main = root.join("main");
4108
    let mut repo = Repo::init(&main).unwrap();
4109
    repo.config
4110
        .set("remote.origin.url", &origin.to_string_lossy())
4111
        .unwrap();
4112
    repo.save_config().unwrap();
4113
    write(&main, "seed.txt", b"seed\n");
4114
    repo.commit("seed", &[]).unwrap();
4115
    let second = root.join("second");
4116
    repo.workspace_add(&second, None).unwrap();
4117
    drop(repo);
4118
4119
    const EACH: usize = 15;
4120
    std::thread::scope(|s| {
4121
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4122
            s.spawn(move || {
4123
                let r = Repo::open(&dir).unwrap();
4124
                for i in 0..EACH {
4125
                    write(
4126
                        &dir,
4127
                        &format!("{tag}-{i}.txt"),
4128
                        format!("{tag} {i}\n").as_bytes(),
4129
                    );
4130
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4131
                    if push && i % 5 == 4 {
4132
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4133
                        let _ = r.push("origin", false);
4134
                    }
4135
                }
4136
            });
4137
        }
4138
    });
4139
4140
    let repo = Repo::open(&main).unwrap();
4141
    let heads = repo.bookmark_heads().unwrap();
4142
    let state = repo.load_state(&heads).unwrap();
4143
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4144
    for tag in ["a", "b"] {
4145
        for i in 0..EACH {
4146
            assert!(
4147
                messages.contains(&format!("{tag} {i}")),
4148
                "lost commit {tag} {i}; have {messages:?}"
4149
            );
4150
        }
4151
    }
4152
    let rep = repo.fsck().unwrap();
4153
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4154
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4155
    let hosted = Repo::open(&origin).unwrap();
4156
    let hosted_heads = hosted.bookmark_heads().unwrap();
4157
    assert_eq!(
4158
        hosted.load_state(&hosted_heads).unwrap().len(),
4159
        state.len(),
4160
        "the remote has every commit"
4161
    );
4162
}
4163
4164
/// Two operations recorded from the same parent (what two processes do
4165
/// when they race) are merged: both bookmarks' heads survive, and a
4166
/// change made on one side only is kept.
4167
#[test]
4168
fn operations_from_the_same_parent_are_merged() {
4169
    hermetic();
4170
    let dir = tempfile::tempdir().unwrap();
4171
    let root = dir.path();
4172
    let repo = Repo::init(root).unwrap();
4173
    write(root, "a.txt", b"a\n");
4174
    let a = repo.commit("a", &[]).unwrap();
4175
    write(root, "b.txt", b"b\n");
4176
    let b = repo.commit("b", &[]).unwrap();
4177
    let (x, op) = repo.head_op().unwrap();
4178
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4179
4180
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4181
    let mut one = op.view.clone();
4182
    one.bookmarks.insert("main".into(), state(vec![a]));
4183
    one.bookmarks.insert("topic".into(), state(vec![a]));
4184
    let mut two = op.view.clone();
4185
    two.bookmarks.insert("main".into(), state(vec![b]));
4186
    repo.record_op(&[x], "one", one).unwrap();
4187
    let merged = repo.record_op(&[x], "two", two).unwrap();
4188
4189
    let (head, op) = repo.head_op().unwrap();
4190
    assert_eq!(head, merged);
4191
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4192
    assert!(op.command.contains("merged with a concurrent operation"));
4193
    let mut main = repo
4194
        .store()
4195
        .get_state(&op.view.bookmarks["main"])
4196
        .unwrap()
4197
        .heads;
4198
    main.sort();
4199
    let mut want = vec![a, b];
4200
    want.sort();
4201
    assert_eq!(main, want, "both sides' heads are kept");
4202
    assert!(
4203
        op.view.bookmarks.contains_key("topic"),
4204
        "a one-sided change survives"
4205
    );
4206
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4207
}
4208
4209
#[test]
4210
fn failed_requests_come_with_a_next_step() {
4211
    use crate::protocol::hint_for;
4212
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4213
        .unwrap()
4214
        .contains("token"));
4215
    assert!(hint_for("…: HTTP 403: forbidden")
4216
        .unwrap()
4217
        .contains("repo:write"));
4218
    assert!(hint_for("…: HTTP 404: no such repository")
4219
        .unwrap()
4220
        .contains("owner and repository name"));
4221
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4222
        .unwrap()
4223
        .contains("oxyhub-ca.pem"));
4224
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4225
        .unwrap()
4226
        .contains("running"));
4227
    assert!(hint_for("Dns Failed: failed to lookup address information")
4228
        .unwrap()
4229
        .contains("resolve"));
4230
    assert_eq!(hint_for("something else entirely"), None);
4231
}
4232
4233
#[test]
4234
fn doctor_names_problems_and_what_to_do() {
4235
    hermetic();
4236
    let dir = tempfile::tempdir().unwrap();
4237
    let root = dir.path();
4238
    let origin = root.join("origin");
4239
    Repo::init_bare_unbound(&origin).unwrap();
4240
    let mut repo = Repo::init(&root.join("r"))
4241
        .unwrap()
4242
        .with_home(root.join("home"));
4243
    let find = |r: &DoctorReport, area: &str, h: Health| {
4244
        r.checks
4245
            .iter()
4246
            .find(|c| c.area == area && c.health == h)
4247
            .cloned()
4248
    };
4249
4250
    let r = repo.doctor(true);
4251
    assert!(find(&r, "identity", Health::Warn)
4252
        .unwrap()
4253
        .hint
4254
        .unwrap()
4255
        .contains("oxy identity create"));
4256
    assert!(find(&r, "repository", Health::Ok).is_some());
4257
4258
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4259
        .unwrap();
4260
    repo.config.set("author.name", "Ada").unwrap();
4261
    repo.config.set("author.email", "[email protected]").unwrap();
4262
    repo.config
4263
        .set("remote.origin.url", &origin.to_string_lossy())
4264
        .unwrap();
4265
    repo.config
4266
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4267
        .unwrap();
4268
    repo.config.set("remote.down.token", "t").unwrap();
4269
    repo.config
4270
        .set("remote.badca.url", "https://example.invalid/a/b")
4271
        .unwrap();
4272
    repo.config
4273
        .set(
4274
            "remote.badca.ca",
4275
            &root.join("missing.pem").to_string_lossy(),
4276
        )
4277
        .unwrap();
4278
    repo.save_config().unwrap();
4279
4280
    let r = repo.doctor(true);
4281
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4282
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4283
    assert!(find(&r, "remote origin", Health::Ok)
4284
        .unwrap()
4285
        .message
4286
        .contains("first push binds it"));
4287
    let down = find(&r, "remote down", Health::Fail).unwrap();
4288
    assert!(
4289
        down.hint.as_deref().unwrap_or("").contains("running"),
4290
        "{down:?}"
4291
    );
4292
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4293
    assert!(
4294
        badca.hint.unwrap().contains("remote.badca.ca"),
4295
        "the remote's own name is in the hint"
4296
    );
4297
    assert_eq!(r.worst(), Health::Fail);
4298
4299
    // Offline, nothing is contacted.
4300
    let r = repo.doctor(false);
4301
    assert!(find(&r, "remote down", Health::Fail).is_none());
4302
    assert!(find(&r, "remote down", Health::Ok)
4303
        .unwrap()
4304
        .message
4305
        .contains("not contacted"));
4306
}
4307
4308
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4309
/// after it. Inserting after `b` and then deleting `b`, one commit after
4310
/// the other, must not leave a delete/insert conflict.
4311
#[test]
4312
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4313
    hermetic();
4314
    let dir = tempfile::tempdir().unwrap();
4315
    let root = dir.path();
4316
    let repo = Repo::init(root).unwrap();
4317
    write(root, "f", b"a\nb\nc\n");
4318
    repo.commit("base", &[]).unwrap();
4319
    write(root, "f", b"a\nb\nx\nc\n");
4320
    let insert = repo.commit("insert x after b", &[]).unwrap();
4321
    write(root, "f", b"a\nx\nc\n");
4322
    let delete = repo.commit("delete b", &[]).unwrap();
4323
    assert!(
4324
        repo.store()
4325
            .get_change(&delete)
4326
            .unwrap()
4327
            .deps
4328
            .contains(&insert),
4329
        "the deletion depends on the insertion below the deleted line"
4330
    );
4331
    let heads = repo.bookmark_heads().unwrap();
4332
    assert_eq!(heads, vec![delete]);
4333
    let snap = repo.load_state(&heads).unwrap().materialize();
4334
    assert!(!snap.is_conflicted());
4335
    assert!(
4336
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4337
    );
4338
}
4339
4340
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4341
/// replacement depends on the change that set the blob it replaces.
4342
#[test]
4343
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4344
    hermetic();
4345
    let dir = tempfile::tempdir().unwrap();
4346
    let root = dir.path();
4347
    let repo = Repo::init(root).unwrap();
4348
    write(root, "bin", b"\0A");
4349
    let v1 = repo.commit("v1", &[]).unwrap();
4350
    write(root, "bin", b"\0B");
4351
    let v2 = repo.commit("v2", &[]).unwrap();
4352
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4353
    write(root, "bin", b"\0A");
4354
    let v3 = repo.commit("back to A", &[]).unwrap();
4355
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4356
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4357
    let state = repo.load_state(&[v3]).unwrap();
4358
    let snap = state.materialize();
4359
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4360
        panic!("opaque")
4361
    };
4362
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4363
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4364
}
4365
4366
/// Spec §23: a binary file changed on two branches and merged in Git to
4367
/// one side's version comes back as that version at the merge, and the
4368
/// import verifies commit by commit.
4369
#[test]
4370
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4371
    hermetic();
4372
    if std::process::Command::new("git")
4373
        .arg("--version")
4374
        .output()
4375
        .is_err()
4376
    {
4377
        eprintln!("git not installed; skipping");
4378
        return;
4379
    }
4380
    let dir = tempfile::tempdir().unwrap();
4381
    let root = dir.path();
4382
    let g = root.join("src.git");
4383
    fs::create_dir_all(&g).unwrap();
4384
    let git = |args: &[&str]| -> String {
4385
        let out = std::process::Command::new("git")
4386
            .arg("-C")
4387
            .arg(&g)
4388
            .args([
4389
                "-c",
4390
                "user.name=Grace",
4391
                "-c",
4392
                "[email protected]",
4393
                "-c",
4394
                "commit.gpgsign=false",
4395
            ])
4396
            .args(args)
4397
            .output()
4398
            .unwrap();
4399
        assert!(
4400
            out.status.success(),
4401
            "git {args:?}: {}",
4402
            String::from_utf8_lossy(&out.stderr)
4403
        );
4404
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4405
    };
4406
    git(&["init", "-q", "-b", "main"]);
4407
    write(&g, "logo.bin", b"\0base");
4408
    write(&g, "notes.txt", b"a\nb\nc\n");
4409
    git(&["add", "."]);
4410
    git(&["commit", "-qm", "base"]);
4411
    git(&["checkout", "-qb", "side"]);
4412
    write(&g, "logo.bin", b"\0side");
4413
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4414
    git(&["commit", "-qam", "side"]);
4415
    git(&["checkout", "-q", "main"]);
4416
    write(&g, "logo.bin", b"\0main");
4417
    git(&["commit", "-qam", "main"]);
4418
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4419
    let _ = std::process::Command::new("git")
4420
        .arg("-C")
4421
        .arg(&g)
4422
        .args([
4423
            "-c",
4424
            "user.name=G",
4425
            "-c",
4426
            "user.email=g@e",
4427
            "merge",
4428
            "-q",
4429
            "side",
4430
        ])
4431
        .output();
4432
    write(&g, "logo.bin", b"\0main");
4433
    git(&["add", "."]);
4434
    git(&["commit", "-qm", "merge side"]);
4435
    // Then a revert of the binary to its first version.
4436
    write(&g, "logo.bin", b"\0base");
4437
    git(&["commit", "-qam", "back to base"]);
4438
4439
    let repo = Repo::init(&root.join("o")).unwrap();
4440
    let rep = repo.import_git(&g, "main").unwrap();
4441
    assert_eq!(rep.merges, 1);
4442
    let v = repo.verify_git_import(&g, "main").unwrap();
4443
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4444
    assert_eq!(v.commits, 5);
4445
    let snap = repo
4446
        .load_state(&repo.bookmark_heads().unwrap())
4447
        .unwrap()
4448
        .materialize();
4449
    assert!(!snap.is_conflicted());
4450
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4451
        panic!("opaque")
4452
    };
4453
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4454
}
4455
4456
/// Spec §7.7 on a file system without executable bits or symlinks: the
4457
/// recorded bit is kept, and a symlink checked out as a plain file holding
4458
/// its target is still that symlink.
4459
#[cfg(unix)]
4460
#[test]
4461
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4462
    use crate::portable::Platform;
4463
    use std::os::unix::fs::PermissionsExt;
4464
    hermetic();
4465
    let dir = tempfile::tempdir().unwrap();
4466
    let root = dir.path();
4467
    let repo = Repo::init(root).unwrap();
4468
    write(root, "run.sh", b"#!/bin/sh\n");
4469
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4470
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4471
    repo.commit("script and link", &[]).unwrap();
4472
    drop(repo);
4473
4474
    // What checking out on Windows leaves: no exec bit, the link as a file.
4475
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4476
    fs::remove_file(root.join("link")).unwrap();
4477
    write(root, "link", b"run.sh");
4478
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4479
    let s = win.snapshot("oxy status").unwrap();
4480
    assert!(
4481
        s.statuses.is_empty(),
4482
        "nothing changed on Windows: {:?}",
4483
        statuses(&s)
4484
    );
4485
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4486
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4487
    write(root, "link", b"other");
4488
    let h = win.commit("edit on Windows", &[]).unwrap();
4489
    let snap = win.load_state(&[h]).unwrap().materialize();
4490
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4491
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4492
    // The same working copy read as Linux sees the lost bit and the plain file.
4493
    let linux = Repo::open(root).unwrap();
4494
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4495
}
4496
4497
/// Paths that collide on case-insensitive or Windows file systems are
4498
/// named at checkout there, and by doctor everywhere.
4499
#[test]
4500
fn paths_other_platforms_cannot_hold_are_reported() {
4501
    use crate::portable::Platform;
4502
    hermetic();
4503
    let dir = tempfile::tempdir().unwrap();
4504
    let root = dir.path();
4505
    let repo = Repo::init(root).unwrap();
4506
    write(root, "README.md", b"a\n");
4507
    write(root, "readme.md", b"b\n");
4508
    write(root, "src/aux.c", b"int x;\n");
4509
    let h = repo.commit("unportable", &[]).unwrap();
4510
    let r = repo.doctor(false);
4511
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4512
    assert_eq!(port.health, Health::Warn);
4513
    assert!(
4514
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4515
        "{}",
4516
        port.message
4517
    );
4518
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4519
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4520
    assert!(
4521
        rep.notes
4522
            .iter()
4523
            .any(|n| n.contains("README.md and readme.md")),
4524
        "{:?}",
4525
        rep.notes
4526
    );
4527
    assert!(
4528
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4529
        "macOS allows aux.c"
4530
    );
4531
}
4532
4533
#[test]
4534
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4535
    hermetic();
4536
    let dir = tempfile::tempdir().unwrap();
4537
    let repo = Repo::init(dir.path()).unwrap();
4538
    write(dir.path(), "a.txt", b"one\n");
4539
    write(dir.path(), "other.txt", b"x\n");
4540
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4541
    repo.snapshot("t").unwrap();
4542
    let c1 = repo.commit("first", &[]).unwrap();
4543
    write(dir.path(), "other.txt", b"y\n");
4544
    repo.snapshot("t").unwrap();
4545
    repo.commit("other only", &[]).unwrap();
4546
    write(dir.path(), "a.txt", b"one\ntwo\n");
4547
    repo.snapshot("t").unwrap();
4548
    let c3 = repo.commit("second line", &[]).unwrap();
4549
    write(dir.path(), "other.txt", b"z\n");
4550
    repo.snapshot("t").unwrap();
4551
    repo.commit("other again", &[]).unwrap();
4552
4553
    let heads = repo.bookmark_heads().unwrap();
4554
    let state = repo.load_state(&heads).unwrap();
4555
    let full: Vec<ChangeHash> = repo
4556
        .log_for_path_in("a.txt", &heads)
4557
        .unwrap()
4558
        .iter()
4559
        .map(|e| e.hash)
4560
        .collect();
4561
    assert_eq!(
4562
        full,
4563
        vec![c3, c1],
4564
        "newest first, only changes touching the path"
4565
    );
4566
    let newest: Vec<ChangeHash> = repo
4567
        .log_for_path_of(&state, "a.txt", Some(1))
4568
        .unwrap()
4569
        .iter()
4570
        .map(|e| e.hash)
4571
        .collect();
4572
    assert_eq!(newest, vec![c3], "stops at the first");
4573
    assert_eq!(
4574
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4575
        2
4576
    );
4577
    assert!(repo
4578
        .log_for_path_of(&state, "missing.txt", Some(1))
4579
        .is_err());
4580
    assert_eq!(
4581
        repo.log_state(&heads).unwrap().len(),
4582
        repo.log_of(&state).len()
4583
    );
4584
4585
    let tree = state.tree().view();
4586
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4587
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4588
    assert_eq!(
4589
        via_state
4590
            .iter()
4591
            .map(|l| (l.hash, l.text.clone()))
4592
            .collect::<Vec<_>>(),
4593
        via_heads
4594
            .iter()
4595
            .map(|l| (l.hash, l.text.clone()))
4596
            .collect::<Vec<_>>()
4597
    );
4598
    assert_eq!(
4599
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4600
        vec![c1, c3]
4601
    );
4602
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4603
}
4604
4605
/// A text file whose stat matches the manifest and whose recorded hash is
4606
/// the base's content is taken from the base without reading it; anything
4607
/// else is read, so no edit is missed (spec §12.3).
4608
#[cfg(unix)]
4609
#[test]
4610
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4611
    use std::os::unix::fs::PermissionsExt;
4612
    hermetic();
4613
    let dir = tempfile::tempdir().unwrap();
4614
    let root = dir.path();
4615
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4616
    write(root, "a.txt", b"one\ntwo\n");
4617
    write(root, "b.txt", b"bee\n");
4618
    repo.commit("base", &[]).unwrap();
4619
    let age = |p: &str| {
4620
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4621
        fs::File::options()
4622
            .write(true)
4623
            .open(root.join(p))
4624
            .unwrap()
4625
            .set_modified(old)
4626
            .unwrap();
4627
    };
4628
    age("a.txt");
4629
    age("b.txt");
4630
    assert!(
4631
        !repo.snapshot("status").unwrap().changed,
4632
        "records the aged stat"
4633
    );
4634
4635
    // Clean and equal to the base: not read at all.
4636
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4637
    let snap = repo.snapshot("status").unwrap();
4638
    assert!(
4639
        !snap.changed && snap.statuses.is_empty(),
4640
        "{:?}",
4641
        snap.statuses
4642
    );
4643
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4644
4645
    // An uncommitted edit that is older than the manifest: stat-clean, but
4646
    // its hash is not the base's, so it is read and stays visible.
4647
    write(root, "b.txt", b"bee edited\n");
4648
    age("b.txt");
4649
    let first = repo.snapshot("status").unwrap();
4650
    assert_eq!(
4651
        statuses(&first),
4652
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4653
    );
4654
    let again = repo.snapshot("status").unwrap();
4655
    assert_eq!(
4656
        statuses(&again),
4657
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4658
        "still seen once stat-clean"
4659
    );
4660
    assert!(!again.changed, "and the working copy hashes the same");
4661
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4662
    assert!(
4663
        repo.snapshot("status").is_err(),
4664
        "an edited file must be read, never taken from the base"
4665
    );
4666
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4667
4668
    // A same-size edit made just now is racy and read.
4669
    write(root, "a.txt", b"one\nTWO\n");
4670
    assert_eq!(
4671
        statuses(&repo.snapshot("status").unwrap()),
4672
        vec![
4673
            ("a.txt".to_string(), ChangeStatus::Modified),
4674
            ("b.txt".to_string(), ChangeStatus::Modified)
4675
        ]
4676
    );
4677
    // Committing makes the edits the base: both are clean and served from it again.
4678
    repo.commit("edits", &[]).unwrap();
4679
    age("a.txt");
4680
    age("b.txt");
4681
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4682
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4683
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4684
    let snap = repo.snapshot("status").unwrap();
4685
    assert!(!snap.changed && snap.statuses.is_empty());
4686
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4687
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4688
}
4689
4690
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4691
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4692
/// file is unchanged, and loading through the checkpoint equals a full load.
4693
#[test]
4694
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4695
    hermetic();
4696
    let dir = tempfile::tempdir().unwrap();
4697
    let root = dir.path();
4698
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4699
    let long: String = (0..300)
4700
        .map(|i| format!("line {i} of a long file\n"))
4701
        .collect();
4702
    write(root, "long.txt", long.as_bytes());
4703
    write(root, "short.txt", b"short\n");
4704
    repo.commit("base", &[]).unwrap();
4705
    let (r1, _, _) = repo.checkpoint().unwrap();
4706
    let cp1 = crate::objects::Checkpoint::decode(
4707
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4708
    )
4709
    .unwrap();
4710
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4711
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4712
4713
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4714
    repo.gc(true).unwrap();
4715
    assert!(repo.store().has(&graphs1[0]));
4716
    let report = repo.fsck().unwrap();
4717
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4718
4719
    // Loading through the checkpoint equals a full load.
4720
    write(root, "short.txt", b"short, edited\n");
4721
    repo.commit("edit the short file", &[]).unwrap();
4722
    let heads = repo.bookmark_heads().unwrap();
4723
    let fast = repo.load_state(&heads).unwrap();
4724
    let full = repo.load_state_full(&heads).unwrap();
4725
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4726
4727
    // The next checkpoint shares the unchanged long file's graph.
4728
    let (r2, _, _) = repo.checkpoint().unwrap();
4729
    let cp2 = crate::objects::Checkpoint::decode(
4730
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
4731
    )
4732
    .unwrap();
4733
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
4734
4735
    // A shallow clone's bundle carries the graph blob with the checkpoint.
4736
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
4737
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
4738
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
4739
4740
    // A version 1 checkpoint written by an older oxy still loads.
4741
    let state = repo.load_state_full(&heads).unwrap();
4742
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
4743
    let cp_old = crate::objects::Checkpoint {
4744
        heads: cp2.heads.clone(),
4745
        count: cp2.count,
4746
        payload: old,
4747
    };
4748
    let r_old = repo
4749
        .store()
4750
        .put(ObjectType::Checkpoint, &cp_old.encode())
4751
        .unwrap();
4752
    repo.install_checkpoint("main", &r_old).unwrap();
4753
    assert_eq!(
4754
        repo.load_state(&heads).unwrap().checkpoint_payload(),
4755
        full.checkpoint_payload()
4756
    );
4757
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4758
4759
    // A lost graph blob fails the load loudly rather than dropping the
4760
    // file, and fsck reports it (a fresh repository, objects still loose).
4761
    let dir2 = tempfile::tempdir().unwrap();
4762
    let root2 = dir2.path();
4763
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
4764
    write(root2, "long.txt", long.as_bytes());
4765
    repo2.commit("base", &[]).unwrap();
4766
    let (r, _, _) = repo2.checkpoint().unwrap();
4767
    let cp = crate::objects::Checkpoint::decode(
4768
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
4769
    )
4770
    .unwrap();
4771
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
4772
    fs::remove_file(repo2.store().path_for(&graph)).unwrap();
4773
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
4774
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
4775
}
4776
4777
/// A new repository has not stored the user's identity yet (that happens
4778
/// at the first signed change); looking it up falls back to the key
4779
/// directory, and a file there that does not hash to the key is refused.
4780
#[test]
4781
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
4782
    hermetic();
4783
    let dir = tempfile::tempdir().unwrap();
4784
    let home = dir.path().join("home");
4785
    let mut first = Repo::init(&dir.path().join("a"))
4786
        .unwrap()
4787
        .with_home(home.clone());
4788
    let (key, _) = first
4789
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4790
        .unwrap();
4791
    let fresh = Repo::init(&dir.path().join("b"))
4792
        .unwrap()
4793
        .with_home(home.clone());
4794
    assert!(!fresh.store().has(&key), "nothing stored yet");
4795
    let id = fresh.identity(&key).unwrap();
4796
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
4797
    // A key file that is not this identity is an error, not a wrong answer.
4798
    let keys = fresh.keys_dir.clone();
4799
    let (other, _) = first
4800
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4801
        .unwrap();
4802
    fs::copy(
4803
        keys.join(format!("{}.identity", other.to_hex())),
4804
        keys.join(format!("{}.identity", key.to_hex())),
4805
    )
4806
    .unwrap();
4807
    assert!(fresh
4808
        .identity(&key)
4809
        .unwrap_err()
4810
        .to_string()
4811
        .contains("does not hold identity"));
4812
}
4813
4814
/// Status snapshots (spec §12.3): a text file whose stat matches the
4815
/// manifest, and whose base graph key is the one the manifest recorded it
4816
/// equal to, is neither read nor rendered; any edit, and any change to the
4817
/// file's graph in the base, brings it back.
4818
#[cfg(unix)]
4819
#[test]
4820
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
4821
    use std::os::unix::fs::PermissionsExt;
4822
    hermetic();
4823
    let dir = tempfile::tempdir().unwrap();
4824
    let root = dir.path();
4825
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4826
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
4827
        write(root, p, c.as_bytes());
4828
    }
4829
    repo.commit("base", &[]).unwrap();
4830
    let age = |p: &str| {
4831
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4832
        fs::File::options()
4833
            .write(true)
4834
            .open(root.join(p))
4835
            .unwrap()
4836
            .set_modified(old)
4837
            .unwrap();
4838
    };
4839
    let lock = |p: &str, mode: u32| {
4840
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
4841
    };
4842
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4843
        age(p);
4844
    }
4845
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4846
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4847
    assert!(
4848
        m.entries.values().all(|e| e.graph.is_some()),
4849
        "keys recorded"
4850
    );
4851
4852
    // Unreadable files prove they are not read; the status snapshot does
4853
    // not render them either, and its base lacks their graphs.
4854
    lock("a.txt", 0o000);
4855
    lock("b.txt", 0o000);
4856
    let snap = repo.snapshot_status("status").unwrap();
4857
    assert!(!snap.changed && snap.statuses.is_empty());
4858
    assert_eq!(
4859
        snap.base_snapshot
4860
            .unrendered
4861
            .iter()
4862
            .cloned()
4863
            .collect::<Vec<_>>(),
4864
        vec!["a.txt", "b.txt", "d/c.txt"]
4865
    );
4866
    assert!(!snap.base.is_full());
4867
    assert!(!snap.base_snapshot.is_conflicted());
4868
    // A full snapshot does not read them either, but renders everything.
4869
    let full = repo.snapshot("status").unwrap();
4870
    assert!(full.statuses.is_empty() && full.base.is_full());
4871
    assert!(full.base_snapshot.unrendered.is_empty());
4872
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
4873
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
4874
4875
    // An edit is seen; the file is rendered, the others still are not.
4876
    write(root, "d/c.txt", b"sea edited\n");
4877
    let snap = repo.snapshot_status("status").unwrap();
4878
    assert_eq!(
4879
        statuses(&snap),
4880
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
4881
    );
4882
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
4883
    // So is a mode change of an unread file.
4884
    lock("b.txt", 0o100);
4885
    assert_eq!(
4886
        statuses(&repo.snapshot_status("status").unwrap()),
4887
        vec![
4888
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
4889
            ("d/c.txt".to_string(), ChangeStatus::Modified)
4890
        ]
4891
    );
4892
    lock("b.txt", 0o000);
4893
4894
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
4895
    // stays unread, c.txt is read once and then skipped too.
4896
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
4897
        .unwrap();
4898
    age("d/c.txt");
4899
    let snap = repo.snapshot_status("status").unwrap();
4900
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
4901
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
4902
    lock("d/c.txt", 0o000);
4903
    let snap = repo.snapshot_status("status").unwrap();
4904
    assert!(snap.statuses.is_empty());
4905
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
4906
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4907
        lock(p, 0o644);
4908
    }
4909
}
4910
4911
/// Attributes decide how a file compares with the base, so a changed
4912
/// `.oxyattributes` makes every text file be compared again.
4913
#[cfg(unix)]
4914
#[test]
4915
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
4916
    hermetic();
4917
    let dir = tempfile::tempdir().unwrap();
4918
    let root = dir.path();
4919
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4920
    write(root, "a.txt", b"crlf\r\n");
4921
    repo.commit("base", &[]).unwrap();
4922
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4923
    fs::File::options()
4924
        .write(true)
4925
        .open(root.join("a.txt"))
4926
        .unwrap()
4927
        .set_modified(old)
4928
        .unwrap();
4929
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
4930
    assert!(repo
4931
        .snapshot_status("status")
4932
        .unwrap()
4933
        .base_snapshot
4934
        .unrendered
4935
        .contains("a.txt"));
4936
    // With eol=lf, a.txt as stored no longer equals the base.
4937
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
4938
    let snap = repo.snapshot_status("status").unwrap();
4939
    assert_eq!(
4940
        statuses(&snap),
4941
        vec![
4942
            (".oxyattributes".to_string(), ChangeStatus::Added),
4943
            ("a.txt".to_string(), ChangeStatus::Modified)
4944
        ]
4945
    );
4946
}
4947
4948
/// Bookmarks with `/` in their names: pushing records their
4949
/// attestations, and checkpoints are kept for them, beside `feature`
4950
/// itself.
4951
#[test]
4952
fn bookmarks_with_slashes_push_and_checkpoint() {
4953
    hermetic();
4954
    let dir = tempfile::tempdir().unwrap();
4955
    let root = dir.path();
4956
    let origin = Repo::init(&root.join("origin")).unwrap();
4957
    let url = root.join("origin").to_string_lossy().to_string();
4958
    let mut repo = Repo::clone(&url, &root.join("r"))
4959
        .unwrap()
4960
        .with_home(root.join("home"));
4961
    // With an identity, pushes carry reference attestations: the case
4962
    // that failed, since the attestation is a file named after the bookmark.
4963
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4964
        .unwrap();
4965
    let r = root.join("r");
4966
    write(&r, "a.txt", b"a\n");
4967
    let h_a = repo.commit("a", &[]).unwrap();
4968
    assert!(repo.push("origin", false).unwrap()[0].ok);
4969
    repo.bookmark_create("feature", None).unwrap();
4970
    repo.bookmark_create("feature/x", None).unwrap();
4971
    repo.bookmark_switch("feature/x", false).unwrap();
4972
    write(&r, "b.txt", b"b\n");
4973
    let h_b = repo.commit("b", &[]).unwrap();
4974
    for name in ["feature", "feature/x"] {
4975
        let res = repo.push_bookmark("origin", name, false).unwrap();
4976
        assert!(res[0].ok, "{name}: {res:?}");
4977
    }
4978
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
4979
    assert_eq!(
4980
        origin.resolve_heads("feature/x").unwrap(),
4981
        repo.resolve_heads("feature/x").unwrap()
4982
    );
4983
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
4984
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
4985
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
4986
4987
    // A checkpoint of feature/x is found again when loading its state.
4988
    let (cp, _, _) = repo.checkpoint().unwrap();
4989
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
4990
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
4991
    let heads = repo.resolve_heads("feature/x").unwrap();
4992
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
4993
}
4994
4995
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
4996
/// never the remote's own bookmark, and a bookmark created again later is
4997
/// accepted although the deletion's attestation stays the latest.
4998
#[test]
4999
fn bookmarks_are_deleted_on_a_remote() {
5000
    hermetic();
5001
    let dir = tempfile::tempdir().unwrap();
5002
    let root = dir.path();
5003
    let origin = Repo::init(&root.join("origin")).unwrap();
5004
    let url = root.join("origin").to_string_lossy().to_string();
5005
    let mut repo = Repo::clone(&url, &root.join("r"))
5006
        .unwrap()
5007
        .with_home(root.join("home"));
5008
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5009
        .unwrap();
5010
    let r = root.join("r");
5011
    write(&r, "a.txt", b"a\n");
5012
    repo.commit("a", &[]).unwrap();
5013
    assert!(repo.push("origin", false).unwrap()[0].ok);
5014
    repo.bookmark_create("feature/x", None).unwrap();
5015
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5016
    assert!(origin.resolve_heads("feature/x").is_ok());
5017
5018
    let res = repo.push_delete("origin", "feature/x").unwrap();
5019
    assert!(res[0].ok, "{res:?}");
5020
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5021
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5022
    assert!(
5023
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5024
        "the deletion is attested"
5025
    );
5026
    assert!(
5027
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5028
        "the local bookmark stays"
5029
    );
5030
    assert!(!repo
5031
        .view()
5032
        .unwrap()
5033
        .remotes
5034
        .get("origin")
5035
        .is_some_and(|m| m.contains_key("feature/x")));
5036
5037
    // Pushing it again creates it again, past the deletion's serial.
5038
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5039
    assert!(res[0].ok, "{res:?}");
5040
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5041
5042
    // Nothing to delete, and never the remote's own bookmark.
5043
    assert!(repo.push_delete("origin", "nope").is_err());
5044
    let res = repo.push_delete("origin", "main").unwrap();
5045
    assert!(
5046
        !res[0].ok && res[0].reason.contains("default bookmark"),
5047
        "{res:?}"
5048
    );
5049
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5050
}