OXYGENHUB
# 2cd40ea1c04c oxygen / crates / oxy-core / src / repo / tests.rs
256.6 KiB · Rust · last changed Strata: S3, Google Cloud Storage and Azure Blob Storage stores 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
            lacks: 1,
438
        }
439
    );
440
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
441
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
442
    assert!(!root.join("bin.dat").exists());
443
    let (_, wc) = repo.working_copy().unwrap();
444
    assert_eq!(wc.deps, vec![h1]);
445
    assert!(
446
        !repo.snapshot("status").unwrap().changed,
447
        "checkout leaves a clean working copy"
448
    );
449
    // The bookmark still points at h2.
450
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
451
452
    // Dirty working copy refuses without --discard.
453
    write(root, "a.txt", b"dirty\n");
454
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
455
    let r = repo
456
        .checkout(&[h2], true, "oxy checkout --discard")
457
        .unwrap();
458
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
459
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
460
    assert!(!root.join("sub").exists(), "empty directories are pruned");
461
    assert_eq!(r.removed, 1);
462
    assert!(!repo.snapshot("status").unwrap().changed);
463
464
    // Refuses to write through a symlinked directory.
465
    #[cfg(unix)]
466
    {
467
        fs::remove_dir_all(root.join("sub")).ok();
468
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
469
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
470
    }
