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