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