OXYGENHUB
# 9b761fe2f751 oxygen / crates / oxy-core / src / repo / tests.rs
141.8 KiB · Rust · last changed Unbound hosted repositories adopt the first pusher's id 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
    let other = SecretKey::generate();
382
    let other_id = other.identity("Mallory", "[email protected]", 0);
383
    let other_key = repo.store().put_identity(&other_id).unwrap();
384
    let forged = other.sign(Domain::Change, &other_key, &h0);
385
    repo.store().put_signature(&h0, &forged).unwrap();
386
    assert!(
387
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
388
    );
389
390
    // Tampering with the stored signature invalidates it.
391
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
392
    sig.ed[0] ^= 1;
393
    repo.store().put_signature(&h2, &sig).unwrap();
394
    assert!(matches!(
395
        repo.verify_change(&h2).unwrap(),
396
        SignatureStatus::Invalid(_)
397
    ));
398
399
    // Without the secret key, signing at commit fails cleanly.
400
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
401
    write(root, "a.txt", b"z\n");
402
    assert!(no_keys.commit("cannot sign", &[]).is_err());
403
}
404
405
#[test]
406
fn checkout_moves_the_working_copy() {
407
    hermetic();
408
    let dir = tempfile::tempdir().unwrap();
409
    let root = dir.path();
410
    let repo = Repo::init(root).unwrap();
411
    write(root, "a.txt", b"one\n");
412
    write(root, "sub/deep/b.txt", b"b\n");
413
    let h1 = repo.commit("first", &[]).unwrap();
414
    write(root, "a.txt", b"two\n");
415
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
416
    write(root, "bin.dat", &[0, 1, 2, 3]);
417
    let h2 = repo.commit("second", &[]).unwrap();
418
419
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
420
    assert_eq!(
421
        r,
422
        CheckoutReport {
423
            written: 2,
424
            removed: 1,
425
            conflicted: false,
426
            notes: vec![]
427
        }
428
    );
429
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
430
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
431
    assert!(!root.join("bin.dat").exists());
432
    let (_, wc) = repo.working_copy().unwrap();
433
    assert_eq!(wc.deps, vec![h1]);
434
    assert!(
435
        !repo.snapshot("status").unwrap().changed,
436
        "checkout leaves a clean working copy"
437
    );
438
    // The bookmark still points at h2.
439
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
440
441
    // Dirty working copy refuses without --discard.
442
    write(root, "a.txt", b"dirty\n");
443
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
444
    let r = repo
445
        .checkout(&[h2], true, "oxy checkout --discard")
446
        .unwrap();
447
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
448
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
449
    assert!(!root.join("sub").exists(), "empty directories are pruned");
450
    assert_eq!(r.removed, 1);
451
    assert!(!repo.snapshot("status").unwrap().changed);
452
453
    // Refuses to write through a symlinked directory.
454
    #[cfg(unix)]
455
    {
456
        fs::remove_dir_all(root.join("sub")).ok();
457
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
458
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
459
    }
460
}
461
462
#[test]
463
fn large_files_are_chunked_and_read_back() {
464
    hermetic();
465
    let dir = tempfile::tempdir().unwrap();
466
    let repo = Repo::init(dir.path()).unwrap();
467
    let mut big = vec![0u8; 700 * 1024];
468
    for (i, b) in big.iter_mut().enumerate() {
469
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
470
    }
471
    let r = repo.store_blob(&big).unwrap();
472
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
473
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
474
    assert_eq!(repo.read_blob(&r).unwrap(), big);
475
    assert_eq!(Repo::blob_ref(&big), r);
476
}
477
478
#[test]
479
fn clone_push_pull_with_seals_and_attestations() {
480
    hermetic();
481
    let dir = tempfile::tempdir().unwrap();
482
    let root = dir.path();
483
    let origin_path = root.join("origin");
484
    let origin = Repo::init(&origin_path).unwrap();
485
    let origin_url = origin_path.to_string_lossy().to_string();
486
487
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
488
    let mut a = Repo::clone(&origin_url, &root.join("a"))
489
        .unwrap()
490
        .with_home(root.join("home-a"));
491
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
492
    let (key_a, _) = a
493
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
494
        .unwrap();
495
    write(&root.join("a"), "f.txt", b"a\n");
496
    let h1 = a.commit("first", &[]).unwrap();
497
    let results = a.push("origin", false).unwrap();
498
    assert!(results[0].ok, "{}", results[0].reason);
499
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
500
    // The change was sealed at push and the reference attested.
501
    assert!(
502
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
503
    );
504
    assert_eq!(
505
        origin.verify_change(&h1).unwrap(),
506
        SignatureStatus::Unsigned
507
    );
508
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
509
    assert!(matches!(att.attest.body, AttestBody::Ref { serial: 1, .. }));
510
    let again = a.push("origin", false).unwrap();
511
    assert!(again[0].ok && again[0].reason.contains("up to date"));
512
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
513
    assert!(
514
        matches!(att.attest.body, AttestBody::Ref { serial: 1, .. }),
515
        "a no-op push does not attest again"
516
    );
517
518
    // B clones and sees the file and the seal.
519
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
520
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
521
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
522
    assert!(matches!(
523
        b.authenticate_change(&h1).unwrap(),
524
        SignatureStatus::Valid { sealed: true, .. }
525
    ));
526
527
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
528
    write(&root.join("b"), "f.txt", b"a\nb\n");
529
    let h2 = b.commit("second", &[]).unwrap();
530
    assert!(b.push("origin", false).unwrap()[0].ok);
531
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
532
533
    // A commits an independent change; push is refused until A pulls.
534
    write(&root.join("a"), "g.txt", b"g\n");
535
    let h3 = a.commit("third", &[]).unwrap();
536
    assert!(a.push("origin", false).is_err());
537
    let pr = a.pull("origin").unwrap();
538
    assert!(pr.changed && pr.checked_out);
539
    let mut want = vec![h2, h3];
540
    want.sort();
541
    assert_eq!(pr.heads, want);
542
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
543
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
544
    let results = a.push("origin", false).unwrap();
545
    assert!(results[0].ok, "{}", results[0].reason);
546
    let mut origin_heads = origin.bookmark_heads().unwrap();
547
    origin_heads.sort();
548
    assert_eq!(origin_heads, want);
549
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
550
    assert!(matches!(att.attest.body, AttestBody::Ref { serial: 2, .. }));
551
552
    // B pulls and ends up identical.
553
    let pr = b.pull("origin").unwrap();
554
    assert_eq!(pr.heads, want);
555
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
556
    assert!(!b.snapshot("status").unwrap().changed);
557
558
    // Concurrent edits of the same line: the union is a reified conflict.
559
    write(&root.join("a"), "f.txt", b"a\nA\n");
560
    a.commit("a-edit", &[]).unwrap();
561
    a.push("origin", false).unwrap();
562
    write(&root.join("b"), "f.txt", b"a\nB\n");
563
    b.commit("b-edit", &[]).unwrap();
564
    let pr = b.pull("origin").unwrap();
565
    assert!(pr.changed && pr.checked_out);
566
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
567
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
568
    write(&root.join("b"), "f.txt", b"a\nAB\n");
569
    let hr = b.commit("resolve", &[]).unwrap();
570
    assert_eq!(
571
        b.store().get_change(&hr).unwrap().kind,
572
        ChangeKind::Resolution
573
    );
574
    assert!(b.push("origin", false).unwrap()[0].ok);
575
    a.pull("origin").unwrap();
576
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
577
    // The resolution depends on the conflicting edits, but nothing depends
578
    // on "third" (it only added g.txt), so it stays a head beside it.
579
    let mut want = vec![hr, h3];
580
    want.sort();
581
    assert_eq!(a.bookmark_heads().unwrap(), want);
582
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
583
}
584
585
#[test]
586
fn receive_push_rejects_bad_updates() {
587
    hermetic();
588
    let dir = tempfile::tempdir().unwrap();
589
    let root = dir.path();
590
    let origin = Repo::init(&root.join("origin")).unwrap();
591
    let url = root.join("origin").to_string_lossy().to_string();
592
    let mut a = Repo::clone(&url, &root.join("a"))
593
        .unwrap()
594
        .with_home(root.join("home"));
595
    let (key, _) = a
596
        .create_identity("Ada", "a@b", IdentityScope::Repo)
597
        .unwrap();
598
    write(&root.join("a"), "f.txt", b"x\n");
599
    let h1 = a.commit("one", &[]).unwrap();
600
    assert!(a.push("origin", false).unwrap()[0].ok);
601
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
602
    let s1 = origin
603
        .store()
604
        .put_state(&StateObject::new(vec![h1]))
605
        .unwrap();
606
607
    // Missing head.
608
    let ghost = origin
609
        .store()
610
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
611
        .unwrap();
612
    let r = origin
613
        .receive_push(
614
            Bundle::default(),
615
            vec![RefUpdate {
616
                name: "main".into(),
617
                old_state: s1,
618
                new_state: ghost,
619
                force: false,
620
                attestation: None,
621
            }],
622
            None,
623
            vec![],
624
        )
625
        .unwrap();
626
    assert!(
627
        !r[0].ok && r[0].reason.contains("missing"),
628
        "{}",
629
        r[0].reason
630
    );
631
632
    // Stale old_state.
633
    let r = origin
634
        .receive_push(
635
            Bundle::default(),
636
            vec![RefUpdate {
637
                name: "main".into(),
638
                old_state: empty,
639
                new_state: s1,
640
                force: false,
641
                attestation: None,
642
            }],
643
            None,
644
            vec![],
645
        )
646
        .unwrap();
647
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
648
649
    // Non-fast-forward without force is refused; with force it passes.
650
    let r = origin
651
        .receive_push(
652
            Bundle::default(),
653
            vec![RefUpdate {
654
                name: "main".into(),
655
                old_state: s1,
656
                new_state: empty,
657
                force: false,
658
                attestation: None,
659
            }],
660
            None,
661
            vec![],
662
        )
663
        .unwrap();
664
    assert!(
665
        !r[0].ok && r[0].reason.contains("fast-forward"),
666
        "{}",
667
        r[0].reason
668
    );
669
    let r = origin
670
        .receive_push(
671
            Bundle::default(),
672
            vec![RefUpdate {
673
                name: "main".into(),
674
                old_state: s1,
675
                new_state: empty,
676
                force: true,
677
                attestation: None,
678
            }],
679
            None,
680
            vec![],
681
        )
682
        .unwrap();
683
    assert!(r[0].ok);
684
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
685
686
    // Attestation with a stale serial is a rollback and is refused.
687
    let sa = a
688
        .sign_attest(&Attest {
689
            repo: a.id().unwrap(),
690
            hlc: Hlc::now(),
691
            body: AttestBody::Ref {
692
                name: "main".into(),
693
                old_state: empty,
694
                new_state: s1,
695
                serial: 1,
696
            },
697
        })
698
        .unwrap();
699
    let r = origin
700
        .receive_push(
701
            Bundle::default(),
702
            vec![RefUpdate {
703
                name: "main".into(),
704
                old_state: empty,
705
                new_state: s1,
706
                force: false,
707
                attestation: Some(sa.clone()),
708
            }],
709
            None,
710
            vec![],
711
        )
712
        .unwrap();
713
    assert!(
714
        !r[0].ok && r[0].reason.contains("serial"),
715
        "{}",
716
        r[0].reason
717
    );
718
    // An attestation for a different update is refused too.
719
    let sa2 = a
720
        .sign_attest(&Attest {
721
            repo: a.id().unwrap(),
722
            hlc: Hlc::now(),
723
            body: AttestBody::Ref {
724
                name: "main".into(),
725
                old_state: s1,
726
                new_state: empty,
727
                serial: 5,
728
            },
729
        })
730
        .unwrap();
731
    let r = origin
732
        .receive_push(
733
            Bundle::default(),
734
            vec![RefUpdate {
735
                name: "main".into(),
736
                old_state: empty,
737
                new_state: s1,
738
                force: false,
739
                attestation: Some(sa2),
740
            }],
741
            None,
742
            vec![],
743
        )
744
        .unwrap();
745
    assert!(
746
        !r[0].ok && r[0].reason.contains("describe"),
747
        "{}",
748
        r[0].reason
749
    );
750
    let _ = key;
751
}
752
753
#[test]
754
fn user_config_supplies_defaults_and_clones_sign() {
755
    hermetic();
756
    let dir = tempfile::tempdir().unwrap();
757
    let root = dir.path();
758
    let home = root.join("home");
759
    let origin = Repo::init(&root.join("origin")).unwrap();
760
    let url = root.join("origin").to_string_lossy().to_string();
761
762
    // Identity at user scope: the repository file stays free of author keys.
763
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
764
    let (key, _) = a
765
        .create_identity("Ada", "[email protected]", IdentityScope::User)
766
        .unwrap();
767
    assert!(!a.config.repo_layer().contains_key("author.key"));
768
    assert_eq!(a.config.author_key, Some(key));
769
    assert!(home.join("config.toml").exists());
770
    a.set_user_config("core.sign", "change").unwrap();
771
    assert!(a.config.sign_changes);
772
773
    // Repository settings override user settings and are the only ones saved.
774
    a.config.set("core.sign", "seal").unwrap();
775
    a.save_config().unwrap();
776
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
777
    assert!(!again.config.sign_changes);
778
    assert_eq!(again.config.author_key, Some(key));
779
    assert_eq!(
780
        read_config_file(&root.join("a/.oxy/config"))
781
            .unwrap()
782
            .get("core.sign")
783
            .map(String::as_str),
784
        Some("seal")
785
    );
786
787
    // A fresh clone made by this user signs with the user-level identity,
788
    // even though the clone's store has never seen the identity object.
789
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
790
    assert!(b.config.sign_changes);
791
    write(&root.join("b"), "f.txt", b"f\n");
792
    let h = b.commit("signed from a clone", &[]).unwrap();
793
    assert!(
794
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
795
    );
796
    assert!(b.push("origin", false).unwrap()[0].ok);
797
    assert!(matches!(
798
        origin.verify_change(&h).unwrap(),
799
        SignatureStatus::Valid { .. }
800
    ));
801
}
802
803
#[test]
804
fn format1_repositories_are_migrated_on_open() {
805
    hermetic();
806
    use crate::oplog::{Format1Op, Format1View};
807
    let dir = tempfile::tempdir().unwrap();
808
    let root = dir.path();
809
    let repo = Repo::init(root).unwrap();
810
    write(root, "a.txt", b"a\n");
811
    let h1 = repo.commit("one", &[]).unwrap();
812
    let (wc_hash, _) = repo.working_copy().unwrap();
813
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
814
    let mut v1 = Format1View::default();
815
    v1.bookmarks.insert("main".into(), vec![]);
816
    v1.workspaces.insert(repo.workspace(), wc_hash);
817
    let init = Format1Op {
818
        parents: vec![],
819
        hlc: Hlc::default(),
820
        command: "oxy init".into(),
821
        view: v1.clone(),
822
    };
823
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
824
    v1.bookmarks.insert("main".into(), vec![h1]);
825
    let commit = Format1Op {
826
        parents: vec![init_ref],
827
        hlc: Hlc::default(),
828
        command: "oxy commit".into(),
829
        view: v1,
830
    };
831
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
832
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
833
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
834
    drop(repo);
835
836
    let repo = Repo::open(root).unwrap();
837
    assert_eq!(
838
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
839
        FORMAT_LINE
840
    );
841
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
842
    let ops = repo.op_log().unwrap();
843
    assert_eq!(
844
        ops.iter()
845
            .map(|(_, o)| o.command.as_str())
846
            .collect::<Vec<_>>(),
847
        ["oxy commit", "oxy init"]
848
    );
849
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
850
    assert!(!repo.snapshot("status").unwrap().changed);
851
    // Reopening again is a no-op.
852
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
853
}
854
855
#[test]
856
fn undo_skips_snapshot_operations() {
857
    hermetic();
858
    let dir = tempfile::tempdir().unwrap();
859
    let root = dir.path();
860
    let repo = Repo::init(root).unwrap();
861
    write(root, "a.txt", b"a\n");
862
    let h1 = repo.commit("a", &[]).unwrap();
863
    // A later command snapshots new edits on top of the commit.
864
    write(root, "b.txt", b"b\n");
865
    let s = repo.snapshot("oxy status").unwrap();
866
    assert!(s.changed);
867
    assert!(repo.head_op().unwrap().1.is_snapshot());
868
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
869
    // Undo must undo the commit, not the snapshot.
870
    repo.undo().unwrap();
871
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
872
    let s = repo.snapshot("oxy status").unwrap();
873
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
874
    assert_eq!(
875
        paths,
876
        ["a.txt", "b.txt"],
877
        "both files are back in the working copy"
878
    );
879
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
880
    // Only snapshots remain above `init`, so there is nothing left to undo.
881
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
882
    assert!(repo.undo().is_err());
883
}
884
885
#[test]
886
fn independent_changes_commute_and_make_multiple_heads() {
887
    hermetic();
888
    let dir = tempfile::tempdir().unwrap();
889
    let root = dir.path();
890
    let repo = Repo::init(root).unwrap();
891
    write(root, "a.txt", b"a\n");
892
    let h1 = repo.commit("a", &[]).unwrap();
893
    write(root, "b.txt", b"b\n");
894
    let h2 = repo.commit("b", &[]).unwrap();
895
    let c2 = repo.store().get_change(&h2).unwrap();
896
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
897
    let mut heads = repo.bookmark_heads().unwrap();
898
    heads.sort();
899
    let mut want = vec![h1, h2];
900
    want.sort();
901
    assert_eq!(heads, want);
902
    // Editing a.txt depends on h1 only.
903
    write(root, "a.txt", b"a\na2\n");
904
    let h3 = repo.commit("a2", &[]).unwrap();
905
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
906
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
907
    assert_eq!(heads, [h2, h3].into_iter().collect());
908
    // Explicit dependency.
909
    write(root, "c.txt", b"c\n");
910
    let h4 = repo.commit("c", &[h2]).unwrap();
911
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
912
}
913
914
#[test]
915
fn mode_change_and_text_binary_switch() {
916
    hermetic();
917
    let dir = tempfile::tempdir().unwrap();
918
    let root = dir.path();
919
    let repo = Repo::init(root).unwrap();
920
    write(root, "run.sh", b"#!/bin/sh\n");
921
    repo.commit("add script", &[]).unwrap();
922
    #[cfg(unix)]
923
    {
924
        use std::os::unix::fs::PermissionsExt;
925
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
926
        let s = repo.snapshot("status").unwrap();
927
        assert_eq!(
928
            statuses(&s),
929
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
930
        );
931
        let h = repo.commit("exec", &[]).unwrap();
932
        let snap = repo.load_state(&[h]).unwrap().materialize();
933
        assert!(snap.files["run.sh"].mode.exec);
934
    }
935
    // Text → binary → text.
936
    write(root, "run.sh", b"\0binary");
937
    let h = repo.commit("binary", &[]).unwrap();
938
    let snap = repo.load_state(&[h]).unwrap().materialize();
939
    assert!(snap.files["run.sh"].mode.opaque);
940
    write(root, "run.sh", b"text again\n");
941
    let h = repo.commit("text", &[]).unwrap();
942
    let snap = repo.load_state(&[h]).unwrap().materialize();
943
    assert!(!snap.files["run.sh"].mode.opaque);
944
    assert!(
945
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
946
    );
947
    assert!(!snap.is_conflicted());
948
}
949
950
#[test]
951
fn trust_policy_governs_pushes_and_fetches() {
952
    hermetic();
953
    let dir = tempfile::tempdir().unwrap();
954
    let root = dir.path();
955
    let origin = Repo::init(&root.join("origin")).unwrap();
956
    let url = root.join("origin").to_string_lossy().to_string();
957
958
    // A is the root. Before the policy, an unsigned push from B is fine.
959
    let mut a = Repo::clone(&url, &root.join("a"))
960
        .unwrap()
961
        .with_home(root.join("home-a"));
962
    let (key_a, _) = a
963
        .create_identity("Ada", "[email protected]", IdentityScope::User)
964
        .unwrap();
965
    let mut b = Repo::clone(&url, &root.join("b"))
966
        .unwrap()
967
        .with_home(root.join("home-b"));
968
    write(&root.join("b"), "b.txt", b"b\n");
969
    b.commit("unsigned before policy", &[]).unwrap();
970
    assert!(b.push("origin", false).unwrap()[0].ok);
971
972
    // A creates the policy and pushes it; origin now enforces it.
973
    write(&root.join("a"), "a.txt", b"a\n");
974
    a.commit("a", &[]).unwrap();
975
    let sp = a.policy_init().unwrap();
976
    assert_eq!(sp.policy.serial, 1);
977
    a.pull("origin").unwrap();
978
    let results = a.push("origin", false).unwrap();
979
    assert!(results.iter().all(|r| r.ok), "{results:?}");
980
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
981
982
    // B pulls the policy. Without an identity B cannot push at all.
983
    b.pull("origin").unwrap();
984
    assert!(
985
        b.current_policy().unwrap().is_some(),
986
        "the policy arrived with the fetch"
987
    );
988
    assert!(b.push("origin", false).is_err());
989
    // With an identity the policy does not list, the push is rejected by origin.
990
    let (key_b, id_b) = b
991
        .create_identity("Bob", "[email protected]", IdentityScope::User)
992
        .unwrap();
993
    write(&root.join("b"), "b.txt", b"b2\n");
994
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
995
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
996
    let r = b.push("origin", false).unwrap();
997
    assert!(
998
        !r[0].ok && r[0].reason.contains("may not update"),
999
        "{:?}",
1000
        r
1001
    );
1002
1003
    // A grants B (identity handed over as a file) and publishes the policy.
1004
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1005
    assert_eq!(sp.policy.serial, 2);
1006
    let r = a.push("origin", false).unwrap();
1007
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1008
    // B must fetch the new policy before pushing.
1009
    assert!(b
1010
        .push("origin", false)
1011
        .unwrap_or_else(|e| vec![RefResult {
1012
            name: "main".into(),
1013
            ok: false,
1014
            reason: e.to_string()
1015
        }])
1016
        .iter()
1017
        .all(|x| !x.ok));
1018
    b.pull("origin").unwrap();
1019
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1020
    let r = b.push("origin", false).unwrap();
1021
    assert!(r[0].ok, "{:?}", r);
1022
    // Origin verified B's change under the policy.
1023
    let heads = origin.bookmark_heads().unwrap();
1024
    for h in &heads {
1025
        let c = origin.store().get_change(h).unwrap();
1026
        if c.author == key_b {
1027
            origin
1028
                .change_allowed(
1029
                    h,
1030
                    &origin.current_policy().unwrap().unwrap().1.policy,
1031
                    "main",
1032
                )
1033
                .unwrap();
1034
        }
1035
    }
1036
1037
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1038
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1039
    forged.serial = 3;
1040
    forged.roots = vec![key_b];
1041
    let fh = forged.hash();
1042
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1043
    let forged = SignedPolicy {
1044
        policy: forged,
1045
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1046
    };
1047
    let r = origin
1048
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1049
        .unwrap();
1050
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1051
    let stale = a.current_policy().unwrap().unwrap().1;
1052
    let mut old = stale.clone();
1053
    old.policy.serial = 1;
1054
    let r = origin
1055
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1056
        .unwrap();
1057
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1058
1059
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1060
    a.pull("origin").unwrap();
1061
    a.policy_revoke(&key_b).unwrap();
1062
    let r = a.push("origin", false).unwrap();
1063
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1064
    b.pull("origin").unwrap();
1065
    write(&root.join("b"), "b.txt", b"b3\n");
1066
    b.commit("b3", &[]).unwrap();
1067
    let r = b.push("origin", false).unwrap();
1068
    assert!(!r[0].ok, "{:?}", r);
1069
1070
    // A clone by a third party receives and verifies everything.
1071
    let c = Repo::clone(&url, &root.join("c"))
1072
        .unwrap()
1073
        .with_home(root.join("home-c"));
1074
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1075
    assert!(c
1076
        .current_policy()
1077
        .unwrap()
1078
        .unwrap()
1079
        .1
1080
        .policy
1081
        .roots
1082
        .contains(&key_a));
1083
    assert!(!c.snapshot("status").unwrap().changed);
1084
}
1085
1086
#[test]
1087
fn gc_packs_objects_and_history_still_works() {
1088
    hermetic();
1089
    let dir = tempfile::tempdir().unwrap();
1090
    let root = dir.path();
1091
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1092
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1093
        .unwrap();
1094
    repo.set_user_config("core.sign", "change").unwrap();
1095
    write(root, "a.txt", b"one\n");
1096
    let h1 = repo.commit("one", &[]).unwrap();
1097
    write(root, "a.txt", b"two\n");
1098
    write(root, "big.bin", &vec![0u8; 100_000]);
1099
    let h2 = repo.commit("two", &[]).unwrap();
1100
    // Several snapshots leave superseded working-copy versions behind.
1101
    for i in 0..5 {
1102
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1103
        repo.snapshot("status").unwrap();
1104
    }
1105
    write(root, "a.txt", b"two\n");
1106
    repo.snapshot("status").unwrap();
1107
    let before = repo.store().list().unwrap();
1108
    assert!(repo.store().loose_count().unwrap() > 0);
1109
1110
    // With the default retention every operation's view is a root: nothing prunes.
1111
    let r = repo.gc(true).unwrap();
1112
    assert_eq!(r.packed.objects, before.len());
1113
    assert_eq!(r.pruned.objects, 0);
1114
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1115
    assert_eq!(repo.store().list().unwrap(), before);
1116
1117
    // With zero retention only the current view is a root: superseded
1118
    // working copies go, everything reachable stays.
1119
    repo.config.set("core.op-retention", "0").unwrap();
1120
    repo.save_config().unwrap();
1121
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1122
    let r = repo.gc(true).unwrap();
1123
    assert!(r.pruned.objects >= 5, "{r:?}");
1124
    let after = repo.store().list().unwrap();
1125
    assert!(after.len() < before.len());
1126
    assert!(after.contains(&h1) && after.contains(&h2));
1127
    for (_, op) in repo.op_log().unwrap() {
1128
        assert!(!op.command.is_empty(), "operation objects are all kept");
1129
    }
1130
    // Everything still works from the pruned, packed store.
1131
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1132
    assert!(matches!(
1133
        repo.verify_change(&h2).unwrap(),
1134
        SignatureStatus::Valid { .. }
1135
    ));
1136
    assert_eq!(repo.log().unwrap().len(), 3);
1137
    repo.checkout(&[h1], false, "checkout").unwrap();
1138
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1139
    repo.checkout(&[h2], false, "checkout").unwrap();
1140
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1141
    assert!(!repo.snapshot("status").unwrap().changed);
1142
    // Grace period defers pruning of young garbage.
1143
    write(root, "a.txt", b"three\n");
1144
    repo.commit("three", &[]).unwrap();
1145
    let r = repo.gc(false).unwrap();
1146
    assert_eq!(r.pruned.objects, 0);
1147
    assert!(r.pruned.deferred > 0);
1148
    let r = repo.gc(true).unwrap();
1149
    assert!(r.pruned.objects > 0);
1150
    assert_eq!(repo.log().unwrap().len(), 4);
1151
}
1152
1153
#[test]
1154
fn describe_amend_abandon_heads() {
1155
    hermetic();
1156
    let dir = tempfile::tempdir().unwrap();
1157
    let root = dir.path();
1158
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1159
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1160
        .unwrap();
1161
    repo.set_user_config("core.sign", "change").unwrap();
1162
    write(root, "a.txt", b"one\n");
1163
    let h1 = repo.commit("first", &[]).unwrap();
1164
    write(root, "a.txt", b"one\ntwo\n");
1165
    let h2 = repo.commit("secnod", &[]).unwrap();
1166
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1167
1168
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1169
    let h2b = repo.describe(&h2, "second").unwrap();
1170
    assert_ne!(h2b, h2);
1171
    let c = repo.store().get_change(&h2b).unwrap();
1172
    assert_eq!(
1173
        (c.change_id, c.message.as_str(), c.deps.clone()),
1174
        (id2, "second", vec![h1])
1175
    );
1176
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1177
    assert!(matches!(
1178
        repo.verify_change(&h2b).unwrap(),
1179
        SignatureStatus::Valid { .. }
1180
    ));
1181
    let s = repo.snapshot("status").unwrap();
1182
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1183
    assert_eq!(
1184
        repo.resolve_change(&id2.short(8)).unwrap(),
1185
        h2b,
1186
        "the old object is no longer reachable from the log"
1187
    );
1188
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1189
    let h1b = repo.describe(&h1, "first, described").unwrap();
1190
    assert_ne!(h1b, h1);
1191
    let heads = repo.bookmark_heads().unwrap();
1192
    assert_eq!(heads.len(), 1);
1193
    let top = repo.store().get_change(&heads[0]).unwrap();
1194
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1195
    assert!(
1196
        matches!(
1197
            repo.verify_change(&heads[0]).unwrap(),
1198
            SignatureStatus::Valid { .. }
1199
        ),
1200
        "rewritten own change is re-signed"
1201
    );
1202
    let (_, wc) = repo.working_copy().unwrap();
1203
    assert_eq!(
1204
        wc.deps,
1205
        vec![heads[0]],
1206
        "the working copy follows the rewrite"
1207
    );
1208
    assert!(!repo.snapshot("status").unwrap().changed);
1209
    let snap = repo.load_state(&heads).unwrap().materialize();
1210
    assert!(
1211
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1212
    );
1213
1214
    // amend: fold an edit into the head; the result is one change from h1.
1215
    write(root, "a.txt", b"one\ntwo\nthree\n");
1216
    write(root, "b.txt", b"b\n");
1217
    let h2c = repo.amend(None).unwrap();
1218
    let c = repo.store().get_change(&h2c).unwrap();
1219
    assert_eq!(c.change_id, id2);
1220
    assert_eq!(c.message, "second");
1221
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1222
    assert_eq!(
1223
        repo.log().unwrap().len(),
1224
        3,
1225
        "working copy, amended head, first"
1226
    );
1227
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1228
    assert!(
1229
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1230
    );
1231
    assert!(snap.files.contains_key("b.txt"));
1232
    assert!(!repo.snapshot("status").unwrap().changed);
1233
    assert!(
1234
        repo.amend(None).is_err(),
1235
        "clean working copy and no message"
1236
    );
1237
    let h2d = repo.amend(Some("second, amended")).unwrap();
1238
    assert_eq!(
1239
        repo.store().get_change(&h2d).unwrap().message,
1240
        "second, amended"
1241
    );
1242
1243
    // abandon: the head goes, its content stays as uncommitted work.
1244
    repo.abandon(&h2d).unwrap();
1245
    assert_eq!(
1246
        repo.bookmark_heads().unwrap(),
1247
        vec![h1b],
1248
        "the described first change is the head again"
1249
    );
1250
    let s = repo.snapshot("status").unwrap();
1251
    let paths: Vec<_> = s
1252
        .statuses
1253
        .iter()
1254
        .map(|p| (p.path.as_str(), p.status))
1255
        .collect();
1256
    assert_eq!(
1257
        paths,
1258
        vec![
1259
            ("a.txt", ChangeStatus::Modified),
1260
            ("b.txt", ChangeStatus::Added)
1261
        ]
1262
    );
1263
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1264
    let h3 = repo.commit("recommitted", &[]).unwrap();
1265
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1266
    // undo brings the abandoned head back.
1267
    repo.undo().unwrap();
1268
    repo.undo().unwrap();
1269
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1270
1271
    // Abandoning a non-head whose dependent references its atoms reifies
1272
    // the references (here: a.txt vanishes with it, so the dependent's edit
1273
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1274
    let base = repo.bookmark_heads().unwrap()[0];
1275
    let base_change = repo.store().get_change(&base).unwrap();
1276
    let h1_now = base_change.deps[0];
1277
    let notes = repo.abandon(&h1_now).unwrap();
1278
    assert!(
1279
        !notes.is_empty(),
1280
        "the dependent's edit of a.txt was reified"
1281
    );
1282
    let heads = repo.bookmark_heads().unwrap();
1283
    let after = repo.load_state(&heads).unwrap().materialize();
1284
    assert!(
1285
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1286
        "{:?}",
1287
        after.files.keys()
1288
    );
1289
    repo.undo().unwrap();
1290
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1291
    write(root, "c.txt", b"c\n");
1292
    let hc = repo.commit("c", &[]).unwrap();
1293
    write(root, "d.txt", b"d\n");
1294
    let hd = repo.commit("d", &[hc]).unwrap();
1295
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1296
    repo.abandon(&hc).unwrap();
1297
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1298
    assert!(!heads.contains(&hc));
1299
    let d_now = heads
1300
        .iter()
1301
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1302
        .copied()
1303
        .unwrap();
1304
    assert!(
1305
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1306
        "d inherited c's (empty) dependencies"
1307
    );
1308
    let s = repo.snapshot("status").unwrap();
1309
    assert_eq!(
1310
        s.statuses
1311
            .iter()
1312
            .map(|p| p.path.as_str())
1313
            .collect::<Vec<_>>(),
1314
        vec!["c.txt"],
1315
        "c's content is now uncommitted work"
1316
    );
1317
}
1318
1319
#[test]
1320
fn git_export_mirrors_history() {
1321
    hermetic();
1322
    if std::process::Command::new("git")
1323
        .arg("--version")
1324
        .output()
1325
        .is_err()
1326
    {
1327
        eprintln!("git not installed; skipping");
1328
        return;
1329
    }
1330
    let dir = tempfile::tempdir().unwrap();
1331
    let root = dir.path();
1332
    let mut repo = Repo::init(&root.join("r"))
1333
        .unwrap()
1334
        .with_home(root.join("home"));
1335
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1336
        .unwrap();
1337
    let r = root.join("r");
1338
    write(&r, "README.md", b"hello\n");
1339
    write(&r, "src/main.rs", b"fn main() {}\n");
1340
    let h1 = repo.commit("first", &[]).unwrap();
1341
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1342
    write(&r, "logo.png", b"\x89PNG\0\0");
1343
    let h2 = repo.commit("second", &[]).unwrap();
1344
1345
    let git_dir = root.join("mirror.git");
1346
    let rep = repo.git_export(&git_dir).unwrap();
1347
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1348
    let git = |args: &[&str]| -> String {
1349
        let out = std::process::Command::new("git")
1350
            .arg("-C")
1351
            .arg(&git_dir)
1352
            .args(args)
1353
            .output()
1354
            .unwrap();
1355
        assert!(
1356
            out.status.success(),
1357
            "{}",
1358
            String::from_utf8_lossy(&out.stderr)
1359
        );
1360
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1361
    };
1362
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1363
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1364
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1365
    let body = git(&["log", "-1", "--format=%B", "main"]);
1366
    assert!(
1367
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1368
        "{body}"
1369
    );
1370
    assert!(body.contains("Change-Id: "), "{body}");
1371
    assert_eq!(
1372
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1373
        "Ada Lovelace <[email protected]>"
1374
    );
1375
    assert_eq!(
1376
        git(&["ls-tree", "--name-only", "main"]),
1377
        "README.md\nlogo.png\nsrc"
1378
    );
1379
1380
    // Re-export is incremental.
1381
    let rep = repo.git_export(&git_dir).unwrap();
1382
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1383
1384
    // An independent change makes two heads; the next state is one more
1385
    // commit on the linear branch whose tree is the union.
1386
    repo.checkout(&[h1], false, "checkout").unwrap();
1387
    write(&r, "other.txt", b"o\n");
1388
    let h3 = repo.commit("third", &[]).unwrap();
1389
    let rep = repo.git_export(&git_dir).unwrap();
1390
    assert_eq!((rep.exported, rep.heads), (1, 2));
1391
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1392
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1393
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1394
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1395
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1396
    assert_eq!(
1397
        git(&["ls-tree", "--name-only", "main"]),
1398
        "README.md\nlogo.png\nother.txt\nsrc"
1399
    );
1400
    let body = git(&["log", "-1", "--format=%B", "main"]);
1401
    assert!(
1402
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1403
        "{body}"
1404
    );
1405
    // A rewrite is a new state whose one new change is the rewritten one.
1406
    repo.describe(&h3, "third, described").unwrap();
1407
    let rep = repo.git_export(&git_dir).unwrap();
1408
    assert_eq!(rep.exported, 1);
1409
    assert_eq!(
1410
        git(&["log", "-1", "--format=%s", "main"]),
1411
        "third, described"
1412
    );
1413
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1414
    let _ = h2;
1415
}
1416
1417
#[test]
1418
fn git_import_reproduces_trees() {
1419
    hermetic();
1420
    if std::process::Command::new("git")
1421
        .arg("--version")
1422
        .output()
1423
        .is_err()
1424
    {
1425
        eprintln!("git not installed; skipping");
1426
        return;
1427
    }
1428
    let dir = tempfile::tempdir().unwrap();
1429
    let root = dir.path();
1430
    let g = root.join("src.git");
1431
    fs::create_dir_all(&g).unwrap();
1432
    let git = |args: &[&str]| -> String {
1433
        let out = std::process::Command::new("git")
1434
            .arg("-C")
1435
            .arg(&g)
1436
            .args([
1437
                "-c",
1438
                "user.name=Grace",
1439
                "-c",
1440
                "[email protected]",
1441
                "-c",
1442
                "commit.gpgsign=false",
1443
            ])
1444
            .args(args)
1445
            .output()
1446
            .unwrap();
1447
        assert!(
1448
            out.status.success(),
1449
            "git {args:?}: {}",
1450
            String::from_utf8_lossy(&out.stderr)
1451
        );
1452
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1453
    };
1454
    git(&["init", "-q", "-b", "main"]);
1455
    write(&g, "README.md", b"# Hi\n");
1456
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1457
    git(&["add", "."]);
1458
    git(&["commit", "-q", "-m", "initial"]);
1459
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1460
    write(&g, "run.sh", b"#!/bin/sh\n");
1461
    #[cfg(unix)]
1462
    {
1463
        use std::os::unix::fs::PermissionsExt;
1464
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1465
    }
1466
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1467
    git(&["add", "."]);
1468
    git(&[
1469
        "commit",
1470
        "-q",
1471
        "-m",
1472
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1473
    ]);
1474
    // A branch that edits README, merged back with a conflict-free merge.
1475
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1476
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1477
    git(&["commit", "-q", "-am", "readme"]);
1478
    git(&["checkout", "-q", "main"]);
1479
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1480
    // A branch from the initial commit inserting at the same place as
1481
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1482
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1483
    git(&["checkout", "-q", "-b", "clash", &initial]);
1484
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1485
    git(&["commit", "-q", "-am", "clash"]);
1486
    git(&["checkout", "-q", "main"]);
1487
    let _ = std::process::Command::new("git")
1488
        .arg("-C")
1489
        .arg(&g)
1490
        .args(["merge", "-q", "clash"])
1491
        .output();
1492
    write(
1493
        &g,
1494
        "src/lib.rs",
1495
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1496
    );
1497
    git(&["add", "."]);
1498
    git(&["commit", "-q", "-m", "resolve clash"]);
1499
    git(&["rm", "-q", "logo.png"]);
1500
    git(&["commit", "-q", "-m", "drop logo"]);
1501
    // A rename with a small edit is imported as a move of the same node.
1502
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1503
    write(
1504
        &g,
1505
        "src/lib2.rs",
1506
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1507
    );
1508
    git(&["add", "."]);
1509
    git(&["commit", "-q", "-m", "rename lib"]);
1510
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1511
1512
    let dest = root.join("oxy");
1513
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1514
    let rep = repo.import_git(&g, "main").unwrap();
1515
    assert_eq!(rep.commits, expected_count);
1516
    assert_eq!(rep.merges, 2);
1517
    // The working copy equals the Git tree at main.
1518
    assert_eq!(
1519
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1520
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1521
    );
1522
    assert!(!dest.join("src/lib.rs").exists());
1523
    assert_eq!(
1524
        fs::read(dest.join("README.md")).unwrap(),
1525
        b"# Hi\n\nMore.\n"
1526
    );
1527
    assert!(!dest.join("logo.png").exists());
1528
    #[cfg(unix)]
1529
    {
1530
        use std::os::unix::fs::PermissionsExt;
1531
        assert!(
1532
            fs::metadata(dest.join("run.sh"))
1533
                .unwrap()
1534
                .permissions()
1535
                .mode()
1536
                & 0o111
1537
                != 0
1538
        );
1539
    }
1540
    assert!(
1541
        !repo.snapshot("status").unwrap().changed,
1542
        "clean after import"
1543
    );
1544
    let heads = repo.bookmark_heads().unwrap();
1545
    let st = repo.load_state(&heads).unwrap();
1546
    assert!(!st.materialize().is_conflicted());
1547
    assert_eq!(st.len(), expected_count);
1548
    let tip = repo
1549
        .log()
1550
        .unwrap()
1551
        .into_iter()
1552
        .find(|e| e.change.message.starts_with("rename lib"))
1553
        .unwrap();
1554
    let c = repo.store().get_change(&tip.hash).unwrap();
1555
    assert!(
1556
        c.tree_ops
1557
            .iter()
1558
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1559
        "{:?}",
1560
        c.tree_ops
1561
    );
1562
    assert!(!c
1563
        .tree_ops
1564
        .iter()
1565
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1566
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1567
    let log = repo.log().unwrap();
1568
    let second = log
1569
        .iter()
1570
        .find(|e| e.change.message.starts_with("second"))
1571
        .unwrap();
1572
    assert_eq!(
1573
        second.change.change_id,
1574
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1575
    );
1576
    assert!(second
1577
        .change
1578
        .message
1579
        .contains("Git-Author: Grace <[email protected]>"));
1580
    let resolve = log
1581
        .iter()
1582
        .find(|e| e.change.message.starts_with("resolve clash"))
1583
        .unwrap();
1584
    assert_eq!(
1585
        resolve.change.kind,
1586
        ChangeKind::Resolution,
1587
        "a conflicting Git merge becomes a resolution"
1588
    );
1589
    // Re-importing into another fresh repository gives the same ChangeIds.
1590
    let repo2 = Repo::init(&root.join("oxy2"))
1591
        .unwrap()
1592
        .with_home(root.join("home"));
1593
    repo2.import_git(&g, "main").unwrap();
1594
    let ids: BTreeSet<ChangeId> = repo
1595
        .log()
1596
        .unwrap()
1597
        .iter()
1598
        .filter(|e| !e.is_working_copy)
1599
        .map(|e| e.change.change_id)
1600
        .collect();
1601
    let ids2: BTreeSet<ChangeId> = repo2
1602
        .log()
1603
        .unwrap()
1604
        .iter()
1605
        .filter(|e| !e.is_working_copy)
1606
        .map(|e| e.change.change_id)
1607
        .collect();
1608
    assert_eq!(ids, ids2);
1609
    // Round trip back out to Git reproduces the tip tree.
1610
    let mirror = root.join("mirror.git");
1611
    repo.git_export(&mirror).unwrap();
1612
    let out = std::process::Command::new("git")
1613
        .arg("-C")
1614
        .arg(&mirror)
1615
        .args(["show", "main:src/lib2.rs"])
1616
        .output()
1617
        .unwrap();
1618
    assert_eq!(
1619
        String::from_utf8_lossy(&out.stdout),
1620
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1621
    );
1622
    let out = std::process::Command::new("git")
1623
        .arg("-C")
1624
        .arg(&mirror)
1625
        .args(["show", "main:src/lib.rs"])
1626
        .output()
1627
        .unwrap();
1628
    assert!(
1629
        !out.status.success(),
1630
        "the old path is gone from the export"
1631
    );
1632
}
1633
1634
#[test]
1635
fn checkpoints_accelerate_loading_and_stay_correct() {
1636
    hermetic();
1637
    let dir = tempfile::tempdir().unwrap();
1638
    let root = dir.path();
1639
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1640
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1641
    repo.save_config().unwrap();
1642
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1643
    let mut hashes = Vec::new();
1644
    for i in 0..12 {
1645
        write(
1646
            root,
1647
            "a.txt",
1648
            format!(
1649
                "{}\n",
1650
                (0..=i)
1651
                    .map(|k| k.to_string())
1652
                    .collect::<Vec<_>>()
1653
                    .join("\n")
1654
            )
1655
            .as_bytes(),
1656
        );
1657
        write(root, &format!("f{i}.txt"), b"x\n");
1658
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1659
    }
1660
    let (_, cp) = repo
1661
        .latest_checkpoint("main")
1662
        .unwrap()
1663
        .expect("automatic checkpoint");
1664
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1665
    // Loading through the checkpoint equals loading everything.
1666
    let heads = repo.bookmark_heads().unwrap();
1667
    let fast = repo.load_state(&heads).unwrap();
1668
    let full = repo.load_state_full(&heads).unwrap();
1669
    assert_eq!(fast.len(), full.len());
1670
    assert_eq!(fast.heads(), full.heads());
1671
    let (a, b) = (fast.materialize(), full.materialize());
1672
    assert_eq!(
1673
        a.files.keys().collect::<Vec<_>>(),
1674
        b.files.keys().collect::<Vec<_>>()
1675
    );
1676
    for (p, f) in &a.files {
1677
        assert_eq!(f.content, b.files[p].content, "{p}");
1678
    }
1679
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1680
    // A head set that does not contain the checkpoint's heads falls back.
1681
    assert!(repo
1682
        .load_state_checkpointed(&[hashes[0]])
1683
        .unwrap()
1684
        .is_none());
1685
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1686
    // Everything else keeps working on top of the checkpoint.
1687
    assert!(!repo.snapshot("status").unwrap().changed);
1688
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1689
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1690
    let (r, n, bytes) = repo.checkpoint().unwrap();
1691
    assert!(n >= 12 && bytes > 0);
1692
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1693
    write(root, "a.txt", b"after\n");
1694
    let h_after = repo.commit("after", &[]).unwrap();
1695
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1696
    assert!(st.contains(&h_after));
1697
    assert!(
1698
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1699
    );
1700
    assert_eq!(repo.log().unwrap().len(), 14);
1701
    // Checkpoints survive gc.
1702
    repo.gc(true).unwrap();
1703
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1704
    assert!(repo
1705
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1706
        .unwrap()
1707
        .is_some());
1708
}
1709
1710
#[test]
1711
fn quick_status_for_prompts() {
1712
    hermetic();
1713
    let dir = tempfile::tempdir().unwrap();
1714
    let root = dir.path();
1715
    let origin = Repo::init(&root.join("origin")).unwrap();
1716
    let url = root.join("origin").to_string_lossy().to_string();
1717
    let a = Repo::clone(&url, &root.join("a"))
1718
        .unwrap()
1719
        .with_home(root.join("home"));
1720
    let ops_before = a.op_log().unwrap().len();
1721
    let info = a.quick_status().unwrap();
1722
    assert_eq!(
1723
        (
1724
            info.bookmark.as_str(),
1725
            info.heads,
1726
            info.dirty,
1727
            info.conflicted,
1728
            info.ahead,
1729
            info.behind
1730
        ),
1731
        ("main", 0, false, false, Some(0), Some(0))
1732
    );
1733
    write(&root.join("a"), "f.txt", b"f\n");
1734
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1735
    assert_eq!(
1736
        a.op_log().unwrap().len(),
1737
        ops_before,
1738
        "quick_status records nothing"
1739
    );
1740
    // A snapshotted but uncommitted change is still dirty.
1741
    a.snapshot("status").unwrap();
1742
    assert!(a.quick_status().unwrap().dirty);
1743
    a.commit("f", &[]).unwrap();
1744
    let info = a.quick_status().unwrap();
1745
    assert!(!info.dirty, "clean right after a commit");
1746
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
1747
    assert_eq!(
1748
        info.format("%b %c%d%x%A%D"),
1749
        format!("main {}+1", info.change_id)
1750
    );
1751
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1752
    // Touching a file without changing it is not dirty; changing content of
1753
    // the same size is.
1754
    let p = root.join("a/f.txt");
1755
    let content = fs::read(&p).unwrap();
1756
    fs::write(&p, &content).unwrap();
1757
    assert!(!a.quick_status().unwrap().dirty);
1758
    fs::write(&p, b"g\n").unwrap();
1759
    assert!(a.quick_status().unwrap().dirty);
1760
    fs::write(&p, b"f\n").unwrap();
1761
    // Push, then a second clone commits and pushes: we are behind.
1762
    assert!(a.push("origin", false).unwrap()[0].ok);
1763
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
1764
    let b = Repo::clone(&url, &root.join("b"))
1765
        .unwrap()
1766
        .with_home(root.join("home-b"));
1767
    write(&root.join("b"), "g.txt", b"g\n");
1768
    b.commit("g", &[]).unwrap();
1769
    b.push("origin", false).unwrap();
1770
    a.fetch("origin").unwrap();
1771
    let info = a.quick_status().unwrap();
1772
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1773
    assert_eq!(info.format("%A%D"), "-1");
1774
    let _ = origin;
1775
}
1776
1777
#[test]
1778
fn lazy_blobs_are_fetched_on_first_read() {
1779
    hermetic();
1780
    let dir = tempfile::tempdir().unwrap();
1781
    let root = dir.path();
1782
    let origin_dir = root.join("origin");
1783
    let origin = Repo::init(&origin_dir)
1784
        .unwrap()
1785
        .with_home(root.join("home"));
1786
    let url = origin_dir.to_string_lossy().to_string();
1787
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1788
    write(&origin_dir, "big.bin", &big);
1789
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1790
    write(&origin_dir, "t.txt", b"t\n");
1791
    let h = origin.commit("blobs", &[]).unwrap();
1792
    let big_ref = Repo::blob_ref(&big);
1793
1794
    // Fetch only (no checkout) with a filter: the big blob stays absent.
1795
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1796
        .unwrap()
1797
        .with_home(root.join("home"));
1798
    let a = {
1799
        let mut a = a;
1800
        a.config.set("remote.origin.url", &url).unwrap();
1801
        a.config.set("filter.max-blob", "100K").unwrap();
1802
        a.save_config().unwrap();
1803
        a
1804
    };
1805
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1806
    a.fetch("origin").unwrap();
1807
    assert!(a.store().has(&h));
1808
    assert!(!a.store().has(&big_ref), "withheld");
1809
    assert!(
1810
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1811
        "small blob came along"
1812
    );
1813
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1814
1815
    // status and commit do not need it: adopt the state, edit a text file, commit.
1816
    let (op_ref, op) = a.head_op().unwrap();
1817
    let mut view = op.view.clone();
1818
    view.bookmarks.insert(
1819
        "main".into(),
1820
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1821
    );
1822
    a.record_op(&[op_ref], "adopt", view).unwrap();
1823
    // Checkout reads the blob lazily, which fetches it.
1824
    a.checkout(&[h], true, "checkout").unwrap();
1825
    assert!(a.store().has(&big_ref), "fetched on first read");
1826
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1827
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1828
    write(&root.join("a"), "t.txt", b"t2\n");
1829
    a.commit("text edit", &[]).unwrap();
1830
1831
    // clone --max-blob records the filter; the checkout fetches lazily.
1832
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
1833
    assert_eq!(b.config.max_blob, Some(1024));
1834
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1835
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1836
    assert!(parse_size("lots").is_err());
1837
}
1838
1839
#[test]
1840
fn sparse_checkout_materializes_only_chosen_paths() {
1841
    hermetic();
1842
    let dir = tempfile::tempdir().unwrap();
1843
    let root = dir.path();
1844
    let origin_dir = root.join("origin");
1845
    let origin = Repo::init(&origin_dir)
1846
        .unwrap()
1847
        .with_home(root.join("home"));
1848
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1849
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1850
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1851
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1852
    write(&origin_dir, "docs/logo.png", &logo);
1853
    write(&origin_dir, "README.md", b"# top\n");
1854
    let h1 = origin.commit("tree", &[]).unwrap();
1855
    let url = origin_dir.to_string_lossy().to_string();
1856
1857
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
1858
        .unwrap()
1859
        .with_home(root.join("home"));
1860
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1861
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1862
    assert!(root.join("a/src/main.rs").exists());
1863
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
1864
    assert!(
1865
        !a.store().has(&Repo::blob_ref(&logo)),
1866
        "out-of-scope blob never fetched"
1867
    );
1868
    assert!(
1869
        !a.snapshot("status").unwrap().changed,
1870
        "out-of-scope files are not removals"
1871
    );
1872
    assert_eq!(a.quick_status().unwrap().dirty, false);
1873
1874
    // Edits in scope commit normally and keep the rest of the tree intact.
1875
    write(
1876
        &root.join("a"),
1877
        "src/lib.rs",
1878
        b"pub fn a() {}\npub fn b() {}\n",
1879
    );
1880
    let h2 = a.commit("edit lib", &[]).unwrap();
1881
    let st = a.load_state(&[h2]).unwrap().materialize();
1882
    assert!(
1883
        st.files.contains_key("docs/guide.md"),
1884
        "the state still has everything"
1885
    );
1886
    assert!(a.push("origin", false).unwrap()[0].ok);
1887
    // Files created outside the scope are ignored by status.
1888
    write(&root.join("a"), "docs/new.md", b"ignored\n");
1889
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
1890
1891
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
1892
    let mut a = a;
1893
    a.config.set("filter.paths", "src,docs").unwrap();
1894
    a.save_config().unwrap();
1895
    let r = a
1896
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
1897
        .unwrap();
1898
    assert!(r.written >= 2);
1899
    assert_eq!(
1900
        fs::read(root.join("a/docs/logo.png")).unwrap(),
1901
        logo,
1902
        "now fetched lazily"
1903
    );
1904
    assert!(!root.join("a/README.md").exists());
1905
    // Origin sees the change made under a sparse checkout with the full tree intact.
1906
    origin.pull("origin").err();
1907
    let full = origin
1908
        .load_state(&origin.bookmark_heads().unwrap())
1909
        .unwrap()
1910
        .materialize();
1911
    assert!(
1912
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
1913
    );
1914
    assert!(full.files.contains_key("README.md"));
1915
    let _ = h1;
1916
}
1917
1918
#[test]
1919
fn shallow_clone_and_deepen() {
1920
    hermetic();
1921
    let dir = tempfile::tempdir().unwrap();
1922
    let root = dir.path();
1923
    let origin_dir = root.join("origin");
1924
    let origin = Repo::init(&origin_dir)
1925
        .unwrap()
1926
        .with_home(root.join("home"));
1927
    let mut hashes = Vec::new();
1928
    for i in 0..8 {
1929
        write(
1930
            &origin_dir,
1931
            "a.txt",
1932
            format!(
1933
                "{}\n",
1934
                (0..=i)
1935
                    .map(|k| k.to_string())
1936
                    .collect::<Vec<_>>()
1937
                    .join("\n")
1938
            )
1939
            .as_bytes(),
1940
        );
1941
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
1942
    }
1943
    let url = origin_dir.to_string_lossy().to_string();
1944
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
1945
        .unwrap()
1946
        .with_home(root.join("home"));
1947
    assert!(a.is_shallow());
1948
    assert_eq!(
1949
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
1950
        "0\n1\n2\n3\n4\n5\n6\n7\n"
1951
    );
1952
    assert!(
1953
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
1954
        "three levels present"
1955
    );
1956
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
1957
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
1958
    assert_eq!(
1959
        a.log().unwrap().len(),
1960
        9,
1961
        "the log shows every change from the checkpoint's metadata"
1962
    );
1963
    assert!(!a.snapshot("status").unwrap().changed);
1964
    assert_eq!(a.quick_status().unwrap().heads, 1);
1965
1966
    // Work continues on top of the shallow history and pushes back.
1967
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
1968
    let h_new = a.commit("c8", &[]).unwrap();
1969
    assert!(a.push("origin", false).unwrap()[0].ok);
1970
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
1971
    // Fetching new work from origin into the shallow clone works too.
1972
    write(&origin_dir, "b.txt", b"b\n");
1973
    origin.pull("origin").err();
1974
    let (_, wc) = origin.working_copy().unwrap();
1975
    let _ = wc;
1976
    origin
1977
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
1978
        .unwrap();
1979
    write(&origin_dir, "b.txt", b"b\n");
1980
    let h_b = origin.commit("b", &[]).unwrap();
1981
    let pr = a.pull("origin").unwrap();
1982
    assert!(pr.changed);
1983
    assert!(a.store().has(&h_b));
1984
    assert!(root.join("a/b.txt").exists());
1985
1986
    // Deepening fetches older history until the boundary is gone.
1987
    // Every commit also depends on the change that created the file, so two
1988
    // levels below the boundary hold h4, h3, and the root.
1989
    assert!(a.deepen("origin", 2).unwrap() >= 2);
1990
    assert!(a.store().has(&hashes[3]));
1991
    assert!(a.is_shallow());
1992
    a.deepen("origin", 100).unwrap();
1993
    assert!(!a.is_shallow(), "boundary reached the root");
1994
    assert!(a.store().has(&hashes[0]));
1995
    assert_eq!(
1996
        a.load_state_full(&a.bookmark_heads().unwrap())
1997
            .unwrap()
1998
            .len(),
1999
        10
2000
    );
2001
}
2002
2003
#[test]
2004
fn tags_are_immutable_named_states_and_travel() {
2005
    hermetic();
2006
    let dir = tempfile::tempdir().unwrap();
2007
    let root = dir.path();
2008
    let origin = Repo::init(&root.join("origin")).unwrap();
2009
    let url = root.join("origin").to_string_lossy().to_string();
2010
    let mut a = Repo::clone(&url, &root.join("a"))
2011
        .unwrap()
2012
        .with_home(root.join("home-a"));
2013
    let (key_a, _) = a
2014
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2015
        .unwrap();
2016
    write(&root.join("a"), "f.txt", b"1\n");
2017
    let h1 = a.commit("one", &[]).unwrap();
2018
    write(&root.join("a"), "f.txt", b"1\n2\n");
2019
    let h2 = a.commit("two", &[]).unwrap();
2020
2021
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2022
    assert_eq!(
2023
        (t.heads.clone(), t.signer.as_deref()),
2024
        (vec![h1], Some("Ada"))
2025
    );
2026
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2027
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2028
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2029
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2030
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2031
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2032
    assert_eq!(sa.sigs[0].key, key_a);
2033
    // Checkout by tag.
2034
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2035
        .unwrap();
2036
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2037
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2038
        .unwrap();
2039
2040
    // Push carries the tag; a second attestation for the name is refused.
2041
    let r = a.push("origin", false).unwrap();
2042
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2043
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2044
    let mut forged = a
2045
        .tag_refs()
2046
        .unwrap()
2047
        .into_iter()
2048
        .find(|t| t.name == "v1")
2049
        .unwrap();
2050
    forged.state = origin
2051
        .store()
2052
        .put_state(&StateObject::new(vec![h2]))
2053
        .unwrap();
2054
    forged.heads = vec![h2];
2055
    forged.attestation = None;
2056
    let r = origin
2057
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2058
        .unwrap();
2059
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2060
2061
    // A clone gets the tag; a later tag arrives on fetch.
2062
    let b = Repo::clone(&url, &root.join("b"))
2063
        .unwrap()
2064
        .with_home(root.join("home-b"));
2065
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2066
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2067
    a.tag_create("v2", &[h2], "second").unwrap();
2068
    a.push("origin", false).unwrap();
2069
    let rep = b.fetch("origin").unwrap();
2070
    assert_eq!(rep.new_tags, 1);
2071
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2072
2073
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2074
    a.policy_init().unwrap();
2075
    a.push("origin", false).unwrap();
2076
    let unattested = crate::protocol::TagRef {
2077
        name: "v3".into(),
2078
        state: origin
2079
            .store()
2080
            .put_state(&StateObject::new(vec![h2]))
2081
            .unwrap(),
2082
        heads: vec![h2],
2083
        attestation: None,
2084
    };
2085
    let r = origin
2086
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2087
        .unwrap();
2088
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2089
    a.tag_create("v3", &[h2], "").unwrap();
2090
    let r = a.push("origin", false).unwrap();
2091
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2092
    assert!(a.gc(true).is_ok());
2093
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2094
}
2095
2096
#[test]
2097
fn multiple_workspaces_share_a_repository() {
2098
    hermetic();
2099
    let dir = tempfile::tempdir().unwrap();
2100
    let root = dir.path();
2101
    let main_dir = root.join("main");
2102
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2103
    write(&main_dir, "a.txt", b"a\n");
2104
    let h1 = repo.commit("a", &[]).unwrap();
2105
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2106
2107
    // A second workspace elsewhere, checked out on the bookmark.
2108
    let ws_dir = root.join("ws2");
2109
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2110
    assert!(ws_dir.join(".oxy").is_file());
2111
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2112
    assert_ne!(ws.workspace(), repo.workspace());
2113
    let list = repo.workspaces().unwrap();
2114
    assert_eq!(list.len(), 2);
2115
    assert!(list
2116
        .iter()
2117
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2118
    assert!(!ws.snapshot("status").unwrap().changed);
2119
2120
    // Work in the second workspace: its own working copy, shared bookmark.
2121
    write(&ws_dir, "b.txt", b"b\n");
2122
    let s = ws.snapshot("status").unwrap();
2123
    assert_eq!(s.statuses.len(), 1);
2124
    assert!(
2125
        !repo.snapshot("status").unwrap().changed,
2126
        "the first workspace is untouched"
2127
    );
2128
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2129
    let mut heads = repo.bookmark_heads().unwrap();
2130
    heads.sort();
2131
    let mut want = vec![h1, h2];
2132
    want.sort();
2133
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2134
    assert!(!main_dir.join("b.txt").exists());
2135
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2136
        .unwrap();
2137
    assert!(main_dir.join("b.txt").exists());
2138
2139
    // Reopening from inside the second workspace finds the shared repository.
2140
    let reopened = Repo::open(&ws_dir).unwrap();
2141
    assert_eq!(reopened.workspace(), ws.workspace());
2142
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2143
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2144
2145
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2146
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2147
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2148
    repo.workspace_forget(&ws.workspace()).unwrap();
2149
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2150
    assert!(ws_dir.join("b.txt").exists());
2151
    assert!(
2152
        ws.snapshot("status").is_err(),
2153
        "a forgotten workspace is no longer in the view"
2154
    );
2155
2156
    // The snapshot lock: a fresh lock blocks a second, a stale one is taken over.
2157
    let lock = repo.lock_snapshot().unwrap();
2158
    drop(lock);
2159
    let lock_path = main_dir
2160
        .join(".oxy/workspaces")
2161
        .join(repo.workspace().to_hex())
2162
        .join("lock");
2163
    fs::write(&lock_path, "1").unwrap();
2164
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2165
    fs::File::open(&lock_path)
2166
        .unwrap()
2167
        .set_modified(old)
2168
        .unwrap();
2169
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2170
}
2171
2172
#[test]
2173
fn attributes_binary_eol_nocompress_lockable() {
2174
    hermetic();
2175
    let dir = tempfile::tempdir().unwrap();
2176
    let root = dir.path();
2177
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2178
    write(
2179
        root,
2180
        ".oxyattributes",
2181
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2182
    );
2183
    write(root, "plain.dat", b"no nul bytes here\n");
2184
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2185
    write(root, "assets/model.bin", b"\0model");
2186
    let h = repo.commit("attrs", &[]).unwrap();
2187
    let snap = repo.load_state(&[h]).unwrap().materialize();
2188
    assert!(
2189
        snap.files["plain.dat"].mode.opaque,
2190
        "binary attribute forces opaque without NUL bytes"
2191
    );
2192
    assert!(
2193
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2194
        "stored with LF"
2195
    );
2196
    assert!(
2197
        !repo.snapshot("status").unwrap().changed,
2198
        "CRLF on disk equals LF in the state"
2199
    );
2200
    // nocompress chunks pack raw.
2201
    let r = repo.gc(true).unwrap();
2202
    assert!(r.packed.objects > 0);
2203
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2204
    fs::remove_file(root.join("notes.txt")).unwrap();
2205
    repo.checkout(&[h], true, "co").unwrap();
2206
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2207
    assert!(fs::metadata(root.join("assets/model.bin"))
2208
        .unwrap()
2209
        .permissions()
2210
        .readonly());
2211
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2212
    repo.lock_path("assets/model.bin").unwrap();
2213
    assert!(!fs::metadata(root.join("assets/model.bin"))
2214
        .unwrap()
2215
        .permissions()
2216
        .readonly());
2217
    assert!(repo.is_locked("assets/model.bin"));
2218
    write(root, "assets/model.bin", b"\0model2");
2219
    repo.commit("edit model", &[]).unwrap();
2220
    repo.unlock_path("assets/model.bin").unwrap();
2221
    assert!(fs::metadata(root.join("assets/model.bin"))
2222
        .unwrap()
2223
        .permissions()
2224
        .readonly());
2225
    // A later checkout can still overwrite a read-only lockable file.
2226
    repo.checkout(&[h], true, "co").unwrap();
2227
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2228
}
2229
2230
#[cfg(unix)]
2231
#[test]
2232
fn hooks_can_veto_observe_and_add_dependencies() {
2233
    use std::os::unix::fs::PermissionsExt;
2234
    hermetic();
2235
    let dir = tempfile::tempdir().unwrap();
2236
    let root = dir.path();
2237
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2238
    let hooks = root.join(".oxy/hooks");
2239
    fs::create_dir_all(&hooks).unwrap();
2240
    let hook = |name: &str, body: &str| {
2241
        let p = hooks.join(name);
2242
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2243
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2244
    };
2245
    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");
2246
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2247
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2248
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2249
    write(root, ".oxyignore", b".last-*\n");
2250
    write(root, "a.txt", b"a\n");
2251
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2252
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2253
    let h1 = repo.commit("first", &[]).unwrap();
2254
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2255
    assert!(
2256
        pre.contains("\"event\":\"pre-commit\"")
2257
            && pre.contains("\"path\":\"a.txt\"")
2258
            && pre.contains("\"message\":\"first\""),
2259
        "{pre}"
2260
    );
2261
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2262
    assert!(post.contains(&h1.to_hex()), "{post}");
2263
    repo.checkout(&[h1], false, "co").unwrap();
2264
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2265
        .unwrap()
2266
        .contains("post-checkout"));
2267
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2268
    repo.save_config().unwrap();
2269
    let err = repo.push("origin", false).unwrap_err().to_string();
2270
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2271
2272
    // semantic-deps: only when enabled; adds an explicit dependency.
2273
    write(root, "b.txt", b"b\n");
2274
    hook(
2275
        "semantic-deps",
2276
        &format!(
2277
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2278
            h1.to_hex()
2279
        ),
2280
    );
2281
    let h2 = repo.commit("b without hook", &[]).unwrap();
2282
    assert!(
2283
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2284
        "hook disabled by default"
2285
    );
2286
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2287
    repo.save_config().unwrap();
2288
    write(root, "c.txt", b"c\n");
2289
    let h3 = repo.commit("c with hook", &[]).unwrap();
2290
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2291
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2292
    assert!(
2293
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2294
        "{sem}"
2295
    );
2296
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2297
}
2298
2299
#[test]
2300
fn amend_into_older_change_and_split() {
2301
    hermetic();
2302
    let dir = tempfile::tempdir().unwrap();
2303
    let root = dir.path();
2304
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2305
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2306
        .unwrap();
2307
    repo.set_user_config("core.sign", "change").unwrap();
2308
    write(root, "a.txt", b"one\ntwo\n");
2309
    let h0 = repo.commit("base", &[]).unwrap();
2310
    write(root, "a.txt", b"one\nTWO\n");
2311
    let h1 = repo.commit("edit two", &[]).unwrap();
2312
    write(root, "a.txt", b"one\nTWO\nthree\n");
2313
    let h2 = repo.commit("add three", &[]).unwrap();
2314
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2315
2316
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2317
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2318
    let h1b = repo.amend_into(&h1, None).unwrap();
2319
    assert_ne!(h1b, h1);
2320
    let c1b = repo.store().get_change(&h1b).unwrap();
2321
    assert_eq!(c1b.change_id, id1);
2322
    assert_eq!(c1b.deps, vec![h0]);
2323
    assert!(matches!(
2324
        repo.verify_change(&h1b).unwrap(),
2325
        SignatureStatus::Valid { .. }
2326
    ));
2327
    let heads = repo.bookmark_heads().unwrap();
2328
    assert_eq!(heads.len(), 1);
2329
    let top = repo.store().get_change(&heads[0]).unwrap();
2330
    assert_eq!(top.message, "add three");
2331
    assert_eq!(
2332
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2333
        [h0, h1b].into_iter().collect(),
2334
        "depends on the file's creator and the rewritten line"
2335
    );
2336
    let snap = repo.load_state(&heads).unwrap().materialize();
2337
    assert!(
2338
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2339
    );
2340
    assert!(
2341
        !repo.snapshot("status").unwrap().changed,
2342
        "the working copy is clean after folding"
2343
    );
2344
    // Only h1b's own state shows the fix without "three".
2345
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2346
    assert!(
2347
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2348
    );
2349
    assert_eq!(repo.log().unwrap().len(), 4);
2350
2351
    // An edit to a line introduced by h2 cannot fold into h1.
2352
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2353
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2354
    assert!(err.contains("introduced after"), "{err}");
2355
    assert!(
2356
        repo.snapshot("status").unwrap().statuses.len() == 1,
2357
        "nothing was changed by the refusal"
2358
    );
2359
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2360
2361
    // Split the head that touches two files.
2362
    write(root, "b.txt", b"b\n");
2363
    write(root, "c.txt", b"c\n");
2364
    let h3 = repo.commit("b and c", &[]).unwrap();
2365
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2366
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2367
    let c_1 = repo.store().get_change(&p1).unwrap();
2368
    let c_2 = repo.store().get_change(&p2).unwrap();
2369
    assert!(c_1.message.contains("part 1: b.txt"));
2370
    assert_eq!(c_2.change_id, id3);
2371
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2372
    assert!(
2373
        heads.contains(&p1) && heads.contains(&p2),
2374
        "independent parts are both heads"
2375
    );
2376
    let snap = repo
2377
        .load_state(&repo.bookmark_heads().unwrap())
2378
        .unwrap()
2379
        .materialize();
2380
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2381
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2382
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2383
    assert!(!repo.snapshot("status").unwrap().changed);
2384
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2385
    let _ = h2;
2386
}
2387
2388
#[test]
2389
fn identity_lifecycle() {
2390
    hermetic();
2391
    let dir = tempfile::tempdir().unwrap();
2392
    let root = dir.path();
2393
    let origin = Repo::init(&root.join("origin")).unwrap();
2394
    let url = root.join("origin").to_string_lossy().to_string();
2395
    let mut a = Repo::clone(&url, &root.join("a"))
2396
        .unwrap()
2397
        .with_home(root.join("home-a"));
2398
    a.set_user_config("core.sign", "change").unwrap();
2399
    let (key_a, _) = a
2400
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2401
        .unwrap();
2402
    write(&root.join("a"), "a.txt", b"a\n");
2403
    let h1 = a.commit("one", &[]).unwrap();
2404
    assert!(a.policy_init().unwrap().applied);
2405
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2406
2407
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2408
    let mut e = Repo::init(&root.join("e"))
2409
        .unwrap()
2410
        .with_home(root.join("home-e"));
2411
    e.set_user_config("core.sign", "change").unwrap();
2412
    e.create_identity_with(
2413
        "Eve",
2414
        "[email protected]",
2415
        IdentityScope::User,
2416
        Some(Hlc::now().wall_ms - 1),
2417
    )
2418
    .unwrap();
2419
    write(&root.join("e"), "e.txt", b"e\n");
2420
    let he = e.commit("late", &[]).unwrap();
2421
    assert!(
2422
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2423
    );
2424
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2425
    let r = e
2426
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2427
        .unwrap();
2428
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2429
    write(&root.join("e"), "e.txt", b"e2\n");
2430
    let he2 = e.commit("in time", &[]).unwrap();
2431
    assert!(
2432
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2433
    );
2434
2435
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2436
    let r = a.rotate_identity().unwrap();
2437
    assert_eq!(r.old, key_a);
2438
    assert_eq!(a.config.author_key, Some(r.new));
2439
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2440
    assert!(r.policy.as_ref().unwrap().applied);
2441
    let (_, sp) = a.current_policy().unwrap().unwrap();
2442
    assert_eq!(
2443
        (sp.policy.serial, sp.policy.roots.clone()),
2444
        (2, vec![r.new])
2445
    );
2446
    assert!(
2447
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2448
        "superseded, not revoked"
2449
    );
2450
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2451
    assert!(
2452
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2453
    );
2454
    write(&root.join("a"), "a.txt", b"a2\n");
2455
    let h2 = a.commit("two", &[]).unwrap();
2456
    assert!(
2457
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2458
    );
2459
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2460
    let res = a.push("origin", false).unwrap();
2461
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2462
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2463
    let key_a = r.new;
2464
2465
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2466
    // identity object, so Ada's KeyId changes while her keys stay the same.
2467
    let mut b = Repo::clone(&url, &root.join("b"))
2468
        .unwrap()
2469
        .with_home(root.join("home-b"));
2470
    let (key_b, id_b) = b
2471
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2472
        .unwrap();
2473
    let r = a.delegate_add(id_b.clone()).unwrap();
2474
    assert_eq!(r.old, key_a);
2475
    let key_a2 = r.new;
2476
    assert_eq!(a.identity(&key_a2).unwrap().delegates, vec![key_b]);
2477
    assert_eq!(
2478
        a.identity(&key_a2).unwrap().ed25519_pk,
2479
        a.identity(&key_a).unwrap().ed25519_pk
2480
    );
2481
    assert!(a.delegate_add(id_b.clone()).is_err(), "already a delegate");
2482
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2483
    write(&root.join("a"), "a.txt", b"a3\n");
2484
    let h3 = a.commit("three", &[]).unwrap();
2485
    assert!(
2486
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2487
        "the same secret signs under the new KeyId"
2488
    );
2489
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2490
    a.set_user_config("core.sign", "seal").unwrap();
2491
    write(&root.join("a"), "a.txt", b"a4\n");
2492
    let h4 = a.commit("four", &[]).unwrap();
2493
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2494
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2495
    a.store()
2496
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2497
        .unwrap();
2498
    assert!(
2499
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2500
    );
2501
    a.set_user_config("core.sign", "change").unwrap();
2502
    // Withdrawing the delegation re-issues the identity again.
2503
    let r = a.delegate_remove(&key_b).unwrap();
2504
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2505
    assert!(a.delegate_remove(&key_b).is_err());
2506
    let key_a3 = r.new;
2507
    let res = a.push("origin", false).unwrap();
2508
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2509
2510
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2511
    // both applied under the old threshold of 1. A grant then needs Bob too.
2512
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2513
    assert!(a.policy_root_add(id_b.clone()).is_err());
2514
    assert!(a.policy_set_threshold(3).is_err());
2515
    assert!(a.policy_set_threshold(2).unwrap().applied);
2516
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2517
    b.pull("origin").unwrap();
2518
    assert_eq!(
2519
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2520
        2
2521
    );
2522
    let mut c = Repo::init(&root.join("c"))
2523
        .unwrap()
2524
        .with_home(root.join("home-c"));
2525
    let (key_c, id_c) = c
2526
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2527
        .unwrap();
2528
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2529
    let proposal = a.policy_grant(id_c, None).unwrap();
2530
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2531
    assert_eq!(proposal.policy.serial, serial_before + 1);
2532
    assert_eq!(
2533
        a.current_policy().unwrap().unwrap().1.policy.serial,
2534
        serial_before,
2535
        "a proposal changes nothing yet"
2536
    );
2537
    // Bob signs the proposal, handed over as a file, and it applies for him.
2538
    let bytes = proposal.signed().encode();
2539
    let signed = b
2540
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2541
        .unwrap();
2542
    assert!(signed.applied && signed.sigs.len() == 2);
2543
    assert!(b
2544
        .current_policy()
2545
        .unwrap()
2546
        .unwrap()
2547
        .1
2548
        .policy
2549
        .authorizes(&key_c, "main"));
2550
    assert!(
2551
        b.policy_sign(signed.signed()).is_err(),
2552
        "a stale proposal is refused"
2553
    );
2554
    // Bob publishes it and Ada picks it up.
2555
    assert!(b
2556
        .push("origin", false)
2557
        .unwrap()
2558
        .iter()
2559
        .any(|x| x.name == "policy" && x.ok));
2560
    a.pull("origin").unwrap();
2561
    assert_eq!(
2562
        a.current_policy().unwrap().unwrap().1.policy.serial,
2563
        serial_before + 1
2564
    );
2565
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2566
    assert!(a.policy_revoke(&key_a3).is_err());
2567
    let u = a
2568
        .revoke_identity(&key_c, "left the project")
2569
        .unwrap()
2570
        .unwrap();
2571
    assert!(!u.applied);
2572
    assert!(a.is_revoked(&key_c).unwrap());
2573
    assert!(!b.is_revoked(&key_c).unwrap());
2574
    let u = b.policy_sign(u.signed()).unwrap();
2575
    assert!(u.applied && u.policy.is_revoked(&key_c));
2576
    assert!(b.is_revoked(&key_c).unwrap());
2577
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2578
    assert!(
2579
        b.policy_revoke(&key_a3).is_err(),
2580
        "would leave one root for a threshold of 2"
2581
    );
2582
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2583
    let key_c_own = c.config.author_key.unwrap();
2584
    assert!(c
2585
        .revoke_identity(&key_c_own, "lost laptop")
2586
        .unwrap()
2587
        .is_none());
2588
    assert!(c.is_revoked(&key_c_own).unwrap());
2589
    assert_eq!(key_c_own, key_c);
2590
}
2591
2592
#[test]
2593
fn renames_are_detected_and_tracked_as_moves() {
2594
    hermetic();
2595
    let dir = tempfile::tempdir().unwrap();
2596
    let root = dir.path();
2597
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2598
    write(
2599
        root,
2600
        "src/old.rs",
2601
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2602
    );
2603
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2604
    write(root, "tiny.txt", b"x\n");
2605
    let h1 = repo.commit("base", &[]).unwrap();
2606
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2607
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2608
2609
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2610
    // that shares nothing with the removed file.
2611
    fs::remove_file(root.join("src/old.rs")).unwrap();
2612
    write(
2613
        root,
2614
        "lib/new.rs",
2615
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2616
    );
2617
    fs::remove_file(root.join("img.bin")).unwrap();
2618
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2619
    fs::remove_file(root.join("tiny.txt")).unwrap();
2620
    write(root, "other.txt", b"completely different\n");
2621
    let snap = repo.snapshot("status").unwrap();
2622
    let statuses: Vec<(&str, ChangeStatus)> = snap
2623
        .statuses
2624
        .iter()
2625
        .map(|s| (s.path.as_str(), s.status))
2626
        .collect();
2627
    assert_eq!(
2628
        statuses,
2629
        vec![
2630
            ("assets/img.bin", ChangeStatus::Renamed),
2631
            ("lib/new.rs", ChangeStatus::Renamed),
2632
            ("other.txt", ChangeStatus::Added),
2633
            ("src", ChangeStatus::Removed),
2634
            ("tiny.txt", ChangeStatus::Removed)
2635
        ]
2636
    );
2637
    let h2 = repo.commit("move things", &[]).unwrap();
2638
    let c = repo.store().get_change(&h2).unwrap();
2639
    let moves: Vec<_> = c
2640
        .tree_ops
2641
        .iter()
2642
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2643
        .collect();
2644
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
2645
    assert!(c.tree_ops.iter().any(
2646
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2647
    ));
2648
    assert!(c.tree_ops.iter().any(
2649
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2650
    ));
2651
    let snap = repo.load_state(&[h2]).unwrap().materialize();
2652
    assert_eq!(
2653
        snap.files["lib/new.rs"].node, node_old,
2654
        "the node survives the rename"
2655
    );
2656
    assert!(
2657
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2658
    );
2659
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
2660
    assert!(render_change(
2661
        &c,
2662
        &repo.load_state(&[h1]).unwrap(),
2663
        &repo.load_state(&[h1]).unwrap().materialize()
2664
    )
2665
    .contains("R "));
2666
    // A fresh checkout reproduces the tree.
2667
    let other = tempfile::tempdir().unwrap();
2668
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
2669
    assert_eq!(
2670
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2671
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2672
    );
2673
    assert!(!other.path().join("src").exists());
2674
    assert!(!clone.snapshot("status").unwrap().changed);
2675
    // Similarity is line based, byte weighted.
2676
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2677
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2678
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2679
    assert_eq!(similarity(b"", b"x\n"), 0);
2680
}
2681
2682
#[test]
2683
fn git_fetch_and_push_round_trip() {
2684
    hermetic();
2685
    if std::process::Command::new("git")
2686
        .arg("--version")
2687
        .output()
2688
        .is_err()
2689
    {
2690
        eprintln!("git not installed; skipping");
2691
        return;
2692
    }
2693
    let dir = tempfile::tempdir().unwrap();
2694
    let root = dir.path();
2695
    let git_in = |d: &Path, args: &[&str]| -> String {
2696
        let out = std::process::Command::new("git")
2697
            .arg("-C")
2698
            .arg(d)
2699
            .args([
2700
                "-c",
2701
                "user.name=Grace",
2702
                "-c",
2703
                "[email protected]",
2704
                "-c",
2705
                "commit.gpgsign=false",
2706
            ])
2707
            .args(args)
2708
            .output()
2709
            .unwrap();
2710
        assert!(
2711
            out.status.success(),
2712
            "git {args:?}: {}",
2713
            String::from_utf8_lossy(&out.stderr)
2714
        );
2715
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2716
    };
2717
    // A bare "remote" and a work tree that pushes to it.
2718
    let remote = root.join("remote.git");
2719
    fs::create_dir_all(&remote).unwrap();
2720
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2721
    let work = root.join("work");
2722
    git_in(
2723
        root,
2724
        &[
2725
            "clone",
2726
            "-q",
2727
            remote.to_str().unwrap(),
2728
            work.to_str().unwrap(),
2729
        ],
2730
    );
2731
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2732
    write(&work, "README.md", b"# Project\n");
2733
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2734
    git_in(&work, &["add", "."]);
2735
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2736
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2737
    git_in(&work, &["commit", "-q", "-am", "second"]);
2738
    git_in(&work, &["push", "-q", "origin", "main"]);
2739
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2740
2741
    // Fetch into a fresh oxy repository.
2742
    let o = root.join("oxy");
2743
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
2744
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2745
        .unwrap();
2746
    let url = remote.to_string_lossy().to_string();
2747
    let r = repo.git_fetch(&url, "main").unwrap();
2748
    assert_eq!((r.commits, r.heads), (2, 1));
2749
    assert_eq!(
2750
        fs::read(o.join("src/lib.rs")).unwrap(),
2751
        b"pub fn a() {}\npub fn b() {}\n"
2752
    );
2753
    assert!(!repo.snapshot("status").unwrap().changed);
2754
    assert_eq!(
2755
        repo.git_fetch(&url, "main").unwrap().commits,
2756
        0,
2757
        "nothing new"
2758
    );
2759
2760
    // An oxy change, pushed back: one commit on top of the Git tip.
2761
    write(
2762
        &o,
2763
        "src/lib.rs",
2764
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2765
    );
2766
    write(&o, "NOTES.md", b"from oxy\n");
2767
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2768
    let r = repo.git_push(&url, "main").unwrap();
2769
    assert_eq!(r.exported, 1, "{r:?}");
2770
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2771
    assert_eq!(
2772
        git_in(&work, &["log", "--format=%s", "main"]),
2773
        "add c and notes\nsecond\ninitial"
2774
    );
2775
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2776
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2777
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
2778
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2779
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2780
    assert_eq!(
2781
        repo.git_push(&url, "main").unwrap().exported,
2782
        0,
2783
        "already pushed"
2784
    );
2785
2786
    // Git moves on; pushing without fetching is refused, fetching brings
2787
    // the commit in and the working copy follows.
2788
    write(&work, "README.md", b"# Project\n\nMore.\n");
2789
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2790
    git_in(&work, &["push", "-q", "origin", "main"]);
2791
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
2792
    assert!(repo
2793
        .git_push(&url, "main")
2794
        .unwrap_err()
2795
        .to_string()
2796
        .contains("fetch"));
2797
    let r = repo.git_fetch(&url, "main").unwrap();
2798
    assert_eq!(
2799
        (r.commits, r.heads),
2800
        (1, 2),
2801
        "the Git change and the oxy change commute"
2802
    );
2803
    assert_eq!(
2804
        fs::read(o.join("README.md")).unwrap(),
2805
        b"# Project\n\nMore.\n"
2806
    );
2807
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2808
    assert!(!repo.snapshot("status").unwrap().changed);
2809
    // Another oxy change pushes on top of Git's newest commit.
2810
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2811
    repo.commit("notes again", &[]).unwrap();
2812
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2813
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2814
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
2815
    assert_eq!(
2816
        fs::read(work.join("NOTES.md")).unwrap(),
2817
        b"from oxy\nagain\n"
2818
    );
2819
    assert_eq!(
2820
        git_in(&work, &["log", "--format=%s", "main"])
2821
            .lines()
2822
            .count(),
2823
        5
2824
    );
2825
}
2826
2827
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2828
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2829
#[test]
2830
#[ignore]
2831
fn bench_one_gibibyte_file() {
2832
    hermetic();
2833
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2834
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2835
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2836
        None => tempfile::tempdir().unwrap(),
2837
    };
2838
    let root = dir.path();
2839
    let repo = Repo::init(&root.join("r"))
2840
        .unwrap()
2841
        .with_home(root.join("home"));
2842
    let size = 1usize << 30;
2843
    let mut data = vec![0u8; size];
2844
    let mut x = 0x9e3779b97f4a7c15u64;
2845
    for chunk in data.chunks_mut(8) {
2846
        x ^= x << 13;
2847
        x ^= x >> 7;
2848
        x ^= x << 17;
2849
        let b = x.to_le_bytes();
2850
        chunk.copy_from_slice(&b[..chunk.len()]);
2851
    }
2852
    let t = std::time::Instant::now();
2853
    write(&root.join("r"), "big.bin", &data);
2854
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
2855
    let t = std::time::Instant::now();
2856
    let h = repo.commit("big", &[]).unwrap();
2857
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
2858
    let t = std::time::Instant::now();
2859
    assert!(!repo.snapshot("status").unwrap().changed);
2860
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
2861
    let t = std::time::Instant::now();
2862
    let objects = repo.store().list().unwrap().len();
2863
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
2864
    let t = std::time::Instant::now();
2865
    let g = repo.gc(true).unwrap();
2866
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
2867
    let t = std::time::Instant::now();
2868
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
2869
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
2870
    let t = std::time::Instant::now();
2871
    let back = fs::read(root.join("c/big.bin")).unwrap();
2872
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
2873
    eprintln!("read back and verify: {:.2?}", t.elapsed());
2874
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
2875
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
2876
    eprintln!(
2877
        "store size: {:.1} MiB for 1 GiB of data",
2878
        store_bytes as f64 / (1024.0 * 1024.0)
2879
    );
2880
}
2881
2882
fn walkdir_size(p: &Path) -> u64 {
2883
    let mut total = 0;
2884
    if let Ok(rd) = fs::read_dir(p) {
2885
        for e in rd.flatten() {
2886
            let path = e.path();
2887
            if path.is_dir() {
2888
                total += walkdir_size(&path);
2889
            } else if let Ok(m) = fs::metadata(&path) {
2890
                total += m.len();
2891
            }
2892
        }
2893
    }
2894
    total
2895
}
2896
2897
/// An opaque file whose size and mtime match the manifest is not read on
2898
/// the next snapshot: its blob comes from the manifest's stat cache.
2899
#[cfg(unix)]
2900
#[test]
2901
fn stat_cache_skips_reading_unchanged_opaque_files() {
2902
    use std::os::unix::fs::PermissionsExt;
2903
    hermetic();
2904
    let dir = tempfile::tempdir().unwrap();
2905
    let root = dir.path();
2906
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2907
    let mut big = vec![0u8; 300 * 1024];
2908
    for (i, b) in big.iter_mut().enumerate() {
2909
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
2910
    }
2911
    big[0] = 0;
2912
    write(root, "big.bin", &big);
2913
    write(root, "a.txt", b"text\n");
2914
    let h1 = repo.commit("base", &[]).unwrap();
2915
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
2916
    assert!(
2917
        m.entries["big.bin"].blob.is_some(),
2918
        "opaque files record their blob"
2919
    );
2920
    assert!(m.entries["a.txt"].blob.is_none());
2921
    let blob = m.entries["big.bin"].blob.unwrap();
2922
    assert!(repo.store().has(&blob));
2923
2924
    // Files modified within two seconds of the manifest are racy and still
2925
    // read; age the file so the cache applies, then snapshot to record it.
2926
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
2927
    fs::File::options()
2928
        .write(true)
2929
        .open(root.join("big.bin"))
2930
        .unwrap()
2931
        .set_modified(old)
2932
        .unwrap();
2933
    assert!(!repo.snapshot("status").unwrap().changed);
2934
    // Now the file cannot be read at all; the snapshot succeeds without it.
2935
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
2936
    let snap = repo.snapshot("status").unwrap();
2937
    assert!(
2938
        !snap.changed && snap.statuses.is_empty(),
2939
        "{:?}",
2940
        snap.statuses
2941
    );
2942
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
2943
    // A real change (new mtime, new content) is seen and committed correctly.
2944
    let mut big2 = big.clone();
2945
    big2[10] ^= 0xff;
2946
    write(root, "big.bin", &big2);
2947
    let snap = repo.snapshot("status").unwrap();
2948
    assert_eq!(
2949
        snap.statuses
2950
            .iter()
2951
            .map(|s| (s.path.as_str(), s.status))
2952
            .collect::<Vec<_>>(),
2953
        vec![("big.bin", ChangeStatus::Modified)]
2954
    );
2955
    let h2 = repo.commit("edit", &[]).unwrap();
2956
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
2957
    assert_eq!(
2958
        files["big.bin"].content,
2959
        FileContent::Opaque {
2960
            blobs: vec![Repo::blob_ref(&big2)]
2961
        }
2962
    );
2963
    // Checkout writes a manifest with blobs too, so the next status is cached.
2964
    repo.checkout(&[h1], false, "checkout").unwrap();
2965
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
2966
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
2967
    assert!(!repo.snapshot("status").unwrap().changed);
2968
}
2969
2970
#[test]
2971
fn status_json_lists_conflicts_with_contributors() {
2972
    hermetic();
2973
    let dir = tempfile::tempdir().unwrap();
2974
    let root = dir.path();
2975
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2976
    write(root, "a.txt", b"one\n");
2977
    let h1 = repo.commit("base", &[]).unwrap();
2978
    write(root, "a.txt", b"one\nleft\n");
2979
    let ha = repo.commit("left", &[]).unwrap();
2980
    repo.checkout(&[h1], true, "checkout").unwrap();
2981
    write(root, "a.txt", b"one\nright\n");
2982
    let hb = repo.commit("right", &[]).unwrap();
2983
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
2984
    let snap = repo.snapshot("status").unwrap();
2985
    assert!(snap.base_snapshot.is_conflicted());
2986
    let json = repo.status_json(&snap).unwrap();
2987
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
2988
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
2989
    assert!(json.contains("\"conflicted\":true"), "{json}");
2990
    assert!(
2991
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
2992
        "{json}"
2993
    );
2994
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
2995
    assert!(json.contains("\"resolved\":false"), "{json}");
2996
    assert!(json.starts_with('{') && json.ends_with('}'));
2997
    // Resolve and the report says so; a clean copy has no conflicts.
2998
    write(root, "a.txt", b"one\nleft\nright\n");
2999
    let snap = repo.snapshot("status").unwrap();
3000
    let json = repo.status_json(&snap).unwrap();
3001
    assert!(json.contains("\"resolved\":true"), "{json}");
3002
    repo.commit("resolve", &[]).unwrap();
3003
    let snap = repo.snapshot("status").unwrap();
3004
    let json = repo.status_json(&snap).unwrap();
3005
    assert!(
3006
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3007
        "{json}"
3008
    );
3009
}
3010
3011
#[test]
3012
fn ignore_rules_do_not_untrack_files() {
3013
    hermetic();
3014
    let dir = tempfile::tempdir().unwrap();
3015
    let root = dir.path();
3016
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3017
    write(root, "src.c", b"int x;\n");
3018
    write(root, "build/out.o", b"\0obj");
3019
    write(root, "sub/keep.log", b"keep\n");
3020
    write(root, "sub/junk.log", b"junk\n");
3021
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3022
    let snap = repo.snapshot("status").unwrap();
3023
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3024
    assert_eq!(
3025
        added,
3026
        vec![".oxyignore", "src.c", "sub/keep.log"],
3027
        "anchored, glob, and negated rules"
3028
    );
3029
    let h1 = repo.commit("base", &[]).unwrap();
3030
    // Ignoring a tracked file changes nothing about it.
3031
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3032
    let snap = repo.snapshot("status").unwrap();
3033
    assert_eq!(
3034
        snap.statuses
3035
            .iter()
3036
            .map(|s| s.path.as_str())
3037
            .collect::<Vec<_>>(),
3038
        vec![".oxyignore"]
3039
    );
3040
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3041
    assert!(repo
3042
        .load_state(&[h2])
3043
        .unwrap()
3044
        .materialize()
3045
        .files
3046
        .contains_key("src.c"));
3047
    // Its edits are still seen, by status and by the prompt.
3048
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3049
    write(root, "src.c", b"int x, y;\n");
3050
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3051
    let snap = repo.snapshot("status").unwrap();
3052
    assert_eq!(
3053
        snap.statuses
3054
            .iter()
3055
            .map(|s| (s.path.as_str(), s.status))
3056
            .collect::<Vec<_>>(),
3057
        vec![("src.c", ChangeStatus::Modified)]
3058
    );
3059
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3060
    assert!(
3061
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3062
    );
3063
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3064
    fs::remove_file(root.join("src.c")).unwrap();
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::Removed)]
3072
    );