471
}
472
473
#[test]
474
fn large_files_are_chunked_and_read_back() {
475
    hermetic();
476
    let dir = tempfile::tempdir().unwrap();
477
    let repo = Repo::init(dir.path()).unwrap();
478
    let mut big = vec![0u8; 700 * 1024];
479
    for (i, b) in big.iter_mut().enumerate() {
480
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
481
    }
482
    let r = repo.store_blob(&big).unwrap();
483
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
484
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
485
    assert_eq!(repo.read_blob(&r).unwrap(), big);
486
    assert_eq!(Repo::blob_ref(&big), r);
487
}
488
489
#[test]
490
fn clone_push_pull_with_seals_and_attestations() {
491
    hermetic();
492
    let dir = tempfile::tempdir().unwrap();
493
    let root = dir.path();
494
    let origin_path = root.join("origin");
495
    let origin = Repo::init(&origin_path).unwrap();
496
    let origin_url = origin_path.to_string_lossy().to_string();
497
498
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
499
    let mut a = Repo::clone(&origin_url, &root.join("a"))
500
        .unwrap()
501
        .with_home(root.join("home-a"));
502
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
503
    let (key_a, _) = a
504
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
505
        .unwrap();
506
    write(&root.join("a"), "f.txt", b"a\n");
507
    let h1 = a.commit("first", &[]).unwrap();
508
    let results = a.push("origin", false).unwrap();
509
    assert!(results[0].ok, "{}", results[0].reason);
510
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
511
    // The change was sealed at push and the reference attested.
512
    assert!(
513
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
514
    );
515
    assert_eq!(
516
        origin.verify_change(&h1).unwrap(),
517
        SignatureStatus::Unsigned
518
    );
519
    let serial_of = |att: &SignedAttest| match att.attest.body {
520
        AttestBody::Ref { serial, .. } => serial,
521
        _ => unreachable!(),
522
    };
523
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
524
    // A bookmark new to the remote starts at the clock (past any deleted
525
    // namesake's serial); later updates count up from there.
526
    let first = serial_of(&att);
527
    assert!(first > 1_000_000_000_000, "{first}");
528
    let again = a.push("origin", false).unwrap();
529
    assert!(again[0].ok && again[0].reason.contains("up to date"));
530
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
531
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
532
533
    // B clones and sees the file and the seal.
534
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
535
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
536
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
537
    assert!(matches!(
538
        b.authenticate_change(&h1).unwrap(),
539
        SignatureStatus::Valid { sealed: true, .. }
540
    ));
541
542
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
543
    write(&root.join("b"), "f.txt", b"a\nb\n");
544
    let h2 = b.commit("second", &[]).unwrap();
545
    assert!(b.push("origin", false).unwrap()[0].ok);
546
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
547
548
    // A commits an independent change; push is refused until A pulls.
549
    write(&root.join("a"), "g.txt", b"g\n");
550
    let h3 = a.commit("third", &[]).unwrap();
551
    assert!(a.push("origin", false).is_err());
552
    let pr = a.pull("origin").unwrap();
553
    assert!(pr.changed && pr.checked_out);
554
    let mut want = vec![h2, h3];
555
    want.sort();
556
    assert_eq!(pr.heads, want);
557
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
558
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
559
    let results = a.push("origin", false).unwrap();
560
    assert!(results[0].ok, "{}", results[0].reason);
561
    let mut origin_heads = origin.bookmark_heads().unwrap();
562
    origin_heads.sort();
563
    assert_eq!(origin_heads, want);
564
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
565
    assert_eq!(serial_of(&att), first + 1);
566
567
    // B pulls and ends up identical.
568
    let pr = b.pull("origin").unwrap();
569
    assert_eq!(pr.heads, want);
570
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
571
    assert!(!b.snapshot("status").unwrap().changed);
572
573
    // Concurrent edits of the same line: the union is a reified conflict.
574
    write(&root.join("a"), "f.txt", b"a\nA\n");
575
    a.commit("a-edit", &[]).unwrap();
576
    a.push("origin", false).unwrap();
577
    write(&root.join("b"), "f.txt", b"a\nB\n");
578
    b.commit("b-edit", &[]).unwrap();
579
    let pr = b.pull("origin").unwrap();
580
    assert!(pr.changed && pr.checked_out);
581
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
582
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
583
    write(&root.join("b"), "f.txt", b"a\nAB\n");
584
    let hr = b.commit("resolve", &[]).unwrap();
585
    assert_eq!(
586
        b.store().get_change(&hr).unwrap().kind,
587
        ChangeKind::Resolution
588
    );
589
    assert!(b.push("origin", false).unwrap()[0].ok);
590
    a.pull("origin").unwrap();
591
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
592
    // The resolution depends on the conflicting edits, but nothing depends
593
    // on "third" (it only added g.txt), so it stays a head beside it.
594
    let mut want = vec![hr, h3];
595
    want.sort();
596
    assert_eq!(a.bookmark_heads().unwrap(), want);
597
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
598
}
599
600
#[test]
601
fn receive_push_rejects_bad_updates() {
602
    hermetic();
603
    let dir = tempfile::tempdir().unwrap();
604
    let root = dir.path();
605
    let origin = Repo::init(&root.join("origin")).unwrap();
606
    let url = root.join("origin").to_string_lossy().to_string();
607
    let mut a = Repo::clone(&url, &root.join("a"))
608
        .unwrap()
609
        .with_home(root.join("home"));
610
    let (key, _) = a
611
        .create_identity("Ada", "a@b", IdentityScope::Repo)
612
        .unwrap();
613
    write(&root.join("a"), "f.txt", b"x\n");
614
    let h1 = a.commit("one", &[]).unwrap();
615
    assert!(a.push("origin", false).unwrap()[0].ok);
616
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
617
    let s1 = origin
618
        .store()
619
        .put_state(&StateObject::new(vec![h1]))
620
        .unwrap();
621
622
    // Missing head.
623
    let ghost = origin
624
        .store()
625
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
626
        .unwrap();
627
    let r = origin
628
        .receive_push(
629
            Bundle::default(),
630
            vec![RefUpdate {
631
                name: "main".into(),
632
                old_state: s1,
633
                new_state: ghost,
634
                force: false,
635
                attestation: None,
636
            }],
637
            None,
638
            vec![],
639
        )
640
        .unwrap();
641
    assert!(
642
        !r[0].ok && r[0].reason.contains("missing"),
643
        "{}",
644
        r[0].reason
645
    );
646
647
    // Stale old_state.
648
    let r = origin
649
        .receive_push(
650
            Bundle::default(),
651
            vec![RefUpdate {
652
                name: "main".into(),
653
                old_state: empty,
654
                new_state: s1,
655
                force: false,
656
                attestation: None,
657
            }],
658
            None,
659
            vec![],
660
        )
661
        .unwrap();
662
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
663
664
    // Non-fast-forward without force is refused; with force it passes.
665
    let r = origin
666
        .receive_push(
667
            Bundle::default(),
668
            vec![RefUpdate {
669
                name: "main".into(),
670
                old_state: s1,
671
                new_state: empty,
672
                force: false,
673
                attestation: None,
674
            }],
675
            None,
676
            vec![],
677
        )
678
        .unwrap();
679
    assert!(
680
        !r[0].ok && r[0].reason.contains("fast-forward"),
681
        "{}",
682
        r[0].reason
683
    );
684
    let r = origin
685
        .receive_push(
686
            Bundle::default(),
687
            vec![RefUpdate {
688
                name: "main".into(),
689
                old_state: s1,
690
                new_state: empty,
691
                force: true,
692
                attestation: None,
693
            }],
694
            None,
695
            vec![],
696
        )
697
        .unwrap();
698
    assert!(r[0].ok);
699
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
700
701
    // Attestation with a stale serial is a rollback and is refused.
702
    let sa = a
703
        .sign_attest(&Attest {
704
            repo: a.id().unwrap(),
705
            hlc: Hlc::now(),
706
            body: AttestBody::Ref {
707
                name: "main".into(),
708
                old_state: empty,
709
                new_state: s1,
710
                serial: 1,
711
            },
712
        })
713
        .unwrap();
714
    let r = origin
715
        .receive_push(
716
            Bundle::default(),
717
            vec![RefUpdate {
718
                name: "main".into(),
719
                old_state: empty,
720
                new_state: s1,
721
                force: false,
722
                attestation: Some(sa.clone()),
723
            }],
724
            None,
725
            vec![],
726
        )
727
        .unwrap();
728
    assert!(
729
        !r[0].ok && r[0].reason.contains("serial"),
730
        "{}",
731
        r[0].reason
732
    );
733
    // An attestation for a different update is refused too.
734
    let sa2 = a
735
        .sign_attest(&Attest {
736
            repo: a.id().unwrap(),
737
            hlc: Hlc::now(),
738
            body: AttestBody::Ref {
739
                name: "main".into(),
740
                old_state: s1,
741
                new_state: empty,
742
                serial: 5,
743
            },
744
        })
745
        .unwrap();
746
    let r = origin
747
        .receive_push(
748
            Bundle::default(),
749
            vec![RefUpdate {
750
                name: "main".into(),
751
                old_state: empty,
752
                new_state: s1,
753
                force: false,
754
                attestation: Some(sa2),
755
            }],
756
            None,
757
            vec![],
758
        )
759
        .unwrap();
760
    assert!(
761
        !r[0].ok && r[0].reason.contains("describe"),
762
        "{}",
763
        r[0].reason
764
    );
765
    let _ = key;
766
}
767
768
#[test]
769
fn user_config_supplies_defaults_and_clones_sign() {
770
    hermetic();
771
    let dir = tempfile::tempdir().unwrap();
772
    let root = dir.path();
773
    let home = root.join("home");
774
    let origin = Repo::init(&root.join("origin")).unwrap();
775
    let url = root.join("origin").to_string_lossy().to_string();
776
777
    // Identity at user scope: the repository file stays free of author keys.
778
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
779
    let (key, _) = a
780
        .create_identity("Ada", "[email protected]", IdentityScope::User)
781
        .unwrap();
782
    assert!(!a.config.repo_layer().contains_key("author.key"));
783
    assert_eq!(a.config.author_key, Some(key));
784
    assert!(home.join("config.toml").exists());
785
    a.set_user_config("core.sign", "change").unwrap();
786
    assert!(a.config.sign_changes);
787
788
    // Repository settings override user settings and are the only ones saved.
789
    a.config.set("core.sign", "seal").unwrap();
790
    a.save_config().unwrap();
791
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
792
    assert!(!again.config.sign_changes);
793
    assert_eq!(again.config.author_key, Some(key));
794
    assert_eq!(
795
        read_config_file(&root.join("a/.oxy/config"))
796
            .unwrap()
797
            .get("core.sign")
798
            .map(String::as_str),
799
        Some("seal")
800
    );
801
802
    // A fresh clone made by this user signs with the user-level identity,
803
    // even though the clone's store has never seen the identity object.
804
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
805
    assert!(b.config.sign_changes);
806
    write(&root.join("b"), "f.txt", b"f\n");
807
    let h = b.commit("signed from a clone", &[]).unwrap();
808
    assert!(
809
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
810
    );
811
    assert!(b.push("origin", false).unwrap()[0].ok);
812
    assert!(matches!(
813
        origin.verify_change(&h).unwrap(),
814
        SignatureStatus::Valid { .. }
815
    ));
816
}
817
818
#[test]
819
fn format1_repositories_are_migrated_on_open() {
820
    hermetic();
821
    use crate::oplog::{Format1Op, Format1View};
822
    let dir = tempfile::tempdir().unwrap();
823
    let root = dir.path();
824
    let repo = Repo::init(root).unwrap();
825
    write(root, "a.txt", b"a\n");
826
    let h1 = repo.commit("one", &[]).unwrap();
827
    let (wc_hash, _) = repo.working_copy().unwrap();
828
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
829
    let mut v1 = Format1View::default();
830
    v1.bookmarks.insert("main".into(), vec![]);
831
    v1.workspaces.insert(repo.workspace(), wc_hash);
832
    let init = Format1Op {
833
        parents: vec![],
834
        hlc: Hlc::default(),
835
        command: "oxy init".into(),
836
        view: v1.clone(),
837
    };
838
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
839
    v1.bookmarks.insert("main".into(), vec![h1]);
840
    let commit = Format1Op {
841
        parents: vec![init_ref],
842
        hlc: Hlc::default(),
843
        command: "oxy commit".into(),
844
        view: v1,
845
    };
846
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
847
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
848
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
849
    drop(repo);
850
851
    let repo = Repo::open(root).unwrap();
852
    assert_eq!(
853
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
854
        FORMAT_LINE
855
    );
856
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
857
    let ops = repo.op_log().unwrap();
858
    assert_eq!(
859
        ops.iter()
860
            .map(|(_, o)| o.command.as_str())
861
            .collect::<Vec<_>>(),
862
        ["oxy commit", "oxy init"]
863
    );
864
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
865
    assert!(!repo.snapshot("status").unwrap().changed);
866
    // Reopening again is a no-op.
867
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
868
}
869
870
#[test]
871
fn undo_skips_snapshot_operations() {
872
    hermetic();
873
    let dir = tempfile::tempdir().unwrap();
874
    let root = dir.path();
875
    let repo = Repo::init(root).unwrap();
876
    write(root, "a.txt", b"a\n");
877
    let h1 = repo.commit("a", &[]).unwrap();
878
    // A later command snapshots new edits on top of the commit.
879
    write(root, "b.txt", b"b\n");
880
    let s = repo.snapshot("oxy status").unwrap();
881
    assert!(s.changed);
882
    assert!(repo.head_op().unwrap().1.is_snapshot());
883
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
884
    // Undo must undo the commit, not the snapshot.
885
    repo.undo().unwrap();
886
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
887
    let s = repo.snapshot("oxy status").unwrap();
888
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
889
    assert_eq!(
890
        paths,
891
        ["a.txt", "b.txt"],
892
        "both files are back in the working copy"
893
    );
894
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
895
    // Only snapshots remain above `init`, so there is nothing left to undo.
896
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
897
    assert!(repo.undo().is_err());
898
}
899
900
#[test]
901
fn independent_changes_commute_and_make_multiple_heads() {
902
    hermetic();
903
    let dir = tempfile::tempdir().unwrap();
904
    let root = dir.path();
905
    let repo = Repo::init(root).unwrap();
906
    write(root, "a.txt", b"a\n");
907
    let h1 = repo.commit("a", &[]).unwrap();
908
    write(root, "b.txt", b"b\n");
909
    let h2 = repo.commit("b", &[]).unwrap();
910
    let c2 = repo.store().get_change(&h2).unwrap();
911
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
912
    let mut heads = repo.bookmark_heads().unwrap();
913
    heads.sort();
914
    let mut want = vec![h1, h2];
915
    want.sort();
916
    assert_eq!(heads, want);
917
    // Editing a.txt depends on h1 only.
918
    write(root, "a.txt", b"a\na2\n");
919
    let h3 = repo.commit("a2", &[]).unwrap();
920
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
921
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
922
    assert_eq!(heads, [h2, h3].into_iter().collect());
923
    // Explicit dependency.
924
    write(root, "c.txt", b"c\n");
925
    let h4 = repo.commit("c", &[h2]).unwrap();
926
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
927
}
928
929
#[test]
930
fn mode_change_and_text_binary_switch() {
931
    hermetic();
932
    let dir = tempfile::tempdir().unwrap();
933
    let root = dir.path();
934
    let repo = Repo::init(root).unwrap();
935
    write(root, "run.sh", b"#!/bin/sh\n");
936
    repo.commit("add script", &[]).unwrap();
937
    #[cfg(unix)]
938
    {
939
        use std::os::unix::fs::PermissionsExt;
940
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
941
        let s = repo.snapshot("status").unwrap();
942
        assert_eq!(
943
            statuses(&s),
944
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
945
        );
946
        let h = repo.commit("exec", &[]).unwrap();
947
        let snap = repo.load_state(&[h]).unwrap().materialize();
948
        assert!(snap.files["run.sh"].mode.exec);
949
    }
950
    // Text → binary → text.
951
    write(root, "run.sh", b"\0binary");
952
    let h = repo.commit("binary", &[]).unwrap();
953
    let snap = repo.load_state(&[h]).unwrap().materialize();
954
    assert!(snap.files["run.sh"].mode.opaque);
955
    write(root, "run.sh", b"text again\n");
956
    let h = repo.commit("text", &[]).unwrap();
957
    let snap = repo.load_state(&[h]).unwrap().materialize();
958
    assert!(!snap.files["run.sh"].mode.opaque);
959
    assert!(
960
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
961
    );
962
    assert!(!snap.is_conflicted());
963
}
964
965
#[test]
966
fn trust_policy_governs_pushes_and_fetches() {
967
    hermetic();
968
    let dir = tempfile::tempdir().unwrap();
969
    let root = dir.path();
970
    let origin = Repo::init(&root.join("origin")).unwrap();
971
    let url = root.join("origin").to_string_lossy().to_string();
972
973
    // A is the root. Before the policy, an unsigned push from B is fine.
974
    let mut a = Repo::clone(&url, &root.join("a"))
975
        .unwrap()
976
        .with_home(root.join("home-a"));
977
    let (key_a, _) = a
978
        .create_identity("Ada", "[email protected]", IdentityScope::User)
979
        .unwrap();
980
    let mut b = Repo::clone(&url, &root.join("b"))
981
        .unwrap()
982
        .with_home(root.join("home-b"));
983
    write(&root.join("b"), "b.txt", b"b\n");
984
    b.commit("unsigned before policy", &[]).unwrap();
985
    assert!(b.push("origin", false).unwrap()[0].ok);
986
987
    // A creates the policy and pushes it; origin now enforces it.
988
    write(&root.join("a"), "a.txt", b"a\n");
989
    a.commit("a", &[]).unwrap();
990
    let sp = a.policy_init().unwrap();
991
    assert_eq!(sp.policy.serial, 1);
992
    a.pull("origin").unwrap();
993
    let results = a.push("origin", false).unwrap();
994
    assert!(results.iter().all(|r| r.ok), "{results:?}");
995
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
996
997
    // B pulls the policy. Without an identity B cannot push at all.
998
    b.pull("origin").unwrap();
999
    assert!(
1000
        b.current_policy().unwrap().is_some(),
1001
        "the policy arrived with the fetch"
1002
    );
1003
    assert!(b.push("origin", false).is_err());
1004
    // With an identity the policy does not list, the push is rejected by origin.
1005
    let (key_b, id_b) = b
1006
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1007
        .unwrap();
1008
    write(&root.join("b"), "b.txt", b"b2\n");
1009
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1010
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1011
    let r = b.push("origin", false).unwrap();
1012
    assert!(
1013
        !r[0].ok && r[0].reason.contains("may not update"),
1014
        "{:?}",
1015
        r
1016
    );
1017
1018
    // A grants B (identity handed over as a file) and publishes the policy.
1019
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1020
    assert_eq!(sp.policy.serial, 2);
1021
    let r = a.push("origin", false).unwrap();
1022
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1023
    // B must fetch the new policy before pushing.
1024
    assert!(b
1025
        .push("origin", false)
1026
        .unwrap_or_else(|e| vec![RefResult {
1027
            name: "main".into(),
1028
            ok: false,
1029
            reason: e.to_string()
1030
        }])
1031
        .iter()
1032
        .all(|x| !x.ok));
1033
    b.pull("origin").unwrap();
1034
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1035
    let r = b.push("origin", false).unwrap();
1036
    assert!(r[0].ok, "{:?}", r);
1037
    // Origin verified B's change under the policy.
1038
    let heads = origin.bookmark_heads().unwrap();
1039
    for h in &heads {
1040
        let c = origin.store().get_change(h).unwrap();
1041
        if c.author == key_b {
1042
            origin
1043
                .change_allowed(
1044
                    h,
1045
                    &origin.current_policy().unwrap().unwrap().1.policy,
1046
                    "main",
1047
                )
1048
                .unwrap();
1049
        }
1050
    }
1051
1052
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1053
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1054
    forged.serial = 3;
1055
    forged.roots = vec![key_b];
1056
    let fh = forged.hash();
1057
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1058
    let forged = SignedPolicy {
1059
        policy: forged,
1060
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1061
    };
1062
    let r = origin
1063
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1064
        .unwrap();
1065
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1066
    let stale = a.current_policy().unwrap().unwrap().1;
1067
    let mut old = stale.clone();
1068
    old.policy.serial = 1;
1069
    let r = origin
1070
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1071
        .unwrap();
1072
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1073
1074
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1075
    a.pull("origin").unwrap();
1076
    a.policy_revoke(&key_b).unwrap();
1077
    let r = a.push("origin", false).unwrap();
1078
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1079
    b.pull("origin").unwrap();
1080
    write(&root.join("b"), "b.txt", b"b3\n");
1081
    b.commit("b3", &[]).unwrap();
1082
    let r = b.push("origin", false).unwrap();
1083
    assert!(!r[0].ok, "{:?}", r);
1084
1085
    // A clone by a third party receives and verifies everything.
1086
    let c = Repo::clone(&url, &root.join("c"))
1087
        .unwrap()
1088
        .with_home(root.join("home-c"));
1089
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1090
    assert!(c
1091
        .current_policy()
1092
        .unwrap()
1093
        .unwrap()
1094
        .1
1095
        .policy
1096
        .roots
1097
        .contains(&key_a));
1098
    assert!(!c.snapshot("status").unwrap().changed);
1099
}
1100
1101
#[test]
1102
fn gc_packs_objects_and_history_still_works() {
1103
    hermetic();
1104
    let dir = tempfile::tempdir().unwrap();
1105
    let root = dir.path();
1106
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1107
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1108
        .unwrap();
1109
    repo.set_user_config("core.sign", "change").unwrap();
1110
    write(root, "a.txt", b"one\n");
1111
    let h1 = repo.commit("one", &[]).unwrap();
1112
    write(root, "a.txt", b"two\n");
1113
    write(root, "big.bin", &vec![0u8; 100_000]);
1114
    let h2 = repo.commit("two", &[]).unwrap();
1115
    // Several snapshots leave superseded working-copy versions behind.
1116
    for i in 0..5 {
1117
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1118
        repo.snapshot("status").unwrap();
1119
    }
1120
    write(root, "a.txt", b"two\n");
1121
    repo.snapshot("status").unwrap();
1122
    let before = repo.store().list().unwrap();
1123
    assert!(repo.store().loose_count().unwrap() > 0);
1124
1125
    // With the default retention every operation's view is a root: nothing prunes.
1126
    let r = repo.gc(true).unwrap();
1127
    assert_eq!(r.packed.objects, before.len());
1128
    assert_eq!(r.pruned.objects, 0);
1129
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1130
    assert_eq!(repo.store().list().unwrap(), before);
1131
1132
    // With zero retention only the current view is a root: superseded
1133
    // working copies go, everything reachable stays.
1134
    repo.config.set("core.op-retention", "0").unwrap();
1135
    repo.save_config().unwrap();
1136
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1137
    let r = repo.gc(true).unwrap();
1138
    assert!(r.pruned.objects >= 5, "{r:?}");
1139
    let after = repo.store().list().unwrap();
1140
    assert!(after.len() < before.len());
1141
    assert!(after.contains(&h1) && after.contains(&h2));
1142
    for (_, op) in repo.op_log().unwrap() {
1143
        assert!(!op.command.is_empty(), "operation objects are all kept");
1144
    }
1145
    // Everything still works from the pruned, packed store.
1146
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1147
    assert!(matches!(
1148
        repo.verify_change(&h2).unwrap(),
1149
        SignatureStatus::Valid { .. }
1150
    ));
1151
    assert_eq!(repo.log().unwrap().len(), 3);
1152
    repo.checkout(&[h1], false, "checkout").unwrap();
1153
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1154
    repo.checkout(&[h2], false, "checkout").unwrap();
1155
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1156
    assert!(!repo.snapshot("status").unwrap().changed);
1157
    // Grace period defers pruning of young garbage.
1158
    write(root, "a.txt", b"three\n");
1159
    repo.commit("three", &[]).unwrap();
1160
    let r = repo.gc(false).unwrap();
1161
    assert_eq!(r.pruned.objects, 0);
1162
    assert!(r.pruned.deferred > 0);
1163
    let r = repo.gc(true).unwrap();
1164
    assert!(r.pruned.objects > 0);
1165
    assert_eq!(repo.log().unwrap().len(), 4);
1166
    // Restoring the default retention makes the old views roots again; the
1167
    // working copies they name were pruned, which gc tolerates.
1168
    repo.config.set("core.op-retention", "90").unwrap();
1169
    repo.save_config().unwrap();
1170
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1171
    let r = repo.gc(false).unwrap();
1172
    assert_eq!(r.pruned.objects, 0);
1173
    assert_eq!(repo.log().unwrap().len(), 4);
1174
}
1175
1176
#[test]
1177
fn describe_amend_abandon_heads() {
1178
    hermetic();
1179
    let dir = tempfile::tempdir().unwrap();
1180
    let root = dir.path();
1181
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1182
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1183
        .unwrap();
1184
    repo.set_user_config("core.sign", "change").unwrap();
1185
    write(root, "a.txt", b"one\n");
1186
    let h1 = repo.commit("first", &[]).unwrap();
1187
    write(root, "a.txt", b"one\ntwo\n");
1188
    let h2 = repo.commit("secnod", &[]).unwrap();
1189
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1190
1191
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1192
    let h2b = repo.describe(&h2, "second").unwrap();
1193
    assert_ne!(h2b, h2);
1194
    let c = repo.store().get_change(&h2b).unwrap();
1195
    assert_eq!(
1196
        (c.change_id, c.message.as_str(), c.deps.clone()),
1197
        (id2, "second", vec![h1])
1198
    );
1199
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1200
    assert!(matches!(
1201
        repo.verify_change(&h2b).unwrap(),
1202
        SignatureStatus::Valid { .. }
1203
    ));
1204
    let s = repo.snapshot("status").unwrap();
1205
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1206
    assert_eq!(
1207
        repo.resolve_change(&id2.short(8)).unwrap(),
1208
        h2b,
1209
        "the old object is no longer reachable from the log"
1210
    );
1211
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1212
    let h1b = repo.describe(&h1, "first, described").unwrap();
1213
    assert_ne!(h1b, h1);
1214
    let heads = repo.bookmark_heads().unwrap();
1215
    assert_eq!(heads.len(), 1);
1216
    let top = repo.store().get_change(&heads[0]).unwrap();
1217
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1218
    assert!(
1219
        matches!(
1220
            repo.verify_change(&heads[0]).unwrap(),
1221
            SignatureStatus::Valid { .. }
1222
        ),
1223
        "rewritten own change is re-signed"
1224
    );
1225
    let (_, wc) = repo.working_copy().unwrap();
1226
    assert_eq!(
1227
        wc.deps,
1228
        vec![heads[0]],
1229
        "the working copy follows the rewrite"
1230
    );
1231
    assert!(!repo.snapshot("status").unwrap().changed);
1232
    let snap = repo.load_state(&heads).unwrap().materialize();
1233
    assert!(
1234
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1235
    );
1236
1237
    // amend: fold an edit into the head; the result is one change from h1.
1238
    write(root, "a.txt", b"one\ntwo\nthree\n");
1239
    write(root, "b.txt", b"b\n");
1240
    let h2c = repo.amend(None).unwrap();
1241
    let c = repo.store().get_change(&h2c).unwrap();
1242
    assert_eq!(c.change_id, id2);
1243
    assert_eq!(c.message, "second");
1244
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1245
    assert_eq!(
1246
        repo.log().unwrap().len(),
1247
        3,
1248
        "working copy, amended head, first"
1249
    );
1250
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1251
    assert!(
1252
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1253
    );
1254
    assert!(snap.files.contains_key("b.txt"));
1255
    assert!(!repo.snapshot("status").unwrap().changed);
1256
    assert!(
1257
        repo.amend(None).is_err(),
1258
        "clean working copy and no message"
1259
    );
1260
    let h2d = repo.amend(Some("second, amended")).unwrap();
1261
    assert_eq!(
1262
        repo.store().get_change(&h2d).unwrap().message,
1263
        "second, amended"
1264
    );
1265
1266
    // abandon: the head goes, its content stays as uncommitted work.
1267
    repo.abandon(&h2d).unwrap();
1268
    assert_eq!(
1269
        repo.bookmark_heads().unwrap(),
1270
        vec![h1b],
1271
        "the described first change is the head again"
1272
    );
1273
    let s = repo.snapshot("status").unwrap();
1274
    let paths: Vec<_> = s
1275
        .statuses
1276
        .iter()
1277
        .map(|p| (p.path.as_str(), p.status))
1278
        .collect();
1279
    assert_eq!(
1280
        paths,
1281
        vec![
1282
            ("a.txt", ChangeStatus::Modified),
1283
            ("b.txt", ChangeStatus::Added)
1284
        ]
1285
    );
1286
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1287
    let h3 = repo.commit("recommitted", &[]).unwrap();
1288
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1289
    // undo brings the abandoned head back.
1290
    repo.undo().unwrap();
1291
    repo.undo().unwrap();
1292
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1293
1294
    // Abandoning a non-head whose dependent references its atoms reifies
1295
    // the references (here: a.txt vanishes with it, so the dependent's edit
1296
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1297
    let base = repo.bookmark_heads().unwrap()[0];
1298
    let base_change = repo.store().get_change(&base).unwrap();
1299
    let h1_now = base_change.deps[0];
1300
    let notes = repo.abandon(&h1_now).unwrap();
1301
    assert!(
1302
        !notes.is_empty(),
1303
        "the dependent's edit of a.txt was reified"
1304
    );
1305
    let heads = repo.bookmark_heads().unwrap();
1306
    let after = repo.load_state(&heads).unwrap().materialize();
1307
    assert!(
1308
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1309
        "{:?}",
1310
        after.files.keys()
1311
    );
1312
    repo.undo().unwrap();
1313
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1314
    write(root, "c.txt", b"c\n");
1315
    let hc = repo.commit("c", &[]).unwrap();
1316
    write(root, "d.txt", b"d\n");
1317
    let hd = repo.commit("d", &[hc]).unwrap();
1318
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1319
    repo.abandon(&hc).unwrap();
1320
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1321
    assert!(!heads.contains(&hc));
1322
    let d_now = heads
1323
        .iter()
1324
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1325
        .copied()
1326
        .unwrap();
1327
    assert!(
1328
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1329
        "d inherited c's (empty) dependencies"
1330
    );
1331
    let s = repo.snapshot("status").unwrap();
1332
    assert_eq!(
1333
        s.statuses
1334
            .iter()
1335
            .map(|p| p.path.as_str())
1336
            .collect::<Vec<_>>(),
1337
        vec!["c.txt"],
1338
        "c's content is now uncommitted work"
1339
    );
1340
}
1341
1342
#[test]
1343
fn git_export_mirrors_history() {
1344
    hermetic();
1345
    if std::process::Command::new("git")
1346
        .arg("--version")
1347
        .output()
1348
        .is_err()
1349
    {
1350
        eprintln!("git not installed; skipping");
1351
        return;
1352
    }
1353
    let dir = tempfile::tempdir().unwrap();
1354
    let root = dir.path();
1355
    let mut repo = Repo::init(&root.join("r"))
1356
        .unwrap()
1357
        .with_home(root.join("home"));
1358
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1359
        .unwrap();
1360
    let r = root.join("r");
1361
    write(&r, "README.md", b"hello\n");
1362
    write(&r, "src/main.rs", b"fn main() {}\n");
1363
    let h1 = repo.commit("first", &[]).unwrap();
1364
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1365
    write(&r, "logo.png", b"\x89PNG\0\0");
1366
    let h2 = repo.commit("second", &[]).unwrap();
1367
1368
    let git_dir = root.join("mirror.git");
1369
    let rep = repo.git_export(&git_dir).unwrap();
1370
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1371
    let git = |args: &[&str]| -> String {
1372
        let out = std::process::Command::new("git")
1373
            .arg("-C")
1374
            .arg(&git_dir)
1375
            .args(args)
1376
            .output()
1377
            .unwrap();
1378
        assert!(
1379
            out.status.success(),
1380
            "{}",
1381
            String::from_utf8_lossy(&out.stderr)
1382
        );
1383
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1384
    };
1385
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1386
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1387
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1388
    let body = git(&["log", "-1", "--format=%B", "main"]);
1389
    assert!(
1390
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1391
        "{body}"
1392
    );
1393
    assert!(body.contains("Change-Id: "), "{body}");
1394
    assert_eq!(
1395
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1396
        "Ada Lovelace <[email protected]>"
1397
    );
1398
    assert_eq!(
1399
        git(&["ls-tree", "--name-only", "main"]),
1400
        "README.md\nlogo.png\nsrc"
1401
    );
1402
1403
    // Re-export is incremental.
1404
    let rep = repo.git_export(&git_dir).unwrap();
1405
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1406
1407
    // An independent change makes two heads; the next state is one more
1408
    // commit on the linear branch whose tree is the union.
1409
    repo.checkout(&[h1], false, "checkout").unwrap();
1410
    write(&r, "other.txt", b"o\n");
1411
    let h3 = repo.commit("third", &[]).unwrap();
1412
    let rep = repo.git_export(&git_dir).unwrap();
1413
    assert_eq!((rep.exported, rep.heads), (1, 2));
1414
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1415
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1416
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1417
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1418
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1419
    assert_eq!(
1420
        git(&["ls-tree", "--name-only", "main"]),
1421
        "README.md\nlogo.png\nother.txt\nsrc"
1422
    );
1423
    let body = git(&["log", "-1", "--format=%B", "main"]);
1424
    assert!(
1425
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1426
        "{body}"
1427
    );
1428
    // A rewrite is a new state whose one new change is the rewritten one.
1429
    repo.describe(&h3, "third, described").unwrap();
1430
    let rep = repo.git_export(&git_dir).unwrap();
1431
    assert_eq!(rep.exported, 1);
1432
    assert_eq!(
1433
        git(&["log", "-1", "--format=%s", "main"]),
1434
        "third, described"
1435
    );
1436
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1437
    let _ = h2;
1438
}
1439
1440
#[test]
1441
fn git_import_reproduces_trees() {
1442
    hermetic();
1443
    if std::process::Command::new("git")
1444
        .arg("--version")
1445
        .output()
1446
        .is_err()
1447
    {
1448
        eprintln!("git not installed; skipping");
1449
        return;
1450
    }
1451
    let dir = tempfile::tempdir().unwrap();
1452
    let root = dir.path();
1453
    let g = root.join("src.git");
1454
    fs::create_dir_all(&g).unwrap();
1455
    let git = |args: &[&str]| -> String {
1456
        let out = std::process::Command::new("git")
1457
            .arg("-C")
1458
            .arg(&g)
1459
            .args([
1460
                "-c",
1461
                "user.name=Grace",
1462
                "-c",
1463
                "[email protected]",
1464
                "-c",
1465
                "commit.gpgsign=false",
1466
            ])
1467
            .args(args)
1468
            .output()
1469
            .unwrap();
1470
        assert!(
1471
            out.status.success(),
1472
            "git {args:?}: {}",
1473
            String::from_utf8_lossy(&out.stderr)
1474
        );
1475
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1476
    };
1477
    git(&["init", "-q", "-b", "main"]);
1478
    write(&g, "README.md", b"# Hi\n");
1479
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1480
    git(&["add", "."]);
1481
    git(&["commit", "-q", "-m", "initial"]);
1482
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1483
    write(&g, "run.sh", b"#!/bin/sh\n");
1484
    #[cfg(unix)]
1485
    {
1486
        use std::os::unix::fs::PermissionsExt;
1487
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1488
    }
1489
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1490
    git(&["add", "."]);
1491
    git(&[
1492
        "commit",
1493
        "-q",
1494
        "-m",
1495
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1496
    ]);
1497
    // A branch that edits README, merged back with a conflict-free merge.
1498
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1499
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1500
    git(&["commit", "-q", "-am", "readme"]);
1501
    git(&["checkout", "-q", "main"]);
1502
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1503
    // A branch from the initial commit inserting at the same place as
1504
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1505
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1506
    git(&["checkout", "-q", "-b", "clash", &initial]);
1507
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1508
    git(&["commit", "-q", "-am", "clash"]);
1509
    git(&["checkout", "-q", "main"]);
1510
    let _ = std::process::Command::new("git")
1511
        .arg("-C")
1512
        .arg(&g)
1513
        .args(["merge", "-q", "clash"])
1514
        .output();
1515
    write(
1516
        &g,
1517
        "src/lib.rs",
1518
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1519
    );
1520
    git(&["add", "."]);
1521
    git(&["commit", "-q", "-m", "resolve clash"]);
1522
    git(&["rm", "-q", "logo.png"]);
1523
    git(&["commit", "-q", "-m", "drop logo"]);
1524
    // A rename with a small edit is imported as a move of the same node.
1525
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1526
    write(
1527
        &g,
1528
        "src/lib2.rs",
1529
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1530
    );
1531
    git(&["add", "."]);
1532
    git(&["commit", "-q", "-m", "rename lib"]);
1533
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1534
    // run.sh is the same as in the first parent's tree, but the merged
1535
    // change touched it, so the importer must compare it, not skip it.
1536
    git(&["checkout", "-q", "-b", "discarded"]);
1537
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1538
    git(&["commit", "-q", "-am", "discarded edit"]);
1539
    git(&["checkout", "-q", "main"]);
1540
    git(&[
1541
        "merge",
1542
        "-q",
1543
        "-s",
1544
        "ours",
1545
        "-m",
1546
        "merge discarded, keeping ours",
1547
        "discarded",
1548
    ]);
1549
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1550
1551
    let dest = root.join("oxy");
1552
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1553
    let rep = repo.import_git(&g, "main").unwrap();
1554
    assert_eq!(rep.commits, expected_count);
1555
    assert_eq!(rep.merges, 3);
1556
    assert_eq!(
1557
        fs::read(dest.join("run.sh")).unwrap(),
1558
        b"#!/bin/sh\n",
1559
        "the ours merge kept main's run.sh"
1560
    );
1561
    let v = repo.verify_git_import(&g, "main").unwrap();
1562
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1563
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1564
    // The working copy equals the Git tree at main.
1565
    assert_eq!(
1566
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1567
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1568
    );
1569
    assert!(!dest.join("src/lib.rs").exists());
1570
    assert_eq!(
1571
        fs::read(dest.join("README.md")).unwrap(),
1572
        b"# Hi\n\nMore.\n"
1573
    );
1574
    assert!(!dest.join("logo.png").exists());
1575
    #[cfg(unix)]
1576
    {
1577
        use std::os::unix::fs::PermissionsExt;
1578
        assert!(
1579
            fs::metadata(dest.join("run.sh"))
1580
                .unwrap()
1581
                .permissions()
1582
                .mode()
1583
                & 0o111
1584
                != 0
1585
        );
1586
    }
1587
    assert!(
1588
        !repo.snapshot("status").unwrap().changed,
1589
        "clean after import"
1590
    );
1591
    let heads = repo.bookmark_heads().unwrap();
1592
    let st = repo.load_state(&heads).unwrap();
1593
    assert!(!st.materialize().is_conflicted());
1594
    assert_eq!(st.len(), expected_count);
1595
    let tip = repo
1596
        .log()
1597
        .unwrap()
1598
        .into_iter()
1599
        .find(|e| e.change.message.starts_with("rename lib"))
1600
        .unwrap();
1601
    let c = repo.store().get_change(&tip.hash).unwrap();
1602
    assert!(
1603
        c.tree_ops
1604
            .iter()
1605
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1606
        "{:?}",
1607
        c.tree_ops
1608
    );
1609
    assert!(!c
1610
        .tree_ops
1611
        .iter()
1612
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1613
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1614
    let log = repo.log().unwrap();
1615
    let second = log
1616
        .iter()
1617
        .find(|e| e.change.message.starts_with("second"))
1618
        .unwrap();
1619
    assert_eq!(
1620
        second.change.change_id,
1621
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1622
    );
1623
    assert!(second
1624
        .change
1625
        .message
1626
        .contains("Git-Author: Grace <[email protected]>"));
1627
    let resolve = log
1628
        .iter()
1629
        .find(|e| e.change.message.starts_with("resolve clash"))
1630
        .unwrap();
1631
    assert_eq!(
1632
        resolve.change.kind,
1633
        ChangeKind::Resolution,
1634
        "a conflicting Git merge becomes a resolution"
1635
    );
1636
    // Re-importing into another fresh repository gives the same ChangeIds.
1637
    let repo2 = Repo::init(&root.join("oxy2"))
1638
        .unwrap()
1639
        .with_home(root.join("home"));
1640
    repo2.import_git(&g, "main").unwrap();
1641
    // New nodes' identifiers derive from the commit (spec §23), so the
1642
    // re-import is not just the same ChangeIds but the same changes.
1643
    assert_eq!(
1644
        repo2.bookmark_heads().unwrap(),
1645
        repo.bookmark_heads().unwrap()
1646
    );
1647
    let ids: BTreeSet<ChangeId> = repo
1648
        .log()
1649
        .unwrap()
1650
        .iter()
1651
        .filter(|e| !e.is_working_copy)
1652
        .map(|e| e.change.change_id)
1653
        .collect();
1654
    let ids2: BTreeSet<ChangeId> = repo2
1655
        .log()
1656
        .unwrap()
1657
        .iter()
1658
        .filter(|e| !e.is_working_copy)
1659
        .map(|e| e.change.change_id)
1660
        .collect();
1661
    assert_eq!(ids, ids2);
1662
    // Round trip back out to Git reproduces the tip tree.
1663
    let mirror = root.join("mirror.git");
1664
    repo.git_export(&mirror).unwrap();
1665
    let out = std::process::Command::new("git")
1666
        .arg("-C")
1667
        .arg(&mirror)
1668
        .args(["show", "main:src/lib2.rs"])
1669
        .output()
1670
        .unwrap();
1671
    assert_eq!(
1672
        String::from_utf8_lossy(&out.stdout),
1673
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1674
    );
1675
    let out = std::process::Command::new("git")
1676
        .arg("-C")
1677
        .arg(&mirror)
1678
        .args(["show", "main:src/lib.rs"])
1679
        .output()
1680
        .unwrap();
1681
    assert!(
1682
        !out.status.success(),
1683
        "the old path is gone from the export"
1684
    );
1685
}
1686
1687
#[test]
1688
fn checkpoints_accelerate_loading_and_stay_correct() {
1689
    hermetic();
1690
    let dir = tempfile::tempdir().unwrap();
1691
    let root = dir.path();
1692
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1693
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1694
    repo.save_config().unwrap();
1695
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1696
    let mut hashes = Vec::new();
1697
    for i in 0..12 {
1698
        write(
1699
            root,
1700
            "a.txt",
1701
            format!(
1702
                "{}\n",
1703
                (0..=i)
1704
                    .map(|k| k.to_string())
1705
                    .collect::<Vec<_>>()
1706
                    .join("\n")
1707
            )
1708
            .as_bytes(),
1709
        );
1710
        write(root, &format!("f{i}.txt"), b"x\n");
1711
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1712
    }
1713
    let (_, cp) = repo
1714
        .latest_checkpoint("main")
1715
        .unwrap()
1716
        .expect("automatic checkpoint");
1717
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1718
    // Loading through the checkpoint equals loading everything.
1719
    let heads = repo.bookmark_heads().unwrap();
1720
    let fast = repo.load_state(&heads).unwrap();
1721
    let full = repo.load_state_full(&heads).unwrap();
1722
    assert_eq!(fast.len(), full.len());
1723
    assert_eq!(fast.heads(), full.heads());
1724
    let (a, b) = (fast.materialize(), full.materialize());
1725
    assert_eq!(
1726
        a.files.keys().collect::<Vec<_>>(),
1727
        b.files.keys().collect::<Vec<_>>()
1728
    );
1729
    for (p, f) in &a.files {
1730
        assert_eq!(f.content, b.files[p].content, "{p}");
1731
    }
1732
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1733
    // A head set that does not contain the checkpoint's heads falls back.
1734
    assert!(repo
1735
        .load_state_checkpointed(&[hashes[0]])
1736
        .unwrap()
1737
        .is_none());
1738
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1739
    // Everything else keeps working on top of the checkpoint.
1740
    assert!(!repo.snapshot("status").unwrap().changed);
1741
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1742
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1743
    let (r, n, bytes) = repo.checkpoint().unwrap();
1744
    assert!(n >= 12 && bytes > 0);
1745
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1746
    write(root, "a.txt", b"after\n");
1747
    let h_after = repo.commit("after", &[]).unwrap();
1748
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1749
    assert!(st.contains(&h_after));
1750
    assert!(
1751
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1752
    );
1753
    assert_eq!(repo.log().unwrap().len(), 14);
1754
    // Checkpoints survive gc.
1755
    repo.gc(true).unwrap();
1756
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1757
    assert!(repo
1758
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1759
        .unwrap()
1760
        .is_some());
1761
}
1762
1763
#[test]
1764
fn quick_status_for_prompts() {
1765
    hermetic();
1766
    let dir = tempfile::tempdir().unwrap();
1767
    let root = dir.path();
1768
    let origin = Repo::init(&root.join("origin")).unwrap();
1769
    let url = root.join("origin").to_string_lossy().to_string();
1770
    let a = Repo::clone(&url, &root.join("a"))
1771
        .unwrap()
1772
        .with_home(root.join("home"));
1773
    let ops_before = a.op_log().unwrap().len();
1774
    let info = a.quick_status().unwrap();
1775
    assert_eq!(
1776
        (
1777
            info.bookmark.as_str(),
1778
            info.heads,
1779
            info.dirty,
1780
            info.conflicted,
1781
            info.ahead,
1782
            info.behind
1783
        ),
1784
        ("main", 0, false, false, Some(0), Some(0))
1785
    );
1786
    write(&root.join("a"), "f.txt", b"f\n");
1787
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1788
    assert_eq!(
1789
        a.op_log().unwrap().len(),
1790
        ops_before,
1791
        "quick_status records nothing"
1792
    );
1793
    // A snapshotted but uncommitted change is still dirty.
1794
    a.snapshot("status").unwrap();
1795
    assert!(a.quick_status().unwrap().dirty);
1796
    a.commit("f", &[]).unwrap();
1797
    let info = a.quick_status().unwrap();
1798
    assert!(!info.dirty, "clean right after a commit");
1799
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
1800
    assert_eq!(
1801
        info.format("%b %c%d%x%A%D"),
1802
        format!("main {}+1", info.change_id)
1803
    );
1804
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1805
    // Touching a file without changing it is not dirty; changing content of
1806
    // the same size is.
1807
    let p = root.join("a/f.txt");
1808
    let content = fs::read(&p).unwrap();
1809
    fs::write(&p, &content).unwrap();
1810
    assert!(!a.quick_status().unwrap().dirty);
1811
    fs::write(&p, b"g\n").unwrap();
1812
    assert!(a.quick_status().unwrap().dirty);
1813
    fs::write(&p, b"f\n").unwrap();
1814
    // Push, then a second clone commits and pushes: we are behind.
1815
    assert!(a.push("origin", false).unwrap()[0].ok);
1816
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
1817
    let b = Repo::clone(&url, &root.join("b"))
1818
        .unwrap()
1819
        .with_home(root.join("home-b"));
1820
    write(&root.join("b"), "g.txt", b"g\n");
1821
    b.commit("g", &[]).unwrap();
1822
    b.push("origin", false).unwrap();
1823
    a.fetch("origin").unwrap();
1824
    let info = a.quick_status().unwrap();
1825
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1826
    assert_eq!(info.format("%A%D"), "-1");
1827
    let _ = origin;
1828
}
1829
1830
#[test]
1831
fn lazy_blobs_are_fetched_on_first_read() {
1832
    hermetic();
1833
    let dir = tempfile::tempdir().unwrap();
1834
    let root = dir.path();
1835
    let origin_dir = root.join("origin");
1836
    let origin = Repo::init(&origin_dir)
1837
        .unwrap()
1838
        .with_home(root.join("home"));
1839
    let url = origin_dir.to_string_lossy().to_string();
1840
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1841
    write(&origin_dir, "big.bin", &big);
1842
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1843
    write(&origin_dir, "t.txt", b"t\n");
1844
    let h = origin.commit("blobs", &[]).unwrap();
1845
    let big_ref = Repo::blob_ref(&big);
1846
1847
    // Fetch only (no checkout) with a filter: the big blob stays absent.
1848
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1849
        .unwrap()
1850
        .with_home(root.join("home"));
1851
    let a = {
1852
        let mut a = a;
1853
        a.config.set("remote.origin.url", &url).unwrap();
1854
        a.config.set("filter.max-blob", "100K").unwrap();
1855
        a.save_config().unwrap();
1856
        a
1857
    };
1858
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1859
    a.fetch("origin").unwrap();
1860
    assert!(a.store().has(&h));
1861
    assert!(!a.store().has(&big_ref), "withheld");
1862
    assert!(
1863
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1864
        "small blob came along"
1865
    );
1866
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1867
1868
    // status and commit do not need it: adopt the state, edit a text file, commit.
1869
    let (op_ref, op) = a.head_op().unwrap();
1870
    let mut view = op.view.clone();
1871
    view.bookmarks.insert(
1872
        "main".into(),
1873
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1874
    );
1875
    a.record_op(&[op_ref], "adopt", view).unwrap();
1876
    // Checkout reads the blob lazily, which fetches it.
1877
    a.checkout(&[h], true, "checkout").unwrap();
1878
    assert!(a.store().has(&big_ref), "fetched on first read");
1879
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1880
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1881
    write(&root.join("a"), "t.txt", b"t2\n");
1882
    a.commit("text edit", &[]).unwrap();
1883
1884
    // clone --max-blob records the filter; the checkout fetches lazily.
1885
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
1886
    assert_eq!(b.config.max_blob, Some(1024));
1887
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1888
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1889
    assert!(parse_size("lots").is_err());
1890
}
1891
1892
#[test]
1893
fn sparse_checkout_materializes_only_chosen_paths() {
1894
    hermetic();
1895
    let dir = tempfile::tempdir().unwrap();
1896
    let root = dir.path();
1897
    let origin_dir = root.join("origin");
1898
    let origin = Repo::init(&origin_dir)
1899
        .unwrap()
1900
        .with_home(root.join("home"));
1901
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1902
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1903
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1904
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1905
    write(&origin_dir, "docs/logo.png", &logo);
1906
    write(&origin_dir, "README.md", b"# top\n");
1907
    let h1 = origin.commit("tree", &[]).unwrap();
1908
    let url = origin_dir.to_string_lossy().to_string();
1909
1910
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
1911
        .unwrap()
1912
        .with_home(root.join("home"));
1913
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1914
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1915
    assert!(root.join("a/src/main.rs").exists());
1916
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
1917
    assert!(
1918
        !a.store().has(&Repo::blob_ref(&logo)),
1919
        "out-of-scope blob never fetched"
1920
    );
1921
    assert!(
1922
        !a.snapshot("status").unwrap().changed,
1923
        "out-of-scope files are not removals"
1924
    );
1925
    assert!(!a.quick_status().unwrap().dirty);
1926
1927
    // Edits in scope commit normally and keep the rest of the tree intact.
1928
    write(
1929
        &root.join("a"),
1930
        "src/lib.rs",
1931
        b"pub fn a() {}\npub fn b() {}\n",
1932
    );
1933
    let h2 = a.commit("edit lib", &[]).unwrap();
1934
    let st = a.load_state(&[h2]).unwrap().materialize();
1935
    assert!(
1936
        st.files.contains_key("docs/guide.md"),
1937
        "the state still has everything"
1938
    );
1939
    assert!(a.push("origin", false).unwrap()[0].ok);
1940
    // Files created outside the scope are ignored by status.
1941
    write(&root.join("a"), "docs/new.md", b"ignored\n");
1942
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
1943
1944
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
1945
    let mut a = a;
1946
    a.config.set("filter.paths", "src,docs").unwrap();
1947
    a.save_config().unwrap();
1948
    let r = a
1949
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
1950
        .unwrap();
1951
    assert!(r.written >= 2);
1952
    assert_eq!(
1953
        fs::read(root.join("a/docs/logo.png")).unwrap(),
1954
        logo,
1955
        "now fetched lazily"
1956
    );
1957
    assert!(!root.join("a/README.md").exists());
1958
    // Origin sees the change made under a sparse checkout with the full tree intact.
1959
    origin.pull("origin").err();
1960
    let full = origin
1961
        .load_state(&origin.bookmark_heads().unwrap())
1962
        .unwrap()
1963
        .materialize();
1964
    assert!(
1965
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
1966
    );
1967
    assert!(full.files.contains_key("README.md"));
1968
    let _ = h1;
1969
}
1970
1971
#[test]
1972
fn shallow_clone_and_deepen() {
1973
    hermetic();
1974
    let dir = tempfile::tempdir().unwrap();
1975
    let root = dir.path();
1976
    let origin_dir = root.join("origin");
1977
    let origin = Repo::init(&origin_dir)
1978
        .unwrap()
1979
        .with_home(root.join("home"));
1980
    let mut hashes = Vec::new();
1981
    for i in 0..8 {
1982
        write(
1983
            &origin_dir,
1984
            "a.txt",
1985
            format!(
1986
                "{}\n",
1987
                (0..=i)
1988
                    .map(|k| k.to_string())
1989
                    .collect::<Vec<_>>()
1990
                    .join("\n")
1991
            )
1992
            .as_bytes(),
1993
        );
1994
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
1995
    }
1996
    let url = origin_dir.to_string_lossy().to_string();
1997
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
1998
        .unwrap()
1999
        .with_home(root.join("home"));
2000
    assert!(a.is_shallow());
2001
    assert_eq!(
2002
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2003
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2004
    );
2005
    assert!(
2006
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2007
        "three levels present"
2008
    );
2009
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2010
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2011
    assert_eq!(
2012
        a.log().unwrap().len(),
2013
        9,
2014
        "the log shows every change from the checkpoint's metadata"
2015
    );
2016
    assert!(!a.snapshot("status").unwrap().changed);
2017
    assert_eq!(a.quick_status().unwrap().heads, 1);
2018
2019
    // Work continues on top of the shallow history and pushes back.
2020
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2021
    let h_new = a.commit("c8", &[]).unwrap();
2022
    assert!(a.push("origin", false).unwrap()[0].ok);
2023
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2024
    // Fetching new work from origin into the shallow clone works too.
2025
    write(&origin_dir, "b.txt", b"b\n");
2026
    origin.pull("origin").err();
2027
    let (_, wc) = origin.working_copy().unwrap();
2028
    let _ = wc;
2029
    origin
2030
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2031
        .unwrap();
2032
    write(&origin_dir, "b.txt", b"b\n");
2033
    let h_b = origin.commit("b", &[]).unwrap();
2034
    let pr = a.pull("origin").unwrap();
2035
    assert!(pr.changed);
2036
    assert!(a.store().has(&h_b));
2037
    assert!(root.join("a/b.txt").exists());
2038
2039
    // Deepening fetches older history until the boundary is gone.
2040
    // Every commit also depends on the change that created the file, so two
2041
    // levels below the boundary hold h4, h3, and the root.
2042
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2043
    assert!(a.store().has(&hashes[3]));
2044
    assert!(a.is_shallow());
2045
    a.deepen("origin", 100).unwrap();
2046
    assert!(!a.is_shallow(), "boundary reached the root");
2047
    assert!(a.store().has(&hashes[0]));
2048
    assert_eq!(
2049
        a.load_state_full(&a.bookmark_heads().unwrap())
2050
            .unwrap()
2051
            .len(),
2052
        10
2053
    );
2054
}
2055
2056
#[test]
2057
fn tags_are_immutable_named_states_and_travel() {
2058
    hermetic();
2059
    let dir = tempfile::tempdir().unwrap();
2060
    let root = dir.path();
2061
    let origin = Repo::init(&root.join("origin")).unwrap();
2062
    let url = root.join("origin").to_string_lossy().to_string();
2063
    let mut a = Repo::clone(&url, &root.join("a"))
2064
        .unwrap()
2065
        .with_home(root.join("home-a"));
2066
    let (key_a, _) = a
2067
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2068
        .unwrap();
2069
    write(&root.join("a"), "f.txt", b"1\n");
2070
    let h1 = a.commit("one", &[]).unwrap();
2071
    write(&root.join("a"), "f.txt", b"1\n2\n");
2072
    let h2 = a.commit("two", &[]).unwrap();
2073
2074
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2075
    assert_eq!(
2076
        (t.heads.clone(), t.signer.as_deref()),
2077
        (vec![h1], Some("Ada"))
2078
    );
2079
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2080
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2081
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2082
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2083
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2084
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2085
    assert_eq!(sa.sigs[0].key, key_a);
2086
    // Checkout by tag.
2087
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2088
        .unwrap();
2089
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2090
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2091
        .unwrap();
2092
2093
    // Push carries the tag; a second attestation for the name is refused.
2094
    let r = a.push("origin", false).unwrap();
2095
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2096
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2097
    let mut forged = a
2098
        .tag_refs()
2099
        .unwrap()
2100
        .into_iter()
2101
        .find(|t| t.name == "v1")
2102
        .unwrap();
2103
    forged.state = origin
2104
        .store()
2105
        .put_state(&StateObject::new(vec![h2]))
2106
        .unwrap();
2107
    forged.heads = vec![h2];
2108
    forged.attestation = None;
2109
    let r = origin
2110
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2111
        .unwrap();
2112
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2113
2114
    // A clone gets the tag; a later tag arrives on fetch.
2115
    let b = Repo::clone(&url, &root.join("b"))
2116
        .unwrap()
2117
        .with_home(root.join("home-b"));
2118
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2119
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2120
    a.tag_create("v2", &[h2], "second").unwrap();
2121
    a.push("origin", false).unwrap();
2122
    let rep = b.fetch("origin").unwrap();
2123
    assert_eq!(rep.new_tags, 1);
2124
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2125
2126
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2127
    a.policy_init().unwrap();
2128
    a.push("origin", false).unwrap();
2129
    let unattested = crate::protocol::TagRef {
2130
        name: "v3".into(),
2131
        state: origin
2132
            .store()
2133
            .put_state(&StateObject::new(vec![h2]))
2134
            .unwrap(),
2135
        heads: vec![h2],
2136
        attestation: None,
2137
    };
2138
    let r = origin
2139
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2140
        .unwrap();
2141
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2142
    a.tag_create("v3", &[h2], "").unwrap();
2143
    let r = a.push("origin", false).unwrap();
2144
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2145
    assert!(a.gc(true).is_ok());
2146
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2147
}
2148
2149
#[test]
2150
fn multiple_workspaces_share_a_repository() {
2151
    hermetic();
2152
    let dir = tempfile::tempdir().unwrap();
2153
    let root = dir.path();
2154
    let main_dir = root.join("main");
2155
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2156
    write(&main_dir, "a.txt", b"a\n");
2157
    let h1 = repo.commit("a", &[]).unwrap();
2158
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2159
2160
    // A second workspace elsewhere, checked out on the bookmark.
2161
    let ws_dir = root.join("ws2");
2162
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2163
    assert!(ws_dir.join(".oxy").is_file());
2164
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2165
    assert_ne!(ws.workspace(), repo.workspace());
2166
    let list = repo.workspaces().unwrap();
2167
    assert_eq!(list.len(), 2);
2168
    assert!(list
2169
        .iter()
2170
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2171
    assert!(!ws.snapshot("status").unwrap().changed);
2172
2173
    // Work in the second workspace: its own working copy, shared bookmark.
2174
    write(&ws_dir, "b.txt", b"b\n");
2175
    let s = ws.snapshot("status").unwrap();
2176
    assert_eq!(s.statuses.len(), 1);
2177
    assert!(
2178
        !repo.snapshot("status").unwrap().changed,
2179
        "the first workspace is untouched"
2180
    );
2181
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2182
    let mut heads = repo.bookmark_heads().unwrap();
2183
    heads.sort();
2184
    let mut want = vec![h1, h2];
2185
    want.sort();
2186
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2187
    assert!(!main_dir.join("b.txt").exists());
2188
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2189
        .unwrap();
2190
    assert!(main_dir.join("b.txt").exists());
2191
2192
    // Reopening from inside the second workspace finds the shared repository.
2193
    let reopened = Repo::open(&ws_dir).unwrap();
2194
    assert_eq!(reopened.workspace(), ws.workspace());
2195
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2196
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2197
2198
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2199
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2200
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2201
    repo.workspace_forget(&ws.workspace()).unwrap();
2202
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2203
    assert!(ws_dir.join("b.txt").exists());
2204
    assert!(
2205
        ws.snapshot("status").is_err(),
2206
        "a forgotten workspace is no longer in the view"
2207
    );
2208
2209
    // The working-copy lock: re-entrant in a thread; a lock whose process
2210
    // is gone is taken over, and a live process's is not, however old.
2211
    let lock = repo.lock_snapshot().unwrap();
2212
    let again = repo.lock_working_copy().unwrap();
2213
    drop(again);
2214
    drop(lock);
2215
    let lock_path = main_dir
2216
        .join(".oxy/workspaces")
2217
        .join(repo.workspace().to_hex())
2218
        .join("lock");
2219
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2220
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2221
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2222
    age(&lock_path);
2223
    assert!(
2224
        !super::workspace::lock_is_stale(&lock_path),
2225
        "a live process keeps its lock"
2226
    );
2227
    fs::write(&lock_path, "4294967295").unwrap();
2228
    age(&lock_path);
2229
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2230
}
2231
2232
#[test]
2233
fn attributes_binary_eol_nocompress_lockable() {
2234
    hermetic();
2235
    let dir = tempfile::tempdir().unwrap();
2236
    let root = dir.path();
2237
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2238
    write(
2239
        root,
2240
        ".oxyattributes",
2241
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2242
    );
2243
    write(root, "plain.dat", b"no nul bytes here\n");
2244
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2245
    write(root, "assets/model.bin", b"\0model");
2246
    let h = repo.commit("attrs", &[]).unwrap();
2247
    let snap = repo.load_state(&[h]).unwrap().materialize();
2248
    assert!(
2249
        snap.files["plain.dat"].mode.opaque,
2250
        "binary attribute forces opaque without NUL bytes"
2251
    );
2252
    assert!(
2253
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2254
        "stored with LF"
2255
    );
2256
    assert!(
2257
        !repo.snapshot("status").unwrap().changed,
2258
        "CRLF on disk equals LF in the state"
2259
    );
2260
    // nocompress chunks pack raw.
2261
    let r = repo.gc(true).unwrap();
2262
    assert!(r.packed.objects > 0);
2263
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2264
    fs::remove_file(root.join("notes.txt")).unwrap();
2265
    repo.checkout(&[h], true, "co").unwrap();
2266
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2267
    assert!(fs::metadata(root.join("assets/model.bin"))
2268
        .unwrap()
2269
        .permissions()
2270
        .readonly());
2271
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2272
    repo.lock_path("assets/model.bin").unwrap();
2273
    assert!(!fs::metadata(root.join("assets/model.bin"))
2274
        .unwrap()
2275
        .permissions()
2276
        .readonly());
2277
    assert!(repo.is_locked("assets/model.bin"));
2278
    write(root, "assets/model.bin", b"\0model2");
2279
    repo.commit("edit model", &[]).unwrap();
2280
    repo.unlock_path("assets/model.bin").unwrap();
2281
    assert!(fs::metadata(root.join("assets/model.bin"))
2282
        .unwrap()
2283
        .permissions()
2284
        .readonly());
2285
    // A later checkout can still overwrite a read-only lockable file.
2286
    repo.checkout(&[h], true, "co").unwrap();
2287
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2288
}
2289
2290
#[cfg(unix)]
2291
#[test]
2292
fn hooks_can_veto_observe_and_add_dependencies() {
2293
    use std::os::unix::fs::PermissionsExt;
2294
    hermetic();
2295
    let dir = tempfile::tempdir().unwrap();
2296
    let root = dir.path();
2297
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2298
    let hooks = root.join(".oxy/hooks");
2299
    fs::create_dir_all(&hooks).unwrap();
2300
    let hook = |name: &str, body: &str| {
2301
        let p = hooks.join(name);
2302
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2303
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2304
    };
2305
    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");
2306
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2307
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2308
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2309
    write(root, ".oxyignore", b".last-*\n");
2310
    write(root, "a.txt", b"a\n");
2311
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2312
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2313
    let h1 = repo.commit("first", &[]).unwrap();
2314
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2315
    assert!(
2316
        pre.contains("\"event\":\"pre-commit\"")
2317
            && pre.contains("\"path\":\"a.txt\"")
2318
            && pre.contains("\"message\":\"first\""),
2319
        "{pre}"
2320
    );
2321
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2322
    assert!(post.contains(&h1.to_hex()), "{post}");
2323
    repo.checkout(&[h1], false, "co").unwrap();
2324
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2325
        .unwrap()
2326
        .contains("post-checkout"));
2327
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2328
    repo.save_config().unwrap();
2329
    let err = repo.push("origin", false).unwrap_err().to_string();
2330
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2331
2332
    // semantic-deps: only when enabled; adds an explicit dependency.
2333
    write(root, "b.txt", b"b\n");
2334
    hook(
2335
        "semantic-deps",
2336
        &format!(
2337
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2338
            h1.to_hex()
2339
        ),
2340
    );
2341
    let h2 = repo.commit("b without hook", &[]).unwrap();
2342
    assert!(
2343
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2344
        "hook disabled by default"
2345
    );
2346
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2347
    repo.save_config().unwrap();
2348
    write(root, "c.txt", b"c\n");
2349
    let h3 = repo.commit("c with hook", &[]).unwrap();
2350
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2351
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2352
    assert!(
2353
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2354
        "{sem}"
2355
    );
2356
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2357
}
2358
2359
#[test]
2360
fn amend_into_older_change_and_split() {
2361
    hermetic();
2362
    let dir = tempfile::tempdir().unwrap();
2363
    let root = dir.path();
2364
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2365
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2366
        .unwrap();
2367
    repo.set_user_config("core.sign", "change").unwrap();
2368
    write(root, "a.txt", b"one\ntwo\n");
2369
    let h0 = repo.commit("base", &[]).unwrap();
2370
    write(root, "a.txt", b"one\nTWO\n");
2371
    let h1 = repo.commit("edit two", &[]).unwrap();
2372
    write(root, "a.txt", b"one\nTWO\nthree\n");
2373
    let h2 = repo.commit("add three", &[]).unwrap();
2374
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2375
2376
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2377
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2378
    let h1b = repo.amend_into(&h1, None).unwrap();
2379
    assert_ne!(h1b, h1);
2380
    let c1b = repo.store().get_change(&h1b).unwrap();
2381
    assert_eq!(c1b.change_id, id1);
2382
    assert_eq!(c1b.deps, vec![h0]);
2383
    assert!(matches!(
2384
        repo.verify_change(&h1b).unwrap(),
2385
        SignatureStatus::Valid { .. }
2386
    ));
2387
    let heads = repo.bookmark_heads().unwrap();
2388
    assert_eq!(heads.len(), 1);
2389
    let top = repo.store().get_change(&heads[0]).unwrap();
2390
    assert_eq!(top.message, "add three");
2391
    assert_eq!(
2392
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2393
        [h0, h1b].into_iter().collect(),
2394
        "depends on the file's creator and the rewritten line"
2395
    );
2396
    let snap = repo.load_state(&heads).unwrap().materialize();
2397
    assert!(
2398
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2399
    );
2400
    assert!(
2401
        !repo.snapshot("status").unwrap().changed,
2402
        "the working copy is clean after folding"
2403
    );
2404
    // Only h1b's own state shows the fix without "three".
2405
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2406
    assert!(
2407
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2408
    );
2409
    assert_eq!(repo.log().unwrap().len(), 4);
2410
2411
    // An edit to a line introduced by h2 cannot fold into h1.
2412
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2413
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2414
    assert!(err.contains("introduced after"), "{err}");
2415
    assert!(
2416
        repo.snapshot("status").unwrap().statuses.len() == 1,
2417
        "nothing was changed by the refusal"
2418
    );
2419
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2420
2421
    // Split the head that touches two files.
2422
    write(root, "b.txt", b"b\n");
2423
    write(root, "c.txt", b"c\n");
2424
    let h3 = repo.commit("b and c", &[]).unwrap();
2425
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2426
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2427
    let c_1 = repo.store().get_change(&p1).unwrap();
2428
    let c_2 = repo.store().get_change(&p2).unwrap();
2429
    assert!(c_1.message.contains("part 1: b.txt"));
2430
    assert_eq!(c_2.change_id, id3);
2431
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2432
    assert!(
2433
        heads.contains(&p1) && heads.contains(&p2),
2434
        "independent parts are both heads"
2435
    );
2436
    let snap = repo
2437
        .load_state(&repo.bookmark_heads().unwrap())
2438
        .unwrap()
2439
        .materialize();
2440
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2441
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2442
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2443
    assert!(!repo.snapshot("status").unwrap().changed);
2444
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2445
    let _ = h2;
2446
}
2447
2448
#[test]
2449
fn identity_lifecycle() {
2450
    hermetic();
2451
    let dir = tempfile::tempdir().unwrap();
2452
    let root = dir.path();
2453
    let origin = Repo::init(&root.join("origin")).unwrap();
2454
    let url = root.join("origin").to_string_lossy().to_string();
2455
    let mut a = Repo::clone(&url, &root.join("a"))
2456
        .unwrap()
2457
        .with_home(root.join("home-a"));
2458
    a.set_user_config("core.sign", "change").unwrap();
2459
    let (key_a, _) = a
2460
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2461
        .unwrap();
2462
    write(&root.join("a"), "a.txt", b"a\n");
2463
    let h1 = a.commit("one", &[]).unwrap();
2464
    assert!(a.policy_init().unwrap().applied);
2465
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2466
2467
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2468
    let mut e = Repo::init(&root.join("e"))
2469
        .unwrap()
2470
        .with_home(root.join("home-e"));
2471
    e.set_user_config("core.sign", "change").unwrap();
2472
    e.create_identity_with(
2473
        "Eve",
2474
        "[email protected]",
2475
        IdentityScope::User,
2476
        Some(Hlc::now().wall_ms - 1),
2477
    )
2478
    .unwrap();
2479
    write(&root.join("e"), "e.txt", b"e\n");
2480
    let he = e.commit("late", &[]).unwrap();
2481
    assert!(
2482
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2483
    );
2484
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2485
    let r = e
2486
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2487
        .unwrap();
2488
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2489
    write(&root.join("e"), "e.txt", b"e2\n");
2490
    let he2 = e.commit("in time", &[]).unwrap();
2491
    assert!(
2492
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2493
    );
2494
2495
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2496
    let r = a.rotate_identity().unwrap();
2497
    assert_eq!(r.old, key_a);
2498
    assert_eq!(a.config.author_key, Some(r.new));
2499
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2500
    assert!(r.policy.as_ref().unwrap().applied);
2501
    let (_, sp) = a.current_policy().unwrap().unwrap();
2502
    assert_eq!(
2503
        (sp.policy.serial, sp.policy.roots.clone()),
2504
        (2, vec![r.new])
2505
    );
2506
    assert!(
2507
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2508
        "superseded, not revoked"
2509
    );
2510
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2511
    assert!(
2512
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2513
    );
2514
    write(&root.join("a"), "a.txt", b"a2\n");
2515
    let h2 = a.commit("two", &[]).unwrap();
2516
    assert!(
2517
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2518
    );
2519
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2520
    let res = a.push("origin", false).unwrap();
2521
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2522
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2523
    let key_a = r.new;
2524
2525
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2526
    // identity object, so Ada's KeyId changes while her keys stay the same.
2527
    let mut b = Repo::clone(&url, &root.join("b"))
2528
        .unwrap()
2529
        .with_home(root.join("home-b"));
2530
    let (key_b, id_b) = b
2531
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2532
        .unwrap();
2533
    let r = a.delegate_add(id_b.clone()).unwrap();
2534
    assert_eq!(r.old, key_a);
2535
    let key_a2 = r.new;
2536
    assert_eq!(a.identity(&key_a2).unwrap().delegates, vec![key_b]);
2537
    assert_eq!(
2538
        a.identity(&key_a2).unwrap().ed25519_pk,
2539
        a.identity(&key_a).unwrap().ed25519_pk
2540
    );
2541
    assert!(a.delegate_add(id_b.clone()).is_err(), "already a delegate");
2542
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2543
    write(&root.join("a"), "a.txt", b"a3\n");
2544
    let h3 = a.commit("three", &[]).unwrap();
2545
    assert!(
2546
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2547
        "the same secret signs under the new KeyId"
2548
    );
2549
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2550
    a.set_user_config("core.sign", "seal").unwrap();
2551
    write(&root.join("a"), "a.txt", b"a4\n");
2552
    let h4 = a.commit("four", &[]).unwrap();
2553
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2554
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2555
    a.store()
2556
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2557
        .unwrap();
2558
    assert!(
2559
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2560
    );
2561
    a.set_user_config("core.sign", "change").unwrap();
2562
    // Withdrawing the delegation re-issues the identity again.
2563
    let r = a.delegate_remove(&key_b).unwrap();
2564
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2565
    assert!(a.delegate_remove(&key_b).is_err());
2566
    let key_a3 = r.new;
2567
    let res = a.push("origin", false).unwrap();
2568
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2569
2570
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2571
    // both applied under the old threshold of 1. A grant then needs Bob too.
2572
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2573
    assert!(a.policy_root_add(id_b.clone()).is_err());
2574
    assert!(a.policy_set_threshold(3).is_err());
2575
    assert!(a.policy_set_threshold(2).unwrap().applied);
2576
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2577
    b.pull("origin").unwrap();
2578
    assert_eq!(
2579
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2580
        2
2581
    );
2582
    let mut c = Repo::init(&root.join("c"))
2583
        .unwrap()
2584
        .with_home(root.join("home-c"));
2585
    let (key_c, id_c) = c
2586
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2587
        .unwrap();
2588
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2589
    let proposal = a.policy_grant(id_c, None).unwrap();
2590
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2591
    assert_eq!(proposal.policy.serial, serial_before + 1);
2592
    assert_eq!(
2593
        a.current_policy().unwrap().unwrap().1.policy.serial,
2594
        serial_before,
2595
        "a proposal changes nothing yet"
2596
    );
2597
    // Bob signs the proposal, handed over as a file, and it applies for him.
2598
    let bytes = proposal.signed().encode();
2599
    let signed = b
2600
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2601
        .unwrap();
2602
    assert!(signed.applied && signed.sigs.len() == 2);
2603
    assert!(b
2604
        .current_policy()
2605
        .unwrap()
2606
        .unwrap()
2607
        .1
2608
        .policy
2609
        .authorizes(&key_c, "main"));
2610
    assert!(
2611
        b.policy_sign(signed.signed()).is_err(),
2612
        "a stale proposal is refused"
2613
    );
2614
    // Bob publishes it and Ada picks it up.
2615
    assert!(b
2616
        .push("origin", false)
2617
        .unwrap()
2618
        .iter()
2619
        .any(|x| x.name == "policy" && x.ok));
2620
    a.pull("origin").unwrap();
2621
    assert_eq!(
2622
        a.current_policy().unwrap().unwrap().1.policy.serial,
2623
        serial_before + 1
2624
    );
2625
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2626
    assert!(a.policy_revoke(&key_a3).is_err());
2627
    let u = a
2628
        .revoke_identity(&key_c, "left the project")
2629
        .unwrap()
2630
        .unwrap();
2631
    assert!(!u.applied);
2632
    assert!(a.is_revoked(&key_c).unwrap());
2633
    assert!(!b.is_revoked(&key_c).unwrap());
2634
    let u = b.policy_sign(u.signed()).unwrap();
2635
    assert!(u.applied && u.policy.is_revoked(&key_c));
2636
    assert!(b.is_revoked(&key_c).unwrap());
2637
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2638
    assert!(
2639
        b.policy_revoke(&key_a3).is_err(),
2640
        "would leave one root for a threshold of 2"
2641
    );
2642
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2643
    let key_c_own = c.config.author_key.unwrap();
2644
    assert!(c
2645
        .revoke_identity(&key_c_own, "lost laptop")
2646
        .unwrap()
2647
        .is_none());
2648
    assert!(c.is_revoked(&key_c_own).unwrap());
2649
    assert_eq!(key_c_own, key_c);
2650
}
2651
2652
#[test]
2653
fn renames_are_detected_and_tracked_as_moves() {
2654
    hermetic();
2655
    let dir = tempfile::tempdir().unwrap();
2656
    let root = dir.path();
2657
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2658
    write(
2659
        root,
2660
        "src/old.rs",
2661
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2662
    );
2663
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2664
    write(root, "tiny.txt", b"x\n");
2665
    let h1 = repo.commit("base", &[]).unwrap();
2666
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2667
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2668
2669
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2670
    // that shares nothing with the removed file.
2671
    fs::remove_file(root.join("src/old.rs")).unwrap();
2672
    write(
2673
        root,
2674
        "lib/new.rs",
2675
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2676
    );
2677
    fs::remove_file(root.join("img.bin")).unwrap();
2678
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2679
    fs::remove_file(root.join("tiny.txt")).unwrap();
2680
    write(root, "other.txt", b"completely different\n");
2681
    let snap = repo.snapshot("status").unwrap();
2682
    let statuses: Vec<(&str, ChangeStatus)> = snap
2683
        .statuses
2684
        .iter()
2685
        .map(|s| (s.path.as_str(), s.status))
2686
        .collect();
2687
    assert_eq!(
2688
        statuses,
2689
        vec![
2690
            ("assets/img.bin", ChangeStatus::Renamed),
2691
            ("lib/new.rs", ChangeStatus::Renamed),
2692
            ("other.txt", ChangeStatus::Added),
2693
            ("src", ChangeStatus::Removed),
2694
            ("tiny.txt", ChangeStatus::Removed)
2695
        ]
2696
    );
2697
    let h2 = repo.commit("move things", &[]).unwrap();
2698
    let c = repo.store().get_change(&h2).unwrap();
2699
    let moves: Vec<_> = c
2700
        .tree_ops
2701
        .iter()
2702
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2703
        .collect();
2704
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
2705
    assert!(c.tree_ops.iter().any(
2706
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2707
    ));
2708
    assert!(c.tree_ops.iter().any(
2709
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2710
    ));
2711
    let snap = repo.load_state(&[h2]).unwrap().materialize();
2712
    assert_eq!(
2713
        snap.files["lib/new.rs"].node, node_old,
2714
        "the node survives the rename"
2715
    );
2716
    assert!(
2717
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2718
    );
2719
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
2720
    assert!(render_change(
2721
        &c,
2722
        &repo.load_state(&[h1]).unwrap(),
2723
        &repo.load_state(&[h1]).unwrap().materialize()
2724
    )
2725
    .contains("R "));
2726
    // A fresh checkout reproduces the tree.
2727
    let other = tempfile::tempdir().unwrap();
2728
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
2729
    assert_eq!(
2730
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2731
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2732
    );
2733
    assert!(!other.path().join("src").exists());
2734
    assert!(!clone.snapshot("status").unwrap().changed);
2735
    // Similarity is line based, byte weighted.
2736
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2737
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2738
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2739
    assert_eq!(similarity(b"", b"x\n"), 0);
2740
}
2741
2742
#[test]
2743
fn git_fetch_and_push_round_trip() {
2744
    hermetic();
2745
    if std::process::Command::new("git")
2746
        .arg("--version")
2747
        .output()
2748
        .is_err()
2749
    {
2750
        eprintln!("git not installed; skipping");
2751
        return;
2752
    }
2753
    let dir = tempfile::tempdir().unwrap();
2754
    let root = dir.path();
2755
    let git_in = |d: &Path, args: &[&str]| -> String {
2756
        let out = std::process::Command::new("git")
2757
            .arg("-C")
2758
            .arg(d)
2759
            .args([
2760
                "-c",
2761
                "user.name=Grace",
2762
                "-c",
2763
                "[email protected]",
2764
                "-c",
2765
                "commit.gpgsign=false",
2766
            ])
2767
            .args(args)
2768
            .output()
2769
            .unwrap();
2770
        assert!(
2771
            out.status.success(),
2772
            "git {args:?}: {}",
2773
            String::from_utf8_lossy(&out.stderr)
2774
        );
2775
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2776
    };
2777
    // A bare "remote" and a work tree that pushes to it.
2778
    let remote = root.join("remote.git");
2779
    fs::create_dir_all(&remote).unwrap();
2780
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2781
    let work = root.join("work");
2782
    git_in(
2783
        root,
2784
        &[
2785
            "clone",
2786
            "-q",
2787
            remote.to_str().unwrap(),
2788
            work.to_str().unwrap(),
2789
        ],
2790
    );
2791
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2792
    write(&work, "README.md", b"# Project\n");
2793
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2794
    git_in(&work, &["add", "."]);
2795
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2796
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2797
    git_in(&work, &["commit", "-q", "-am", "second"]);
2798
    git_in(&work, &["push", "-q", "origin", "main"]);
2799
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2800
2801
    // Fetch into a fresh oxy repository.
2802
    let o = root.join("oxy");
2803
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
2804
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2805
        .unwrap();
2806
    let url = remote.to_string_lossy().to_string();
2807
    let r = repo.git_fetch(&url, "main").unwrap();
2808
    assert_eq!((r.commits, r.heads), (2, 1));
2809
    assert_eq!(
2810
        fs::read(o.join("src/lib.rs")).unwrap(),
2811
        b"pub fn a() {}\npub fn b() {}\n"
2812
    );
2813
    assert!(!repo.snapshot("status").unwrap().changed);
2814
    assert_eq!(
2815
        repo.git_fetch(&url, "main").unwrap().commits,
2816
        0,
2817
        "nothing new"
2818
    );
2819
2820
    // An oxy change, pushed back: one commit on top of the Git tip.
2821
    write(
2822
        &o,
2823
        "src/lib.rs",
2824
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2825
    );
2826
    write(&o, "NOTES.md", b"from oxy\n");
2827
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2828
    let r = repo.git_push(&url, "main").unwrap();
2829
    assert_eq!(r.exported, 1, "{r:?}");
2830
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2831
    assert_eq!(
2832
        git_in(&work, &["log", "--format=%s", "main"]),
2833
        "add c and notes\nsecond\ninitial"
2834
    );
2835
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2836
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2837
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
2838
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2839
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2840
    assert_eq!(
2841
        repo.git_push(&url, "main").unwrap().exported,
2842
        0,
2843
        "already pushed"
2844
    );
2845
2846
    // Git moves on; pushing without fetching is refused, fetching brings
2847
    // the commit in and the working copy follows.
2848
    write(&work, "README.md", b"# Project\n\nMore.\n");
2849
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2850
    git_in(&work, &["push", "-q", "origin", "main"]);
2851
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
2852
    assert!(repo
2853
        .git_push(&url, "main")
2854
        .unwrap_err()
2855
        .to_string()
2856
        .contains("fetch"));
2857
    let r = repo.git_fetch(&url, "main").unwrap();
2858
    assert_eq!(
2859
        (r.commits, r.heads),
2860
        (1, 2),
2861
        "the Git change and the oxy change commute"
2862
    );
2863
    assert_eq!(
2864
        fs::read(o.join("README.md")).unwrap(),
2865
        b"# Project\n\nMore.\n"
2866
    );
2867
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2868
    assert!(!repo.snapshot("status").unwrap().changed);
2869
    // Another oxy change pushes on top of Git's newest commit.
2870
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2871
    repo.commit("notes again", &[]).unwrap();
2872
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2873
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2874
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
2875
    assert_eq!(
2876
        fs::read(work.join("NOTES.md")).unwrap(),
2877
        b"from oxy\nagain\n"
2878
    );
2879
    assert_eq!(
2880
        git_in(&work, &["log", "--format=%s", "main"])
2881
            .lines()
2882
            .count(),
2883
        5
2884
    );
2885
}
2886
2887
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2888
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2889
#[test]
2890
#[ignore]
2891
fn bench_one_gibibyte_file() {
2892
    hermetic();
2893
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2894
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2895
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2896
        None => tempfile::tempdir().unwrap(),
2897
    };
2898
    let root = dir.path();
2899
    let repo = Repo::init(&root.join("r"))
2900
        .unwrap()
2901
        .with_home(root.join("home"));
2902
    let size = 1usize << 30;
2903
    let mut data = vec![0u8; size];
2904
    let mut x = 0x9e3779b97f4a7c15u64;
2905
    for chunk in data.chunks_mut(8) {
2906
        x ^= x << 13;
2907
        x ^= x >> 7;
2908
        x ^= x << 17;
2909
        let b = x.to_le_bytes();
2910
        chunk.copy_from_slice(&b[..chunk.len()]);
2911
    }
2912
    let t = std::time::Instant::now();
2913
    write(&root.join("r"), "big.bin", &data);
2914
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
2915
    let t = std::time::Instant::now();
2916
    let h = repo.commit("big", &[]).unwrap();
2917
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
2918
    let t = std::time::Instant::now();
2919
    assert!(!repo.snapshot("status").unwrap().changed);
2920
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
2921
    let t = std::time::Instant::now();
2922
    let objects = repo.store().list().unwrap().len();
2923
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
2924
    let t = std::time::Instant::now();
2925
    let g = repo.gc(true).unwrap();
2926
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
2927
    let t = std::time::Instant::now();
2928
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
2929
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
2930
    let t = std::time::Instant::now();
2931
    let back = fs::read(root.join("c/big.bin")).unwrap();
2932
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
2933
    eprintln!("read back and verify: {:.2?}", t.elapsed());
2934
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
2935
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
2936
    eprintln!(
2937
        "store size: {:.1} MiB for 1 GiB of data",
2938
        store_bytes as f64 / (1024.0 * 1024.0)
2939
    );
2940
}
2941
2942
fn walkdir_size(p: &Path) -> u64 {
2943
    let mut total = 0;
2944
    if let Ok(rd) = fs::read_dir(p) {
2945
        for e in rd.flatten() {
2946
            let path = e.path();
2947
            if path.is_dir() {
2948
                total += walkdir_size(&path);
2949
            } else if let Ok(m) = fs::metadata(&path) {
2950
                total += m.len();
2951
            }
2952
        }
2953
    }
2954
    total
2955
}
2956
2957
/// An opaque file whose size and mtime match the manifest is not read on
2958
/// the next snapshot: its blob comes from the manifest's stat cache.
2959
#[cfg(unix)]
2960
#[test]
2961
fn stat_cache_skips_reading_unchanged_opaque_files() {
2962
    use std::os::unix::fs::PermissionsExt;
2963
    hermetic();
2964
    let dir = tempfile::tempdir().unwrap();
2965
    let root = dir.path();
2966
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2967
    let mut big = vec![0u8; 300 * 1024];
2968
    for (i, b) in big.iter_mut().enumerate() {
2969
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
2970
    }
2971
    big[0] = 0;
2972
    write(root, "big.bin", &big);
2973
    write(root, "a.txt", b"text\n");
2974
    let h1 = repo.commit("base", &[]).unwrap();
2975
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
2976
    assert!(
2977
        m.entries["big.bin"].blob.is_some(),
2978
        "opaque files record their blob"
2979
    );
2980
    assert!(m.entries["a.txt"].blob.is_none());
2981
    let blob = m.entries["big.bin"].blob.unwrap();
2982
    assert!(repo.store().has(&blob));
2983
2984
    // Files modified within two seconds of the manifest are racy and still
2985
    // read; age the file so the cache applies, then snapshot to record it.
2986
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
2987
    fs::File::options()
2988
        .write(true)
2989
        .open(root.join("big.bin"))
2990
        .unwrap()
2991
        .set_modified(old)
2992
        .unwrap();
2993
    assert!(!repo.snapshot("status").unwrap().changed);
2994
    // Now the file cannot be read at all; the snapshot succeeds without it.
2995
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
2996
    let snap = repo.snapshot("status").unwrap();
2997
    assert!(
2998
        !snap.changed && snap.statuses.is_empty(),
2999
        "{:?}",
3000
        snap.statuses
3001
    );
3002
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3003
    // A real change (new mtime, new content) is seen and committed correctly.
3004
    let mut big2 = big.clone();
3005
    big2[10] ^= 0xff;
3006
    write(root, "big.bin", &big2);
3007
    let snap = repo.snapshot("status").unwrap();
3008
    assert_eq!(
3009
        snap.statuses
3010
            .iter()
3011
            .map(|s| (s.path.as_str(), s.status))
3012
            .collect::<Vec<_>>(),
3013
        vec![("big.bin", ChangeStatus::Modified)]
3014
    );
3015
    let h2 = repo.commit("edit", &[]).unwrap();
3016
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3017
    assert_eq!(
3018
        files["big.bin"].content,
3019
        FileContent::Opaque {
3020
            blobs: vec![Repo::blob_ref(&big2)]
3021
        }
3022
    );
3023
    // Checkout writes a manifest with blobs too, so the next status is cached.
3024
    repo.checkout(&[h1], false, "checkout").unwrap();
3025
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3026
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3027
    assert!(!repo.snapshot("status").unwrap().changed);
3028
}
3029
3030
#[test]
3031
fn status_json_lists_conflicts_with_contributors() {
3032
    hermetic();
3033
    let dir = tempfile::tempdir().unwrap();
3034
    let root = dir.path();
3035
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3036
    write(root, "a.txt", b"one\n");
3037
    let h1 = repo.commit("base", &[]).unwrap();
3038
    write(root, "a.txt", b"one\nleft\n");
3039
    let ha = repo.commit("left", &[]).unwrap();
3040
    repo.checkout(&[h1], true, "checkout").unwrap();
3041
    write(root, "a.txt", b"one\nright\n");
3042
    let hb = repo.commit("right", &[]).unwrap();
3043
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3044
    let snap = repo.snapshot("status").unwrap();
3045
    assert!(snap.base_snapshot.is_conflicted());
3046
    let json = repo.status_json(&snap).unwrap();
3047
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3048
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3049
    assert!(json.contains("\"conflicted\":true"), "{json}");
3050
    assert!(
3051
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3052
        "{json}"
3053
    );
3054
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3055
    assert!(json.contains("\"resolved\":false"), "{json}");
3056
    assert!(json.starts_with('{') && json.ends_with('}'));
3057
    // Resolve and the report says so; a clean copy has no conflicts.
3058
    write(root, "a.txt", b"one\nleft\nright\n");
3059
    let snap = repo.snapshot("status").unwrap();
3060
    let json = repo.status_json(&snap).unwrap();
3061
    assert!(json.contains("\"resolved\":true"), "{json}");
3062
    repo.commit("resolve", &[]).unwrap();
3063
    let snap = repo.snapshot("status").unwrap();
3064
    let json = repo.status_json(&snap).unwrap();
3065
    assert!(
3066
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3067
        "{json}"
3068
    );
3069
}
3070
3071
#[test]
3072
fn ignore_rules_do_not_untrack_files() {
3073
    hermetic();
3074
    let dir = tempfile::tempdir().unwrap();
3075
    let root = dir.path();
3076
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3077
    write(root, "src.c", b"int x;\n");
3078
    write(root, "build/out.o", b"\0obj");
3079
    write(root, "sub/keep.log", b"keep\n");
3080
    write(root, "sub/junk.log", b"junk\n");
3081
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3082
    let snap = repo.snapshot("status").unwrap();
3083
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3084
    assert_eq!(
3085
        added,
3086
        vec![".oxyignore", "src.c", "sub/keep.log"],
3087
        "anchored, glob, and negated rules"
3088
    );
3089
    let h1 = repo.commit("base", &[]).unwrap();
3090
    // Ignoring a tracked file changes nothing about it.
3091
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3092
    let snap = repo.snapshot("status").unwrap();
3093
    assert_eq!(
3094
        snap.statuses
3095
            .iter()
3096
            .map(|s| s.path.as_str())
3097
            .collect::<Vec<_>>(),
3098
        vec![".oxyignore"]
3099
    );
3100
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3101
    assert!(repo
3102
        .load_state(&[h2])
3103
        .unwrap()
3104
        .materialize()
3105
        .files
3106
        .contains_key("src.c"));
3107
    // Its edits are still seen, by status and by the prompt.
3108
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3109
    write(root, "src.c", b"int x, y;\n");
3110
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3111
    let snap = repo.snapshot("status").unwrap();
3112
    assert_eq!(
3113
        snap.statuses
3114
            .iter()
3115
            .map(|s| (s.path.as_str(), s.status))
3116
            .collect::<Vec<_>>(),
3117
        vec![("src.c", ChangeStatus::Modified)]
3118
    );
3119
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3120
    assert!(
3121
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3122
    );
3123
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3124
    fs::remove_file(root.join("src.c")).unwrap();
3125
    let snap = repo.snapshot("status").unwrap();
3126
    assert_eq!(
3127
        snap.statuses
3128
            .iter()
3129
            .map(|s| (s.path.as_str(), s.status))
3130
            .collect::<Vec<_>>(),
3131
        vec![("src.c", ChangeStatus::Removed)]
3132
    );
3133
    repo.checkout(&[h3], true, "checkout").unwrap();
3134
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3135
    assert!(!repo.snapshot("status").unwrap().changed);
3136
    let _ = h1;
3137
}
3138
3139
#[test]
3140
fn split_works_on_non_heads_by_node() {
3141
    hermetic();
3142
    let dir = tempfile::tempdir().unwrap();
3143
    let root = dir.path();
3144
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3145
    write(root, "a.txt", b"one\n");
3146
    write(root, "junk/x.lock", b"lock\n");
3147
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3148
    write(root, "a.txt", b"one\ntwo\n");
3149
    let h2 = repo.commit("more work", &[]).unwrap();
3150
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3151
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3152
    // h1 is not a head: split it by node.
3153
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3154
    assert_ne!(h1b, h1);
3155
    assert_eq!(
3156
        repo.store().get_change(&h1b).unwrap().change_id,
3157
        id1,
3158
        "the rest keeps the ChangeId"
3159
    );
3160
    let junk = repo.store().get_change(&hj).unwrap();
3161
    assert!(junk.tree_ops.iter().all(
3162
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3163
    ));
3164
    let heads = repo.bookmark_heads().unwrap();
3165
    assert!(
3166
        heads.contains(&hj),
3167
        "the split-off part is a head of its own"
3168
    );
3169
    let snap = repo.load_state(&heads).unwrap().materialize();
3170
    assert!(
3171
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3172
        "the dependent was rewritten onto the new hash"
3173
    );
3174
    assert!(snap.files.contains_key("junk/x.lock"));
3175
    let h2b = heads
3176
        .iter()
3177
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3178
        .copied()
3179
        .unwrap();
3180
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3181
    assert!(!repo.snapshot("status").unwrap().changed);
3182
    // Abandoning the split-off head removes the junk from history.
3183
    repo.abandon(&hj).unwrap();
3184
    let heads = repo.bookmark_heads().unwrap();
3185
    let snap = repo.load_state(&heads).unwrap().materialize();
3186
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3187
    assert!(snap.files.contains_key("a.txt"));
3188
    // A dependent that touches the split-off paths blocks the split.
3189
    write(root, "junk/y.lock", b"y\n");
3190
    let hb = repo.commit("junk base", &[]).unwrap();
3191
    write(root, "junk/y.lock", b"yy\n");
3192
    write(root, "b.txt", b"b\n");
3193
    repo.commit("touches junk", &[]).unwrap();
3194
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3195
    assert!(err.contains("depends on the split-off paths"), "{err}");
3196
}
3197
3198
#[test]
3199
fn bookmarks_switch_merge_and_push() {
3200
    hermetic();
3201
    let dir = tempfile::tempdir().unwrap();
3202
    let root = dir.path();
3203
    let origin = Repo::init(&root.join("origin")).unwrap();
3204
    let url = root.join("origin").to_string_lossy().to_string();
3205
    let mut repo = Repo::clone(&url, &root.join("r"))
3206
        .unwrap()
3207
        .with_home(root.join("home"));
3208
    let r = root.join("r");
3209
    write(&r, "a.txt", b"a\n");
3210
    let h_a = repo.commit("a", &[]).unwrap();
3211
    assert!(repo.push("origin", false).unwrap()[0].ok);
3212
3213
    // A bookmark at the working copy's base, then work on it.
3214
    assert!(repo.bookmark_create("bad name..", None).is_err());
3215
    assert!(repo.bookmark_create("-x", None).is_err());
3216
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3217
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3218
    repo.bookmark_switch("feature", false).unwrap();
3219
    assert_eq!(repo.config.bookmark, "feature");
3220
    write(&r, "a.txt", b"a\nb\n");
3221
    write(&r, "b.txt", b"b\n");
3222
    let h_b = repo.commit("b on feature", &[]).unwrap();
3223
    assert_eq!(
3224
        repo.bookmark_heads().unwrap(),
3225
        vec![h_b],
3226
        "b edits a.txt, so it depends on a"
3227
    );
3228
    assert_eq!(
3229
        repo.resolve_heads("main").unwrap(),
3230
        vec![h_a],
3231
        "main is untouched"
3232
    );
3233
    assert_eq!(
3234
        repo.resolve_change("feature").unwrap(),
3235
        h_b,
3236
        "a one-head bookmark names its change"
3237
    );
3238
    // Reopening keeps the workspace's bookmark.
3239
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3240
    assert_eq!(reopened.config.bookmark, "feature");
3241
    // Back to main: b.txt goes away; work there.
3242
    repo.bookmark_switch("main", false).unwrap();
3243
    assert!(!r.join("b.txt").exists());
3244
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3245
    write(&r, "c.txt", b"c\n");
3246
    let h_c = repo.commit("c on main", &[]).unwrap();
3247
    let list = repo.bookmarks().unwrap();
3248
    assert_eq!(
3249
        list.iter()
3250
            .map(|b| (b.name.as_str(), b.current))
3251
            .collect::<Vec<_>>(),
3252
        vec![("feature", false), ("main", true)]
3253
    );
3254
    assert_eq!(
3255
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3256
        Some(1),
3257
        "c is not on origin yet"
3258
    );
3259
    // Merge feature into main: the union, both heads, no merge change.
3260
    let m = repo.merge("feature").unwrap();
3261
    assert!(m.changed && m.checked_out);
3262
    let mut want = vec![h_b, h_c];
3263
    want.sort();
3264
    assert_eq!(m.heads, want);
3265
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3266
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3267
    assert!(repo.merge("main").is_err());
3268
    // The other bookmark can be pushed by name and appears at origin.
3269
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3270
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3271
    assert!(repo.push("origin", false).unwrap()[0].ok);
3272
    assert_eq!(
3273
        repo.bookmarks()
3274
            .unwrap()
3275
            .iter()
3276
            .find(|b| b.name == "main")
3277
            .unwrap()
3278
            .ahead,
3279
        Some(0)
3280
    );
3281
    // A second workspace inherits the current bookmark and can switch independently.
3282
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3283
    assert_eq!(ws.config.bookmark, "main");
3284
    let mut ws = ws;
3285
    ws.bookmark_switch("feature", false).unwrap();
3286
    assert_eq!(
3287
        Repo::open(&r).unwrap().config.bookmark,
3288
        "main",
3289
        "the first workspace is unaffected"
3290
    );
3291
    assert!(
3292
        repo.bookmark_delete("feature").is_err(),
3293
        "current bookmark of another workspace"
3294
    );
3295
    ws.bookmark_switch("main", false).unwrap();
3296
    // Set and delete.
3297
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3298
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3299
    repo.bookmark_delete("feature").unwrap();
3300
    assert!(repo.resolve_heads("feature").is_err());
3301
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3302
    assert!(
3303
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3304
        "changes of a deleted bookmark remain"
3305
    );
3306
}
3307
3308
#[test]
3309
fn oxygen_subrepos_pin_follow_and_update() {
3310
    hermetic();
3311
    let dir = tempfile::tempdir().unwrap();
3312
    let root = dir.path();
3313
    // A library repository with two commits, and a bare-ish origin for it.
3314
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3315
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3316
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3317
        .unwrap()
3318
        .with_home(root.join("home"));
3319
    write(&root.join("lib"), "lib.txt", b"v1\n");
3320
    let l1 = lib.commit("lib v1", &[]).unwrap();
3321
    assert!(lib.push("origin", false).unwrap()[0].ok);
3322
    let _ = lib_origin;
3323
3324
    // The application (a clone of its own origin) adds it as a subrepo.
3325
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3326
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3327
    let _ = app_origin;
3328
    let app_dir = root.join("app");
3329
    let app = Repo::clone(&app_url, &app_dir)
3330
        .unwrap()
3331
        .with_home(root.join("home"));
3332
    write(&app_dir, "main.txt", b"app\n");
3333
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3334
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3335
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3336
    let snap = app.snapshot("status").unwrap();
3337
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3338
    assert_eq!(
3339
        paths,
3340
        vec![".oxymodules", "libs/lib", "main.txt"],
3341
        "the nested files are not walked"
3342
    );
3343
    let a1 = app.commit("app with lib", &[]).unwrap();
3344
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3345
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3346
    assert!(!files.contains_key("libs/lib/lib.txt"));
3347
    assert!(!app.snapshot("status").unwrap().changed);
3348
    let subs = app.subrepos().unwrap();
3349
    assert_eq!(subs.len(), 1);
3350
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3351
3352
    // Advance the nested repository: the parent sees a modified pin.
3353
    let nested = Repo::open(&app_dir.join("libs/lib"))
3354
        .unwrap()
3355
        .with_home(root.join("home"));
3356
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3357
    let l2 = nested.commit("lib v2", &[]).unwrap();
3358
    assert!(nested.push("origin", false).unwrap()[0].ok);
3359
    let snap = app.snapshot("status").unwrap();
3360
    assert_eq!(
3361
        snap.statuses
3362
            .iter()
3363
            .map(|s| (s.path.as_str(), s.status))
3364
            .collect::<Vec<_>>(),
3365
        vec![("libs/lib", ChangeStatus::Modified)]
3366
    );
3367
    let a2 = app.commit("bump lib", &[]).unwrap();
3368
    // Checking out the older app state brings the nested working copy back
3369
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3370
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3371
    assert!(
3372
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3373
        "{:?}",
3374
        r.notes
3375
    );
3376
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3377
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3378
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3379
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3380
    assert!(!app.snapshot("status").unwrap().changed);
3381
    // A dirty nested repository is left alone and reported.
3382
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3383
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3384
    assert!(
3385
        r.notes.iter().any(|n| n.contains("uncommitted")),
3386
        "{:?}",
3387
        r.notes
3388
    );
3389
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3390
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3391
    let r = app.submodule_update(false, &[]).unwrap();
3392
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3393
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3394
    let _ = l2;
3395
3396
    // A fresh clone of the app has the pin but no nested repository until update --init.
3397
    assert!(app.push("origin", false).unwrap()[0].ok);
3398
    let clone_dir = root.join("app-clone");
3399
    let clone = Repo::clone(&app_url, &clone_dir)
3400
        .unwrap()
3401
        .with_home(root.join("home"));
3402
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3403
    assert_eq!(
3404
        clone.submodule_update(false, &[]).unwrap(),
3405
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3406
    );
3407
    assert_eq!(
3408
        clone.submodule_update(true, &[]).unwrap(),
3409
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3410
    );
3411
    assert_eq!(
3412
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3413
        b"v2\n"
3414
    );
3415
    assert!(!clone.snapshot("status").unwrap().changed);
3416
    // Removing the subrepo leaves the directory and drops the node.
3417
    clone.submodule_remove("libs/lib").unwrap();
3418
    let snap = clone.snapshot("status").unwrap();
3419
    assert!(
3420
        snap.statuses
3421
            .iter()
3422
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3423
        "{:?}",
3424
        snap.statuses
3425
    );
3426
    let c = clone.commit("drop lib", &[]).unwrap();
3427
    assert!(!clone
3428
        .load_state(&[c])
3429
        .unwrap()
3430
        .materialize()
3431
        .files
3432
        .contains_key("libs/lib"));
3433
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3434
    assert!(
3435
        !clone.snapshot("status").unwrap().changed,
3436
        "an unregistered nested repository is ignored"
3437
    );
3438
}
3439
3440
#[test]
3441
fn git_submodules_import_and_export_as_gitlinks() {
3442
    hermetic();
3443
    if std::process::Command::new("git")
3444
        .arg("--version")
3445
        .output()
3446
        .is_err()
3447
    {
3448
        eprintln!("git not installed; skipping");
3449
        return;
3450
    }
3451
    let dir = tempfile::tempdir().unwrap();
3452
    let root = dir.path();
3453
    let git_in = |d: &Path, args: &[&str]| -> String {
3454
        let out = std::process::Command::new("git")
3455
            .arg("-C")
3456
            .arg(d)
3457
            .args([
3458
                "-c",
3459
                "user.name=Grace",
3460
                "-c",
3461
                "[email protected]",
3462
                "-c",
3463
                "commit.gpgsign=false",
3464
                "-c",
3465
                "protocol.file.allow=always",
3466
            ])
3467
            .args(args)
3468
            .output()
3469
            .unwrap();
3470
        assert!(
3471
            out.status.success(),
3472
            "git {args:?}: {}",
3473
            String::from_utf8_lossy(&out.stderr)
3474
        );
3475
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3476
    };
3477
    let sub = root.join("sub");
3478
    fs::create_dir_all(&sub).unwrap();
3479
    git_in(&sub, &["init", "-q", "-b", "main"]);
3480
    write(&sub, "s.txt", b"sub\n");
3481
    git_in(&sub, &["add", "."]);
3482
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3483
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3484
    let g = root.join("main.git");
3485
    fs::create_dir_all(&g).unwrap();
3486
    git_in(&g, &["init", "-q", "-b", "main"]);
3487
    write(&g, "README.md", b"# app\n");
3488
    git_in(&g, &["add", "."]);
3489
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3490
    git_in(
3491
        &g,
3492
        &[
3493
            "submodule",
3494
            "add",
3495
            "-q",
3496
            sub.to_str().unwrap(),
3497
            "vendor/sub",
3498
        ],
3499
    );
3500
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3501
3502
    let dest = root.join("oxy");
3503
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3504
    let rep = repo.import_git(&g, "main").unwrap();
3505
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3506
    let files = repo
3507
        .load_state(&repo.bookmark_heads().unwrap())
3508
        .unwrap()
3509
        .materialize()
3510
        .files;
3511
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3512
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3513
        panic!()
3514
    };
