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