3073
    repo.checkout(&[h3], true, "checkout").unwrap();
3074
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3075
    assert!(!repo.snapshot("status").unwrap().changed);
3076
    let _ = h1;
3077
}
3078
3079
#[test]
3080
fn split_works_on_non_heads_by_node() {
3081
    hermetic();
3082
    let dir = tempfile::tempdir().unwrap();
3083
    let root = dir.path();
3084
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3085
    write(root, "a.txt", b"one\n");
3086
    write(root, "junk/x.lock", b"lock\n");
3087
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3088
    write(root, "a.txt", b"one\ntwo\n");
3089
    let h2 = repo.commit("more work", &[]).unwrap();
3090
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3091
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3092
    // h1 is not a head: split it by node.
3093
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3094
    assert_ne!(h1b, h1);
3095
    assert_eq!(
3096
        repo.store().get_change(&h1b).unwrap().change_id,
3097
        id1,
3098
        "the rest keeps the ChangeId"
3099
    );
3100
    let junk = repo.store().get_change(&hj).unwrap();
3101
    assert!(junk.tree_ops.iter().all(
3102
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3103
    ));
3104
    let heads = repo.bookmark_heads().unwrap();
3105
    assert!(
3106
        heads.contains(&hj),
3107
        "the split-off part is a head of its own"
3108
    );
3109
    let snap = repo.load_state(&heads).unwrap().materialize();
3110
    assert!(
3111
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3112
        "the dependent was rewritten onto the new hash"
3113
    );
3114
    assert!(snap.files.contains_key("junk/x.lock"));
3115
    let h2b = heads
3116
        .iter()
3117
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3118
        .copied()
3119
        .unwrap();
3120
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3121
    assert!(!repo.snapshot("status").unwrap().changed);
3122
    // Abandoning the split-off head removes the junk from history.
3123
    repo.abandon(&hj).unwrap();
3124
    let heads = repo.bookmark_heads().unwrap();
3125
    let snap = repo.load_state(&heads).unwrap().materialize();
3126
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3127
    assert!(snap.files.contains_key("a.txt"));
3128
    // A dependent that touches the split-off paths blocks the split.
3129
    write(root, "junk/y.lock", b"y\n");
3130
    let hb = repo.commit("junk base", &[]).unwrap();
3131
    write(root, "junk/y.lock", b"yy\n");
3132
    write(root, "b.txt", b"b\n");
3133
    repo.commit("touches junk", &[]).unwrap();
3134
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3135
    assert!(err.contains("depends on the split-off paths"), "{err}");
3136
}
3137
3138
#[test]
3139
fn bookmarks_switch_merge_and_push() {
3140
    hermetic();
3141
    let dir = tempfile::tempdir().unwrap();
3142
    let root = dir.path();
3143
    let origin = Repo::init(&root.join("origin")).unwrap();
3144
    let url = root.join("origin").to_string_lossy().to_string();
3145
    let mut repo = Repo::clone(&url, &root.join("r"))
3146
        .unwrap()
3147
        .with_home(root.join("home"));
3148
    let r = root.join("r");
3149
    write(&r, "a.txt", b"a\n");
3150
    let h_a = repo.commit("a", &[]).unwrap();
3151
    assert!(repo.push("origin", false).unwrap()[0].ok);
3152
3153
    // A bookmark at the working copy's base, then work on it.
3154
    assert!(repo.bookmark_create("bad name..", None).is_err());
3155
    assert!(repo.bookmark_create("-x", None).is_err());
3156
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3157
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3158
    repo.bookmark_switch("feature", false).unwrap();
3159
    assert_eq!(repo.config.bookmark, "feature");
3160
    write(&r, "a.txt", b"a\nb\n");
3161
    write(&r, "b.txt", b"b\n");
3162
    let h_b = repo.commit("b on feature", &[]).unwrap();
3163
    assert_eq!(
3164
        repo.bookmark_heads().unwrap(),
3165
        vec![h_b],
3166
        "b edits a.txt, so it depends on a"
3167
    );
3168
    assert_eq!(
3169
        repo.resolve_heads("main").unwrap(),
3170
        vec![h_a],
3171
        "main is untouched"
3172
    );
3173
    assert_eq!(
3174
        repo.resolve_change("feature").unwrap(),
3175
        h_b,
3176
        "a one-head bookmark names its change"
3177
    );
3178
    // Reopening keeps the workspace's bookmark.
3179
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3180
    assert_eq!(reopened.config.bookmark, "feature");
3181
    // Back to main: b.txt goes away; work there.
3182
    repo.bookmark_switch("main", false).unwrap();
3183
    assert!(!r.join("b.txt").exists());
3184
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3185
    write(&r, "c.txt", b"c\n");
3186
    let h_c = repo.commit("c on main", &[]).unwrap();
3187
    let list = repo.bookmarks().unwrap();
3188
    assert_eq!(
3189
        list.iter()
3190
            .map(|b| (b.name.as_str(), b.current))
3191
            .collect::<Vec<_>>(),
3192
        vec![("feature", false), ("main", true)]
3193
    );
3194
    assert_eq!(
3195
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3196
        Some(1),
3197
        "c is not on origin yet"
3198
    );
3199
    // Merge feature into main: the union, both heads, no merge change.
3200
    let m = repo.merge("feature").unwrap();
3201
    assert!(m.changed && m.checked_out);
3202
    let mut want = vec![h_b, h_c];
3203
    want.sort();
3204
    assert_eq!(m.heads, want);
3205
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3206
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3207
    assert!(repo.merge("main").is_err());
3208
    // The other bookmark can be pushed by name and appears at origin.
3209
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3210
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3211
    assert!(repo.push("origin", false).unwrap()[0].ok);
3212
    assert_eq!(
3213
        repo.bookmarks()
3214
            .unwrap()
3215
            .iter()
3216
            .find(|b| b.name == "main")
3217
            .unwrap()
3218
            .ahead,
3219
        Some(0)
3220
    );
3221
    // A second workspace inherits the current bookmark and can switch independently.
3222
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3223
    assert_eq!(ws.config.bookmark, "main");
3224
    let mut ws = ws;
3225
    ws.bookmark_switch("feature", false).unwrap();
3226
    assert_eq!(
3227
        Repo::open(&r).unwrap().config.bookmark,
3228
        "main",
3229
        "the first workspace is unaffected"
3230
    );
3231
    assert!(
3232
        repo.bookmark_delete("feature").is_err(),
3233
        "current bookmark of another workspace"
3234
    );
3235
    ws.bookmark_switch("main", false).unwrap();
3236
    // Set and delete.
3237
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3238
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3239
    repo.bookmark_delete("feature").unwrap();
3240
    assert!(repo.resolve_heads("feature").is_err());
3241
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3242
    assert!(
3243
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3244
        "changes of a deleted bookmark remain"
3245
    );
3246
}
3247
3248
#[test]
3249
fn oxygen_subrepos_pin_follow_and_update() {
3250
    hermetic();
3251
    let dir = tempfile::tempdir().unwrap();
3252
    let root = dir.path();
3253
    // A library repository with two commits, and a bare-ish origin for it.
3254
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3255
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3256
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3257
        .unwrap()
3258
        .with_home(root.join("home"));
3259
    write(&root.join("lib"), "lib.txt", b"v1\n");
3260
    let l1 = lib.commit("lib v1", &[]).unwrap();
3261
    assert!(lib.push("origin", false).unwrap()[0].ok);
3262
    let _ = lib_origin;
3263
3264
    // The application (a clone of its own origin) adds it as a subrepo.
3265
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3266
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3267
    let _ = app_origin;
3268
    let app_dir = root.join("app");
3269
    let app = Repo::clone(&app_url, &app_dir)
3270
        .unwrap()
3271
        .with_home(root.join("home"));
3272
    write(&app_dir, "main.txt", b"app\n");
3273
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3274
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3275
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3276
    let snap = app.snapshot("status").unwrap();
3277
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3278
    assert_eq!(
3279
        paths,
3280
        vec![".oxymodules", "libs/lib", "main.txt"],
3281
        "the nested files are not walked"
3282
    );
3283
    let a1 = app.commit("app with lib", &[]).unwrap();
3284
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3285
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3286
    assert!(!files.contains_key("libs/lib/lib.txt"));
3287
    assert!(!app.snapshot("status").unwrap().changed);
3288
    let subs = app.subrepos().unwrap();
3289
    assert_eq!(subs.len(), 1);
3290
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3291
3292
    // Advance the nested repository: the parent sees a modified pin.
3293
    let nested = Repo::open(&app_dir.join("libs/lib"))
3294
        .unwrap()
3295
        .with_home(root.join("home"));
3296
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3297
    let l2 = nested.commit("lib v2", &[]).unwrap();
3298
    assert!(nested.push("origin", false).unwrap()[0].ok);
3299
    let snap = app.snapshot("status").unwrap();
3300
    assert_eq!(
3301
        snap.statuses
3302
            .iter()
3303
            .map(|s| (s.path.as_str(), s.status))
3304
            .collect::<Vec<_>>(),
3305
        vec![("libs/lib", ChangeStatus::Modified)]
3306
    );
3307
    let a2 = app.commit("bump lib", &[]).unwrap();
3308
    // Checking out the older app state moves the nested repository back.
3309
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3310
    assert!(r.notes.is_empty(), "{:?}", r.notes);
3311
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3312
    assert_eq!(
3313
        Repo::open(&app_dir.join("libs/lib"))
3314
            .unwrap()
3315
            .bookmark_heads()
3316
            .unwrap(),
3317
        vec![l1]
3318
    );
3319
    assert!(!app.snapshot("status").unwrap().changed);
3320
    // A dirty nested repository is left alone and reported.
3321
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3322
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3323
    assert!(
3324
        r.notes.iter().any(|n| n.contains("uncommitted")),
3325
        "{:?}",
3326
        r.notes
3327
    );
3328
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3329
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3330
    let r = app.submodule_update(false, &[]).unwrap();
3331
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3332
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3333
    let _ = l2;
3334
3335
    // A fresh clone of the app has the pin but no nested repository until update --init.
3336
    assert!(app.push("origin", false).unwrap()[0].ok);
3337
    let clone_dir = root.join("app-clone");
3338
    let clone = Repo::clone(&app_url, &clone_dir)
3339
        .unwrap()
3340
        .with_home(root.join("home"));
3341
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3342
    assert_eq!(
3343
        clone.submodule_update(false, &[]).unwrap(),
3344
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3345
    );
3346
    assert_eq!(
3347
        clone.submodule_update(true, &[]).unwrap(),
3348
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3349
    );
3350
    assert_eq!(
3351
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3352
        b"v2\n"
3353
    );
3354
    assert!(!clone.snapshot("status").unwrap().changed);
3355
    // Removing the subrepo leaves the directory and drops the node.
3356
    clone.submodule_remove("libs/lib").unwrap();
3357
    let snap = clone.snapshot("status").unwrap();
3358
    assert!(
3359
        snap.statuses
3360
            .iter()
3361
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3362
        "{:?}",
3363
        snap.statuses
3364
    );
3365
    let c = clone.commit("drop lib", &[]).unwrap();
3366
    assert!(!clone
3367
        .load_state(&[c])
3368
        .unwrap()
3369
        .materialize()
3370
        .files
3371
        .contains_key("libs/lib"));
3372
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3373
    assert!(
3374
        !clone.snapshot("status").unwrap().changed,
3375
        "an unregistered nested repository is ignored"
3376
    );
3377
}
3378
3379
#[test]
3380
fn git_submodules_import_and_export_as_gitlinks() {
3381
    hermetic();
3382
    if std::process::Command::new("git")
3383
        .arg("--version")
3384
        .output()
3385
        .is_err()
3386
    {
3387
        eprintln!("git not installed; skipping");
3388
        return;
3389
    }
3390
    let dir = tempfile::tempdir().unwrap();
3391
    let root = dir.path();
3392
    let git_in = |d: &Path, args: &[&str]| -> String {
3393
        let out = std::process::Command::new("git")
3394
            .arg("-C")
3395
            .arg(d)
3396
            .args([
3397
                "-c",
3398
                "user.name=Grace",
3399
                "-c",
3400
                "[email protected]",
3401
                "-c",
3402
                "commit.gpgsign=false",
3403
                "-c",
3404
                "protocol.file.allow=always",
3405
            ])
3406
            .args(args)
3407
            .output()
3408
            .unwrap();
3409
        assert!(
3410
            out.status.success(),
3411
            "git {args:?}: {}",
3412
            String::from_utf8_lossy(&out.stderr)
3413
        );
3414
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3415
    };
3416
    let sub = root.join("sub");
3417
    fs::create_dir_all(&sub).unwrap();
3418
    git_in(&sub, &["init", "-q", "-b", "main"]);
3419
    write(&sub, "s.txt", b"sub\n");
3420
    git_in(&sub, &["add", "."]);
3421
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3422
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3423
    let g = root.join("main.git");
3424
    fs::create_dir_all(&g).unwrap();
3425
    git_in(&g, &["init", "-q", "-b", "main"]);
3426
    write(&g, "README.md", b"# app\n");
3427
    git_in(&g, &["add", "."]);
3428
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3429
    git_in(
3430
        &g,
3431
        &[
3432
            "submodule",
3433
            "add",
3434
            "-q",
3435
            sub.to_str().unwrap(),
3436
            "vendor/sub",
3437
        ],
3438
    );
3439
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3440
3441
    let dest = root.join("oxy");
3442
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3443
    let rep = repo.import_git(&g, "main").unwrap();
3444
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3445
    let files = repo
3446
        .load_state(&repo.bookmark_heads().unwrap())
3447
        .unwrap()
3448
        .materialize()
3449
        .files;
3450
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3451
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3452
        panic!()
3453
    };