3515
    assert_eq!(
3516
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3517
        crate::subrepo::Pin::Git {
3518
            sha: sub_sha.clone(),
3519
            branch: "HEAD".into()
3520
        }
3521
    );
3522
    let modules =
3523
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3524
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3525
    assert!(modules.entries["vendor/sub"].git);
3526
    assert!(
3527
        files.contains_key(".gitmodules"),
3528
        "the Git file is kept for round trips"
3529
    );
3530
    assert!(
3531
        !dest.join("vendor/sub/.git").exists(),
3532
        "not cloned until update --init"
3533
    );
3534
    assert!(!repo.snapshot("status").unwrap().changed);
3535
    // update --init clones it at the pinned commit; status is unchanged.
3536
    assert_eq!(
3537
        repo.submodule_update(true, &[]).unwrap(),
3538
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3539
    );
3540
    assert_eq!(
3541
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3542
        sub_sha
3543
    );
3544
    assert!(!repo.snapshot("status").unwrap().changed);
3545
    // Export writes the gitlink and .gitmodules back.
3546
    let mirror = root.join("mirror.git");
3547
    let rep = repo.git_export(&mirror).unwrap();
3548
    assert_eq!(rep.skipped_subrepos, 0);
3549
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3550
    assert!(
3551
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3552
        "{ls}"
3553
    );
