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