3454
    assert_eq!(
3455
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3456
        crate::subrepo::Pin::Git {
3457
            sha: sub_sha.clone(),
3458
            branch: "HEAD".into()
3459
        }
3460
    );
3461
    let modules =
3462
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3463
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3464
    assert!(modules.entries["vendor/sub"].git);
3465
    assert!(
3466
        files.contains_key(".gitmodules"),
3467
        "the Git file is kept for round trips"
3468
    );
3469
    assert!(
3470
        !dest.join("vendor/sub/.git").exists(),
3471
        "not cloned until update --init"
3472
    );
3473
    assert!(!repo.snapshot("status").unwrap().changed);
3474
    // update --init clones it at the pinned commit; status is unchanged.
3475
    assert_eq!(
3476
        repo.submodule_update(true, &[]).unwrap(),
3477
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3478
    );
3479
    assert_eq!(
3480
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3481
        sub_sha
3482
    );
3483
    assert!(!repo.snapshot("status").unwrap().changed);
3484
    // Export writes the gitlink and .gitmodules back.
3485
    let mirror = root.join("mirror.git");
3486
    let rep = repo.git_export(&mirror).unwrap();
3487
    assert_eq!(rep.skipped_subrepos, 0);
3488
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3489
    assert!(
3490
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3491
        "{ls}"
3492
    );