3554
    assert_eq!(
3555
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3556
        ".gitmodules\nREADME.md\nvendor"
3557
    );
3558
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3559
    assert_eq!(
3560
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3561
        orig_tree,
3562
        "tree round trip"
3563
    );
3564
}
3565
3566
#[test]
3567
fn partial_commits_by_path_and_by_hunk() {
3568
    hermetic();
3569
    let dir = tempfile::tempdir().unwrap();
3570
    let root = dir.path();
3571
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3572
    write(root, "a.txt", b"1\n2\n3\n");
3573
    write(root, "b.txt", b"b\n");
3574
    let h0 = repo.commit("base", &[]).unwrap();
3575
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3576
    write(root, "b.txt", b"b\nbb\n");
3577
    write(root, "c.txt", b"c\n");
3578
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3579
    let h1 = repo
3580
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3581
        .unwrap();
3582
    let c1 = repo.store().get_change(&h1).unwrap();
3583
    assert!(
3584
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3585
        "{:?}",
3586
        c1.tree_ops
3587
    );
3588
    assert_eq!(c1.deps, vec![h0]);
3589
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3590
    assert!(
3591
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3592
    );
3593
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3594
    assert!(!files.contains_key("c.txt"));
3595
    let snap = repo.snapshot("status").unwrap();
3596
    assert_eq!(
3597
        snap.statuses
3598
            .iter()
3599
            .map(|s| (s.path.as_str(), s.status))
3600
            .collect::<Vec<_>>(),
3601
        vec![
3602
            ("b.txt", ChangeStatus::Modified),
3603
            ("c.txt", ChangeStatus::Added)
3604
        ]
3605
    );
3606
    assert_eq!(
3607
        fs::read(root.join("b.txt")).unwrap(),
3608
        b"b\nbb\n",
3609
        "disk untouched"
3610
    );
3611
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3612
    let (_, hunks) = repo.hunks().unwrap();
3613
    let b_hunk = hunks
3614
        .iter()
3615
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3616
        .unwrap()
3617
        .index;
3618
    let h2 = repo
3619
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3620
        .unwrap();
3621
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3622
    assert!(
3623
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3624
    );
3625
    assert!(!files.contains_key("c.txt"));
3626
    let snap = repo.snapshot("status").unwrap();
3627
    assert_eq!(
3628
        snap.statuses
3629
            .iter()
3630
            .map(|s| s.path.as_str())
3631
            .collect::<Vec<_>>(),
3632
        vec!["c.txt"]
3633
    );
3634
    // Choosing only the content hunk of a file in a new directory pulls in
3635
    // the directory and file additions it needs.
3636
    write(root, "d/e.txt", b"e\n");
3637
    let (_, hunks) = repo.hunks().unwrap();
3638
    let e_insert = hunks
3639
        .iter()
3640
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3641
        .unwrap()
3642
        .index;
3643
    let h3 = repo
3644
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3645
        .unwrap();
3646
    let c3 = repo.store().get_change(&h3).unwrap();
3647
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3648
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3649
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3650
    // Choosing a new file's addition hunk brings its content along.
3651
    write(root, "f/g.txt", b"g\n");
3652
    let (_, hunks) = repo.hunks().unwrap();
3653
    let g_add = hunks
3654
        .iter()
3655
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3656
        .unwrap()
3657
        .index;
3658
    let h4 = repo
3659
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3660
        .unwrap();
3661
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
3662
    assert!(
3663
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3664
    );
3665
    assert!(!repo
3666
        .snapshot("status")
3667
        .unwrap()
3668
        .statuses
3669
        .iter()
3670
        .any(|s| s.path == "f/g.txt"));
3671
    // Everything left commits normally; the working copy is then clean.
3672
    repo.commit("the rest", &[]).unwrap();
3673
    assert!(!repo.snapshot("status").unwrap().changed);
3674
    let files = repo
3675
        .load_state(&repo.bookmark_heads().unwrap())
3676
        .unwrap()
3677
        .materialize()
3678
        .files;
3679
    assert!(files.contains_key("c.txt"));
3680
}
3681
3682
#[test]
3683
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3684
    hermetic();
3685
    let dir = tempfile::tempdir().unwrap();
3686
    let root = dir.path();
3687
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3688
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3689
        .unwrap();
3690
    write(root, "a.txt", b"one\n");
3691
    let h1 = repo.commit("first", &[]).unwrap();
3692
    write(root, "a.txt", b"one\ntwo\n");
3693
    let h2 = repo.commit("second", &[]).unwrap();
3694
    let b = repo.blame("a.txt").unwrap();
3695
    assert_eq!(
3696
        b.iter()
3697
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3698
            .collect::<Vec<_>>(),
3699
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3700
    );
3701
    assert!(b.iter().all(|l| l.author == "Ada"));
3702
    assert_eq!(
3703
        b[0].change_id,
3704
        repo.store().get_change(&h1).unwrap().change_id
3705
    );
3706
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3707
    repo.commit("rename", &[]).unwrap();
3708
    let b = repo.blame("b.txt").unwrap();
3709
    assert_eq!(
3710
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3711
        vec![h1, h2],
3712
        "the node survives the rename"
3713
    );
3714
    assert!(repo.blame("a.txt").is_err());
