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