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