3715
}
3716
3717
#[test]
3718
fn bisect_finds_the_first_bad_change() {
3719
    hermetic();
3720
    let dir = tempfile::tempdir().unwrap();
3721
    let root = dir.path();
3722
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3723
    let mut content = String::new();
3724
    let mut hashes = Vec::new();
3725
    for i in 1..=8 {
3726
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3727
        write(root, "f.txt", content.as_bytes());
3728
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3729
    }
3730
    // Each step appends after the previous line, so the chain is linear.
3731
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3732
    repo.bisect_start().unwrap();
3733
    assert!(matches!(
3734
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3735
        BisectStep::NeedMarks { good: 1, bad: 0 }
3736
    ));
3737
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3738
    assert!(
3739
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3740
        "{step:?}"
3741
    );
3742
    // Automated: bad when the bug line is present.
3743
    let step = repo
3744
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3745
        .unwrap();
3746
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3747
    assert_eq!(
3748
        repo.bisect_status().unwrap(),
3749
        Some(BisectStep::Found { culprit: hashes[4] })
3750
    );
3751
    repo.bisect_reset().unwrap();
3752
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3753
    assert!(repo.bisect_status().unwrap().is_none());
3754
    assert!(!repo.snapshot("status").unwrap().changed);
3755
    // Manual marks and a skip.
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 skipped_once = false;
3760
    let mut guard = 0;
3761
    while let BisectStep::Testing { .. } = step {
3762
        guard += 1;
3763
        assert!(guard < 20);
3764
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3765
        if !skipped_once && text.contains("line 6") {
3766
            // An untestable state away from the boundary: the search routes around it.
3767
            skipped_once = true;
3768
            step = repo.bisect_mark(None, &[]).unwrap();
3769
            continue;
3770
        }
3771
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3772
    }
3773
    assert!(skipped_once);
3774
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3775
    repo.bisect_reset().unwrap();
3776
    // Skipping the culprit itself leaves it among the candidates reported.
3777
    repo.bisect_start().unwrap();
3778
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3779
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3780
    let mut guard = 0;
3781
    while let BisectStep::Testing { heads, .. } = &step {
3782
        guard += 1;
3783
        assert!(guard < 20);
3784
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3785
        let is_culprit_state =
3786
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3787
        step = if is_culprit_state {
3788
            repo.bisect_mark(None, &[]).unwrap()
3789
        } else {
3790
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3791
        };
3792
    }
3793
    match step {
3794
        BisectStep::Inconclusive { candidates } => assert!(
3795
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3796
            "{candidates:?}"
3797
        ),
3798
        other => panic!("{other:?}"),
3799
    }
3800
    repo.bisect_reset().unwrap();
3801
}
3802
3803
#[test]
3804
fn squash_folds_a_change_into_its_dependency() {
3805
    hermetic();
3806
    let dir = tempfile::tempdir().unwrap();
3807
    let root = dir.path();
3808
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3809
    write(root, "a.txt", b"1\n");
3810
    let a = repo.commit("A", &[]).unwrap();
3811
    write(root, "a.txt", b"1\n2\n");
3812
    let c = repo.commit("C", &[]).unwrap();
3813
    write(root, "a.txt", b"1\n2\n3\n");
3814
    let e = repo.commit("E", &[]).unwrap();
3815
    write(root, "b.txt", b"b\n");
3816
    let b = repo.commit("B", &[]).unwrap();
3817
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3818
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3819
    // E depends on C which A lacks: refused, naming it.
3820
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3821
    assert!(err.contains(&c.short(12)), "{err}");
3822
    // C into A: A' has both, C is gone, E follows and still reads the same.
3823
    let a2 = repo.squash(&c, &a).unwrap();
3824
    let a2c = repo.store().get_change(&a2).unwrap();
3825
    assert_eq!(a2c.change_id, id_a);
3826
    assert!(a2c.deps.is_empty());
3827
    let heads = repo.bookmark_heads().unwrap();
3828
    let st = repo.load_state(&heads).unwrap();
3829
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
3830
    let e2 = st
3831
        .changes()
3832
        .find(|(_, m)| m.change_id == id_e)
3833
        .map(|(h, _)| *h)
3834
        .unwrap();
3835
    assert_eq!(
3836
        repo.store().get_change(&e2).unwrap().deps,
3837
        vec![a2],
3838
        "E now depends on A' alone"
3839
    );
3840
    let files = st.materialize().files;
3841
    assert!(
3842
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3843
    );
3844
    assert!(files.contains_key("b.txt"));
3845
    assert!(st.contains(&b));
3846
    assert!(!repo.snapshot("status").unwrap().changed);
3847
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3848
    // Undo restores the three original changes.
3849
    repo.undo().unwrap();
3850
    repo.undo().unwrap();
3851
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3852
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3853
}
3854
3855
#[test]
3856
fn rebase_re_expresses_a_change_against_another_base() {
3857
    hermetic();
3858
    let dir = tempfile::tempdir().unwrap();
3859
    let root = dir.path();
3860
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3861
    write(root, "a.txt", b"1\n2\n");
3862
    let a = repo.commit("A", &[]).unwrap();
3863
    write(root, "a.txt", b"1\n2\n3\n");
3864
    let c = repo.commit("C: append 3", &[]).unwrap();
3865
    write(root, "a.txt", b"1\n2\n3\n4\n");
3866
    let e = repo.commit("E: append 4", &[]).unwrap();
3867
    // A different base: A plus a change that prepends a line.
3868
    repo.checkout(&[a], true, "checkout").unwrap();
3869
    write(root, "a.txt", b"0\n1\n2\n");
3870
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3871
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3872
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3873
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3874
    let c2 = repo.rebase(&c, &[d]).unwrap();
3875
    let c2c = repo.store().get_change(&c2).unwrap();
3876
    assert_eq!(c2c.change_id, id_c);
3877
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3878
    let heads = repo.bookmark_heads().unwrap();
3879
    let st = repo.load_state(&heads).unwrap();
3880
    assert!(!st.contains(&c) && st.contains(&d));
3881
    let e2 = st
3882
        .changes()
3883
        .find(|(_, m)| m.change_id == id_e)
3884
        .map(|(h, _)| *h)
3885
        .unwrap();
3886
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
3887
    assert!(
3888
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3889
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3890
    );
3891
    let files = st.materialize().files;
3892
    assert!(
3893
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3894
        "{:?}",
3895
        files["a.txt"].content
3896
    );
3897
    assert!(!files["a.txt"].is_conflicted());
3898
    // Rebasing onto a state that already contains the change is refused.
3899
    assert!(repo.rebase(&c2, &[c2]).is_err());
3900
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
3901
    assert!(
3902
        err.contains("lacks dependencies"),
3903
        "E needs C, which D's state does not have: {err}"
3904
    );
3905
}
3906
3907
#[test]
3908
fn unsigned_tags_keep_their_message() {
3909
    hermetic();
3910
    let dir = tempfile::tempdir().unwrap();
3911
    let root = dir.path();
3912
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3913
    write(root, "a.txt", b"a\n");
3914
    repo.commit("a", &[]).unwrap();
3915
    assert!(repo.secret_key().unwrap().is_none());
3916
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
3917
        .unwrap();
3918
    let tags = repo.tags().unwrap();
3919
    assert_eq!(
3920
        (
3921
            tags[0].name.as_str(),
3922
            tags[0].message.as_str(),
3923
            tags[0].signer.as_deref()
3924
        ),
3925
        ("v1", "first release", None)
3926
    );
3927
    assert!(
3928
        repo.tag_refs().unwrap()[0].attestation.is_none(),
3929
        "an unsigned attestation is not advertised"
3930
    );
3931
}
3932
3933
#[test]
3934
fn fsck_passes_a_sound_repository_and_names_each_fault() {
3935
    hermetic();
3936
    let dir = tempfile::tempdir().unwrap();
3937
    let root = dir.path();
3938
    let origin_path = root.join("origin");
3939
    let origin = Repo::init(&origin_path).unwrap();
3940
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
3941
        .unwrap()
3942
        .with_home(root.join("home-a"));
3943
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
3944
        .unwrap();
3945
    write(&root.join("a"), "f.txt", b"one\n");
3946
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
3947
    let h1 = a.commit("first", &[]).unwrap();
3948
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
3949
    let h2 = a.commit("second", &[]).unwrap();
3950
    a.tag_create("v1", &[h2], "first release").unwrap();
3951
    a.checkpoint().unwrap();
3952
    assert!(a.push("origin", false).unwrap()[0].ok);
3953
3954
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
3955
    for repo in [&a, &origin] {
3956
        let rep = repo.fsck().unwrap();
3957
        assert_eq!(rep.problems, vec![], "{rep:?}");
3958
        // The two commits, plus the working copy's change in `a`.
3959
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
3960
        assert!(rep.ops > 1 && rep.objects > 5);
3961
    }
3962
    assert!(origin.fsck().unwrap().attestations >= 1);
3963
3964
    // A flipped byte in a stored object is corruption, named by hash.
3965
    let c1 = a.store().path_for(&h1);
3966
    let pristine = fs::read(&c1).unwrap();
3967
    let mut bytes = pristine.clone();
3968
    *bytes.last_mut().unwrap() ^= 1;
3969
    fs::write(&c1, &bytes).unwrap();
3970
    let rep = a.fsck().unwrap();
3971
    assert!(rep.errors() >= 1);
3972
    assert!(
3973
        rep.problems
3974
            .iter()
3975
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
3976
        "{rep:?}"
3977
    );
3978
    fs::write(&c1, &pristine).unwrap();
3979
    assert_eq!(a.fsck().unwrap().errors(), 0);
3980
3981
    // A missing change is named with what needed it.
3982
    fs::remove_file(&c1).unwrap();
3983
    let rep = a.fsck().unwrap();
3984
    assert!(
3985
        rep.problems.iter().any(|p| p.severity == Severity::Error
3986
            && p.object == Some(h1)
3987
            && p.what.contains("change missing, needed by change")),
3988
        "{rep:?}"
3989
    );
3990
    fs::write(&c1, &pristine).unwrap();
3991
3992
    // A missing blob is an error in a full clone.
3993
    let c2 = a.store().get_change(&h1).unwrap();
3994
    let blob = c2
3995
        .edits
3996
        .iter()
3997
        .find_map(|e| match e {
3998
            Edit::Replace { new: Some(b), .. } => Some(*b),
3999
            _ => None,
4000
        })
4001
        .expect("the binary file is a blob");
4002
    let bp = a.store().path_for(&blob);
4003
    let blob_bytes = fs::read(&bp).unwrap();
4004
    fs::remove_file(&bp).unwrap();
4005
    let rep = a.fsck().unwrap();
4006
    assert!(
4007
        rep.problems
4008
            .iter()
4009
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4010
        "{rep:?}"
4011
    );
4012
    fs::write(&bp, &blob_bytes).unwrap();
4013
4014
    // A broken op log head is reported, not a crash.
4015
    let head = root.join("a/.oxy/ops/head");
4016
    let saved = fs::read(&head).unwrap();
4017
    fs::write(&head, b"not a hash").unwrap();
4018
    let rep = a.fsck().unwrap();
4019
    assert!(
4020
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4021
        "{rep:?}"
4022
    );
4023
    fs::write(&head, saved).unwrap();
4024
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4025
}
4026
4027
/// Copy a directory tree (for restoring a pristine repository).
4028
fn copy_tree(from: &Path, to: &Path) {
4029
    fs::create_dir_all(to).unwrap();
4030
    for e in fs::read_dir(from).unwrap() {
4031
        let e = e.unwrap();
4032
        let target = to.join(e.file_name());
4033
        if e.file_type().unwrap().is_dir() {
4034
            copy_tree(&e.path(), &target);
4035
        } else {
4036
            fs::copy(e.path(), &target).unwrap();
4037
        }
4038
    }
4039
}
4040
4041
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4042
/// would, and check that both repositories still open, pass `fsck`, and
4043
/// accept the same operation again.
4044
#[test]
4045
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4046
    use crate::durable::failpoint;
4047
    hermetic();
4048
    let dir = tempfile::tempdir().unwrap();
4049
    let pristine = dir.path().join("pristine");
4050
    let origin_path = pristine.join("origin");
4051
    Repo::init(&origin_path).unwrap();
4052
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4053
        .unwrap()
4054
        .with_home(dir.path().join("home"));
4055
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4056
        .unwrap();
4057
    write(&pristine.join("a"), "f.txt", b"one\n");
4058
    a.commit("first", &[]).unwrap();
4059
    assert!(a.push("origin", false).unwrap()[0].ok);
4060
    drop(a);
4061
4062
    type Op = fn(&Repo) -> Result<()>;
4063
    let edit_and_commit: Op = |r| {
4064
        write(r.root(), "f.txt", b"one\ntwo\n");
4065
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4066
        r.commit("second", &[]).map(|_| ())
4067
    };
4068
    let push: Op = |r| {
4069
        let res = r.push("origin", false)?;
4070
        if res.iter().all(|x| x.ok) {
4071
            Ok(())
4072
        } else {
4073
            Err(RepoError::Msg(format!("{res:?}")))
4074
        }
4075
    };
4076
4077
    for (name, prepare, op) in [
4078
        ("commit", None, edit_and_commit),
4079
        ("push", Some(edit_and_commit), push),
4080
    ] {
4081
        let mut steps = 0;
4082
        for n in 1.. {
4083
            let run = dir.path().join(format!("{name}-{n}"));
4084
            copy_tree(&pristine, &run);
4085
            // Clones record their remote by path; point it at this copy.
4086
            let open = |p: &Path| {
4087
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4088
                r.config
4089
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4090
                    .unwrap();
4091
                r.save_config().unwrap();
4092
                r
4093
            };
4094
            let a = open(&run.join("a"));
4095
            if let Some(prep) = prepare {
4096
                prep(&a).unwrap();
4097
            }
4098
            failpoint::crash_after(n);
4099
            let outcome = op(&a);
4100
            let crashed = failpoint::disarm();
4101
            drop(a);
4102
            if !crashed {
4103
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4104
                steps = n - 1;
4105
                break;
4106
            }
4107
            assert!(
4108
                outcome.is_err(),
4109
                "{name}: a crash at step {n} was swallowed"
4110
            );
4111
            for repo in ["a", "origin"] {
4112
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4113
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4114
                });
4115
                let rep = r.fsck().unwrap();
4116
                assert_eq!(
4117
                    rep.errors(),
4118
                    0,
4119
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4120
                    rep.problems
4121
                );
4122
            }
4123
            // The interrupted operation can simply be run again.
4124
            let a = open(&run.join("a"));
4125
            // A crash after the commit point leaves the commit done.
4126
            let landed = a
4127
                .bookmark_heads()
4128
                .unwrap()
4129
                .iter()
4130
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4131
            let again = match (name, landed) {
4132
                ("commit", true) => Ok(()),
4133
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4134
                _ => op(&a),
4135
            };
4136
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4137
            assert_eq!(a.fsck().unwrap().errors(), 0);
4138
            fs::remove_dir_all(&run).unwrap();
4139
        }
4140
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4141
    }
4142
}
4143
4144
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4145
/// running at the same time lose nothing: every commit ends up on the
4146
/// bookmark, locally and on the remote, and the repository passes fsck.
4147
#[test]
4148
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4149
    hermetic();
4150
    let dir = tempfile::tempdir().unwrap();
4151
    let root = dir.path();
4152
    let origin = root.join("origin");
4153
    Repo::init_bare_unbound(&origin).unwrap();
4154
    let main = root.join("main");
4155
    let mut repo = Repo::init(&main).unwrap();
4156
    repo.config
4157
        .set("remote.origin.url", &origin.to_string_lossy())
4158
        .unwrap();
4159
    repo.save_config().unwrap();
4160
    write(&main, "seed.txt", b"seed\n");
4161
    repo.commit("seed", &[]).unwrap();
4162
    let second = root.join("second");
4163
    repo.workspace_add(&second, None).unwrap();
4164
    drop(repo);
4165
4166
    const EACH: usize = 15;
4167
    std::thread::scope(|s| {
4168
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4169
            s.spawn(move || {
4170
                let r = Repo::open(&dir).unwrap();
4171
                for i in 0..EACH {
4172
                    write(
4173
                        &dir,
4174
                        &format!("{tag}-{i}.txt"),
4175
                        format!("{tag} {i}\n").as_bytes(),
4176
                    );
4177
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4178
                    if push && i % 5 == 4 {
4179
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4180
                        let _ = r.push("origin", false);
4181
                    }
4182
                }
4183
            });
4184
        }
4185
    });
4186
4187
    let repo = Repo::open(&main).unwrap();
4188
    let heads = repo.bookmark_heads().unwrap();
4189
    let state = repo.load_state(&heads).unwrap();
4190
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4191
    for tag in ["a", "b"] {
4192
        for i in 0..EACH {
4193
            assert!(
4194
                messages.contains(&format!("{tag} {i}")),
4195
                "lost commit {tag} {i}; have {messages:?}"
4196
            );
4197
        }
4198
    }
4199
    let rep = repo.fsck().unwrap();
4200
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4201
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4202
    let hosted = Repo::open(&origin).unwrap();
4203
    let hosted_heads = hosted.bookmark_heads().unwrap();
4204
    assert_eq!(
4205
        hosted.load_state(&hosted_heads).unwrap().len(),
4206
        state.len(),
4207
        "the remote has every commit"
4208
    );
4209
}
4210
4211
/// Two operations recorded from the same parent (what two processes do
4212
/// when they race) are merged: both bookmarks' heads survive, and a
4213
/// change made on one side only is kept.
4214
#[test]
4215
fn operations_from_the_same_parent_are_merged() {
4216
    hermetic();
4217
    let dir = tempfile::tempdir().unwrap();
4218
    let root = dir.path();
4219
    let repo = Repo::init(root).unwrap();
4220
    write(root, "a.txt", b"a\n");
4221
    let a = repo.commit("a", &[]).unwrap();
4222
    write(root, "b.txt", b"b\n");
4223
    let b = repo.commit("b", &[]).unwrap();
4224
    let (x, op) = repo.head_op().unwrap();
4225
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4226
4227
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4228
    let mut one = op.view.clone();
4229
    one.bookmarks.insert("main".into(), state(vec![a]));
4230
    one.bookmarks.insert("topic".into(), state(vec![a]));
4231
    let mut two = op.view.clone();
4232
    two.bookmarks.insert("main".into(), state(vec![b]));
4233
    repo.record_op(&[x], "one", one).unwrap();
4234
    let merged = repo.record_op(&[x], "two", two).unwrap();
4235
4236
    let (head, op) = repo.head_op().unwrap();
4237
    assert_eq!(head, merged);
4238
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4239
    assert!(op.command.contains("merged with a concurrent operation"));
4240
    let mut main = repo
4241
        .store()
4242
        .get_state(&op.view.bookmarks["main"])
4243
        .unwrap()
4244
        .heads;
4245
    main.sort();
4246
    let mut want = vec![a, b];
4247
    want.sort();
4248
    assert_eq!(main, want, "both sides' heads are kept");
4249
    assert!(
4250
        op.view.bookmarks.contains_key("topic"),
4251
        "a one-sided change survives"
4252
    );
4253
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4254
}
4255
4256
#[test]
4257
fn failed_requests_come_with_a_next_step() {
4258
    use crate::protocol::hint_for;
4259
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4260
        .unwrap()
4261
        .contains("token"));
4262
    assert!(hint_for("…: HTTP 403: forbidden")
4263
        .unwrap()
4264
        .contains("repo:write"));
4265
    assert!(hint_for("…: HTTP 404: no such repository")
4266
        .unwrap()
4267
        .contains("owner and repository name"));
4268
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4269
        .unwrap()
4270
        .contains("oxyhub-ca.pem"));
4271
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4272
        .unwrap()
4273
        .contains("running"));
4274
    assert!(hint_for("Dns Failed: failed to lookup address information")
4275
        .unwrap()
4276
        .contains("resolve"));
4277
    assert_eq!(hint_for("something else entirely"), None);
4278
}
4279
4280
#[test]
4281
fn doctor_names_problems_and_what_to_do() {
4282
    hermetic();
4283
    let dir = tempfile::tempdir().unwrap();
4284
    let root = dir.path();
4285
    let origin = root.join("origin");
4286
    Repo::init_bare_unbound(&origin).unwrap();
4287
    let mut repo = Repo::init(&root.join("r"))
4288
        .unwrap()
4289
        .with_home(root.join("home"));
4290
    let find = |r: &DoctorReport, area: &str, h: Health| {
4291
        r.checks
4292
            .iter()
4293
            .find(|c| c.area == area && c.health == h)
4294
            .cloned()
4295
    };
4296
4297
    let r = repo.doctor(true);
4298
    assert!(find(&r, "identity", Health::Warn)
4299
        .unwrap()
4300
        .hint
4301
        .unwrap()
4302
        .contains("oxy identity create"));
4303
    assert!(find(&r, "repository", Health::Ok).is_some());
4304
4305
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4306
        .unwrap();
4307
    repo.config.set("author.name", "Ada").unwrap();
4308
    repo.config.set("author.email", "[email protected]").unwrap();
4309
    repo.config
4310
        .set("remote.origin.url", &origin.to_string_lossy())
4311
        .unwrap();
4312
    repo.config
4313
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4314
        .unwrap();
4315
    repo.config.set("remote.down.token", "t").unwrap();
4316
    repo.config
4317
        .set("remote.badca.url", "https://example.invalid/a/b")
4318
        .unwrap();
4319
    repo.config
4320
        .set(
4321
            "remote.badca.ca",
4322
            &root.join("missing.pem").to_string_lossy(),
4323
        )
4324
        .unwrap();
4325
    repo.save_config().unwrap();
4326
4327
    let r = repo.doctor(true);
4328
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4329
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4330
    assert!(find(&r, "remote origin", Health::Ok)
4331
        .unwrap()
4332
        .message
4333
        .contains("first push binds it"));
4334
    let down = find(&r, "remote down", Health::Fail).unwrap();
4335
    assert!(
4336
        down.hint.as_deref().unwrap_or("").contains("running"),
4337
        "{down:?}"
4338
    );
4339
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4340
    assert!(
4341
        badca.hint.unwrap().contains("remote.badca.ca"),
4342
        "the remote's own name is in the hint"
4343
    );
4344
    assert_eq!(r.worst(), Health::Fail);
4345
4346
    // Offline, nothing is contacted.
4347
    let r = repo.doctor(false);
4348
    assert!(find(&r, "remote down", Health::Fail).is_none());
4349
    assert!(find(&r, "remote down", Health::Ok)
4350
        .unwrap()
4351
        .message
4352
        .contains("not contacted"));
4353
}
4354
4355
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4356
/// after it. Inserting after `b` and then deleting `b`, one commit after
4357
/// the other, must not leave a delete/insert conflict.
4358
#[test]
4359
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4360
    hermetic();
4361
    let dir = tempfile::tempdir().unwrap();
4362
    let root = dir.path();
4363
    let repo = Repo::init(root).unwrap();
4364
    write(root, "f", b"a\nb\nc\n");
4365
    repo.commit("base", &[]).unwrap();
4366
    write(root, "f", b"a\nb\nx\nc\n");
4367
    let insert = repo.commit("insert x after b", &[]).unwrap();
4368
    write(root, "f", b"a\nx\nc\n");
4369
    let delete = repo.commit("delete b", &[]).unwrap();
4370
    assert!(
4371
        repo.store()
4372
            .get_change(&delete)
4373
            .unwrap()
4374
            .deps
4375
            .contains(&insert),
4376
        "the deletion depends on the insertion below the deleted line"
4377
    );
4378
    let heads = repo.bookmark_heads().unwrap();
4379
    assert_eq!(heads, vec![delete]);
4380
    let snap = repo.load_state(&heads).unwrap().materialize();
4381
    assert!(!snap.is_conflicted());
4382
    assert!(
4383
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4384
    );
4385
}
4386
4387
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4388
/// replacement depends on the change that set the blob it replaces.
4389
#[test]
4390
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4391
    hermetic();
4392
    let dir = tempfile::tempdir().unwrap();
4393
    let root = dir.path();
4394
    let repo = Repo::init(root).unwrap();
4395
    write(root, "bin", b"\0A");
4396
    let v1 = repo.commit("v1", &[]).unwrap();
4397
    write(root, "bin", b"\0B");
4398
    let v2 = repo.commit("v2", &[]).unwrap();
4399
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4400
    write(root, "bin", b"\0A");
4401
    let v3 = repo.commit("back to A", &[]).unwrap();
4402
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4403
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4404
    let state = repo.load_state(&[v3]).unwrap();
4405
    let snap = state.materialize();
4406
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4407
        panic!("opaque")
4408
    };
4409
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4410
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4411
}
4412
4413
/// Spec §23: a binary file changed on two branches and merged in Git to
4414
/// one side's version comes back as that version at the merge, and the
4415
/// import verifies commit by commit.
4416
#[test]
4417
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4418
    hermetic();
4419
    if std::process::Command::new("git")
4420
        .arg("--version")
4421
        .output()
4422
        .is_err()
4423
    {
4424
        eprintln!("git not installed; skipping");
4425
        return;
4426
    }
4427
    let dir = tempfile::tempdir().unwrap();
4428
    let root = dir.path();
4429
    let g = root.join("src.git");
4430
    fs::create_dir_all(&g).unwrap();
4431
    let git = |args: &[&str]| -> String {
4432
        let out = std::process::Command::new("git")
4433
            .arg("-C")
4434
            .arg(&g)
4435
            .args([
4436
                "-c",
4437
                "user.name=Grace",
4438
                "-c",
4439
                "[email protected]",
4440
                "-c",
4441
                "commit.gpgsign=false",
4442
            ])
4443
            .args(args)
4444
            .output()
4445
            .unwrap();
4446
        assert!(
4447
            out.status.success(),
4448
            "git {args:?}: {}",
4449
            String::from_utf8_lossy(&out.stderr)
4450
        );
4451
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4452
    };
4453
    git(&["init", "-q", "-b", "main"]);
4454
    write(&g, "logo.bin", b"\0base");
4455
    write(&g, "notes.txt", b"a\nb\nc\n");
4456
    git(&["add", "."]);
4457
    git(&["commit", "-qm", "base"]);
4458
    git(&["checkout", "-qb", "side"]);
4459
    write(&g, "logo.bin", b"\0side");
4460
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4461
    git(&["commit", "-qam", "side"]);
4462
    git(&["checkout", "-q", "main"]);
4463
    write(&g, "logo.bin", b"\0main");
4464
    git(&["commit", "-qam", "main"]);
4465
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4466
    let _ = std::process::Command::new("git")
4467
        .arg("-C")
4468
        .arg(&g)
4469
        .args([
4470
            "-c",
4471
            "user.name=G",
4472
            "-c",
4473
            "user.email=g@e",
4474
            "merge",
4475
            "-q",
4476
            "side",
4477
        ])
4478
        .output();
4479
    write(&g, "logo.bin", b"\0main");
4480
    git(&["add", "."]);
4481
    git(&["commit", "-qm", "merge side"]);
4482
    // Then a revert of the binary to its first version.
4483
    write(&g, "logo.bin", b"\0base");
4484
    git(&["commit", "-qam", "back to base"]);
4485
4486
    let repo = Repo::init(&root.join("o")).unwrap();
4487
    let rep = repo.import_git(&g, "main").unwrap();
4488
    assert_eq!(rep.merges, 1);
4489
    let v = repo.verify_git_import(&g, "main").unwrap();
4490
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4491
    assert_eq!(v.commits, 5);
4492
    let snap = repo
4493
        .load_state(&repo.bookmark_heads().unwrap())
4494
        .unwrap()
4495
        .materialize();
4496
    assert!(!snap.is_conflicted());
4497
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4498
        panic!("opaque")
4499
    };
4500
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4501
}
4502
4503
/// Spec §7.7 on a file system without executable bits or symlinks: the
4504
/// recorded bit is kept, and a symlink checked out as a plain file holding
4505
/// its target is still that symlink.
4506
#[cfg(unix)]
4507
#[test]
4508
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4509
    use crate::portable::Platform;
4510
    use std::os::unix::fs::PermissionsExt;
4511
    hermetic();
4512
    let dir = tempfile::tempdir().unwrap();
4513
    let root = dir.path();
4514
    let repo = Repo::init(root).unwrap();
4515
    write(root, "run.sh", b"#!/bin/sh\n");
4516
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4517
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4518
    repo.commit("script and link", &[]).unwrap();
4519
    drop(repo);
4520
4521
    // What checking out on Windows leaves: no exec bit, the link as a file.
4522
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4523
    fs::remove_file(root.join("link")).unwrap();
4524
    write(root, "link", b"run.sh");
4525
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4526
    let s = win.snapshot("oxy status").unwrap();
4527
    assert!(
4528
        s.statuses.is_empty(),
4529
        "nothing changed on Windows: {:?}",
4530
        statuses(&s)
4531
    );
4532
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4533
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4534
    write(root, "link", b"other");
4535
    let h = win.commit("edit on Windows", &[]).unwrap();
4536
    let snap = win.load_state(&[h]).unwrap().materialize();
4537
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4538
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4539
    // The same working copy read as Linux sees the lost bit and the plain file.
4540
    let linux = Repo::open(root).unwrap();
4541
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4542
}
4543
4544
/// Paths that collide on case-insensitive or Windows file systems are
4545
/// named at checkout there, and by doctor everywhere.
4546
#[test]
4547
fn paths_other_platforms_cannot_hold_are_reported() {
4548
    use crate::portable::Platform;
4549
    hermetic();
4550
    let dir = tempfile::tempdir().unwrap();
4551
    let root = dir.path();
4552
    let repo = Repo::init(root).unwrap();
4553
    write(root, "README.md", b"a\n");
4554
    write(root, "readme.md", b"b\n");
4555
    write(root, "src/aux.c", b"int x;\n");
4556
    let h = repo.commit("unportable", &[]).unwrap();
4557
    let r = repo.doctor(false);
4558
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4559
    assert_eq!(port.health, Health::Warn);
4560
    assert!(
4561
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4562
        "{}",
4563
        port.message
4564
    );
4565
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4566
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4567
    assert!(
4568
        rep.notes
4569
            .iter()
4570
            .any(|n| n.contains("README.md and readme.md")),
4571
        "{:?}",
4572
        rep.notes
4573
    );
4574
    assert!(
4575
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4576
        "macOS allows aux.c"
4577
    );
4578
}
4579
4580
#[test]
4581
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4582
    hermetic();
4583
    let dir = tempfile::tempdir().unwrap();
4584
    let repo = Repo::init(dir.path()).unwrap();
4585
    write(dir.path(), "a.txt", b"one\n");