3493
    assert_eq!(
3494
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3495
        ".gitmodules\nREADME.md\nvendor"
3496
    );
3497
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3498
    assert_eq!(
3499
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3500
        orig_tree,
3501
        "tree round trip"
3502
    );
3503
}
3504
3505
#[test]
3506
fn partial_commits_by_path_and_by_hunk() {
3507
    hermetic();
3508
    let dir = tempfile::tempdir().unwrap();
3509
    let root = dir.path();
3510
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3511
    write(root, "a.txt", b"1\n2\n3\n");
3512
    write(root, "b.txt", b"b\n");
3513
    let h0 = repo.commit("base", &[]).unwrap();
3514
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3515
    write(root, "b.txt", b"b\nbb\n");
3516
    write(root, "c.txt", b"c\n");
3517
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3518
    let h1 = repo
3519
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3520
        .unwrap();
3521
    let c1 = repo.store().get_change(&h1).unwrap();
3522
    assert!(
3523
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3524
        "{:?}",
3525
        c1.tree_ops
3526
    );
3527
    assert_eq!(c1.deps, vec![h0]);
3528
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3529
    assert!(
3530
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3531
    );
3532
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3533
    assert!(!files.contains_key("c.txt"));
3534
    let snap = repo.snapshot("status").unwrap();
3535
    assert_eq!(
3536
        snap.statuses
3537
            .iter()
3538
            .map(|s| (s.path.as_str(), s.status))
3539
            .collect::<Vec<_>>(),
3540
        vec![
3541
            ("b.txt", ChangeStatus::Modified),
3542
            ("c.txt", ChangeStatus::Added)
3543
        ]
3544
    );
3545
    assert_eq!(
3546
        fs::read(root.join("b.txt")).unwrap(),
3547
        b"b\nbb\n",
3548
        "disk untouched"
3549
    );
3550
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3551
    let (_, hunks) = repo.hunks().unwrap();
3552
    let b_hunk = hunks
3553
        .iter()
3554
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3555
        .unwrap()
3556
        .index;
3557
    let h2 = repo
3558
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3559
        .unwrap();
3560
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3561
    assert!(
3562
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3563
    );
3564
    assert!(!files.contains_key("c.txt"));
3565
    let snap = repo.snapshot("status").unwrap();
3566
    assert_eq!(
3567
        snap.statuses
3568
            .iter()
3569
            .map(|s| s.path.as_str())
3570
            .collect::<Vec<_>>(),
3571
        vec!["c.txt"]
3572
    );
3573
    // Choosing only the content hunk of a file in a new directory pulls in
3574
    // the directory and file additions it needs.
3575
    write(root, "d/e.txt", b"e\n");
3576
    let (_, hunks) = repo.hunks().unwrap();
3577
    let e_insert = hunks
3578
        .iter()
3579
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3580
        .unwrap()
3581
        .index;
3582
    let h3 = repo
3583
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3584
        .unwrap();
3585
    let c3 = repo.store().get_change(&h3).unwrap();
3586
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3587
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3588
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3589
    // Choosing a new file's addition hunk brings its content along.
3590
    write(root, "f/g.txt", b"g\n");
3591
    let (_, hunks) = repo.hunks().unwrap();
3592
    let g_add = hunks
3593
        .iter()
3594
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3595
        .unwrap()
3596
        .index;
3597
    let h4 = repo
3598
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3599
        .unwrap();
3600
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
3601
    assert!(
3602
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3603
    );
3604
    assert!(!repo
3605
        .snapshot("status")
3606
        .unwrap()
3607
        .statuses
3608
        .iter()
3609
        .any(|s| s.path == "f/g.txt"));
3610
    // Everything left commits normally; the working copy is then clean.
3611
    repo.commit("the rest", &[]).unwrap();
3612
    assert!(!repo.snapshot("status").unwrap().changed);
3613
    let files = repo
3614
        .load_state(&repo.bookmark_heads().unwrap())
3615
        .unwrap()
3616
        .materialize()
3617
        .files;
3618
    assert!(files.contains_key("c.txt"));
3619
}
3620
3621
#[test]
3622
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3623
    hermetic();