4586
    write(dir.path(), "other.txt", b"x\n");
4587
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4588
    repo.snapshot("t").unwrap();
4589
    let c1 = repo.commit("first", &[]).unwrap();
4590
    write(dir.path(), "other.txt", b"y\n");
4591
    repo.snapshot("t").unwrap();
4592
    repo.commit("other only", &[]).unwrap();
4593
    write(dir.path(), "a.txt", b"one\ntwo\n");
4594
    repo.snapshot("t").unwrap();
4595
    let c3 = repo.commit("second line", &[]).unwrap();
4596
    write(dir.path(), "other.txt", b"z\n");
4597
    repo.snapshot("t").unwrap();
4598
    repo.commit("other again", &[]).unwrap();
4599
4600
    let heads = repo.bookmark_heads().unwrap();
4601
    let state = repo.load_state(&heads).unwrap();
4602
    let full: Vec<ChangeHash> = repo
4603
        .log_for_path_in("a.txt", &heads)
4604
        .unwrap()
4605
        .iter()
4606
        .map(|e| e.hash)
4607
        .collect();
4608
    assert_eq!(
4609
        full,
4610
        vec![c3, c1],
4611
        "newest first, only changes touching the path"
4612
    );
4613
    let newest: Vec<ChangeHash> = repo
4614
        .log_for_path_of(&state, "a.txt", Some(1))
4615
        .unwrap()
4616
        .iter()
4617
        .map(|e| e.hash)
4618
        .collect();
4619
    assert_eq!(newest, vec![c3], "stops at the first");
4620
    assert_eq!(
4621
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4622
        2
4623
    );
4624
    assert!(repo
4625
        .log_for_path_of(&state, "missing.txt", Some(1))
4626
        .is_err());
4627
    assert_eq!(
4628
        repo.log_state(&heads).unwrap().len(),
4629
        repo.log_of(&state).len()
4630
    );
4631
4632
    let tree = state.tree().view();
4633
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4634
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4635
    assert_eq!(
4636
        via_state
4637
            .iter()
4638
            .map(|l| (l.hash, l.text.clone()))
4639
            .collect::<Vec<_>>(),
4640
        via_heads
4641
            .iter()
4642
            .map(|l| (l.hash, l.text.clone()))
4643
            .collect::<Vec<_>>()
4644
    );
4645
    assert_eq!(
4646
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4647
        vec![c1, c3]
4648
    );
4649
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4650
}
4651
4652
/// A text file whose stat matches the manifest and whose recorded hash is
4653
/// the base's content is taken from the base without reading it; anything
4654
/// else is read, so no edit is missed (spec §12.3).
4655
#[cfg(unix)]
4656
#[test]
4657
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4658
    use std::os::unix::fs::PermissionsExt;
4659
    hermetic();
4660
    let dir = tempfile::tempdir().unwrap();
4661
    let root = dir.path();
4662
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4663
    write(root, "a.txt", b"one\ntwo\n");
4664
    write(root, "b.txt", b"bee\n");
4665
    repo.commit("base", &[]).unwrap();
4666
    let age = |p: &str| {
4667
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4668
        fs::File::options()
4669
            .write(true)
4670
            .open(root.join(p))
4671
            .unwrap()
4672
            .set_modified(old)
4673
            .unwrap();
4674
    };
4675
    age("a.txt");
4676
    age("b.txt");
4677
    assert!(
4678
        !repo.snapshot("status").unwrap().changed,
4679
        "records the aged stat"
4680
    );
4681
4682
    // Clean and equal to the base: not read at all.
4683
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4684
    let snap = repo.snapshot("status").unwrap();
4685
    assert!(
4686
        !snap.changed && snap.statuses.is_empty(),
4687
        "{:?}",
4688
        snap.statuses
4689
    );
4690
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4691
4692
    // An uncommitted edit that is older than the manifest: stat-clean, but
4693
    // its hash is not the base's, so it is read and stays visible.
4694
    write(root, "b.txt", b"bee edited\n");
4695
    age("b.txt");
4696
    let first = repo.snapshot("status").unwrap();
4697
    assert_eq!(
4698
        statuses(&first),
4699
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4700
    );
4701
    let again = repo.snapshot("status").unwrap();
4702
    assert_eq!(
4703
        statuses(&again),
4704
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4705
        "still seen once stat-clean"
4706
    );
4707
    assert!(!again.changed, "and the working copy hashes the same");
4708
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4709
    assert!(
4710
        repo.snapshot("status").is_err(),
4711
        "an edited file must be read, never taken from the base"
4712
    );
4713
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4714
4715
    // A same-size edit made just now is racy and read.
4716
    write(root, "a.txt", b"one\nTWO\n");
4717
    assert_eq!(
4718
        statuses(&repo.snapshot("status").unwrap()),
4719
        vec![
4720
            ("a.txt".to_string(), ChangeStatus::Modified),
4721
            ("b.txt".to_string(), ChangeStatus::Modified)
4722
        ]
4723
    );
4724
    // Committing makes the edits the base: both are clean and served from it again.
4725
    repo.commit("edits", &[]).unwrap();
4726
    age("a.txt");
4727
    age("b.txt");
4728
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4729
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4730
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4731
    let snap = repo.snapshot("status").unwrap();
4732
    assert!(!snap.changed && snap.statuses.is_empty());
4733
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4734
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4735
}
4736
4737
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4738
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4739
/// file is unchanged, and loading through the checkpoint equals a full load.
4740
#[test]
4741
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4742
    hermetic();
4743
    let dir = tempfile::tempdir().unwrap();
4744
    let root = dir.path();
4745
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4746
    let long: String = (0..300)
4747
        .map(|i| format!("line {i} of a long file\n"))
4748
        .collect();
4749
    write(root, "long.txt", long.as_bytes());
4750
    write(root, "short.txt", b"short\n");
4751
    repo.commit("base", &[]).unwrap();
4752
    let (r1, _, _) = repo.checkpoint().unwrap();
4753
    let cp1 = crate::objects::Checkpoint::decode(
4754
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4755
    )
4756
    .unwrap();
4757
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4758
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4759
4760
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4761
    repo.gc(true).unwrap();
4762
    assert!(repo.store().has(&graphs1[0]));
4763
    let report = repo.fsck().unwrap();
4764
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4765
4766
    // Loading through the checkpoint equals a full load.
4767
    write(root, "short.txt", b"short, edited\n");
4768
    repo.commit("edit the short file", &[]).unwrap();
4769
    let heads = repo.bookmark_heads().unwrap();
4770
    let fast = repo.load_state(&heads).unwrap();
4771
    let full = repo.load_state_full(&heads).unwrap();
4772
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4773
4774
    // The next checkpoint shares the unchanged long file's graph.
4775
    let (r2, _, _) = repo.checkpoint().unwrap();
4776
    let cp2 = crate::objects::Checkpoint::decode(
4777
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
4778
    )
4779
    .unwrap();
4780
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
4781
4782
    // A shallow clone's bundle carries the graph blob with the checkpoint.
4783
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
4784
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
4785
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
4786
4787
    // A version 1 checkpoint written by an older oxy still loads.
4788
    let state = repo.load_state_full(&heads).unwrap();
4789
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
4790
    let cp_old = crate::objects::Checkpoint {
4791
        heads: cp2.heads.clone(),
4792
        count: cp2.count,
4793
        payload: old,
4794
    };
4795
    let r_old = repo
4796
        .store()
4797
        .put(ObjectType::Checkpoint, &cp_old.encode())
4798
        .unwrap();
4799
    repo.install_checkpoint("main", &r_old).unwrap();
4800
    assert_eq!(
4801
        repo.load_state(&heads).unwrap().checkpoint_payload(),
4802
        full.checkpoint_payload()
4803
    );
4804
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4805
4806
    // A lost graph blob fails the load loudly rather than dropping the
4807
    // file, and fsck reports it (a fresh repository, objects still loose).
4808
    let dir2 = tempfile::tempdir().unwrap();
4809
    let root2 = dir2.path();
4810
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
4811
    write(root2, "long.txt", long.as_bytes());
4812
    repo2.commit("base", &[]).unwrap();
4813
    let (r, _, _) = repo2.checkpoint().unwrap();
4814
    let cp = crate::objects::Checkpoint::decode(
4815
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
4816
    )
4817
    .unwrap();
4818
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
4819
    fs::remove_file(repo2.store().path_for(&graph)).unwrap();
4820
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
4821
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
4822
}
4823
4824
/// A new repository has not stored the user's identity yet (that happens
4825
/// at the first signed change); looking it up falls back to the key
4826
/// directory, and a file there that does not hash to the key is refused.
4827
#[test]
4828
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
4829
    hermetic();
4830
    let dir = tempfile::tempdir().unwrap();
4831
    let home = dir.path().join("home");
4832
    let mut first = Repo::init(&dir.path().join("a"))
4833
        .unwrap()
4834
        .with_home(home.clone());
4835
    let (key, _) = first
4836
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4837
        .unwrap();
4838
    let fresh = Repo::init(&dir.path().join("b"))
4839
        .unwrap()
4840
        .with_home(home.clone());
4841
    assert!(!fresh.store().has(&key), "nothing stored yet");
4842
    let id = fresh.identity(&key).unwrap();
4843
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
4844
    // A key file that is not this identity is an error, not a wrong answer.
4845
    let keys = fresh.keys_dir.clone();
4846
    let (other, _) = first
4847
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4848
        .unwrap();
4849
    fs::copy(
4850
        keys.join(format!("{}.identity", other.to_hex())),
4851
        keys.join(format!("{}.identity", key.to_hex())),
4852
    )
4853
    .unwrap();
4854
    assert!(fresh
4855
        .identity(&key)
4856
        .unwrap_err()
4857
        .to_string()
4858
        .contains("does not hold identity"));
4859
}
4860
4861
/// Status snapshots (spec §12.3): a text file whose stat matches the
4862
/// manifest, and whose base graph key is the one the manifest recorded it
4863
/// equal to, is neither read nor rendered; any edit, and any change to the
4864
/// file's graph in the base, brings it back.
4865
#[cfg(unix)]
4866
#[test]
4867
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
4868
    use std::os::unix::fs::PermissionsExt;
4869
    hermetic();
4870
    let dir = tempfile::tempdir().unwrap();
4871
    let root = dir.path();
4872
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4873
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
4874
        write(root, p, c.as_bytes());
4875
    }
4876
    repo.commit("base", &[]).unwrap();
4877
    let age = |p: &str| {
4878
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4879
        fs::File::options()
4880
            .write(true)
4881
            .open(root.join(p))
4882
            .unwrap()
4883
            .set_modified(old)
4884
            .unwrap();
4885
    };
4886
    let lock = |p: &str, mode: u32| {
4887
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
4888
    };
4889
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4890
        age(p);
4891
    }
4892
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4893
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4894
    assert!(
4895
        m.entries.values().all(|e| e.graph.is_some()),
4896
        "keys recorded"
4897
    );
4898
4899
    // Unreadable files prove they are not read; the status snapshot does
4900
    // not render them either, and its base lacks their graphs.
4901
    lock("a.txt", 0o000);
4902
    lock("b.txt", 0o000);
4903
    let snap = repo.snapshot_status("status").unwrap();
4904
    assert!(!snap.changed && snap.statuses.is_empty());
4905
    assert_eq!(
4906
        snap.base_snapshot
4907
            .unrendered
4908
            .iter()
4909
            .cloned()
4910
            .collect::<Vec<_>>(),
4911
        vec!["a.txt", "b.txt", "d/c.txt"]
4912
    );
4913
    assert!(!snap.base.is_full());
4914
    assert!(!snap.base_snapshot.is_conflicted());
4915
    // A full snapshot does not read them either, but renders everything.
4916
    let full = repo.snapshot("status").unwrap();
4917
    assert!(full.statuses.is_empty() && full.base.is_full());
4918
    assert!(full.base_snapshot.unrendered.is_empty());
4919
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
4920
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
4921
4922
    // An edit is seen; the file is rendered, the others still are not.
4923
    write(root, "d/c.txt", b"sea edited\n");
4924
    let snap = repo.snapshot_status("status").unwrap();
4925
    assert_eq!(
4926
        statuses(&snap),
4927
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
4928
    );
4929
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
4930
    // So is a mode change of an unread file.
4931
    lock("b.txt", 0o100);
4932
    assert_eq!(
4933
        statuses(&repo.snapshot_status("status").unwrap()),
4934
        vec![
4935
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
4936
            ("d/c.txt".to_string(), ChangeStatus::Modified)
4937
        ]
4938
    );
4939
    lock("b.txt", 0o000);
4940
4941
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
4942
    // stays unread, c.txt is read once and then skipped too.
4943
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
4944
        .unwrap();
4945
    age("d/c.txt");
4946
    let snap = repo.snapshot_status("status").unwrap();
4947
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
4948
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
4949
    lock("d/c.txt", 0o000);
4950
    let snap = repo.snapshot_status("status").unwrap();
4951
    assert!(snap.statuses.is_empty());
4952
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
4953
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4954
        lock(p, 0o644);
4955
    }
4956
}
4957
4958
/// Attributes decide how a file compares with the base, so a changed
4959
/// `.oxyattributes` makes every text file be compared again.
4960
#[cfg(unix)]
4961
#[test]
4962
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
4963
    hermetic();
4964
    let dir = tempfile::tempdir().unwrap();
4965
    let root = dir.path();
4966
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4967
    write(root, "a.txt", b"crlf\r\n");
4968
    repo.commit("base", &[]).unwrap();
4969
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4970
    fs::File::options()
4971
        .write(true)
4972
        .open(root.join("a.txt"))
4973
        .unwrap()
4974
        .set_modified(old)
4975
        .unwrap();
4976
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
4977
    assert!(repo
4978
        .snapshot_status("status")
4979
        .unwrap()
4980
        .base_snapshot
4981
        .unrendered
4982
        .contains("a.txt"));
4983
    // With eol=lf, a.txt as stored no longer equals the base.
4984
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
4985
    let snap = repo.snapshot_status("status").unwrap();
4986
    assert_eq!(
4987
        statuses(&snap),
4988
        vec![
4989
            (".oxyattributes".to_string(), ChangeStatus::Added),
4990
            ("a.txt".to_string(), ChangeStatus::Modified)
4991
        ]
4992
    );
4993
}
4994
4995
/// Bookmarks with `/` in their names: pushing records their
4996
/// attestations, and checkpoints are kept for them, beside `feature`
4997
/// itself.
4998
#[test]
4999
fn bookmarks_with_slashes_push_and_checkpoint() {
5000
    hermetic();
5001
    let dir = tempfile::tempdir().unwrap();
5002
    let root = dir.path();
5003
    let origin = Repo::init(&root.join("origin")).unwrap();
5004
    let url = root.join("origin").to_string_lossy().to_string();
5005
    let mut repo = Repo::clone(&url, &root.join("r"))
5006
        .unwrap()
5007
        .with_home(root.join("home"));
5008
    // With an identity, pushes carry reference attestations: the case
5009
    // that failed, since the attestation is a file named after the bookmark.
5010
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5011
        .unwrap();
5012
    let r = root.join("r");
5013
    write(&r, "a.txt", b"a\n");
5014
    let h_a = repo.commit("a", &[]).unwrap();
5015
    assert!(repo.push("origin", false).unwrap()[0].ok);
5016
    repo.bookmark_create("feature", None).unwrap();
5017
    repo.bookmark_create("feature/x", None).unwrap();
5018
    repo.bookmark_switch("feature/x", false).unwrap();
5019
    write(&r, "b.txt", b"b\n");
5020
    let h_b = repo.commit("b", &[]).unwrap();
5021
    for name in ["feature", "feature/x"] {
5022
        let res = repo.push_bookmark("origin", name, false).unwrap();
5023
        assert!(res[0].ok, "{name}: {res:?}");
5024
    }
5025
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5026
    assert_eq!(
5027
        origin.resolve_heads("feature/x").unwrap(),
5028
        repo.resolve_heads("feature/x").unwrap()
5029
    );
5030
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5031
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5032
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5033
5034
    // A checkpoint of feature/x is found again when loading its state.
5035
    let (cp, _, _) = repo.checkpoint().unwrap();
5036
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5037
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5038
    let heads = repo.resolve_heads("feature/x").unwrap();
5039
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5040
}
5041
5042
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5043
/// never the remote's own bookmark, and a bookmark created again later is
5044
/// accepted although the deletion's attestation stays the latest.
5045
#[test]
5046
fn bookmarks_are_deleted_on_a_remote() {
5047
    hermetic();
5048
    let dir = tempfile::tempdir().unwrap();
5049
    let root = dir.path();
5050
    let origin = Repo::init(&root.join("origin")).unwrap();
5051
    let url = root.join("origin").to_string_lossy().to_string();
5052
    let mut repo = Repo::clone(&url, &root.join("r"))
5053
        .unwrap()
5054
        .with_home(root.join("home"));
5055
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5056
        .unwrap();
5057
    let r = root.join("r");
5058
    write(&r, "a.txt", b"a\n");
5059
    repo.commit("a", &[]).unwrap();
5060
    assert!(repo.push("origin", false).unwrap()[0].ok);
5061
    repo.bookmark_create("feature/x", None).unwrap();
5062
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5063
    assert!(origin.resolve_heads("feature/x").is_ok());
5064
5065
    let res = repo.push_delete("origin", "feature/x").unwrap();
5066
    assert!(res[0].ok, "{res:?}");
5067
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5068
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5069
    assert!(
5070
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5071
        "the deletion is attested"
5072
    );
5073
    assert!(
5074
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5075
        "the local bookmark stays"
5076
    );
5077
    assert!(!repo
5078
        .view()
5079
        .unwrap()
5080
        .remotes
5081
        .get("origin")
5082
        .is_some_and(|m| m.contains_key("feature/x")));
5083
5084
    // Pushing it again creates it again, past the deletion's serial.
5085
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5086
    assert!(res[0].ok, "{res:?}");
5087
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5088
5089
    // Nothing to delete, and never the remote's own bookmark.
5090
    assert!(repo.push_delete("origin", "nope").is_err());
5091
    let res = repo.push_delete("origin", "main").unwrap();
5092
    assert!(
5093
        !res[0].ok && res[0].reason.contains("default bookmark"),
5094
        "{res:?}"
5095
    );
5096
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5097
}
5098
5099
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5100
/// when the target has the same versions of the files it touches, and is
5101
/// refused, untouched, when it has others.
5102
#[test]
5103
fn switching_bookmarks_carries_uncommitted_work() {
5104
    hermetic();
5105
    let dir = tempfile::tempdir().unwrap();
5106
    let root = dir.path();
5107
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5108
    write(root, "a.txt", b"a\n");
5109
    write(root, "b.txt", b"b\n");
5110
    write(root, "gone.txt", b"gone\n");
5111
    repo.commit("base", &[]).unwrap();
5112
    repo.bookmark_create("feature", None).unwrap();
5113
    // Started on main, belongs on feature: edit, add, remove.
5114
    write(root, "a.txt", b"a\nmore\n");
5115
    write(root, "new.txt", b"new\n");
5116
    fs::remove_file(root.join("gone.txt")).unwrap();
5117
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5118
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5119
    assert_eq!(repo.config.bookmark, "feature");
5120
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5121
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5122
    assert!(!root.join("gone.txt").exists());
5123
    let snap = repo.snapshot("status").unwrap();
5124
    assert_eq!(
5125
        statuses(&snap),
5126
        vec![
5127
            ("a.txt".to_string(), ChangeStatus::Modified),
5128
            ("gone.txt".to_string(), ChangeStatus::Removed),
5129
            ("new.txt".to_string(), ChangeStatus::Added)
5130
        ]
5131
    );
5132
    repo.commit("the work", &[]).unwrap();
5133
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5134
5135
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5136
    repo.bookmark_switch("main", false).unwrap();
5137
    write(root, "b.txt", b"b on main\n");
5138
    repo.commit("b on main", &[]).unwrap();
5139
    repo.bookmark_switch("feature", false).unwrap();
5140
    write(root, "b.txt", b"b edited\n");
5141
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5142
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5143
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5144
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5145
}
5146
5147
/// Merging and checking out (feedback 3): a working copy without changes
5148
/// follows a merge whichever state it sat on; a refused checkout names
5149
/// what is in the way; `checkout --carry` takes the work along.
5150
#[test]
5151
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5152
    hermetic();
5153
    let dir = tempfile::tempdir().unwrap();
5154
    let root = dir.path();
5155
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5156
    write(root, "a.txt", b"a\n");
5157
    let h1 = repo.commit("a", &[]).unwrap();
5158
    write(root, "b.txt", b"b\n");
5159
    repo.commit("b", &[]).unwrap();
5160
    repo.bookmark_create("feature", None).unwrap();
5161
    repo.bookmark_switch("feature", false).unwrap();
5162
    write(root, "c.txt", b"c\n");
5163
    repo.commit("c on feature", &[]).unwrap();
5164
    repo.bookmark_switch("main", false).unwrap();
5165
    // The working copy sits on an older state than main's heads.
5166
    repo.checkout(&[h1], false, "checkout").unwrap();
5167
    assert!(!root.join("b.txt").exists());
5168
    let m = repo.merge("feature").unwrap();
5169
    assert!(m.checked_out, "a clean working copy follows the merge");
5170
    for f in ["a.txt", "b.txt", "c.txt"] {
5171
        assert!(root.join(f).exists(), "{f}");
5172
    }
5173
5174
    // A refusal says which paths are in the way and what to do.
5175
    fs::remove_file(root.join("b.txt")).unwrap();
5176
    write(root, "a.txt", b"a edited\n");
5177
    let err = repo
5178
        .checkout(&[h1], false, "checkout")
5179
        .unwrap_err()
5180
        .to_string();
5181
    assert!(
5182
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5183
        "{err}"
5184
    );
5185
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5186
    // is carried as absent (h1 has none either, so that is refused).
5187
    let err = repo
5188
        .checkout_carry(&[h1], "the first change", "checkout")
5189
        .unwrap_err()
5190
        .to_string();
5191
    assert!(
5192
        err.contains("b.txt") && err.contains("the first change"),
5193
        "{err}"
5194
    );
5195
    write(root, "b.txt", b"b\n");
5196
    let (_, carried) = repo
5197
        .checkout_carry(&[h1], "the first change", "checkout")
5198
        .unwrap();
5199
    assert_eq!(carried, vec!["a.txt"]);
5200
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5201
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5202
}
5203
5204
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5205
/// user identity not stored in a new repository yet is fine while its
5206
/// secret key is there; an added subrepo is listed as not committed yet.
5207
#[test]
5208
fn a_new_repository_is_healthy_before_its_first_commit() {
5209
    hermetic();
5210
    let dir = tempfile::tempdir().unwrap();
5211
    let root = dir.path();
5212
    let home = root.join("home");
5213
    let mut first = Repo::init(&root.join("first"))
5214
        .unwrap()
5215
        .with_home(home.clone());
5216
    let (key, _) = first
5217
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5218
        .unwrap();
5219
    let repo = Repo::init(&root.join("second"))
5220
        .unwrap()
5221
        .with_home(home.clone());
5222
    // Only the secret key: no identity object anywhere this repository sees.
5223
    let keys = repo.keys_dir.clone();
5224
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5225
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5226
    let r = repo.doctor(true);
5227
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5228
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5229
    assert!(id.message.contains("first signed change"), "{}", id.message);
5230
5231
    // A subrepo added and not committed yet is listed, pinned where it is.
5232
    let lib = root.join("lib");
5233
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5234
    write(&lib, "x.txt", b"x\n");
5235
    l.commit("x", &[]).unwrap();
5236
    let second = root.join("second");
5237
    write(&second, "a.txt", b"a\n");
5238
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5239
        .unwrap();
5240
    let subs = repo.subrepos().unwrap();
5241
    assert_eq!(subs.len(), 1);
5242
    assert_eq!(
5243
        (subs[0].path.as_str(), subs[0].committed),
5244
        ("deps/lib", false)
5245
    );
5246
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5247
    repo.commit("add lib", &[]).unwrap();
5248
    let subs = repo.subrepos().unwrap();
5249
    assert!(subs[0].committed, "committed now");
5250
}
5251
5252
/// Commit, diff, hunks and discard use the partial snapshot: a file
5253
/// unchanged since the manifest is neither read nor rendered, and showing
5254
/// a change renders only what it edits, the same as from a full base.
5255
#[cfg(unix)]
5256
#[test]
5257
fn commits_and_diffs_leave_unchanged_files_alone() {
5258
    use std::os::unix::fs::PermissionsExt;
5259
    hermetic();
5260
    let dir = tempfile::tempdir().unwrap();
5261
    let root = dir.path();
5262
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5263
    write(root, "big.txt", b"lots\nof\nlines\n");
5264
    write(root, "a.txt", b"one\ntwo\n");
5265
    repo.commit("base", &[]).unwrap();
5266
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5267
    for f in ["big.txt", "a.txt"] {
5268
        fs::File::options()
5269
            .write(true)
5270
            .open(root.join(f))
5271
            .unwrap()
5272
            .set_modified(old)
5273
            .unwrap();
5274
    }
5275
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5276
    // big.txt cannot be read at all from here on.
5277
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5278
5279
    write(root, "a.txt", b"one\nTWO\nthree\n");
5280
    let diff = repo.diff_files(None).unwrap();
5281
    assert_eq!(
5282
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5283
        ["a.txt"]
5284
    );
5285
    let (_, hunks) = repo.hunks().unwrap();
5286
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5287
    let h = repo.commit("edit a", &[]).unwrap();
5288
5289
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5290
    let c = repo.store().get_change(&h).unwrap();
5291
    let full = repo.load_state(&c.deps).unwrap();
5292
    let want = render_change(&c, &full, &full.materialize());
5293
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5294
    let (base, snap) = repo.change_base(&c).unwrap();
5295
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5296
5297
    // Discarding works the same way.
5298
    write(root, "a.txt", b"scratch\n");
5299
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5300
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5301
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5302
}
5303
5304
/// A replace conflict (spec §9.3) is settled by a change that writes one
5305
/// candidate, or new bytes, at the path when the caller names it; a plain
5306
/// snapshot of a checkout never settles it on its own.
5307
#[test]
5308
fn replace_conflicts_are_settled_when_asked() {
5309
    hermetic();
5310
    let dir = tempfile::tempdir().unwrap();
5311
    let root = dir.path();
5312
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5313
    let blob = |n: u8| {
5314
        let mut v = vec![0u8; 64];
5315
        v[1] = n;
5316
        v
5317
    };
5318
    write(root, "img.bin", &blob(1));
5319
    repo.commit("add img", &[]).unwrap();
5320
    repo.bookmark_create("other", None).unwrap();
5321
    write(root, "img.bin", &blob(2));
5322
    repo.commit("img two", &[]).unwrap();
5323
    repo.bookmark_switch("other", false).unwrap();
5324
    write(root, "img.bin", &blob(3));
5325
    repo.commit("img three", &[]).unwrap();
5326
    repo.bookmark_switch("main", false).unwrap();
5327
    repo.merge("other").unwrap();
5328
    let heads = repo.bookmark_heads().unwrap();
5329
    let merged = repo.load_state(&heads).unwrap().materialize();
5330
    assert!(
5331
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5332
        "a replace conflict"
5333
    );
5334
    // A snapshot of the checkout records nothing.
5335
    assert!(repo
5336
        .snapshot("status")
5337
        .unwrap()
5338
        .statuses
5339
        .iter()
5340
        .all(|s| s.path != "img.bin"));
5341
5342
    // Keeping candidate 3 settles it.
5343
    let author = repo.author();
5344
    let edits = [FileEdit {
5345
        path: "img.bin".into(),
5346
        content: Some(blob(3)),
5347
    }];
5348
    let c = repo
5349
        .build_change(&heads, &edits, "keep three", author)
5350
        .unwrap();
5351
    assert_eq!(c.kind, ChangeKind::Resolution);
5352
    let mut st = repo.load_state(&heads).unwrap();
5353
    for d in &c.deps {
5354
        assert!(st.contains(d));
5355
    }
5356
    assert!(
5357
        heads.iter().all(|h| c.deps.contains(h)),
5358
        "depends on both contributors"
5359
    );
5360
    st.add(c).unwrap();
5361
    let after = st.materialize();
5362
    assert!(!after.is_conflicted());
5363
    assert_eq!(
5364
        after.files["img.bin"].content,
5365
        FileContent::Opaque {
5366
            blobs: vec![Repo::blob_ref(&blob(3))]
5367
        }
5368
    );
5369
5370
    // New bytes settle it too.
5371
    let edits = [FileEdit {
5372
        path: "img.bin".into(),
5373
        content: Some(blob(9)),
5374
    }];
5375
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5376
    let mut st = repo.load_state(&heads).unwrap();
5377
    st.add(c).unwrap();
5378
    assert_eq!(
5379
        st.materialize().files["img.bin"].content,
5380
        FileContent::Opaque {
5381
            blobs: vec![Repo::blob_ref(&blob(9))]
5382
        }
5383
    );
5384
}
5385
5386
/// The history of a range of lines (spec §27): the changes that wrote
5387
/// or deleted its atoms, or deleted atoms from between them; edits outside
5388
/// the range and changes the range's lines survived are not in it.
5389
#[test]
5390
fn line_ranges_have_exact_histories() {
5391
    hermetic();
5392
    let dir = tempfile::tempdir().unwrap();
5393
    let root = dir.path();
5394
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5395
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5396
    let base = repo.commit("add f", &[]).unwrap();
5397
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5398
    let outside = repo.commit("change the import", &[]).unwrap();
5399
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5400
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5401
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5402
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5403
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5404
    let after = repo.commit("add b after a", &[]).unwrap();
5405
    let heads = repo.bookmark_heads().unwrap();
5406
5407
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5408
    let hist: Vec<ChangeHash> = repo
5409
        .line_history(&heads, "f.rs", 2, 4)
5410
        .unwrap()
5411
        .iter()
5412
        .map(|e| e.hash)
5413
        .collect();
5414
    for (h, what) in [
5415
        (base, "wrote it"),
5416
        (inside, "edited a line"),
5417
        (deleted, "deleted a line from inside"),
5418
    ] {
5419
        assert!(hist.contains(&h), "{what}");
5420
    }
5421
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5422
        assert!(!hist.contains(&h), "{what}");
5423
    }
5424
    assert_eq!(hist[0], deleted, "newest first");
5425
    // One line: only what touched it.
5426
    let one: Vec<ChangeHash> = repo
5427
        .line_history(&heads, "f.rs", 1, 1)
5428
        .unwrap()
5429
        .iter()
5430
        .map(|e| e.hash)
5431
        .collect();
5432
    assert!(one.contains(&outside) && !one.contains(&inside));
5433
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5434
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5435
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5436
}
5437
5438
#[test]
5439
fn receipts_are_kept_with_their_state_and_verified() {
5440
    use crate::receipt::{Receipt, SignedReceipt};
5441
    hermetic();
5442
    let dir = tempfile::tempdir().unwrap();
5443
    let root = dir.path();
5444
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5445
    write(root, "a.txt", b"1\n");
5446
    repo.commit("A", &[]).unwrap();
5447
    let heads = repo.bookmark_heads().unwrap();
5448
    let state = repo
5449
        .store()
5450
        .put_state(&StateObject::new(heads.clone()))
5451
        .unwrap();
5452
    let out = repo.store_blob(b"built\n").unwrap();
5453
    let receipt = Receipt {
5454
        job_name: "build".into(),
5455
        pipeline_hash: ObjectRef([1; 32]),
5456
        scope_tree_hash: ObjectRef([2; 32]),
5457
        inputs: vec![],
5458
        environment: ObjectRef([3; 32]),
5459
        outputs: vec![out],
5460
        exit_code: 0,
5461
        duration_ms: 42,
5462
    };
5463
    let sk = SecretKey::generate();
5464
    let runner = sk.identity("earth-1", "runner@earth", 1);
5465
    let sr = SignedReceipt::sign(
5466
        receipt.clone(),
5467
        repo.id().unwrap(),
5468
        state,
5469
        "demo#1",
5470
        &runner,
5471
        &sk,
5472
    );
5473
5474
    let r = repo.add_receipt(&sr).unwrap();
5475
    let found = repo.receipts(&heads).unwrap();
5476
    assert_eq!(found.len(), 1);
5477
    assert_eq!(found[0].attest, r);
5478
    assert_eq!(found[0].signed, sr);
5479
    assert!(found[0].problem.is_none() && !found[0].revoked);
5480
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5481
5482
    // Another repository's receipt, or a forged one, is refused.
5483
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5484
    assert!(repo
5485
        .add_receipt(&elsewhere)
5486
        .unwrap_err()
5487
        .to_string()
5488
        .contains("another repository"));
5489
    let mut forged = sr.clone();
5490
    forged.receipt.exit_code = 1;
5491
    assert!(repo
5492
        .add_receipt(&forged)
5493
        .unwrap_err()
5494
        .to_string()
5495
        .contains("does not verify"));
5496
5497
    // gc keeps the receipt, its runner and its output while the state lives.
5498
    repo.gc(true).unwrap();
5499
    assert_eq!(repo.receipts(&heads).unwrap().len(), 1);
5500
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5501
    assert!(repo.fsck().unwrap().problems.is_empty());
5502
}
5503
5504
#[test]
5505
fn status_leaves_an_unchanged_manifest_alone() {
5506
    hermetic();
5507
    let dir = tempfile::tempdir().unwrap();
5508
    let root = dir.path();
5509
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5510
    write(root, "a.txt", b"1\n");
5511
    write(root, "b.txt", b"2\n");
5512
    repo.commit("A", &[]).unwrap();
5513
    // Files last touched well outside the racy window.
5514
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5515
    for f in ["a.txt", "b.txt"] {
5516
        fs::File::options()
5517
            .write(true)
5518
            .open(root.join(f))
5519
            .unwrap()
5520
            .set_modified(old)
5521
            .unwrap();
5522
    }
5523
    repo.snapshot_status("status").unwrap();
5524
    let path = repo.manifest_path();
5525
    let first = fs::read(&path).unwrap();
5526
    repo.snapshot_status("status").unwrap();
5527
    assert_eq!(
5528
        fs::read(&path).unwrap(),
5529
        first,
5530
        "an unchanged tree does not rewrite the manifest"
5531
    );
5532
    // A change rewrites it.
5533
    write(root, "a.txt", b"1\n2\n");
5534
    repo.snapshot_status("status").unwrap();
5535
    assert_ne!(fs::read(&path).unwrap(), first);
5536
}
5537
5538
#[test]
5539
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5540
    hermetic();
5541
    let dir = tempfile::tempdir().unwrap();
5542
    let root = dir.path();
5543
    let origin_path = root.join("origin");
5544
    Repo::init(&origin_path).unwrap();
5545
    let origin_url = origin_path.to_string_lossy().to_string();
5546
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5547
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5548
    write(&root.join("a"), "big.txt", big.as_bytes());
5549
    write(&root.join("a"), "small.txt", b"small\n");
5550
    let h1 = a.commit("large", &[]).unwrap();
5551
    let (_, body) = a.store().get(&h1).unwrap();
5552
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5553
    assert!(a.push("origin", false).unwrap()[0].ok);
5554
5555
    // A clone reads the text from the blobs that came with the change.
5556
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5557
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5558
    // An edit in the middle of the stored insert is an ordinary change.
5559
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5560
    write(&root.join("b"), "big.txt", edited.as_bytes());
5561
    let h2 = b.commit("edit", &[]).unwrap();
5562
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5563
    assert!(b.push("origin", false).unwrap()[0].ok);
5564
    assert!(a.pull("origin").unwrap().checked_out);
5565
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5566
    assert_eq!(
5567
        a.fsck().unwrap().errors(),
5568
        0,
5569
        "{:?}",
5570
        a.fsck().unwrap().problems
5571
    );
5572
5573
    // With zero retention gc keeps the text blobs of every kept change.
5574
    let mut a = Repo::open(&root.join("a")).unwrap();
5575
    a.config.set("core.op-retention", "0").unwrap();
5576
    a.save_config().unwrap();
5577
    let a = Repo::open(&root.join("a")).unwrap();
5578
    a.gc(true).unwrap();
5579
    let a = Repo::open(&root.join("a")).unwrap();
5580
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5581
    assert_eq!(
5582
        a.fsck().unwrap().errors(),
5583
        0,
5584
        "{:?}",
5585
        a.fsck().unwrap().problems
5586
    );
5587
    // And a clone of the packed repository reads them from its packs.
5588
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5589
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5590
    drop(c);
5591
}
5592
5593
#[test]
5594
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5595
    hermetic();
5596
    let dir = tempfile::tempdir().unwrap();
5597
    let root = dir.path();
5598
    let repo = Repo::init(root).unwrap();
5599
    write(root, "a.txt", b"a\n");
5600
    let a = repo.commit("a", &[]).unwrap();
5601
    write(root, "b.txt", b"b\n");
5602
    repo.commit("b", &[]).unwrap();
5603
    let (x, op) = repo.head_op().unwrap();
5604
    let ws = *op.view.workspaces.keys().next().unwrap();
5605
    let mut one = op.view.clone();
5606
    one.workspaces.insert(ws, a);
5607
    let mut two = op.view.clone();
5608
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5609
    let first = repo.record_op(&[x], "one", one).unwrap();
5610
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5611
    assert!(
5612
        e.to_string()
5613
            .contains("changed this working copy at the same time"),
5614
        "{e}"
5615
    );
5616
    assert_eq!(
5617
        repo.head_op().unwrap().0,
5618
        first,
5619
        "the second is not recorded"
5620
    );
5621
}
5622
5623
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5624
/// rewrote the working copy recorded the half-written files as edits, and
5625
/// its view replaced the switch's.
5626
#[test]
5627
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5628
    hermetic();
5629
    let dir = tempfile::tempdir().unwrap();
5630
    let root = dir.path().to_path_buf();
5631
    let mut repo = Repo::init(&root).unwrap();
5632
    write(&root, "keep.txt", b"keep\n");
5633
    repo.commit("base", &[]).unwrap();
5634
    repo.bookmark_create("small", None).unwrap();
5635
    for i in 0..300 {
5636
        write(
5637
            &root,
5638
            &format!("many/f{i}.txt"),
5639
            format!("file {i}\n").as_bytes(),
5640
        );
5641
    }
5642
    repo.commit("many", &[]).unwrap();
5643
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5644
    let watcher = {
5645
        let (root, stop) = (root.clone(), stop.clone());
5646
        std::thread::spawn(move || {
5647
            let r = Repo::open(&root).unwrap();
5648
            let mut ran = 0;
5649
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
5650
                if r.snapshot_status("oxy status").is_ok() {
5651
                    ran += 1;
5652
                }
5653
            }
5654
            ran
5655
        })
5656
    };
5657
    for i in 0..20 {
5658
        let to = if i % 2 == 0 { "small" } else { "main" };
5659
        repo.bookmark_switch(to, false).unwrap();
5660
    }
5661
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
5662
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
5663
    // Back on main, clean, with every file where main has it.
5664
    let repo = Repo::open(&root).unwrap();
5665
    let s = repo.snapshot_status("oxy status").unwrap();
5666
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
5667
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
5668
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
5669
    assert!(root.join("many/f299.txt").exists());
5670
}
5671
5672
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
5673
/// put a subrepo that was ahead of its pin back at the pin and moved the
5674
/// subrepo's own bookmark backwards.
5675
#[test]
5676
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
5677
    hermetic();
5678
    let dir = tempfile::tempdir().unwrap();
5679
    let root = dir.path();
5680
    Repo::init(&root.join("lib-origin")).unwrap();
5681
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5682
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
5683
    write(&root.join("lib"), "lib.txt", b"v1\n");
5684
    lib.commit("lib v1", &[]).unwrap();
5685
    assert!(lib.push("origin", false).unwrap()[0].ok);
5686
5687
    let app_dir = root.join("app");
5688
    let mut app = Repo::init(&app_dir).unwrap();
5689
    write(&app_dir, "main.txt", b"app\n");
5690
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5691
    app.commit("app with lib", &[]).unwrap();
5692
    app.bookmark_create("feature", None).unwrap();
5693
5694
    // New work in the subrepo, not yet pinned by the parent.
5695
    let nested_dir = app_dir.join("libs/lib");
5696
    let nested = Repo::open(&nested_dir).unwrap();
5697
    write(&nested_dir, "new.txt", b"new\n");
5698
    let l2 = nested.commit("lib: new file", &[]).unwrap();
5699
    drop(nested);
5700
5701
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
5702
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
5703
    let nested = Repo::open(&nested_dir).unwrap();
5704
    assert!(
5705
        nested.bookmark_heads().unwrap().contains(&l2),
5706
        "its bookmark kept its work"
5707
    );
5708
    assert!(nested_dir.join("new.txt").exists(), "and its files");
5709
    let s = app.snapshot("status").unwrap();
5710
    assert_eq!(
5711
        statuses(&s),
5712
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
5713
    );
5714
}
5715
5716
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
5717
/// moving `main` to a change this clone had pushed on another bookmark,
5718
/// the first `pull` said "Already up to date" while `main` was behind.
5719
#[test]
5720
fn pull_takes_a_remote_move_to_changes_already_here() {
5721
    hermetic();
5722
    let dir = tempfile::tempdir().unwrap();
5723
    let root = dir.path();
5724
    let origin_path = root.join("origin");
5725
    let origin = Repo::init(&origin_path).unwrap();
5726
    let url = origin_path.to_string_lossy().to_string();
5727
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
5728
    write(&root.join("b"), "base.txt", b"base\n");
5729
    b.commit("base", &[]).unwrap();
5730
    assert!(b.push("origin", false).unwrap()[0].ok);
5731
5732
    // A feature bookmark with one change, pushed.
5733
    b.bookmark_create("feat", None).unwrap();
5734
    b.bookmark_switch("feat", false).unwrap();
5735
    write(&root.join("b"), "x.txt", b"x\n");
5736
    let x = b.commit("x", &[]).unwrap();
5737
    assert!(b.push("origin", false).unwrap()[0].ok);
5738
    b.bookmark_switch("main", false).unwrap();
5739
5740
    // The remote lands it: its main moves to the feature's state.
5741
    let feat = origin
5742
        .store()
5743
        .get_state(&origin.view().unwrap().bookmarks["feat"])
5744
        .unwrap()
5745
        .heads;
5746
    origin.bookmark_set("main", &feat).unwrap();
5747
5748
    let r = b.pull("origin").unwrap();
5749
    assert!(r.changed, "{r:?}");
5750
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
5751
    let main = b
5752
        .bookmarks()
5753
        .unwrap()
5754
        .into_iter()
5755
        .find(|m| m.name == "main")
5756
        .unwrap();
5757
    assert_eq!(main.behind, Some(0), "{main:?}");
5758
}
5759
5760
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
5761
/// to one only the remote has makes a local bookmark from it; a pull moves
5762
/// every local bookmark the remote has too; a clone checks out the remote's
5763
/// default bookmark.
5764
#[test]
5765
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
5766
    hermetic();
5767
    let dir = tempfile::tempdir().unwrap();
5768
    let root = dir.path();
5769
    let origin_path = root.join("origin");
5770
    let mut origin = Repo::init(&origin_path).unwrap();
5771
    let url = origin_path.to_string_lossy().to_string();
5772
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
5773
    write(&root.join("a"), "base.txt", b"base\n");
5774
    a.commit("base", &[]).unwrap();
5775
    assert!(a.push("origin", false).unwrap()[0].ok);
5776
    a.bookmark_create("develop", None).unwrap();
5777
    a.bookmark_switch("develop", false).unwrap();
5778
    write(&root.join("a"), "base.txt", b"base\nd1\n");
5779
    let d1 = a.commit("d1", &[]).unwrap();
5780
    assert!(a.push("origin", false).unwrap()[0].ok);
5781
5782
    // A clone has main only; origin/develop is a name all the same.
5783
    let c_root = root.join("c");
5784
    let mut c = Repo::clone(&url, &c_root).unwrap();
5785
    assert_eq!(c.config.bookmark, "main");
5786
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
5787
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
5788
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
5789
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
5790
5791
    // Switching makes the local bookmark from origin's.
5792
    c.bookmark_switch("develop", false).unwrap();
5793
    assert_eq!(c.config.bookmark, "develop");
5794
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
5795
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
5796
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
5797
    assert!(c.bookmark_switch("nowhere", false).is_err());
5798
5799
    // Both bookmarks move on the remote; one pull takes both.
5800
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
5801
    let d2 = a.commit("d2", &[]).unwrap();
5802
    assert!(a.push("origin", false).unwrap()[0].ok);
5803
    a.bookmark_switch("main", false).unwrap();
5804
    write(&root.join("a"), "m.txt", b"m\n");
5805
    let m = a.commit("m", &[]).unwrap();
5806
    assert!(a.push("origin", false).unwrap()[0].ok);
5807
    let r = c.pull("origin").unwrap();
5808
    assert!(r.changed && r.checked_out, "{r:?}");
5809
    assert_eq!(r.heads, vec![d2]);
5810
    assert_eq!(r.others, vec!["main".to_string()]);
5811
    assert!(c.resolve_heads("main").unwrap().contains(&m));
5812
    assert_eq!(
5813
        fs::read(c_root.join("base.txt")).unwrap(),
5814
        b"base\nd1\nd2\n"
5815
    );
5816
    let again = c.pull("origin").unwrap();
5817
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
5818
5819
    // A clone checks out the remote's default bookmark.
5820
    origin.config.set("workspace.bookmark", "develop").unwrap();
5821
    origin.save_config().unwrap();
5822
    let e = Repo::clone(&url, &root.join("e")).unwrap();
5823
    assert_eq!(e.config.bookmark, "develop");
5824
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
5825
    let reopened = Repo::open(&root.join("e")).unwrap();
5826
    assert_eq!(reopened.config.bookmark, "develop");
5827
    // REMOTE/NAME names the remote's bookmark to switch to.
5828
    let mut e = reopened;
5829
    e.bookmark_switch("origin/main", false).unwrap();
5830
    assert_eq!(e.config.bookmark, "main");
5831
    assert!(e.bookmark_heads().unwrap().contains(&m));
5832
}
5833
5834
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
5835
/// op restore goes back to an operation, files included, and undo takes
5836
/// the restore back whole; op revert undoes one operation alone; each
5837
/// operation's changes are described from the views.
5838
#[test]
5839
fn operations_can_be_read_restored_and_reverted() {
5840
    hermetic();
5841
    let dir = tempfile::tempdir().unwrap();
5842
    let root = dir.path();
5843
    let repo = Repo::init(root).unwrap();
5844
    write(root, "a.txt", b"a\n");
5845
    let first = repo.commit("first", &[]).unwrap();
5846
    write(root, "a.txt", b"a\nb\n");
5847
    let second = repo.commit("second", &[]).unwrap();
5848
    let at_second = repo.head_op().unwrap().0.to_hex();
5849
    repo.bookmark_create("keep", None).unwrap();
5850
    let created = repo.head_op().unwrap().0.to_hex();
5851
    write(root, "n.txt", b"n\n");
5852
    let third = repo.commit("third", &[]).unwrap();
5853
5854
    // What each operation changed.
5855
    let ops = repo.op_log().unwrap();
5856
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
5857
    assert!(
5858
        changes
5859
            .iter()
5860
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
5861
        "{changes:?}"
5862
    );
5863
    assert!(changes
5864
        .iter()
5865
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
5866
5867
    // Reading at an earlier operation.
5868
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
5869
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
5870
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
5871
    write(root, "z.txt", b"z\n");
5872
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
5873
    fs::remove_file(root.join("z.txt")).unwrap();
5874
    assert!(repo.resolve_op("zz").is_err());
5875
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
5876
5877
    // Restore goes back, files and all; undo takes it back whole.
5878
    repo.op_restore(&at_second, false).unwrap();
5879
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
5880
    assert!(!root.join("n.txt").exists());
5881
    repo.undo().unwrap();
5882
    let mut heads = repo.bookmark_heads().unwrap();
5883
    heads.sort();
5884
    let mut want = vec![second, third];
5885
    want.sort();
5886
    assert_eq!(heads, want);
5887
    assert!(
5888
        root.join("n.txt").exists(),
5889
        "the files came back with the undo"
5890
    );
5891
5892
    // Revert the bookmark's creation alone: the commit after it stays.
5893
    let r = repo.op_revert(&created).unwrap();
5894
    assert_eq!(r.reverted, vec!["keep".to_string()]);
5895
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
5896
    assert!(repo
5897
        .load_state(&repo.bookmark_heads().unwrap())
5898
        .unwrap()
5899
        .contains(&third));
5900
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
5901
    let _ = first;
5902
}
5903
5904
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
5905
/// from the status cache while every file is as the snapshot left it, and
5906
/// from a snapshot again as soon as one is not.
5907
#[test]
5908
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
5909
    hermetic();
5910
    let dir = tempfile::tempdir().unwrap();
5911
    let root = dir.path();
5912
    let repo = Repo::init(root).unwrap();
5913
    write(root, "a.txt", b"a\n");
5914
    write(root, "b.txt", b"b\n");
5915
    repo.commit("base", &[]).unwrap();
5916
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
5917
5918
    write(root, "a.txt", b"a\nmore\n");
5919
    assert_eq!(
5920
        repo.status_by_manifest().unwrap(),
5921
        None,
5922
        "no snapshot of the edit yet"
5923
    );
5924
    let snap = repo.snapshot_status("oxy status").unwrap();
5925
    assert_eq!(snap.statuses.len(), 1);
5926
    let cached = repo
5927
        .status_by_manifest()
5928
        .unwrap()
5929
        .expect("answered from the cache");
5930
    assert_eq!(cached.len(), 1);
5931
    assert_eq!(
5932
        (cached[0].path.as_str(), cached[0].status),
5933
        ("a.txt", ChangeStatus::Modified)
5934
    );
5935
5936
    // Any further change sends status back to a snapshot.
5937
    write(root, "a.txt", b"a\nmore\nand more\n");
5938
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
5939
    repo.snapshot_status("oxy status").unwrap();
5940
    assert!(repo.status_by_manifest().unwrap().is_some());
5941
    write(root, "new.txt", b"n\n");
5942
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
5943
    fs::remove_file(root.join("new.txt")).unwrap();
5944
    assert!(
5945
        repo.status_by_manifest().unwrap().is_some(),
5946
        "back as it was"
5947
    );
5948
    fs::remove_file(root.join("b.txt")).unwrap();
5949
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
5950
    write(root, "b.txt", b"b\n");
5951
5952
    // A commit leaves nothing uncommitted: clean again, no cache needed.
5953
    repo.snapshot_status("oxy status").unwrap();
5954
    repo.commit("more", &[]).unwrap();
5955
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
5956
}
5957
5958
/// oxygen#41: while the status cache holds, the working copy's diff is
5959
/// rendered from the stored working-copy change, and says exactly what a
5960
/// snapshot's diff says.
5961
#[test]
5962
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
5963
    hermetic();
5964
    let dir = tempfile::tempdir().unwrap();
5965
    let root = dir.path();
5966
    let repo = Repo::init(root).unwrap();
5967
    write(root, "a.txt", b"one\ntwo\nthree\n");
5968
    write(root, "gone.txt", b"bye\n");
5969
    repo.commit("base", &[]).unwrap();
5970
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
5971
    write(root, "new.txt", b"hello\n");
5972
    fs::remove_file(root.join("gone.txt")).unwrap();
5973
    let snap = repo.snapshot_status("oxy status").unwrap();
5974
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
5975
    assert!(
5976
        repo.status_by_manifest().unwrap().is_some(),
5977
        "the cache holds"
5978
    );
5979
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
5980
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
5981
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
5982
}
5983
5984
/// oxygen#41: a manifest written from a walk keeps every directory's time;
5985
/// while none has moved, the check stats the tracked files without listing
5986
/// the tree, and a file added or removed anywhere moves its directory's
5987
/// time, so the tree is listed again.
5988
#[test]
5989
fn the_manifest_check_skips_listing_while_no_directory_changed() {
5990
    hermetic();
5991
    let dir = tempfile::tempdir().unwrap();
5992
    let root = dir.path();
5993
    let repo = Repo::init(root).unwrap();
5994
    write(root, "a.txt", b"a\n");
5995
    write(root, "sub/deep/b.txt", b"b\n");
5996
    repo.commit("base", &[]).unwrap();
5997
    // Out of the racy window: every file and directory a minute old.
5998
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5999
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6000
        fs::File::open(root.join(p))
6001
            .unwrap()
6002
            .set_modified(old)
6003
            .unwrap();
6004
    }
6005
    repo.snapshot_status("oxy status").unwrap();
6006
    repo.write_manifest(false, false).unwrap();
6007
    let m = repo.read_manifest().unwrap().unwrap().2;
6008
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6009
    assert_eq!(
6010
        repo.disk_differs_by_dirs(&m),
6011
        Some(false),
6012
        "no listing needed"
6013
    );
6014
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6015
6016
    // A same-size edit with a new time: found by its stat.
6017
    write(root, "sub/deep/b.txt", b"c\n");
6018
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6019
    write(root, "sub/deep/b.txt", b"b\n");
6020
    fs::File::open(root.join("sub/deep/b.txt"))
6021
        .unwrap()
6022
        .set_modified(old)
6023
        .unwrap();
6024
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6025
6026
    // A new file moves its directory's time: the tree must be listed.
6027
    write(root, "sub/deep/new.txt", b"n\n");
6028
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6029
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6030
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6031
    // A removed one too.
6032
    fs::remove_file(root.join("a.txt")).unwrap();
6033
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6034
}
6035
6036
/// oxygen#41: a commit right after a status takes the snapshot the status
6037
/// left (the status cache holds) rather than walking again, and commits
6038
/// exactly what a snapshot would have.
6039
#[test]
6040
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6041
    hermetic();
6042
    let dir = tempfile::tempdir().unwrap();
6043
    let root = dir.path();
6044
    let repo = Repo::init(root).unwrap();
6045
    write(root, "a.txt", b"a\nb\n");
6046
    write(root, ".oxyattributes", b"*.bin binary\n");
6047
    repo.commit("base", &[]).unwrap();
6048
    write(root, "a.txt", b"a\nB\n");
6049
    write(root, "new.txt", b"new\n");
6050
    let snap = repo.snapshot_status("oxy status").unwrap();
6051
    let cached = repo
6052
        .snapshot_from_cache()
6053
        .unwrap()
6054
        .expect("the cache holds");
6055
    assert_eq!(cached.wc_hash, snap.wc_hash);
6056
    assert_eq!(cached.statuses, snap.statuses);
6057
    assert!(
6058
        !cached.attributes.is_empty(),
6059
        "the .oxyattributes file was read"
6060
    );
6061
    let h = repo.commit("edit", &[]).unwrap();
6062
    let c = repo.store().get_change(&h).unwrap();
6063
    assert_eq!(
6064
        c.tree_ops.len() + c.edits.len(),
6065
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6066
    );
6067
    assert_eq!(
6068
        repo.status_by_manifest().unwrap(),
6069
        Some(vec![]),
6070
        "clean after the commit"
6071
    );
6072
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6073
}
6074
6075
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6076
/// stored insert's text blob only when it builds that file's graph, and
6077
/// builds the same graph a full load does.
6078
#[test]
6079
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6080
    hermetic();
6081
    let dir = tempfile::tempdir().unwrap();
6082
    let root = dir.path();
6083
    let repo = Repo::init(root).unwrap();
6084
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6085
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6086
    write(root, "big.txt", big.as_bytes());
6087
    write(root, "other.txt", other.as_bytes());
6088
    let h = repo.commit("two large files", &[]).unwrap();
6089
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6090
    let h2 = repo.commit("append", &[]).unwrap();
6091
6092
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6093
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6094
        FileContent::Text { bytes, .. } => bytes.clone(),
6095
        other => panic!("{other:?}"),
6096
    };
6097
    // Built on demand, every graph renders as the full load's.
6098
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6099
    let big_node = full.files["big.txt"].node;
6100
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6101
    repo.load_all_graphs(&mut hist).unwrap();
6102
    let rendered = hist.materialize();
6103
    for p in ["big.txt", "other.txt"] {
6104
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6105
    }
6106
6107
    // Without other.txt's text blob, history still loads and big.txt still
6108
    // builds: nothing read the other text.
6109
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6110
    assert_eq!(texts.len(), 2);
6111
    let content = |r: &ObjectRef| -> Vec<u8> {
6112
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6113
        blob.chunks
6114
            .iter()
6115
            .flat_map(|c| repo.store().get(c).unwrap().1)
6116
            .collect()
6117
    };
6118
    let other_text = texts
6119
        .iter()
6120
        .filter_map(|t| match t {
6121
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6122
            _ => None,
6123
        })
6124
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6125
        .unwrap();
6126
    fs::remove_file(repo.store().path_for(&other_text)).unwrap();
6127
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6128
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6129
    assert!(repo
6130
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6131
        .is_err());
6132
}
6133
6134
/// oxygen#35: the first status after a commit read and rendered every
6135
/// file (79 s and more than 14 GB on the Linux tree), because the
6136
/// manifest had no graph keys for files the commit added.
6137
#[test]
6138
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6139
    use std::os::unix::fs::PermissionsExt;
6140
    hermetic();
6141
    let dir = tempfile::tempdir().unwrap();
6142
    let root = dir.path();
6143
    let repo = Repo::init(root).unwrap();
6144
    let files = ["a.txt", "b.txt", "d/c.txt"];
6145
    for p in files {
6146
        write(root, p, format!("{p}\n").as_bytes());
6147
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6148
        fs::File::options()
6149
            .write(true)
6150
            .open(root.join(p))
6151
            .unwrap()
6152
            .set_modified(old)
6153
            .unwrap();
6154
    }
6155
    repo.commit("added", &[]).unwrap();
6156
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6157
    assert!(
6158
        m.entries.values().all(|e| e.graph.is_some()),
6159
        "keys recorded at commit"
6160
    );