3624
    let dir = tempfile::tempdir().unwrap();
3625
    let root = dir.path();
3626
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3627
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3628
        .unwrap();
3629
    write(root, "a.txt", b"one\n");
3630
    let h1 = repo.commit("first", &[]).unwrap();
3631
    write(root, "a.txt", b"one\ntwo\n");
3632
    let h2 = repo.commit("second", &[]).unwrap();
3633
    let b = repo.blame("a.txt").unwrap();
3634
    assert_eq!(
3635
        b.iter()
3636
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3637
            .collect::<Vec<_>>(),
3638
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3639
    );
3640
    assert!(b.iter().all(|l| l.author == "Ada"));
3641
    assert_eq!(
3642
        b[0].change_id,
3643
        repo.store().get_change(&h1).unwrap().change_id
3644
    );
3645
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3646
    repo.commit("rename", &[]).unwrap();
3647
    let b = repo.blame("b.txt").unwrap();
3648
    assert_eq!(
3649
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3650
        vec![h1, h2],
3651
        "the node survives the rename"
3652
    );
3653
    assert!(repo.blame("a.txt").is_err());
3654
}
3655
3656
#[test]
3657
fn bisect_finds_the_first_bad_change() {
3658
    hermetic();
3659
    let dir = tempfile::tempdir().unwrap();
3660
    let root = dir.path();
3661
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3662
    let mut content = String::new();
3663
    let mut hashes = Vec::new();
3664
    for i in 1..=8 {
3665
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3666
        write(root, "f.txt", content.as_bytes());
3667
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3668
    }
3669
    // Each step appends after the previous line, so the chain is linear.
3670
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3671
    repo.bisect_start().unwrap();
3672
    assert!(matches!(
3673
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3674
        BisectStep::NeedMarks { good: 1, bad: 0 }
3675
    ));
3676
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3677
    assert!(
3678
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3679
        "{step:?}"
3680
    );
3681
    // Automated: bad when the bug line is present.
3682
    let step = repo
3683
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3684
        .unwrap();
3685
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3686
    assert_eq!(
3687
        repo.bisect_status().unwrap(),
3688
        Some(BisectStep::Found { culprit: hashes[4] })
3689
    );
3690
    repo.bisect_reset().unwrap();
3691
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3692
    assert!(repo.bisect_status().unwrap().is_none());
3693
    assert!(!repo.snapshot("status").unwrap().changed);
3694
    // Manual marks and a skip.
3695
    repo.bisect_start().unwrap();
3696
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3697
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3698
    let mut skipped_once = false;
3699
    let mut guard = 0;
3700
    while let BisectStep::Testing { .. } = step {
3701
        guard += 1;
3702
        assert!(guard < 20);
3703
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3704
        if !skipped_once && text.contains("line 6") {
3705
            // An untestable state away from the boundary: the search routes around it.
3706
            skipped_once = true;
3707
            step = repo.bisect_mark(None, &[]).unwrap();
3708
            continue;
3709
        }
3710
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3711
    }
3712
    assert!(skipped_once);
3713
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3714
    repo.bisect_reset().unwrap();
3715
    // Skipping the culprit itself leaves it among the candidates reported.
3716
    repo.bisect_start().unwrap();
3717
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3718
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3719
    let mut guard = 0;
3720
    while let BisectStep::Testing { heads, .. } = &step {
3721
        guard += 1;
3722
        assert!(guard < 20);
3723
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3724
        let is_culprit_state =
3725
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3726
        step = if is_culprit_state {
3727
            repo.bisect_mark(None, &[]).unwrap()
3728
        } else {
3729
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3730
        };
3731
    }
3732
    match step {
3733
        BisectStep::Inconclusive { candidates } => assert!(
3734
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3735
            "{candidates:?}"
3736
        ),
3737
        other => panic!("{other:?}"),
3738
    }
3739
    repo.bisect_reset().unwrap();
3740
}
3741
3742
#[test]
3743
fn squash_folds_a_change_into_its_dependency() {
3744
    hermetic();
3745
    let dir = tempfile::tempdir().unwrap();
3746
    let root = dir.path();
3747
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3748
    write(root, "a.txt", b"1\n");
3749
    let a = repo.commit("A", &[]).unwrap();
3750
    write(root, "a.txt", b"1\n2\n");
3751
    let c = repo.commit("C", &[]).unwrap();
3752
    write(root, "a.txt", b"1\n2\n3\n");
3753
    let e = repo.commit("E", &[]).unwrap();
3754
    write(root, "b.txt", b"b\n");
3755
    let b = repo.commit("B", &[]).unwrap();
3756
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3757
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3758
    // E depends on C which A lacks: refused, naming it.
3759
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3760
    assert!(err.contains(&c.short(12)), "{err}");
3761
    // C into A: A' has both, C is gone, E follows and still reads the same.
3762
    let a2 = repo.squash(&c, &a).unwrap();
3763
    let a2c = repo.store().get_change(&a2).unwrap();
3764
    assert_eq!(a2c.change_id, id_a);
3765
    assert!(a2c.deps.is_empty());
3766
    let heads = repo.bookmark_heads().unwrap();
3767
    let st = repo.load_state(&heads).unwrap();
3768
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
3769
    let e2 = st
3770
        .changes()
3771
        .find(|(_, m)| m.change_id == id_e)
3772
        .map(|(h, _)| *h)
3773
        .unwrap();
3774
    assert_eq!(
3775
        repo.store().get_change(&e2).unwrap().deps,
3776
        vec![a2],
3777
        "E now depends on A' alone"
3778
    );
3779
    let files = st.materialize().files;
3780
    assert!(
3781
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3782
    );
3783
    assert!(files.contains_key("b.txt"));
3784
    assert!(st.contains(&b));
3785
    assert!(!repo.snapshot("status").unwrap().changed);
3786
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3787
    // Undo restores the three original changes.
3788
    repo.undo().unwrap();
3789
    repo.undo().unwrap();
3790
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3791
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3792
}
3793
3794
#[test]
3795
fn rebase_re_expresses_a_change_against_another_base() {
3796
    hermetic();
3797
    let dir = tempfile::tempdir().unwrap();
3798
    let root = dir.path();
3799
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3800
    write(root, "a.txt", b"1\n2\n");
3801
    let a = repo.commit("A", &[]).unwrap();
3802
    write(root, "a.txt", b"1\n2\n3\n");
3803
    let c = repo.commit("C: append 3", &[]).unwrap();
3804
    write(root, "a.txt", b"1\n2\n3\n4\n");
3805
    let e = repo.commit("E: append 4", &[]).unwrap();
3806
    // A different base: A plus a change that prepends a line.
3807
    repo.checkout(&[a], true, "checkout").unwrap();
3808
    write(root, "a.txt", b"0\n1\n2\n");
3809
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3810
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3811
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3812
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3813
    let c2 = repo.rebase(&c, &[d]).unwrap();
3814
    let c2c = repo.store().get_change(&c2).unwrap();
3815
    assert_eq!(c2c.change_id, id_c);
3816
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3817
    let heads = repo.bookmark_heads().unwrap();
3818
    let st = repo.load_state(&heads).unwrap();
3819
    assert!(!st.contains(&c) && st.contains(&d));
3820
    let e2 = st
3821
        .changes()
3822
        .find(|(_, m)| m.change_id == id_e)
3823
        .map(|(h, _)| *h)
3824
        .unwrap();
3825
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
3826
    assert!(
3827
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3828
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3829
    );
3830
    let files = st.materialize().files;
3831
    assert!(
3832
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3833
        "{:?}",
3834
        files["a.txt"].content
3835
    );
3836
    assert!(!files["a.txt"].is_conflicted());
3837
    // Rebasing onto a state that already contains the change is refused.
3838
    assert!(repo.rebase(&c2, &[c2]).is_err());
3839
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
3840
    assert!(
3841
        err.contains("lacks dependencies"),
3842
        "E needs C, which D's state does not have: {err}"
3843
    );
3844
}
3845
3846
#[test]
3847
fn unsigned_tags_keep_their_message() {
3848
    hermetic();
3849
    let dir = tempfile::tempdir().unwrap();
3850
    let root = dir.path();
3851
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3852
    write(root, "a.txt", b"a\n");
3853
    repo.commit("a", &[]).unwrap();
3854
    assert!(repo.secret_key().unwrap().is_none());
3855
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
3856
        .unwrap();
3857
    let tags = repo.tags().unwrap();
3858
    assert_eq!(
3859
        (
3860
            tags[0].name.as_str(),
3861
            tags[0].message.as_str(),
3862
            tags[0].signer.as_deref()
3863
        ),
3864
        ("v1", "first release", None)
3865
    );
3866
    assert!(
3867
        repo.tag_refs().unwrap()[0].attestation.is_none(),
3868
        "an unsigned attestation is not advertised"
3869
    );
3870
}