6161
    // Unreadable files prove the next status reads none of them.
6162
    for p in files {
6163
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6164
    }
6165
    let snap = repo.snapshot_status("status").unwrap();
6166
    for p in files {
6167
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6168
    }
6169
    assert!(!snap.changed && snap.statuses.is_empty());
6170
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6171
}
6172
6173
/// oxygen#35: a checkout reads, renders and writes only the files whose
6174
/// graphs differ, and renders the rest a batch at a time.
6175
#[test]
6176
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6177
    use std::os::unix::fs::PermissionsExt;
6178
    hermetic();
6179
    let dir = tempfile::tempdir().unwrap();
6180
    let root = dir.path();
6181
    let origin = root.join("origin");
6182
    let mut repo = Repo::init(&origin).unwrap();
6183
    // More files than one batch holds.
6184
    let n = 2100;
6185
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6186
    for i in 0..n {
6187
        let p = format!("f/{i:04}.txt");
6188
        write(&origin, &p, format!("file {i}\n").as_bytes());
6189
        fs::File::options()
6190
            .write(true)
6191
            .open(origin.join(&p))
6192
            .unwrap()
6193
            .set_modified(old)
6194
            .unwrap();
6195
    }
6196
    repo.commit("many", &[]).unwrap();
6197
    repo.bookmark_create("feature", None).unwrap();
6198
    repo.bookmark_switch("feature", false).unwrap();
6199
    write(&origin, "f/0007.txt", b"changed\n");
6200
    repo.commit("one change", &[]).unwrap();
6201
6202
    // Switching back to main must not read the unchanged files.
6203
    for i in 0..n {
6204
        if i != 7 {
6205
            let p = origin.join(format!("f/{i:04}.txt"));
6206
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6207
        }
6208
    }
6209
    let r = repo.bookmark_switch("main", false).unwrap();
6210
    for i in 0..n {
6211
        let p = origin.join(format!("f/{i:04}.txt"));
6212
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6213
    }
6214
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6215
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6216
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6217
6218
    // A clone renders every file, across batches.
6219
    let c = root.join("clone");
6220
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6221
    for i in [0, 2047, 2048, n - 1] {
6222
        assert_eq!(
6223
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6224
            format!("file {i}\n").as_bytes()
6225
        );
6226
    }
6227
    let cloned = Repo::open(&c).unwrap();
6228
    assert!(cloned
6229
        .snapshot_status("status")
6230
        .unwrap()
6231
        .statuses
6232
        .is_empty());
6233
}
6234
6235
/// A file written just before the manifest (inside the racy window) is
6236
/// checked by its hash: trusted when equal, caught when edited in place
6237
/// with the same size and time.
6238
#[test]
6239
fn a_racy_manifest_entry_is_checked_by_hash() {
6240
    hermetic();
6241
    let dir = tempfile::tempdir().unwrap();
6242
    let root = dir.path();
6243
    let repo = Repo::init(root).unwrap();
6244
    write(root, "a.txt", b"one\n");
6245
    repo.commit("fresh", &[]).unwrap();
6246
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6247
    let t = fs::metadata(root.join("a.txt"))
6248
        .unwrap()
6249
        .modified()
6250
        .unwrap();
6251
    write(root, "a.txt", b"two\n");
6252
    fs::File::options()
6253
        .write(true)
6254
        .open(root.join("a.txt"))
6255
        .unwrap()
6256
        .set_modified(t)
6257
        .unwrap();
6258
    assert!(
6259
        !repo.clean_by_manifest().unwrap(),
6260
        "same size and time, other bytes"
6261
    );
6262
    assert_eq!(
6263
        statuses(&repo.snapshot_status("status").unwrap()),
6264
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6265
    );
6266
}
6267
6268
/// A fetch on one machine moves changes as stored, text blobs among the
6269
/// objects; a change whose text blob did not come is refused, not stored.
6270
#[test]
6271
fn a_raw_bundle_without_a_changes_text_is_refused() {
6272
    hermetic();
6273
    let dir = tempfile::tempdir().unwrap();
6274
    let root = dir.path();
6275
    let a = Repo::init(&root.join("a")).unwrap();
6276
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6277
    write(&root.join("a"), "big.txt", big.as_bytes());
6278
    let h = a.commit("big", &[]).unwrap();
6279
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6280
    assert_eq!(bundle.raw_changes.len(), 1);
6281
    assert!(bundle.changes.is_empty());
6282
    let b = Repo::init(&root.join("b")).unwrap();
6283
    let mut without = bundle.clone();
6284
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6285
    let e = b.import_bundle(&without, false).unwrap_err();
6286
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6287
    assert!(!b.store().has(&h));
6288
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6289
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6290
}
6291
6292
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6293
/// again was a second node for one Git path, so a file moved into it on
6294
/// another line, where the first node still stood, ended up in two places.
6295
/// An import now brings the directory back rather than make a new one.
6296
#[test]
6297
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6298
    hermetic();
6299
    if std::process::Command::new("git")
6300
        .arg("--version")
6301
        .output()
6302
        .is_err()
6303
    {
6304
        eprintln!("git not installed; skipping");
6305
        return;
6306
    }
6307
    let dir = tempfile::tempdir().unwrap();
6308
    let root = dir.path();
6309
    let g = root.join("src.git");
6310
    fs::create_dir_all(&g).unwrap();
6311
    let git = |args: &[&str]| -> String {
6312
        let out = std::process::Command::new("git")
6313
            .arg("-C")
6314
            .arg(&g)
6315
            .args([
6316
                "-c",
6317
                "user.name=Grace",
6318
                "-c",
6319
                "[email protected]",
6320
                "-c",
6321
                "commit.gpgsign=false",
6322
            ])
6323
            .args(args)
6324
            .output()
6325
            .unwrap();
6326
        assert!(
6327
            out.status.success(),
6328
            "git {args:?}: {}",
6329
            String::from_utf8_lossy(&out.stderr)
6330
        );
6331
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6332
    };
6333
    git(&["init", "-q", "-b", "main"]);
6334
    write(&g, "d/a.txt", b"a\n");
6335
    write(&g, "c/x.txt", b"x\n");
6336
    git(&["add", "."]);
6337
    git(&["commit", "-qm", "base"]);
6338
    // One line: move x into d while d still stands.
6339
    git(&["checkout", "-qb", "side"]);
6340
    git(&["mv", "c/x.txt", "d/x.txt"]);
6341
    git(&["commit", "-qm", "x into d"]);
6342
    // The other: d goes, comes back, and x moves into it too.
6343
    git(&["checkout", "-q", "main"]);
6344
    git(&["rm", "-q", "d/a.txt"]);
6345
    git(&["commit", "-qm", "d goes"]);
6346
    write(&g, "d/b.txt", b"b\n");
6347
    git(&["add", "."]);
6348
    git(&["commit", "-qm", "d comes back"]);
6349
    git(&["mv", "c/x.txt", "d/x.txt"]);
6350
    git(&["commit", "-qm", "x into d again"]);
6351
    git(&["merge", "-q", "--no-edit", "side"]);
6352
6353
    let repo = Repo::init(&root.join("o")).unwrap();
6354
    repo.import_git(&g, "main").unwrap();
6355
    let v = repo.verify_git_import(&g, "main").unwrap();
6356
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6357
    let st = repo
6358
        .load_state_history(&repo.bookmark_heads().unwrap())
6359
        .unwrap();
6360
    let view = st.tree().view();
6361
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6362
    // The directory is the one the first commit made.
6363
    // Commits made in one second tie on time: find the first by its message.
6364
    let first = repo
6365
        .log()
6366
        .unwrap()
6367
        .into_iter()
6368
        .find(|e| e.change.message.starts_with("base"))
6369
        .unwrap();
6370
    let base = repo
6371
        .load_state_history(&[first.hash])
6372
        .unwrap()
6373
        .tree()
6374
        .view();
6375
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6376
}
6377
6378
/// oxygen#30, the rest: a placement left under a directory another line
6379
/// removed is out of sight, so no diff reaches it; the merge that settles
6380
/// where the file is retires it.
6381
#[test]
6382
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6383
    hermetic();
6384
    if std::process::Command::new("git")
6385
        .arg("--version")
6386
        .output()
6387
        .is_err()
6388
    {
6389
        eprintln!("git not installed; skipping");
6390
        return;
6391
    }
6392
    let dir = tempfile::tempdir().unwrap();
6393
    let root = dir.path();
6394
    let g = root.join("src.git");
6395
    fs::create_dir_all(&g).unwrap();
6396
    let run = |args: &[&str]| {
6397
        std::process::Command::new("git")
6398
            .arg("-C")
6399
            .arg(&g)
6400
            .args([
6401
                "-c",
6402
                "user.name=Grace",
6403
                "-c",
6404
                "[email protected]",
6405
                "-c",
6406
                "commit.gpgsign=false",
6407
            ])
6408
            .args(args)
6409
            .output()
6410
            .unwrap()
6411
    };
6412
    let git = |args: &[&str]| {
6413
        let out = run(args);
6414
        assert!(
6415
            out.status.success(),
6416
            "git {args:?}: {}",
6417
            String::from_utf8_lossy(&out.stderr)
6418
        );
6419
    };
6420
    git(&["init", "-q", "-b", "main"]);
6421
    write(&g, "c/x.txt", b"x\n");
6422
    write(&g, "keep.txt", b"k\n");
6423
    git(&["add", "."]);
6424
    git(&["commit", "-qm", "base"]);
6425
    // One line renames the file within c; the other moves it out of c,
6426
    // which goes.
6427
    git(&["checkout", "-qb", "side"]);
6428
    git(&["mv", "c/x.txt", "c/y.txt"]);
6429
    git(&["commit", "-qm", "rename within c"]);
6430
    git(&["checkout", "-q", "main"]);
6431
    fs::create_dir_all(g.join("n")).unwrap();
6432
    git(&["mv", "c/x.txt", "n/x.txt"]);
6433
    git(&["commit", "-qm", "move out of c"]);
6434
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6435
    let _ = run(&["merge", "-q", "side"]);
6436
    let _ = run(&[
6437
        "rm",
6438
        "-q",
6439
        "--cached",
6440
        "--ignore-unmatch",
6441
        "c/y.txt",
6442
        "c/x.txt",
6443
    ]);
6444
    let _ = std::fs::remove_dir_all(g.join("c"));
6445
    write(&g, "n/x.txt", b"x\n");
6446
    git(&["add", "-A"]);
6447
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6448
6449
    let repo = Repo::init(&root.join("o")).unwrap();
6450
    repo.import_git(&g, "main").unwrap();
6451
    let v = repo.verify_git_import(&g, "main").unwrap();
6452
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6453
    let st = repo
6454
        .load_state_history(&repo.bookmark_heads().unwrap())
6455
        .unwrap();
6456
    let view = st.tree().view();
6457
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6458
    assert!(view.entries.contains_key("n/x.txt"));
6459
}
6460
6461
/// oxygen#30, orphans: a file added on one line into a directory the other
6462
/// line removed is placed where the tree cannot show it; Git's merge keeps
6463
/// the file, and the import's merge leaves exactly one of it.
6464
#[test]
6465
fn git_import_merge_leaves_no_orphan_behind() {
6466
    hermetic();
6467
    if std::process::Command::new("git")
6468
        .arg("--version")
6469
        .output()
6470
        .is_err()
6471
    {
6472
        eprintln!("git not installed; skipping");
6473
        return;
6474
    }
6475
    let dir = tempfile::tempdir().unwrap();
6476
    let root = dir.path();
6477
    let g = root.join("src.git");
6478
    fs::create_dir_all(&g).unwrap();
6479
    let git = |args: &[&str]| {
6480
        let out = std::process::Command::new("git")
6481
            .arg("-C")
6482
            .arg(&g)
6483
            .args([
6484
                "-c",
6485
                "user.name=Grace",
6486
                "-c",
6487
                "[email protected]",
6488
                "-c",
6489
                "commit.gpgsign=false",
6490
            ])
6491
            .args(args)
6492
            .output()
6493
            .unwrap();
6494
        assert!(
6495
            out.status.success(),
6496
            "git {args:?}: {}",
6497
            String::from_utf8_lossy(&out.stderr)
6498
        );
6499
    };
6500
    git(&["init", "-q", "-b", "main"]);
6501
    write(&g, "d/f.txt", b"f\n");
6502
    write(&g, "keep.txt", b"k\n");
6503
    git(&["add", "."]);
6504
    git(&["commit", "-qm", "base"]);
6505
    git(&["checkout", "-qb", "side"]);
6506
    write(&g, "d/new.txt", b"new\n");
6507
    git(&["add", "."]);
6508
    git(&["commit", "-qm", "add into d"]);
6509
    git(&["checkout", "-q", "main"]);
6510
    git(&["rm", "-q", "d/f.txt"]);
6511
    git(&["commit", "-qm", "d goes"]);
6512
    git(&["merge", "-q", "--no-edit", "side"]);
6513
6514
    let repo = Repo::init(&root.join("o")).unwrap();
6515
    repo.import_git(&g, "main").unwrap();
6516
    let v = repo.verify_git_import(&g, "main").unwrap();
6517
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6518
    let st = repo
6519
        .load_state_history(&repo.bookmark_heads().unwrap())
6520
        .unwrap();
6521
    let view = st.tree().view();
6522
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6523
    assert!(view.entries.contains_key("d/new.txt"));
6524
}
6525
6526
/// fsck checks a change's text as the blobs it is stored in, without
6527
/// decoding it: a missing text blob is an error named for the change.
6528
#[test]
6529
fn fsck_names_a_missing_text_blob() {
6530
    hermetic();
6531
    let dir = tempfile::tempdir().unwrap();
6532
    let root = dir.path();
6533
    let repo = Repo::init(root).unwrap();
6534
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6535
    write(root, "big.txt", big.as_bytes());
6536
    let h = repo.commit("big", &[]).unwrap();
6537
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6538
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6539
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6540
        panic!("a stored text")
6541
    };
6542
    fs::remove_file(repo.store().path_for(&b)).unwrap();
6543
    let rep = repo.fsck().unwrap();
6544
    assert!(rep.errors() > 0);
6545
    assert!(
6546
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6547
        "{:?}",
6548
        rep.problems
6549
    );
6550
}
6551
6552
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6553
/// reached with that remote's token and CA (a private subrepo then clones
6554
/// for anyone who can read the parent); another hub gets none of them.
6555
#[test]
6556
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6557
    hermetic();
6558
    let dir = tempfile::tempdir().unwrap();
6559
    let mut repo = Repo::init(dir.path()).unwrap();
6560
    repo.config
6561
        .set(
6562
            "remote.origin.url",
6563
            "https://Hub.example:7343/doomsdayone/metalgear",
6564
        )
6565
        .unwrap();
6566
    repo.config.set("remote.origin.token", "secret").unwrap();
6567
    repo.config
6568
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6569
        .unwrap();
6570
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6571
    assert_eq!(same.token.as_deref(), Some("secret"));
6572
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6573
    for other in [
6574
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6575
        "https://hub.example/doomsdayone/rstar-api",
6576
        "http://hub.example:7343/doomsdayone/rstar-api",
6577
    ] {
6578
        let o = repo.credentials_for(other);
6579
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6580
    }
6581
}
6582
6583
/// oxygen#47: a remote with no token of its own uses the user's credential
6584
/// store for its hub, and a nested checkout finds its parent's remote
6585
/// token there instead of keeping a copy.
6586
#[test]
6587
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
6588
    hermetic();
6589
    let home = tempfile::tempdir().unwrap();
6590
    let dir = tempfile::tempdir().unwrap();
6591
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
6592
    parent
6593
        .config
6594
        .set("remote.origin.url", "https://hub.example/o/parent")
6595
        .unwrap();
6596
    parent.save_config().unwrap();
6597
    assert_eq!(parent.remote_options("origin").token, None);
6598
    crate::credentials::Credentials::at(home.path())
6599
        .save("https://hub.example", "stored", Some("andy"), None)
6600
        .unwrap();
6601
    assert_eq!(
6602
        parent.remote_options("origin").token.as_deref(),
6603
        Some("stored")
6604
    );
6605
6606
    let empty_home = tempfile::tempdir().unwrap();
6607
    let nested = dir.path().join("deps").join("child");
6608
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
6609
    child
6610
        .config
6611
        .set("remote.origin.url", "https://hub.example/o/child")
6612
        .unwrap();
6613
    child.save_config().unwrap();
6614
    assert_eq!(child.remote_options("origin").token, None);
6615
    parent
6616
        .config
6617
        .set("remote.origin.token", "checkout")
6618
        .unwrap();
6619
    parent.save_config().unwrap();
6620
    assert_eq!(
6621
        child.remote_options("origin").token.as_deref(),
6622
        Some("checkout")
6623
    );
6624
    // Another hub's checkout token is not borrowed.
6625
    child
6626
        .config
6627
        .set("remote.origin.url", "https://other.example/o/child")
6628
        .unwrap();
6629
    assert_eq!(child.remote_options("origin").token, None);
6630
}
6631
6632
#[test]
6633
fn the_metadata_cache_survives_a_torn_tail() {
6634
    hermetic();
6635
    let dir = tempfile::tempdir().unwrap();
6636
    let root = dir.path();
6637
    let repo = Repo::init(root).unwrap();
6638
    write(root, "a.txt", b"1\n");
6639
    let h = repo.commit("first", &[]).unwrap();
6640
    let meta = repo.store().get_change_meta(&h).unwrap();
6641
    let cache = repo.store().dir().join("metas");
6642
    let len = fs::metadata(&cache).unwrap().len();
6643
    assert!(len > 0, "a change read is cached");
6644
    // A torn record at the end: the cache reads up to it and cuts it off.
6645
    fs::OpenOptions::new()
6646
        .append(true)
6647
        .open(&cache)
6648
        .unwrap()
6649
        .write_all(&[7; 20])
6650
        .unwrap();
6651
    let again = Repo::open(root).unwrap();
6652
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
6653
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
6654
}
6655
6656
#[test]
6657
fn a_manifest_that_does_not_check_reads_as_none() {
6658
    hermetic();
6659
    let dir = tempfile::tempdir().unwrap();
6660
    let root = dir.path();
6661
    let repo = Repo::init(root).unwrap();
6662
    write(root, "a.txt", b"1\n");
6663
    repo.commit("first", &[]).unwrap();
6664
    let path = repo.manifest_path();
6665
    let mut bytes = fs::read(&path).unwrap();
6666
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
6667
    let last = bytes.len() - 1;
6668
    bytes[last] ^= 1;
6669
    fs::write(&path, &bytes).unwrap();
6670
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
6671
    // The next status reads the files and writes it again.
6672
    let again = Repo::open(root).unwrap();
6673
    assert!(!again.snapshot("status").unwrap().changed);
6674
    assert!(again.read_manifest().unwrap().is_some());
6675
}
6676
6677
#[test]
6678
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
6679
    hermetic();
6680
    let dir = tempfile::tempdir().unwrap();
6681
    let root = dir.path();
6682
    let repo = Repo::init(root).unwrap();
6683
    write(root, "a.txt", b"1\n");
6684
    write(root, "b.txt", b"2\n");
6685
    // b.txt outside the racy window, so snapshots take it as unchanged.
6686
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6687
    fs::File::options()
6688
        .write(true)
6689
        .open(root.join("b.txt"))
6690
        .unwrap()
6691
        .set_modified(old)
6692
        .unwrap();
6693
    repo.commit("first", &[]).unwrap();
6694
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
6695
    repo.snapshot_status("status").unwrap();
6696
    write(root, "a.txt", b"1\n2\n");
6697
    repo.commit("second", &[]).unwrap();
6698
    assert!(
6699
        repo.clean_by_manifest().unwrap(),
6700
        "after a commit of one file"
6701
    );
6702
    // Edited, seen by a status, edited again, then committed: the status
6703
    // left the first edit's stat, which the commit must not keep.
6704
    write(root, "a.txt", b"1\n2\n3\n");
6705
    repo.snapshot_status("status").unwrap();
6706
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
6707
    repo.commit("third", &[]).unwrap();
6708
    assert!(
6709
        repo.clean_by_manifest().unwrap(),
6710
        "after an edit a status saw"
6711
    );
6712
}
6713
6714
#[test]
6715
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
6716
    hermetic();
6717
    let dir = tempfile::tempdir().unwrap();
6718
    let root = dir.path();
6719
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6720
    write(root, "a.txt", b"1\n2\n");
6721
    let a = repo.commit("A", &[]).unwrap();
6722
    repo.bookmark_create("develop", Some(&[a])).unwrap();
6723
    write(root, "a.txt", b"1\nX\n");
6724
    let c = repo.commit("C: 2 to X", &[]).unwrap();
6725
    repo.bookmark_switch("develop", false).unwrap();
6726
    write(root, "a.txt", b"1\nY\n");
6727
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
6728
    repo.bookmark_switch("main", false).unwrap();
6729
6730
    let err = repo.rebase(&c, &[d]).unwrap_err();
6731
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
6732
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
6733
    assert!(r.changed && r.checked_out);
6734
    let snap = repo.snapshot_status("status").unwrap();
6735
    assert!(
6736
        snap.base_snapshot.is_conflicted(),
6737
        "the conflict is in the working copy"
6738
    );
6739
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
6740
    assert!(text.contains('X') && text.contains('Y'), "{text}");
6741
6742
    write(root, "a.txt", b"1\nXY\n");
6743
    repo.commit("Resolve", &[]).unwrap();
6744
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
6745
    assert!(st.contains(&c) && st.contains(&d));
6746
    let files = st.materialize().files;
6747
    assert!(!files["a.txt"].is_conflicted());
6748
    assert!(
6749
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
6750
    );
6751
6752
    // A change the current bookmark does not hold is refused.
6753
    repo.bookmark_switch("develop", false).unwrap();
6754
    write(root, "b.txt", b"b\n");
6755
    let e = repo.commit("E", &[]).unwrap();
6756
    repo.bookmark_switch("main", false).unwrap();
6757
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
6758
    assert!(
6759
        err.to_string().contains("not on the current bookmark"),
6760
        "{err}"
6761
    );
6762
}
6763
6764
#[test]
6765
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
6766
    hermetic();
6767
    let dir = tempfile::tempdir().unwrap();
6768
    let root = dir.path();
6769
    let repo = Repo::init(root).unwrap();
6770
    write(root, "a.txt", b"a\n");
6771
    write(root, "kept.log", b"tracked\n");
6772
    repo.commit("first", &[]).unwrap();
6773
    write(root, "build.log", b"made\n");
6774
    let snap = repo.snapshot_status("status").unwrap();
6775
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
6776
    // A rule written afterwards leaves the added file out again, while the
6777
    // committed one stays tracked.
6778
    write(root, ".gitignore", b"*.log\n");
6779
    let snap = repo.snapshot_status("status").unwrap();
6780
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
6781
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
6782
    write(root, "kept.log", b"tracked, edited\n");
6783
    let snap = repo.snapshot_status("status").unwrap();
6784
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
6785
}
6786
6787
#[test]
6788
fn shed_graphs_come_back_the_same() {
6789
    hermetic();
6790
    let dir = tempfile::tempdir().unwrap();
6791
    let root = dir.path();
6792
    let repo = Repo::init(root).unwrap();
6793
    write(root, "a.txt", b"1\n2\n3\n");
6794
    write(root, "b.txt", b"x\n");
6795
    repo.commit("first", &[]).unwrap();
6796
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
6797
    repo.commit("second", &[]).unwrap();
6798
    let heads = repo.bookmark_heads().unwrap();
6799
    let mut st = repo.load_state_history(&heads).unwrap();
6800
    let view = st.tree().view();
6801
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
6802
        .iter()
6803
        .map(|p| view.entries[*p].node)
6804
        .collect();
6805
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6806
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6807
    assert_eq!(st.built_count(), 2);
6808
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
6809
    assert_eq!((shed, st.built_count()), (2, 0));
6810
    // A later change applies on top of the shed history.
6811
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
6812
    let h3 = repo.commit("third", &[]).unwrap();
6813
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
6814
    st.add_known(h3, skeleton, texts);
6815
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6816
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6817
    assert_eq!(after[1], before[1]);
6818
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
6819
}
6820
6821
#[test]
6822
fn many_edited_files_diff_in_parallel() {
6823
    // Enough edited files that the builder diffs them in parallel; the
6824
    // commit must hold exactly what is on disk, and a second snapshot
6825
    // must find nothing left to commit.
6826
    hermetic();
6827
    let dir = tempfile::tempdir().unwrap();
6828
    let root = dir.path();
6829
    let repo = Repo::init(root).unwrap();
6830
    let text = |i: usize, round: usize| {
6831
        let mut s = String::new();
6832
        for line in 0..50 {
6833
            if round > 0 && line % 7 == i % 7 {
6834
                s.push_str(&format!("edited {round} {i} {line}\n"));
6835
            } else {
6836
                s.push_str(&format!("file {i} line {line}\n"));
6837
            }
6838
        }
6839
        if round > 0 && i.is_multiple_of(3) {
6840
            s.push_str("appended\n");
6841
        }
6842
        s
6843
    };
6844
    for i in 0..40 {
6845
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
6846
    }
6847
    repo.commit("first", &[]).unwrap();
6848
    for i in 0..40 {
6849
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
6850
    }
6851
    let h = repo.commit("edit every file", &[]).unwrap();
6852
    let snap = repo.load_state(&[h]).unwrap().materialize();
6853
    for i in 0..40 {
6854
        let want = text(i, 1);
6855
        assert!(
6856
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
6857
            "d/f{i}.txt as committed"
6858
        );
6859
    }
6860
    assert!(
6861
        repo.commit("nothing", &[]).is_err(),
6862
        "nothing left to commit"
6863
    );
6864
}
6865
6866
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
6867
/// is known (fetch printed "up to date" while main was behind), a change
6868
/// only fetched resolves and says where it is, and a checkout whose only
6869
/// remote is not `origin` uses that one.
6870
#[test]
6871
fn a_fetched_change_shows_as_behind_and_resolves() {
6872
    hermetic();
6873
    let dir = tempfile::tempdir().unwrap();
6874
    let root = dir.path();
6875
    let origin = Repo::init(&root.join("origin")).unwrap();
6876
    drop(origin);
6877
    let url = root.join("origin").to_string_lossy().to_string();
6878
    let a = Repo::clone(&url, &root.join("a"))
6879
        .unwrap()
6880
        .with_home(root.join("home-a"));
6881
    write(&root.join("a"), "f.txt", b"one\n");
6882
    a.commit("one", &[]).unwrap();
6883
    a.push("origin", false).unwrap();
6884
    let b = Repo::clone(&url, &root.join("b"))
6885
        .unwrap()
6886
        .with_home(root.join("home-b"));
6887
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
6888
6889
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
6890
    let h2 = a.commit("two", &[]).unwrap();
6891
    a.push("origin", false).unwrap();
6892
    b.fetch("origin").unwrap();
6893
    // Fetched, not pulled: one behind, the change found and placed.
6894
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
6895
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
6896
    assert_eq!(
6897
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
6898
            .unwrap(),
6899
        h2
6900
    );
6901
    assert_eq!(
6902
        b.remote_only_location(&h2).unwrap().as_deref(),
6903
        Some("origin/main")
6904
    );
6905
    // Fetching again changes nothing: still behind, which is what the
6906
    // CLI now says rather than "up to date".
6907
    b.fetch("origin").unwrap();
6908
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
6909
    b.pull("origin").unwrap();
6910
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
6911
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
6912
6913
    // One remote, not called origin: it is the default.
6914
    let mut c = Repo::init(&root.join("c")).unwrap();
6915
    assert_eq!(c.default_remote(), "origin");
6916
    c.config.set("remote.earth.url", &url).unwrap();
6917
    assert_eq!(c.default_remote(), "earth");
6918
    c.config.set("remote.origin.url", &url).unwrap();
6919
    assert_eq!(c.default_remote(), "origin");
6920
}
6921
6922
/// oxygen#57: a clone from a relative local path records the remote as an
6923
/// absolute path, so fetch still finds it from inside the clone.
6924
#[test]
6925
fn a_clone_from_a_relative_path_records_it_absolute() {
6926
    hermetic();
6927
    let dir = tempfile::tempdir().unwrap();
6928
    let root = dir.path();
6929
    Repo::init(&root.join("origin")).unwrap();
6930
    let rel = crate::protocol::stored_url("relative/repo");
6931
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
6932
    assert_eq!(
6933
        crate::protocol::stored_url("https://hub.example/o/n"),
6934
        "https://hub.example/o/n"
6935
    );
6936
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
6937
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
6938
    // A bucket is kept as written: it is not a path.
6939
    assert_eq!(
6940
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
6941
        "s3://bucket/prefix?profile=p"
6942
    );
6943
    let url = root.join("origin").to_string_lossy().to_string();
6944
    let b = Repo::clone(&url, &root.join("b")).unwrap();
6945
    assert_eq!(b.config.remotes["origin"], url);
6946
    b.fetch("origin").unwrap();
6947
}