OXYGENHUB
◆ show-stat oxygen / crates / oxy-core / src / repo / tests.rs
345.3 KiB · Rust · last changed Readers never wait: one head per handle, retry on a miss, retire before deleting 17 days ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
use crate::protocol::SignedPolicy;
5
use crate::repo::{BisectStep, Selection};
6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
137
    assert!(
138
        d.lines()
139
            .any(|l| l.starts_with("M ") && l.ends_with("main.rs")),
140
        "a modified file is in the summary too: {d}"
141
    );
142
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
143
    assert!(d.contains("-fn main() {}"), "{d}");
144
145
    // Resolution by prefix.
146
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
147
    assert_eq!(
148
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
149
        h1
150
    );
151
    assert!(repo.resolve_change("zzzz").is_err());
152
153
    // Undo the commit: bookmark and working copy go back.
154
    repo.undo().unwrap();
155
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
156
    let s = repo.snapshot("oxy status").unwrap();
157
    assert!(
158
        !s.changed,
159
        "files on disk still match the pre-commit working copy"
160
    );
161
    assert_eq!(s.statuses.len(), 3);
162
}
163
164
/// Make `main` conflicted: two commits on the same base that edit the same line.
165
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
166
    let dir = tempfile::tempdir().unwrap();
167
    let root = dir.path();
168
    let repo = Repo::init(root).unwrap();
169
    write(root, "f.txt", b"a\nb\nc\n");
170
    let h1 = repo.commit("base", &[]).unwrap();
171
    write(root, "f.txt", b"a\nB\nc\n");
172
    let h2 = repo.commit("upper", &[]).unwrap();
173
    repo.checkout(&[h1], false, "checkout").unwrap();
174
    write(root, "f.txt", b"a\nX\nc\n");
175
    let h3 = repo.commit("ex", &[]).unwrap();
176
    (dir, repo, h1, h2, h3)
177
}
178
179
#[test]
180
fn concurrent_edits_conflict_and_can_be_resolved() {
181
    hermetic();
182
    let (dir, repo, h1, h2, h3) = conflicted_repo();
183
    let root = dir.path();
184
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
185
    assert_eq!(heads, [h2, h3].into_iter().collect());
186
    let st = repo.load_state(&[h2, h3]).unwrap();
187
    assert!(st.materialize().is_conflicted());
188
189
    // Checking out main writes markers.
190
    let r = repo
191
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
192
        .unwrap();
193
    assert!(r.conflicted);
194
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
195
    assert!(
196
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
197
        "{marked}"
198
    );
199
    assert!(
200
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
201
        "{marked}"
202
    );
203
    assert!(has_conflict_markers(marked.as_bytes()));
204
    // Untouched markers: clean working copy; commit has nothing to do.
205
    let s = repo.snapshot("status").unwrap();
206
    assert!(s.statuses.is_empty());
207
    assert!(!s.resolves);
208
209
    // Partially edited file that still has markers cannot be committed.
210
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
211
    let s = repo.snapshot("status").unwrap();
212
    assert_eq!(
213
        statuses(&s),
214
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
215
    );
216
    assert!(repo.commit("no", &[]).is_err());
217
218
    // Resolve by keeping one side and adding a line elsewhere.
219
    write(root, "f.txt", b"a\nX\nc\nd\n");
220
    let s = repo.snapshot("status").unwrap();
221
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
222
    assert!(s.resolves);
223
    let h4 = repo.commit("resolve", &[]).unwrap();
224
    let c4 = repo.store().get_change(&h4).unwrap();
225
    assert_eq!(c4.kind, ChangeKind::Resolution);
226
    let mut want = vec![h1, h2, h3];
227
    want.sort();
228
    assert_eq!(
229
        c4.deps, want,
230
        "a resolution depends on exactly the contributors and what it references"
231
    );
232
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
233
    let snap = repo.load_state(&[h4]).unwrap().materialize();
234
    assert!(!snap.is_conflicted());
235
    assert!(
236
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
237
    );
238
    assert!(!repo.snapshot("status").unwrap().changed);
239
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
240
    // whatever order the changes arrive in.
241
    let mut st = State::new();
242
    for h in [h4, h3, h1, h2] {
243
        st.add_unchecked(repo.store().get_change(&h).unwrap());
244
    }
245
    st.validate().unwrap();
246
    assert!(
247
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
248
    );
249
}
250
251
#[test]
252
fn resolution_may_keep_both_sides_or_neither() {
253
    hermetic();
254
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
255
    let root = dir.path();
256
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
257
        .unwrap();
258
    // Keep both sides in a chosen order.
259
    write(root, "f.txt", b"a\nX\nB\nc\n");
260
    let h = repo.commit("both", &[]).unwrap();
261
    let snap = repo.load_state(&[h]).unwrap().materialize();
262
    assert!(!snap.is_conflicted());
263
    assert!(
264
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
265
    );
266
    // Undo and instead drop the whole region.
267
    repo.undo().unwrap();
268
    write(root, "f.txt", b"a\nc\n");
269
    let h = repo.commit("neither", &[]).unwrap();
270
    let snap = repo.load_state(&[h]).unwrap().materialize();
271
    assert!(!snap.is_conflicted());
272
    assert!(
273
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
274
    );
275
}
276
277
#[test]
278
fn name_conflict_resolved_by_removing_a_candidate() {
279
    hermetic();
280
    let dir = tempfile::tempdir().unwrap();
281
    let root = dir.path();
282
    let repo = Repo::init(root).unwrap();
283
    write(root, "keep.txt", b"k\n");
284
    let h1 = repo.commit("base", &[]).unwrap();
285
    write(root, "new.txt", b"one\n");
286
    repo.commit("one", &[]).unwrap();
287
    repo.checkout(&[h1], false, "checkout").unwrap();
288
    write(root, "new.txt", b"two\n");
289
    repo.commit("two", &[]).unwrap();
290
    let r = repo
291
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
292
        .unwrap();
293
    assert!(r.conflicted);
294
    assert!(
295
        root.join("new.txt.oxy-conflict-1").exists()
296
            && root.join("new.txt.oxy-conflict-2").exists()
297
    );
298
    assert!(!root.join("new.txt").exists());
299
    // Candidate numbering follows change-hash order, so pick by content:
300
    // keep the "two" candidate under the real name and drop the other.
301
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
302
        (1, 2)
303
    } else {
304
        (2, 1)
305
    };
306
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
307
    fs::rename(
308
        root.join(format!("new.txt.oxy-conflict-{keep}")),
309
        root.join("new.txt"),
310
    )
311
    .unwrap();
312
    let h = repo.commit("pick two", &[]).unwrap();
313
    assert_eq!(
314
        repo.store().get_change(&h).unwrap().kind,
315
        ChangeKind::Resolution
316
    );
317
    // The resolution does not touch keep.txt, so it does not depend on h1;
318
    // the bookmark keeps both as heads and their union is the state.
319
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
320
    assert_eq!(heads, [h1, h].into_iter().collect());
321
    let snap = repo
322
        .load_state(&repo.bookmark_heads().unwrap())
323
        .unwrap()
324
        .materialize();
325
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
326
    assert_eq!(
327
        snap.files.keys().cloned().collect::<Vec<_>>(),
328
        ["keep.txt", "new.txt"]
329
    );
330
    assert!(
331
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
332
    );
333
}
334
335
#[test]
336
fn identities_and_signed_commits() {
337
    hermetic();
338
    let dir = tempfile::tempdir().unwrap();
339
    let root = dir.path();
340
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
341
    write(root, "a.txt", b"a\n");
342
    let h0 = repo.commit("unsigned", &[]).unwrap();
343
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
344
    assert_eq!(
345
        repo.store().get_change(&h0).unwrap().author,
346
        ObjectRef::ZERO
347
    );
348
349
    let (key, id) = repo
350
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
351
        .unwrap();
352
    assert_eq!(id.hash(), key);
353
    assert_eq!(repo.config.author_key, Some(key));
354
    // Config survives reopen; the secret key is found again.
355
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
356
    assert_eq!(reopened.config.author_key, Some(key));
357
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
358
359
    // Default core.sign = seal: commits carry the author but no signature.
360
    write(root, "a.txt", b"a\nb\n");
361
    let h1 = repo.commit("authored", &[]).unwrap();
362
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
363
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
364
    // Signing later works too.
365
    repo.sign_change(&h1).unwrap();
366
    assert!(
367
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
368
    );
369
370
    repo.config.set("core.sign", "change").unwrap();
371
    repo.save_config().unwrap();
372
    write(root, "a.txt", b"a\nb\nc\n");
373
    let h2 = repo.commit("signed", &[]).unwrap();
374
    assert_eq!(
375
        repo.verify_change(&h2).unwrap(),
376
        SignatureStatus::Valid {
377
            key,
378
            name: "Ada".into(),
379
            email: "[email protected]".into(),
380
            sealed: false,
381
            revoked: false
382
        }
383
    );
384
385
    // A signature by a key that is not the author or a delegate is rejected
386
    // when the change names an author; an anonymous change (made before any
387
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
388
    let other = SecretKey::generate();
389
    let other_id = other.identity("Mallory", "[email protected]", 0);
390
    let other_key = repo.store().put_identity(&other_id).unwrap();
391
    write(root, "a.txt", b"a\nb\nc\nd\n");
392
    repo.config.set("core.sign", "seal").unwrap();
393
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
394
    let forged = other.sign(Domain::Change, &other_key, &h3);
395
    repo.store().put_signature(&h3, &forged).unwrap();
396
    assert!(
397
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
398
    );
399
    let adopted = other.sign(Domain::Change, &other_key, &h0);
400
    repo.store().put_signature(&h0, &adopted).unwrap();
401
    assert!(
402
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
403
    );
404
405
    // Tampering with the stored signature invalidates it.
406
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
407
    sig.ed[0] ^= 1;
408
    repo.store().put_signature(&h2, &sig).unwrap();
409
    assert!(matches!(
410
        repo.verify_change(&h2).unwrap(),
411
        SignatureStatus::Invalid(_)
412
    ));
413
414
    // Without the secret key, signing at commit fails cleanly.
415
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
416
    write(root, "a.txt", b"z\n");
417
    assert!(no_keys.commit("cannot sign", &[]).is_err());
418
}
419
420
#[test]
421
fn checkout_moves_the_working_copy() {
422
    hermetic();
423
    let dir = tempfile::tempdir().unwrap();
424
    let root = dir.path();
425
    let repo = Repo::init(root).unwrap();
426
    write(root, "a.txt", b"one\n");
427
    write(root, "sub/deep/b.txt", b"b\n");
428
    let h1 = repo.commit("first", &[]).unwrap();
429
    write(root, "a.txt", b"two\n");
430
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
431
    write(root, "bin.dat", &[0, 1, 2, 3]);
432
    let h2 = repo.commit("second", &[]).unwrap();
433
434
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
435
    assert_eq!(
436
        r,
437
        CheckoutReport {
438
            written: 2,
439
            removed: 1,
440
            removed_paths: vec!["bin.dat".into()],
441
            conflicted: false,
442
            notes: vec![],
443
            lacks: 1,
444
        }
445
    );
446
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
447
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
448
    assert!(!root.join("bin.dat").exists());
449
    let (_, wc) = repo.working_copy().unwrap();
450
    assert_eq!(wc.deps, vec![h1]);
451
    assert!(
452
        !repo.snapshot("status").unwrap().changed,
453
        "checkout leaves a clean working copy"
454
    );
455
    // The bookmark still points at h2.
456
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
457
458
    // Dirty working copy refuses without --discard.
459
    write(root, "a.txt", b"dirty\n");
460
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
461
    let r = repo
462
        .checkout(&[h2], true, "oxy checkout --discard")
463
        .unwrap();
464
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
465
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
466
    assert!(!root.join("sub").exists(), "empty directories are pruned");
467
    assert_eq!(r.removed, 1);
468
    assert!(!repo.snapshot("status").unwrap().changed);
469
470
    // Refuses to write through a symlinked directory.
471
    #[cfg(unix)]
472
    {
473
        fs::remove_dir_all(root.join("sub")).ok();
474
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
475
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
476
    }
477
}
478
479
#[test]
480
fn large_files_are_chunked_and_read_back() {
481
    hermetic();
482
    let dir = tempfile::tempdir().unwrap();
483
    let repo = Repo::init(dir.path()).unwrap();
484
    let mut big = vec![0u8; 700 * 1024];
485
    for (i, b) in big.iter_mut().enumerate() {
486
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
487
    }
488
    let r = repo.store_blob(&big).unwrap();
489
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
490
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
491
    assert_eq!(repo.read_blob(&r).unwrap(), big);
492
    assert_eq!(Repo::blob_ref(&big), r);
493
}
494
495
#[test]
496
fn clone_push_pull_with_seals_and_attestations() {
497
    hermetic();
498
    let dir = tempfile::tempdir().unwrap();
499
    let root = dir.path();
500
    let origin_path = root.join("origin");
501
    let origin = Repo::init(&origin_path).unwrap();
502
    let origin_url = origin_path.to_string_lossy().to_string();
503
504
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
505
    let mut a = Repo::clone(&origin_url, &root.join("a"))
506
        .unwrap()
507
        .with_home(root.join("home-a"));
508
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
509
    let (key_a, _) = a
510
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
511
        .unwrap();
512
    write(&root.join("a"), "f.txt", b"a\n");
513
    let h1 = a.commit("first", &[]).unwrap();
514
    let results = a.push("origin", false).unwrap();
515
    origin.refresh().unwrap();
516
    assert!(results[0].ok, "{}", results[0].reason);
517
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
518
    // The change was sealed at push and the reference attested.
519
    assert!(
520
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
521
    );
522
    assert_eq!(
523
        origin.verify_change(&h1).unwrap(),
524
        SignatureStatus::Unsigned
525
    );
526
    let serial_of = |att: &SignedAttest| match att.attest.body {
527
        AttestBody::Ref { serial, .. } => serial,
528
        _ => unreachable!(),
529
    };
530
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
531
    // A bookmark new to the remote starts at the clock (past any deleted
532
    // namesake's serial); later updates count up from there.
533
    let first = serial_of(&att);
534
    assert!(first > 1_000_000_000_000, "{first}");
535
    let again = a.push("origin", false).unwrap();
536
    origin.refresh().unwrap();
537
    assert!(again[0].ok && again[0].reason.contains("up to date"));
538
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
539
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
540
541
    // B clones and sees the file and the seal.
542
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
543
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
544
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
545
    assert!(matches!(
546
        b.authenticate_change(&h1).unwrap(),
547
        SignatureStatus::Valid { sealed: true, .. }
548
    ));
549
550
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
551
    write(&root.join("b"), "f.txt", b"a\nb\n");
552
    let h2 = b.commit("second", &[]).unwrap();
553
    assert!(b.push("origin", false).unwrap()[0].ok);
554
    origin.refresh().unwrap();
555
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
556
557
    // A commits an independent change; push is refused until A pulls.
558
    write(&root.join("a"), "g.txt", b"g\n");
559
    let h3 = a.commit("third", &[]).unwrap();
560
    assert!(a.push("origin", false).is_err());
561
    let pr = a.pull("origin").unwrap();
562
    assert!(pr.changed && pr.checked_out);
563
    let mut want = vec![h2, h3];
564
    want.sort();
565
    assert_eq!(pr.heads, want);
566
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
567
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
568
    let results = a.push("origin", false).unwrap();
569
    origin.refresh().unwrap();
570
    assert!(results[0].ok, "{}", results[0].reason);
571
    let mut origin_heads = origin.bookmark_heads().unwrap();
572
    origin_heads.sort();
573
    assert_eq!(origin_heads, want);
574
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
575
    assert_eq!(serial_of(&att), first + 1);
576
577
    // B pulls and ends up identical.
578
    let pr = b.pull("origin").unwrap();
579
    assert_eq!(pr.heads, want);
580
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
581
    assert!(!b.snapshot("status").unwrap().changed);
582
583
    // Concurrent edits of the same line: the union is a reified conflict.
584
    write(&root.join("a"), "f.txt", b"a\nA\n");
585
    a.commit("a-edit", &[]).unwrap();
586
    a.push("origin", false).unwrap();
587
    origin.refresh().unwrap();
588
    write(&root.join("b"), "f.txt", b"a\nB\n");
589
    b.commit("b-edit", &[]).unwrap();
590
    let pr = b.pull("origin").unwrap();
591
    assert!(pr.changed && pr.checked_out);
592
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
593
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
594
    write(&root.join("b"), "f.txt", b"a\nAB\n");
595
    let hr = b.commit("resolve", &[]).unwrap();
596
    assert_eq!(
597
        b.store().get_change(&hr).unwrap().kind,
598
        ChangeKind::Resolution
599
    );
600
    assert!(b.push("origin", false).unwrap()[0].ok);
601
    origin.refresh().unwrap();
602
    a.pull("origin").unwrap();
603
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
604
    // The resolution depends on the conflicting edits, but nothing depends
605
    // on "third" (it only added g.txt), so it stays a head beside it.
606
    let mut want = vec![hr, h3];
607
    want.sort();
608
    assert_eq!(a.bookmark_heads().unwrap(), want);
609
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
610
}
611
612
#[test]
613
fn receive_push_rejects_bad_updates() {
614
    hermetic();
615
    let dir = tempfile::tempdir().unwrap();
616
    let root = dir.path();
617
    let origin = Repo::init(&root.join("origin")).unwrap();
618
    let url = root.join("origin").to_string_lossy().to_string();
619
    let mut a = Repo::clone(&url, &root.join("a"))
620
        .unwrap()
621
        .with_home(root.join("home"));
622
    let (key, _) = a
623
        .create_identity("Ada", "a@b", IdentityScope::Repo)
624
        .unwrap();
625
    write(&root.join("a"), "f.txt", b"x\n");
626
    let h1 = a.commit("one", &[]).unwrap();
627
    assert!(a.push("origin", false).unwrap()[0].ok);
628
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
629
    let s1 = origin
630
        .store()
631
        .put_state(&StateObject::new(vec![h1]))
632
        .unwrap();
633
634
    // Missing head.
635
    let ghost = origin
636
        .store()
637
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
638
        .unwrap();
639
    let r = origin
640
        .receive_push(
641
            Bundle::default(),
642
            vec![RefUpdate {
643
                name: "main".into(),
644
                old_state: s1,
645
                new_state: ghost,
646
                force: false,
647
                attestation: None,
648
            }],
649
            None,
650
            vec![],
651
        )
652
        .unwrap();
653
    assert!(
654
        !r[0].ok && r[0].reason.contains("missing"),
655
        "{}",
656
        r[0].reason
657
    );
658
659
    // Stale old_state.
660
    let r = origin
661
        .receive_push(
662
            Bundle::default(),
663
            vec![RefUpdate {
664
                name: "main".into(),
665
                old_state: empty,
666
                new_state: s1,
667
                force: false,
668
                attestation: None,
669
            }],
670
            None,
671
            vec![],
672
        )
673
        .unwrap();
674
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
675
676
    // Non-fast-forward without force is refused; with force it passes.
677
    let r = origin
678
        .receive_push(
679
            Bundle::default(),
680
            vec![RefUpdate {
681
                name: "main".into(),
682
                old_state: s1,
683
                new_state: empty,
684
                force: false,
685
                attestation: None,
686
            }],
687
            None,
688
            vec![],
689
        )
690
        .unwrap();
691
    assert!(
692
        !r[0].ok && r[0].reason.contains("fast-forward"),
693
        "{}",
694
        r[0].reason
695
    );
696
    let r = origin
697
        .receive_push(
698
            Bundle::default(),
699
            vec![RefUpdate {
700
                name: "main".into(),
701
                old_state: s1,
702
                new_state: empty,
703
                force: true,
704
                attestation: None,
705
            }],
706
            None,
707
            vec![],
708
        )
709
        .unwrap();
710
    assert!(r[0].ok);
711
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
712
713
    // Attestation with a stale serial is a rollback and is refused.
714
    let sa = a
715
        .sign_attest(&Attest {
716
            repo: a.id().unwrap(),
717
            hlc: Hlc::now(),
718
            body: AttestBody::Ref {
719
                name: "main".into(),
720
                old_state: empty,
721
                new_state: s1,
722
                serial: 1,
723
            },
724
        })
725
        .unwrap();
726
    let r = origin
727
        .receive_push(
728
            Bundle::default(),
729
            vec![RefUpdate {
730
                name: "main".into(),
731
                old_state: empty,
732
                new_state: s1,
733
                force: false,
734
                attestation: Some(sa.clone()),
735
            }],
736
            None,
737
            vec![],
738
        )
739
        .unwrap();
740
    assert!(
741
        !r[0].ok && r[0].reason.contains("serial"),
742
        "{}",
743
        r[0].reason
744
    );
745
    // An attestation for a different update is refused too.
746
    let sa2 = a
747
        .sign_attest(&Attest {
748
            repo: a.id().unwrap(),
749
            hlc: Hlc::now(),
750
            body: AttestBody::Ref {
751
                name: "main".into(),
752
                old_state: s1,
753
                new_state: empty,
754
                serial: 5,
755
            },
756
        })
757
        .unwrap();
758
    let r = origin
759
        .receive_push(
760
            Bundle::default(),
761
            vec![RefUpdate {
762
                name: "main".into(),
763
                old_state: empty,
764
                new_state: s1,
765
                force: false,
766
                attestation: Some(sa2),
767
            }],
768
            None,
769
            vec![],
770
        )
771
        .unwrap();
772
    assert!(
773
        !r[0].ok && r[0].reason.contains("describe"),
774
        "{}",
775
        r[0].reason
776
    );
777
    let _ = key;
778
}
779
780
#[test]
781
fn user_config_supplies_defaults_and_clones_sign() {
782
    hermetic();
783
    let dir = tempfile::tempdir().unwrap();
784
    let root = dir.path();
785
    let home = root.join("home");
786
    let origin = Repo::init(&root.join("origin")).unwrap();
787
    let url = root.join("origin").to_string_lossy().to_string();
788
789
    // Identity at user scope: the repository file stays free of author keys.
790
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
791
    let (key, _) = a
792
        .create_identity("Ada", "[email protected]", IdentityScope::User)
793
        .unwrap();
794
    assert!(!a.config.repo_layer().contains_key("author.key"));
795
    assert_eq!(a.config.author_key, Some(key));
796
    assert!(home.join("config.toml").exists());
797
    a.set_user_config("core.sign", "change").unwrap();
798
    assert!(a.config.sign_changes);
799
800
    // Repository settings override user settings and are the only ones saved.
801
    a.config.set("core.sign", "seal").unwrap();
802
    a.save_config().unwrap();
803
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
804
    assert!(!again.config.sign_changes);
805
    assert_eq!(again.config.author_key, Some(key));
806
    assert_eq!(
807
        read_config_file(&root.join("a/.oxy/config"))
808
            .unwrap()
809
            .get("core.sign")
810
            .map(String::as_str),
811
        Some("seal")
812
    );
813
814
    // A fresh clone made by this user signs with the user-level identity,
815
    // even though the clone's store has never seen the identity object.
816
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
817
    assert!(b.config.sign_changes);
818
    write(&root.join("b"), "f.txt", b"f\n");
819
    let h = b.commit("signed from a clone", &[]).unwrap();
820
    assert!(
821
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
822
    );
823
    assert!(b.push("origin", false).unwrap()[0].ok);
824
    assert!(matches!(
825
        origin.verify_change(&h).unwrap(),
826
        SignatureStatus::Valid { .. }
827
    ));
828
}
829
830
#[test]
831
fn format1_repositories_are_migrated_on_open() {
832
    hermetic();
833
    use crate::oplog::{Format1Op, Format1View};
834
    let dir = tempfile::tempdir().unwrap();
835
    let root = dir.path();
836
    let repo = Repo::init(root).unwrap();
837
    write(root, "a.txt", b"a\n");
838
    let h1 = repo.commit("one", &[]).unwrap();
839
    let (wc_hash, _) = repo.working_copy().unwrap();
840
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
841
    let mut v1 = Format1View::default();
842
    v1.bookmarks.insert("main".into(), vec![]);
843
    v1.workspaces.insert(repo.workspace(), wc_hash);
844
    let init = Format1Op {
845
        parents: vec![],
846
        hlc: Hlc::default(),
847
        command: "oxy init".into(),
848
        view: v1.clone(),
849
    };
850
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
851
    v1.bookmarks.insert("main".into(), vec![h1]);
852
    let commit = Format1Op {
853
        parents: vec![init_ref],
854
        hlc: Hlc::default(),
855
        command: "oxy commit".into(),
856
        view: v1,
857
    };
858
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
859
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
860
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
861
    drop(repo);
862
863
    let repo = Repo::open(root).unwrap();
864
    assert_eq!(
865
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
866
        FORMAT_LINE
867
    );
868
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
869
    let ops = repo.op_log().unwrap();
870
    assert_eq!(
871
        ops.iter()
872
            .map(|(_, o)| o.command.as_str())
873
            .collect::<Vec<_>>(),
874
        ["oxy commit", "oxy init"]
875
    );
876
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
877
    assert!(!repo.snapshot("status").unwrap().changed);
878
    // Reopening again is a no-op.
879
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
880
}
881
882
#[test]
883
fn undo_skips_snapshot_operations() {
884
    hermetic();
885
    let dir = tempfile::tempdir().unwrap();
886
    let root = dir.path();
887
    let repo = Repo::init(root).unwrap();
888
    write(root, "a.txt", b"a\n");
889
    let h1 = repo.commit("a", &[]).unwrap();
890
    // A later command snapshots new edits on top of the commit.
891
    write(root, "b.txt", b"b\n");
892
    let s = repo.snapshot("oxy status").unwrap();
893
    assert!(s.changed);
894
    assert!(repo.head_op().unwrap().1.is_snapshot());
895
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
896
    // Undo must undo the commit, not the snapshot.
897
    repo.undo().unwrap();
898
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
899
    let s = repo.snapshot("oxy status").unwrap();
900
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
901
    assert_eq!(
902
        paths,
903
        ["a.txt", "b.txt"],
904
        "both files are back in the working copy"
905
    );
906
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
907
    // Only snapshots remain above `init`, so there is nothing left to undo.
908
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
909
    assert!(repo.undo().is_err());
910
}
911
912
#[test]
913
fn independent_changes_commute_and_make_multiple_heads() {
914
    hermetic();
915
    let dir = tempfile::tempdir().unwrap();
916
    let root = dir.path();
917
    let repo = Repo::init(root).unwrap();
918
    write(root, "a.txt", b"a\n");
919
    let h1 = repo.commit("a", &[]).unwrap();
920
    write(root, "b.txt", b"b\n");
921
    let h2 = repo.commit("b", &[]).unwrap();
922
    let c2 = repo.store().get_change(&h2).unwrap();
923
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
924
    let mut heads = repo.bookmark_heads().unwrap();
925
    heads.sort();
926
    let mut want = vec![h1, h2];
927
    want.sort();
928
    assert_eq!(heads, want);
929
    // Editing a.txt depends on h1 only.
930
    write(root, "a.txt", b"a\na2\n");
931
    let h3 = repo.commit("a2", &[]).unwrap();
932
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
933
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
934
    assert_eq!(heads, [h2, h3].into_iter().collect());
935
    // Explicit dependency.
936
    write(root, "c.txt", b"c\n");
937
    let h4 = repo.commit("c", &[h2]).unwrap();
938
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
939
}
940
941
#[test]
942
fn mode_change_and_text_binary_switch() {
943
    hermetic();
944
    let dir = tempfile::tempdir().unwrap();
945
    let root = dir.path();
946
    let repo = Repo::init(root).unwrap();
947
    write(root, "run.sh", b"#!/bin/sh\n");
948
    repo.commit("add script", &[]).unwrap();
949
    #[cfg(unix)]
950
    {
951
        use std::os::unix::fs::PermissionsExt;
952
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
953
        let s = repo.snapshot("status").unwrap();
954
        assert_eq!(
955
            statuses(&s),
956
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
957
        );
958
        let h = repo.commit("exec", &[]).unwrap();
959
        let snap = repo.load_state(&[h]).unwrap().materialize();
960
        assert!(snap.files["run.sh"].mode.exec);
961
    }
962
    // Text → binary → text.
963
    write(root, "run.sh", b"\0binary");
964
    let h = repo.commit("binary", &[]).unwrap();
965
    let snap = repo.load_state(&[h]).unwrap().materialize();
966
    assert!(snap.files["run.sh"].mode.opaque);
967
    write(root, "run.sh", b"text again\n");
968
    let h = repo.commit("text", &[]).unwrap();
969
    let snap = repo.load_state(&[h]).unwrap().materialize();
970
    assert!(!snap.files["run.sh"].mode.opaque);
971
    assert!(
972
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
973
    );
974
    assert!(!snap.is_conflicted());
975
}
976
977
/// oxygen#87: a binary file given new contents and the executable bit in
978
/// one commit kept the contents and lost the bit.
979
#[cfg(unix)]
980
#[test]
981
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
982
    use std::os::unix::fs::PermissionsExt;
983
    hermetic();
984
    let dir = tempfile::tempdir().unwrap();
985
    let root = dir.path();
986
    let repo = Repo::init(root).unwrap();
987
    write(root, "tool.exe", b"MZ\0one");
988
    repo.commit("add", &[]).unwrap();
989
    write(root, "tool.exe", b"MZ\0two");
990
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
991
    let h = repo.commit("update and +x", &[]).unwrap();
992
    let snap = repo.load_state(&[h]).unwrap().materialize();
993
    let f = &snap.files["tool.exe"];
994
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
995
    assert!(
996
        repo.snapshot("status").unwrap().statuses.is_empty(),
997
        "nothing left to commit"
998
    );
999
}
1000
1001
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
1002
/// key whose certificate an issuer gave pushes when the policy grants its
1003
/// subject, and a fetch accepts what it attested; an expired certificate,
1004
/// or a subject the policy does not grant, may not move the bookmark.
1005
#[test]
1006
fn a_certified_key_pushes_under_a_subject_grant() {
1007
    use crate::cert::{Certificate, SignedCertificate};
1008
    use crate::identity::Scope;
1009
    hermetic();
1010
    let dir = tempfile::tempdir().unwrap();
1011
    let root = dir.path();
1012
    let _origin = Repo::init(&root.join("origin")).unwrap();
1013
    let url = root.join("origin").to_string_lossy().to_string();
1014
    let mut a = Repo::clone(&url, &root.join("a"))
1015
        .unwrap()
1016
        .with_home(root.join("home-a"));
1017
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1018
        .unwrap();
1019
    write(&root.join("a"), "a.txt", b"a\n");
1020
    a.commit("a", &[]).unwrap();
1021
    a.policy_init().unwrap();
1022
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1023
    let hub_sk = SecretKey::generate();
1024
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1025
    a.policy_grant_subject(
1026
        "agent:claude@ada",
1027
        hub.clone(),
1028
        Scope::CHANGES | Scope::REFS,
1029
        None,
1030
    )
1031
    .unwrap();
1032
    assert!(a
1033
        .push("origin", false)
1034
        .unwrap()
1035
        .iter()
1036
        .any(|r| r.name == "policy" && r.ok));
1037
1038
    let now = Hlc::now().wall_ms;
1039
    // An agent repository whose key the hub certified for `subject`, from
1040
    // `from` to `to`.
1041
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1042
        let mut r = Repo::clone(&url, &root.join(name))
1043
            .unwrap()
1044
            .with_home(root.join(format!("home-{name}")));
1045
        let (_, id) = r
1046
            .create_identity(name, "[email protected]", IdentityScope::User)
1047
            .unwrap();
1048
        let cert = SignedCertificate::sign(
1049
            Certificate {
1050
                key: id,
1051
                issuer: hub.hash(),
1052
                subject: subject.into(),
1053
                claims: vec![],
1054
                scope: Scope::CHANGES | Scope::REFS,
1055
                not_before: from,
1056
                expires: to,
1057
                grant: None,
1058
            },
1059
            &hub,
1060
            &hub_sk,
1061
        );
1062
        r.store().put_identity(&hub).unwrap();
1063
        r.store().put_certificate(&cert).unwrap();
1064
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1065
        r.commit("work", &[]).unwrap();
1066
        r
1067
    };
1068
1069
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1070
    let r = claude.push("origin", false).unwrap();
1071
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1072
    // Ada's fetch accepts the bookmark the certified key attested.
1073
    a.pull("origin").unwrap();
1074
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1075
        .store()
1076
        .get_change(h)
1077
        .map(|c| c.message == "work")
1078
        .unwrap_or(false)));
1079
1080
    // Step 4c: a host with an acceptor key records when it accepted the
1081
    // certified update and serves it; a fetch checks the certificate at
1082
    // that time only when the certificate's issuer signed it for exactly
1083
    // this attestation, else at the attestation's own time.
1084
    let host = Repo::open(&root.join("origin"))
1085
        .unwrap()
1086
        .with_acceptor(hub.clone(), hub_sk.clone());
1087
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1088
    host.record_acceptance(&attest_ref).unwrap();
1089
    let served = host.remote_refs().unwrap();
1090
    let acc = served
1091
        .refs
1092
        .iter()
1093
        .find(|r| r.name == "main")
1094
        .unwrap()
1095
        .accepted
1096
        .clone()
1097
        .expect("served with the refs");
1098
    let signer = sa.sigs[0].key;
1099
    assert_eq!(
1100
        a.certified_time(&signer, &sa, Some(&acc)),
1101
        acc.attest.hlc.wall_ms
1102
    );
1103
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1104
    let stranger_sk = SecretKey::generate();
1105
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1106
    let mut forged = acc.clone();
1107
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1108
    assert_eq!(
1109
        a.certified_time(&signer, &sa, Some(&forged)),
1110
        sa.attest.hlc.wall_ms,
1111
        "not the issuer's"
1112
    );
1113
    let mut elsewhere = acc.clone();
1114
    elsewhere.attest.body = AttestBody::Accepted {
1115
        attest: ObjectRef([7; 32]),
1116
    };
1117
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1118
    assert_eq!(
1119
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1120
        sa.attest.hlc.wall_ms,
1121
        "another attestation's"
1122
    );
1123
    a.pull("origin").unwrap();
1124
    // gc keeps the acceptance with the attestation.
1125
    host.gc(true).unwrap();
1126
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1127
1128
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1129
    let r = late.push("origin", false).unwrap();
1130
    assert!(
1131
        !r[0].ok && r[0].reason.contains("may not update"),
1132
        "an expired certificate: {r:?}"
1133
    );
1134
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1135
    let r = other.push("origin", false).unwrap();
1136
    assert!(
1137
        !r[0].ok && r[0].reason.contains("may not update"),
1138
        "a subject not granted: {r:?}"
1139
    );
1140
}
1141
1142
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1143
/// subject the author granted, seals changes in the author's name; with
1144
/// no grant, a stranger's, or one that had ended, it is neither the
1145
/// author nor a delegate.
1146
#[test]
1147
fn a_certified_key_acts_for_its_author_under_a_grant() {
1148
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1149
    use crate::identity::{Identity, Scope};
1150
    hermetic();
1151
    let dir = tempfile::tempdir().unwrap();
1152
    let root = dir.path();
1153
    let _origin = Repo::init(&root.join("origin")).unwrap();
1154
    let url = root.join("origin").to_string_lossy().to_string();
1155
    let mut a = Repo::clone(&url, &root.join("a"))
1156
        .unwrap()
1157
        .with_home(root.join("home-a"));
1158
    let (ada, _) = a
1159
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1160
        .unwrap();
1161
    write(&root.join("a"), "a.txt", b"a\n");
1162
    a.commit("a", &[]).unwrap();
1163
    a.policy_init().unwrap();
1164
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1165
    let hub_sk = SecretKey::generate();
1166
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1167
    a.policy_grant_subject(
1168
        "agent:claude@ada",
1169
        hub.clone(),
1170
        Scope::CHANGES | Scope::REFS,
1171
        None,
1172
    )
1173
    .unwrap();
1174
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1175
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1176
    let ada_id = a.identity(&ada).unwrap();
1177
1178
    let now = Hlc::now().wall_ms;
1179
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1180
        SignedGrant::sign(
1181
            Grant {
1182
                grantor: by.hash(),
1183
                subject: "agent:claude@ada".into(),
1184
                issuer: hub.hash(),
1185
                scope: Scope::CHANGES | Scope::SEAL,
1186
                not_before: from,
1187
                expires: to,
1188
            },
1189
            by,
1190
            sk,
1191
        )
1192
    };
1193
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1194
    // certified (with `g` inside) the signer.
1195
    let agent = |name: &str, g: Option<SignedGrant>| {
1196
        let mut r = Repo::clone(&url, &root.join(name))
1197
            .unwrap()
1198
            .with_home(root.join(format!("home-{name}")));
1199
        let (key, id) = r
1200
            .create_identity(name, "[email protected]", IdentityScope::User)
1201
            .unwrap();
1202
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1203
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1204
        let cert = SignedCertificate::sign(
1205
            Certificate {
1206
                key: id,
1207
                issuer: hub.hash(),
1208
                subject: "agent:claude@ada".into(),
1209
                claims: vec![],
1210
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1211
                not_before: now - 60_000,
1212
                expires: now + 600_000,
1213
                grant: g,
1214
            },
1215
            &hub,
1216
            &hub_sk,
1217
        );
1218
        r.store().put_identity(&hub).unwrap();
1219
        r.store().put_certificate(&cert).unwrap();
1220
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1221
        let h = r.commit("work", &[]).unwrap();
1222
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1223
        (r, key, h)
1224
    };
1225
1226
    let (claude, key, h) = agent(
1227
        "claude",
1228
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1229
    );
1230
    let r = claude.push("origin", false).unwrap();
1231
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1232
    let host = Repo::open(&root.join("origin")).unwrap();
1233
    assert!(
1234
        matches!(
1235
            host.authenticate_change(&h).unwrap(),
1236
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
1237
        ),
1238
        "named by its certificate's subject"
1239
    );
1240
    a.pull("origin").unwrap();
1241
    assert!(matches!(
1242
        a.authenticate_change(&h).unwrap(),
1243
        SignatureStatus::Valid { key: k, .. } if k == key
1244
    ));
1245
1246
    let (none, _, _) = agent("none", None);
1247
    let r = none.push("origin", false).unwrap();
1248
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1249
    let mallory_sk = SecretKey::generate();
1250
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1251
    let (stranger, _, _) = agent(
1252
        "stranger",
1253
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1254
    );
1255
    let r = stranger.push("origin", false).unwrap();
1256
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1257
    let (ended, _, eh) = agent(
1258
        "ended",
1259
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1260
    );
1261
    let r = ended.push("origin", false).unwrap();
1262
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1263
    assert!(matches!(
1264
        ended.authenticate_change(&eh).unwrap(),
1265
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1266
    ));
1267
}
1268
1269
#[test]
1270
fn trust_policy_governs_pushes_and_fetches() {
1271
    hermetic();
1272
    let dir = tempfile::tempdir().unwrap();
1273
    let root = dir.path();
1274
    let origin = Repo::init(&root.join("origin")).unwrap();
1275
    let url = root.join("origin").to_string_lossy().to_string();
1276
1277
    // A is the root. Before the policy, an unsigned push from B is fine.
1278
    let mut a = Repo::clone(&url, &root.join("a"))
1279
        .unwrap()
1280
        .with_home(root.join("home-a"));
1281
    let (key_a, _) = a
1282
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1283
        .unwrap();
1284
    let mut b = Repo::clone(&url, &root.join("b"))
1285
        .unwrap()
1286
        .with_home(root.join("home-b"));
1287
    write(&root.join("b"), "b.txt", b"b\n");
1288
    b.commit("unsigned before policy", &[]).unwrap();
1289
    assert!(b.push("origin", false).unwrap()[0].ok);
1290
    origin.refresh().unwrap();
1291
1292
    // A creates the policy and pushes it; origin now enforces it.
1293
    write(&root.join("a"), "a.txt", b"a\n");
1294
    a.commit("a", &[]).unwrap();
1295
    let sp = a.policy_init().unwrap();
1296
    assert_eq!(sp.policy.serial, 1);
1297
    a.pull("origin").unwrap();
1298
    let results = a.push("origin", false).unwrap();
1299
    origin.refresh().unwrap();
1300
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1301
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1302
1303
    // B pulls the policy. Without an identity B cannot push at all.
1304
    b.pull("origin").unwrap();
1305
    assert!(
1306
        b.current_policy().unwrap().is_some(),
1307
        "the policy arrived with the fetch"
1308
    );
1309
    assert!(b.push("origin", false).is_err());
1310
    // With an identity the policy does not list, the push is rejected by origin.
1311
    let (key_b, id_b) = b
1312
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1313
        .unwrap();
1314
    write(&root.join("b"), "b.txt", b"b2\n");
1315
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1316
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1317
    let r = b.push("origin", false).unwrap();
1318
    origin.refresh().unwrap();
1319
    assert!(
1320
        !r[0].ok && r[0].reason.contains("may not update"),
1321
        "{:?}",
1322
        r
1323
    );
1324
1325
    // A grants B (identity handed over as a file) and publishes the policy.
1326
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1327
    assert_eq!(sp.policy.serial, 2);
1328
    let r = a.push("origin", false).unwrap();
1329
    origin.refresh().unwrap();
1330
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1331
    // B must fetch the new policy before pushing.
1332
    assert!(b
1333
        .push("origin", false)
1334
        .unwrap_or_else(|e| vec![RefResult {
1335
            name: "main".into(),
1336
            ok: false,
1337
            reason: e.to_string()
1338
        }])
1339
        .iter()
1340
        .all(|x| !x.ok));
1341
    b.pull("origin").unwrap();
1342
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1343
    let r = b.push("origin", false).unwrap();
1344
    origin.refresh().unwrap();
1345
    assert!(r[0].ok, "{:?}", r);
1346
    // Origin verified B's change under the policy.
1347
    let heads = origin.bookmark_heads().unwrap();
1348
    for h in &heads {
1349
        let c = origin.store().get_change(h).unwrap();
1350
        if c.author == key_b {
1351
            origin
1352
                .change_allowed(
1353
                    h,
1354
                    &origin.current_policy().unwrap().unwrap().1.policy,
1355
                    "main",
1356
                )
1357
                .unwrap();
1358
        }
1359
    }
1360
1361
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1362
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1363
    forged.serial = 3;
1364
    forged.roots = vec![key_b];
1365
    let fh = forged.hash();
1366
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1367
    let forged = SignedPolicy {
1368
        policy: forged,
1369
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1370
    };
1371
    let r = origin
1372
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1373
        .unwrap();
1374
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1375
    let stale = a.current_policy().unwrap().unwrap().1;
1376
    let mut old = stale.clone();
1377
    old.policy.serial = 1;
1378
    let r = origin
1379
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1380
        .unwrap();
1381
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1382
1383
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1384
    a.pull("origin").unwrap();
1385
    a.policy_revoke(&key_b).unwrap();
1386
    let r = a.push("origin", false).unwrap();
1387
    origin.refresh().unwrap();
1388
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1389
    b.pull("origin").unwrap();
1390
    write(&root.join("b"), "b.txt", b"b3\n");
1391
    b.commit("b3", &[]).unwrap();
1392
    let r = b.push("origin", false).unwrap();
1393
    origin.refresh().unwrap();
1394
    assert!(!r[0].ok, "{:?}", r);
1395
1396
    // A clone by a third party receives and verifies everything.
1397
    let c = Repo::clone(&url, &root.join("c"))
1398
        .unwrap()
1399
        .with_home(root.join("home-c"));
1400
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1401
    assert!(c
1402
        .current_policy()
1403
        .unwrap()
1404
        .unwrap()
1405
        .1
1406
        .policy
1407
        .roots
1408
        .contains(&key_a));
1409
    assert!(!c.snapshot("status").unwrap().changed);
1410
}
1411
1412
/// oxygen#66: a gc says what it is doing, phase by phase.
1413
#[test]
1414
fn gc_reports_its_phases() {
1415
    hermetic();
1416
    let dir = tempfile::tempdir().unwrap();
1417
    let repo = Repo::init(dir.path()).unwrap();
1418
    for i in 0..3 {
1419
        write(
1420
            dir.path(),
1421
            &format!("f{i}.txt"),
1422
            format!("{i}\n").as_bytes(),
1423
        );
1424
        repo.commit(&format!("c{i}"), &[]).unwrap();
1425
    }
1426
    let mut phases = Vec::new();
1427
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1428
        .unwrap();
1429
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1430
    assert!(
1431
        phases.iter().any(|p| p.starts_with("pruning")),
1432
        "{phases:?}"
1433
    );
1434
    assert!(
1435
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1436
        "{phases:?}"
1437
    );
1438
    assert!(
1439
        phases
1440
            .iter()
1441
            .any(|p| p.starts_with("writing the index of ")),
1442
        "{phases:?}"
1443
    );
1444
}
1445
1446
#[test]
1447
fn gc_packs_objects_and_history_still_works() {
1448
    hermetic();
1449
    let dir = tempfile::tempdir().unwrap();
1450
    let root = dir.path();
1451
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1452
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1453
        .unwrap();
1454
    repo.set_user_config("core.sign", "change").unwrap();
1455
    write(root, "a.txt", b"one\n");
1456
    let h1 = repo.commit("one", &[]).unwrap();
1457
    write(root, "a.txt", b"two\n");
1458
    write(root, "big.bin", &vec![0u8; 100_000]);
1459
    let h2 = repo.commit("two", &[]).unwrap();
1460
    // Several snapshots leave superseded working-copy versions behind.
1461
    for i in 0..5 {
1462
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1463
        repo.snapshot("status").unwrap();
1464
    }
1465
    write(root, "a.txt", b"two\n");
1466
    repo.snapshot("status").unwrap();
1467
    let before = repo.store().list().unwrap();
1468
    assert!(repo.store().loose_count().unwrap() > 0);
1469
1470
    // With the default retention every operation's view is a root: nothing prunes.
1471
    let r = repo.gc(true).unwrap();
1472
    assert_eq!(r.packed.objects, before.len());
1473
    assert_eq!(r.pruned.objects, 0);
1474
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1475
    assert_eq!(repo.store().list().unwrap(), before);
1476
1477
    // With zero retention only the current view is a root: superseded
1478
    // working copies go, everything reachable stays.
1479
    repo.config.set("core.op-retention", "0").unwrap();
1480
    repo.save_config().unwrap();
1481
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1482
    let r = repo.gc(true).unwrap();
1483
    assert!(r.pruned.objects >= 5, "{r:?}");
1484
    let after = repo.store().list().unwrap();
1485
    assert!(after.len() < before.len());
1486
    assert!(after.contains(&h1) && after.contains(&h2));
1487
    for (_, op) in repo.op_log().unwrap() {
1488
        assert!(!op.command.is_empty(), "operation objects are all kept");
1489
    }
1490
    // Everything still works from the pruned, packed store.
1491
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1492
    assert!(matches!(
1493
        repo.verify_change(&h2).unwrap(),
1494
        SignatureStatus::Valid { .. }
1495
    ));
1496
    assert_eq!(repo.log().unwrap().len(), 3);
1497
    repo.checkout(&[h1], false, "checkout").unwrap();
1498
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1499
    repo.checkout(&[h2], false, "checkout").unwrap();
1500
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1501
    assert!(!repo.snapshot("status").unwrap().changed);
1502
    // Grace period defers pruning of young garbage.
1503
    write(root, "a.txt", b"three\n");
1504
    repo.commit("three", &[]).unwrap();
1505
    let r = repo.gc(false).unwrap();
1506
    assert_eq!(r.pruned.objects, 0);
1507
    assert!(r.pruned.deferred > 0);
1508
    let r = repo.gc(true).unwrap();
1509
    assert!(r.pruned.objects > 0);
1510
    assert_eq!(repo.log().unwrap().len(), 4);
1511
    // Restoring the default retention makes the old views roots again; the
1512
    // working copies they name were pruned, which gc tolerates.
1513
    repo.config.set("core.op-retention", "90").unwrap();
1514
    repo.save_config().unwrap();
1515
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1516
    let r = repo.gc(false).unwrap();
1517
    assert_eq!(r.pruned.objects, 0);
1518
    assert_eq!(repo.log().unwrap().len(), 4);
1519
}
1520
1521
#[test]
1522
fn describe_amend_abandon_heads() {
1523
    hermetic();
1524
    let dir = tempfile::tempdir().unwrap();
1525
    let root = dir.path();
1526
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1527
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1528
        .unwrap();
1529
    repo.set_user_config("core.sign", "change").unwrap();
1530
    write(root, "a.txt", b"one\n");
1531
    let h1 = repo.commit("first", &[]).unwrap();
1532
    write(root, "a.txt", b"one\ntwo\n");
1533
    let h2 = repo.commit("secnod", &[]).unwrap();
1534
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1535
1536
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1537
    let h2b = repo.describe(&h2, "second").unwrap();
1538
    assert_ne!(h2b, h2);
1539
    let c = repo.store().get_change(&h2b).unwrap();
1540
    assert_eq!(
1541
        (c.change_id, c.message.as_str(), c.deps.clone()),
1542
        (id2, "second", vec![h1])
1543
    );
1544
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1545
    assert!(matches!(
1546
        repo.verify_change(&h2b).unwrap(),
1547
        SignatureStatus::Valid { .. }
1548
    ));
1549
    let s = repo.snapshot("status").unwrap();
1550
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1551
    assert_eq!(
1552
        repo.resolve_change(&id2.short(8)).unwrap(),
1553
        h2b,
1554
        "the old object is no longer reachable from the log"
1555
    );
1556
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1557
    let h1b = repo.describe(&h1, "first, described").unwrap();
1558
    assert_ne!(h1b, h1);
1559
    let heads = repo.bookmark_heads().unwrap();
1560
    assert_eq!(heads.len(), 1);
1561
    let top = repo.store().get_change(&heads[0]).unwrap();
1562
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1563
    assert!(
1564
        matches!(
1565
            repo.verify_change(&heads[0]).unwrap(),
1566
            SignatureStatus::Valid { .. }
1567
        ),
1568
        "rewritten own change is re-signed"
1569
    );
1570
    let (_, wc) = repo.working_copy().unwrap();
1571
    assert_eq!(
1572
        wc.deps,
1573
        vec![heads[0]],
1574
        "the working copy follows the rewrite"
1575
    );
1576
    assert!(!repo.snapshot("status").unwrap().changed);
1577
    let snap = repo.load_state(&heads).unwrap().materialize();
1578
    assert!(
1579
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1580
    );
1581
1582
    // amend: fold an edit into the head; the result is one change from h1.
1583
    write(root, "a.txt", b"one\ntwo\nthree\n");
1584
    write(root, "b.txt", b"b\n");
1585
    let h2c = repo.amend(None).unwrap();
1586
    let c = repo.store().get_change(&h2c).unwrap();
1587
    assert_eq!(c.change_id, id2);
1588
    assert_eq!(c.message, "second");
1589
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1590
    assert_eq!(
1591
        repo.log().unwrap().len(),
1592
        3,
1593
        "working copy, amended head, first"
1594
    );
1595
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1596
    assert!(
1597
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1598
    );
1599
    assert!(snap.files.contains_key("b.txt"));
1600
    assert!(!repo.snapshot("status").unwrap().changed);
1601
    assert!(
1602
        repo.amend(None).is_err(),
1603
        "clean working copy and no message"
1604
    );
1605
    let h2d = repo.amend(Some("second, amended")).unwrap();
1606
    assert_eq!(
1607
        repo.store().get_change(&h2d).unwrap().message,
1608
        "second, amended"
1609
    );
1610
1611
    // abandon: the head goes, its content stays as uncommitted work.
1612
    repo.abandon(&h2d).unwrap();
1613
    assert_eq!(
1614
        repo.bookmark_heads().unwrap(),
1615
        vec![h1b],
1616
        "the described first change is the head again"
1617
    );
1618
    let s = repo.snapshot("status").unwrap();
1619
    let paths: Vec<_> = s
1620
        .statuses
1621
        .iter()
1622
        .map(|p| (p.path.as_str(), p.status))
1623
        .collect();
1624
    assert_eq!(
1625
        paths,
1626
        vec![
1627
            ("a.txt", ChangeStatus::Modified),
1628
            ("b.txt", ChangeStatus::Added)
1629
        ]
1630
    );
1631
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1632
    let h3 = repo.commit("recommitted", &[]).unwrap();
1633
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1634
    // undo brings the abandoned head back.
1635
    repo.undo().unwrap();
1636
    repo.undo().unwrap();
1637
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1638
1639
    // Abandoning a non-head whose dependent references its atoms reifies
1640
    // the references (here: a.txt vanishes with it, so the dependent's edit
1641
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1642
    let base = repo.bookmark_heads().unwrap()[0];
1643
    let base_change = repo.store().get_change(&base).unwrap();
1644
    let h1_now = base_change.deps[0];
1645
    let notes = repo.abandon(&h1_now).unwrap();
1646
    assert!(
1647
        !notes.is_empty(),
1648
        "the dependent's edit of a.txt was reified"
1649
    );
1650
    let heads = repo.bookmark_heads().unwrap();
1651
    let after = repo.load_state(&heads).unwrap().materialize();
1652
    assert!(
1653
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1654
        "{:?}",
1655
        after.files.keys()
1656
    );
1657
    repo.undo().unwrap();
1658
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1659
    write(root, "c.txt", b"c\n");
1660
    let hc = repo.commit("c", &[]).unwrap();
1661
    write(root, "d.txt", b"d\n");
1662
    let hd = repo.commit("d", &[hc]).unwrap();
1663
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1664
    repo.abandon(&hc).unwrap();
1665
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1666
    assert!(!heads.contains(&hc));
1667
    let d_now = heads
1668
        .iter()
1669
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1670
        .copied()
1671
        .unwrap();
1672
    assert!(
1673
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1674
        "d inherited c's (empty) dependencies"
1675
    );
1676
    let s = repo.snapshot("status").unwrap();
1677
    assert_eq!(
1678
        s.statuses
1679
            .iter()
1680
            .map(|p| p.path.as_str())
1681
            .collect::<Vec<_>>(),
1682
        vec!["c.txt"],
1683
        "c's content is now uncommitted work"
1684
    );
1685
}
1686
1687
#[test]
1688
fn git_export_mirrors_history() {
1689
    hermetic();
1690
    if std::process::Command::new("git")
1691
        .arg("--version")
1692
        .output()
1693
        .is_err()
1694
    {
1695
        eprintln!("git not installed; skipping");
1696
        return;
1697
    }
1698
    let dir = tempfile::tempdir().unwrap();
1699
    let root = dir.path();
1700
    let mut repo = Repo::init(&root.join("r"))
1701
        .unwrap()
1702
        .with_home(root.join("home"));
1703
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1704
        .unwrap();
1705
    let r = root.join("r");
1706
    write(&r, "README.md", b"hello\n");
1707
    write(&r, "src/main.rs", b"fn main() {}\n");
1708
    let h1 = repo.commit("first", &[]).unwrap();
1709
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1710
    write(&r, "logo.png", b"\x89PNG\0\0");
1711
    let h2 = repo.commit("second", &[]).unwrap();
1712
1713
    let git_dir = root.join("mirror.git");
1714
    let rep = repo.git_export(&git_dir).unwrap();
1715
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1716
    let git = |args: &[&str]| -> String {
1717
        let out = std::process::Command::new("git")
1718
            .arg("-C")
1719
            .arg(&git_dir)
1720
            .args(args)
1721
            .output()
1722
            .unwrap();
1723
        assert!(
1724
            out.status.success(),
1725
            "{}",
1726
            String::from_utf8_lossy(&out.stderr)
1727
        );
1728
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1729
    };
1730
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1731
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1732
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1733
    let body = git(&["log", "-1", "--format=%B", "main"]);
1734
    assert!(
1735
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1736
        "{body}"
1737
    );
1738
    assert!(body.contains("Change-Id: "), "{body}");
1739
    assert_eq!(
1740
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1741
        "Ada Lovelace <[email protected]>"
1742
    );
1743
    assert_eq!(
1744
        git(&["ls-tree", "--name-only", "main"]),
1745
        "README.md\nlogo.png\nsrc"
1746
    );
1747
1748
    // Re-export is incremental.
1749
    let rep = repo.git_export(&git_dir).unwrap();
1750
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1751
1752
    // An independent change makes two heads; the next state is one more
1753
    // commit on the linear branch whose tree is the union.
1754
    repo.checkout(&[h1], false, "checkout").unwrap();
1755
    write(&r, "other.txt", b"o\n");
1756
    let h3 = repo.commit("third", &[]).unwrap();
1757
    let rep = repo.git_export(&git_dir).unwrap();
1758
    assert_eq!((rep.exported, rep.heads), (1, 2));
1759
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1760
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1761
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1762
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1763
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1764
    assert_eq!(
1765
        git(&["ls-tree", "--name-only", "main"]),
1766
        "README.md\nlogo.png\nother.txt\nsrc"
1767
    );
1768
    let body = git(&["log", "-1", "--format=%B", "main"]);
1769
    assert!(
1770
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1771
        "{body}"
1772
    );
1773
    // A rewrite is a new state whose one new change is the rewritten one.
1774
    repo.describe(&h3, "third, described").unwrap();
1775
    let rep = repo.git_export(&git_dir).unwrap();
1776
    assert_eq!(rep.exported, 1);
1777
    assert_eq!(
1778
        git(&["log", "-1", "--format=%s", "main"]),
1779
        "third, described"
1780
    );
1781
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1782
    let _ = h2;
1783
}
1784
1785
#[test]
1786
fn git_import_reproduces_trees() {
1787
    git_import_reproduces_trees_with(None);
1788
}
1789
1790
/// The same import with every merge rendered in batches of one file
1791
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1792
#[test]
1793
fn git_import_reproduces_trees_in_batches() {
1794
    git_import_reproduces_trees_with(Some(1));
1795
}
1796
1797
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1798
    crate::repo::git::set_merge_batch_for_tests(batch);
1799
    hermetic();
1800
    if std::process::Command::new("git")
1801
        .arg("--version")
1802
        .output()
1803
        .is_err()
1804
    {
1805
        eprintln!("git not installed; skipping");
1806
        return;
1807
    }
1808
    let dir = tempfile::tempdir().unwrap();
1809
    let root = dir.path();
1810
    let g = root.join("src.git");
1811
    fs::create_dir_all(&g).unwrap();
1812
    let git = |args: &[&str]| -> String {
1813
        let out = std::process::Command::new("git")
1814
            .arg("-C")
1815
            .arg(&g)
1816
            .args([
1817
                "-c",
1818
                "user.name=Grace",
1819
                "-c",
1820
                "[email protected]",
1821
                "-c",
1822
                "commit.gpgsign=false",
1823
            ])
1824
            .args(args)
1825
            .output()
1826
            .unwrap();
1827
        assert!(
1828
            out.status.success(),
1829
            "git {args:?}: {}",
1830
            String::from_utf8_lossy(&out.stderr)
1831
        );
1832
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1833
    };
1834
    git(&["init", "-q", "-b", "main"]);
1835
    write(&g, "README.md", b"# Hi\n");
1836
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1837
    git(&["add", "."]);
1838
    git(&["commit", "-q", "-m", "initial"]);
1839
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1840
    write(&g, "run.sh", b"#!/bin/sh\n");
1841
    #[cfg(unix)]
1842
    {
1843
        use std::os::unix::fs::PermissionsExt;
1844
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1845
    }
1846
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1847
    git(&["add", "."]);
1848
    git(&[
1849
        "commit",
1850
        "-q",
1851
        "-m",
1852
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1853
    ]);
1854
    // A branch that edits README, merged back with a conflict-free merge.
1855
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1856
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1857
    git(&["commit", "-q", "-am", "readme"]);
1858
    git(&["checkout", "-q", "main"]);
1859
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1860
    // A branch from the initial commit inserting at the same place as
1861
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1862
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1863
    git(&["checkout", "-q", "-b", "clash", &initial]);
1864
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1865
    git(&["commit", "-q", "-am", "clash"]);
1866
    git(&["checkout", "-q", "main"]);
1867
    // Expected to stop at the conflict, so its status is ignored; the
1868
    // identity is passed as for every other git call here, or a machine
1869
    // without one refuses to start the merge at all.
1870
    let _ = std::process::Command::new("git")
1871
        .arg("-C")
1872
        .arg(&g)
1873
        .args([
1874
            "-c",
1875
            "user.name=Grace",
1876
            "-c",
1877
            "[email protected]",
1878
            "merge",
1879
            "-q",
1880
            "clash",
1881
        ])
1882
        .output();
1883
    assert!(
1884
        g.join(".git/MERGE_HEAD").exists(),
1885
        "the clash merge stopped at its conflict"
1886
    );
1887
    write(
1888
        &g,
1889
        "src/lib.rs",
1890
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1891
    );
1892
    git(&["add", "."]);
1893
    git(&["commit", "-q", "-m", "resolve clash"]);
1894
    git(&["rm", "-q", "logo.png"]);
1895
    git(&["commit", "-q", "-m", "drop logo"]);
1896
    // A rename with a small edit is imported as a move of the same node.
1897
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1898
    write(
1899
        &g,
1900
        "src/lib2.rs",
1901
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1902
    );
1903
    git(&["add", "."]);
1904
    git(&["commit", "-q", "-m", "rename lib"]);
1905
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1906
    // run.sh is the same as in the first parent's tree, but the merged
1907
    // change touched it, so the importer must compare it, not skip it.
1908
    git(&["checkout", "-q", "-b", "discarded"]);
1909
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1910
    git(&["commit", "-q", "-am", "discarded edit"]);
1911
    git(&["checkout", "-q", "main"]);
1912
    git(&[
1913
        "merge",
1914
        "-q",
1915
        "-s",
1916
        "ours",
1917
        "-m",
1918
        "merge discarded, keeping ours",
1919
        "discarded",
1920
    ]);
1921
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1922
1923
    let dest = root.join("oxy");
1924
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1925
    let rep = repo.import_git(&g, "main").unwrap();
1926
    assert_eq!(rep.commits, expected_count);
1927
    assert_eq!(rep.merges, 3);
1928
    assert_eq!(
1929
        fs::read(dest.join("run.sh")).unwrap(),
1930
        b"#!/bin/sh\n",
1931
        "the ours merge kept main's run.sh"
1932
    );
1933
    let v = repo.verify_git_import(&g, "main").unwrap();
1934
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1935
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1936
    // The working copy equals the Git tree at main.
1937
    assert_eq!(
1938
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1939
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1940
    );
1941
    assert!(!dest.join("src/lib.rs").exists());
1942
    assert_eq!(
1943
        fs::read(dest.join("README.md")).unwrap(),
1944
        b"# Hi\n\nMore.\n"
1945
    );
1946
    assert!(!dest.join("logo.png").exists());
1947
    #[cfg(unix)]
1948
    {
1949
        use std::os::unix::fs::PermissionsExt;
1950
        assert!(
1951
            fs::metadata(dest.join("run.sh"))
1952
                .unwrap()
1953
                .permissions()
1954
                .mode()
1955
                & 0o111
1956
                != 0
1957
        );
1958
    }
1959
    assert!(
1960
        !repo.snapshot("status").unwrap().changed,
1961
        "clean after import"
1962
    );
1963
    let heads = repo.bookmark_heads().unwrap();
1964
    let st = repo.load_state(&heads).unwrap();
1965
    assert!(!st.materialize().is_conflicted());
1966
    assert_eq!(st.len(), expected_count);
1967
    let tip = repo
1968
        .log()
1969
        .unwrap()
1970
        .into_iter()
1971
        .find(|e| e.change.message.starts_with("rename lib"))
1972
        .unwrap();
1973
    let c = repo.store().get_change(&tip.hash).unwrap();
1974
    assert!(
1975
        c.tree_ops
1976
            .iter()
1977
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1978
        "{:?}",
1979
        c.tree_ops
1980
    );
1981
    assert!(!c
1982
        .tree_ops
1983
        .iter()
1984
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1985
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1986
    let log = repo.log().unwrap();
1987
    let second = log
1988
        .iter()
1989
        .find(|e| e.change.message.starts_with("second"))
1990
        .unwrap();
1991
    assert_eq!(
1992
        second.change.change_id,
1993
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1994
    );
1995
    assert!(second
1996
        .change
1997
        .message
1998
        .contains("Git-Author: Grace <[email protected]>"));
1999
    let resolve = log
2000
        .iter()
2001
        .find(|e| e.change.message.starts_with("resolve clash"))
2002
        .unwrap();
2003
    assert_eq!(
2004
        resolve.change.kind,
2005
        ChangeKind::Resolution,
2006
        "a conflicting Git merge becomes a resolution"
2007
    );
2008
    // Re-importing into another fresh repository gives the same ChangeIds.
2009
    let repo2 = Repo::init(&root.join("oxy2"))
2010
        .unwrap()
2011
        .with_home(root.join("home"));
2012
    repo2.import_git(&g, "main").unwrap();
2013
    // New nodes' identifiers derive from the commit (spec §23), so the
2014
    // re-import is not just the same ChangeIds but the same changes.
2015
    assert_eq!(
2016
        repo2.bookmark_heads().unwrap(),
2017
        repo.bookmark_heads().unwrap()
2018
    );
2019
    let ids: BTreeSet<ChangeId> = repo
2020
        .log()
2021
        .unwrap()
2022
        .iter()
2023
        .filter(|e| !e.is_working_copy)
2024
        .map(|e| e.change.change_id)
2025
        .collect();
2026
    let ids2: BTreeSet<ChangeId> = repo2
2027
        .log()
2028
        .unwrap()
2029
        .iter()
2030
        .filter(|e| !e.is_working_copy)
2031
        .map(|e| e.change.change_id)
2032
        .collect();
2033
    assert_eq!(ids, ids2);
2034
    // Round trip back out to Git reproduces the tip tree.
2035
    let mirror = root.join("mirror.git");
2036
    repo.git_export(&mirror).unwrap();
2037
    let out = std::process::Command::new("git")
2038
        .arg("-C")
2039
        .arg(&mirror)
2040
        .args(["show", "main:src/lib2.rs"])
2041
        .output()
2042
        .unwrap();
2043
    assert_eq!(
2044
        String::from_utf8_lossy(&out.stdout),
2045
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2046
    );
2047
    let out = std::process::Command::new("git")
2048
        .arg("-C")
2049
        .arg(&mirror)
2050
        .args(["show", "main:src/lib.rs"])
2051
        .output()
2052
        .unwrap();
2053
    assert!(
2054
        !out.status.success(),
2055
        "the old path is gone from the export"
2056
    );
2057
}
2058
2059
#[test]
2060
fn checkpoints_accelerate_loading_and_stay_correct() {
2061
    hermetic();
2062
    let dir = tempfile::tempdir().unwrap();
2063
    let root = dir.path();
2064
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2065
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2066
    repo.save_config().unwrap();
2067
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2068
    let mut hashes = Vec::new();
2069
    for i in 0..12 {
2070
        write(
2071
            root,
2072
            "a.txt",
2073
            format!(
2074
                "{}\n",
2075
                (0..=i)
2076
                    .map(|k| k.to_string())
2077
                    .collect::<Vec<_>>()
2078
                    .join("\n")
2079
            )
2080
            .as_bytes(),
2081
        );
2082
        write(root, &format!("f{i}.txt"), b"x\n");
2083
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2084
    }
2085
    let (_, cp) = repo
2086
        .latest_checkpoint("main")
2087
        .unwrap()
2088
        .expect("automatic checkpoint");
2089
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2090
    // Loading through the checkpoint equals loading everything.
2091
    let heads = repo.bookmark_heads().unwrap();
2092
    let fast = repo.load_state(&heads).unwrap();
2093
    let full = repo.load_state_full(&heads).unwrap();
2094
    assert_eq!(fast.len(), full.len());
2095
    assert_eq!(fast.heads(), full.heads());
2096
    let (a, b) = (fast.materialize(), full.materialize());
2097
    assert_eq!(
2098
        a.files.keys().collect::<Vec<_>>(),
2099
        b.files.keys().collect::<Vec<_>>()
2100
    );
2101
    for (p, f) in &a.files {
2102
        assert_eq!(f.content, b.files[p].content, "{p}");
2103
    }
2104
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2105
    // A head set that does not contain the checkpoint's heads falls back.
2106
    assert!(repo
2107
        .load_state_checkpointed(&[hashes[0]])
2108
        .unwrap()
2109
        .is_none());
2110
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2111
    // Everything else keeps working on top of the checkpoint.
2112
    assert!(!repo.snapshot("status").unwrap().changed);
2113
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2114
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2115
    let (r, n, bytes) = repo.checkpoint().unwrap();
2116
    assert!(n >= 12 && bytes > 0);
2117
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2118
    write(root, "a.txt", b"after\n");
2119
    let h_after = repo.commit("after", &[]).unwrap();
2120
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2121
    assert!(st.contains(&h_after));
2122
    assert!(
2123
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2124
    );
2125
    assert_eq!(repo.log().unwrap().len(), 14);
2126
    // Checkpoints survive gc.
2127
    repo.gc(true).unwrap();
2128
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
2129
    assert!(repo
2130
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2131
        .unwrap()
2132
        .is_some());
2133
}
2134
2135
#[test]
2136
fn quick_status_for_prompts() {
2137
    hermetic();
2138
    let dir = tempfile::tempdir().unwrap();
2139
    let root = dir.path();
2140
    let origin = Repo::init(&root.join("origin")).unwrap();
2141
    let url = root.join("origin").to_string_lossy().to_string();
2142
    let a = Repo::clone(&url, &root.join("a"))
2143
        .unwrap()
2144
        .with_home(root.join("home"));
2145
    let ops_before = a.op_log().unwrap().len();
2146
    let info = a.quick_status().unwrap();
2147
    assert_eq!(
2148
        (
2149
            info.bookmark.as_str(),
2150
            info.heads,
2151
            info.dirty,
2152
            info.conflicted,
2153
            info.ahead,
2154
            info.behind
2155
        ),
2156
        ("main", 0, false, false, Some(0), Some(0))
2157
    );
2158
    write(&root.join("a"), "f.txt", b"f\n");
2159
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
2160
    assert_eq!(
2161
        a.op_log().unwrap().len(),
2162
        ops_before,
2163
        "quick_status records nothing"
2164
    );
2165
    // A snapshotted but uncommitted change is still dirty.
2166
    a.snapshot("status").unwrap();
2167
    assert!(a.quick_status().unwrap().dirty);
2168
    a.commit("f", &[]).unwrap();
2169
    let info = a.quick_status().unwrap();
2170
    assert!(!info.dirty, "clean right after a commit");
2171
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
2172
    assert_eq!(
2173
        info.format("%b %c%d%x%A%D"),
2174
        format!("main {}+1", info.change_id)
2175
    );
2176
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2177
    // Touching a file without changing it is not dirty; changing content of
2178
    // the same size is.
2179
    let p = root.join("a/f.txt");
2180
    let content = fs::read(&p).unwrap();
2181
    fs::write(&p, &content).unwrap();
2182
    assert!(!a.quick_status().unwrap().dirty);
2183
    fs::write(&p, b"g\n").unwrap();
2184
    assert!(a.quick_status().unwrap().dirty);
2185
    fs::write(&p, b"f\n").unwrap();
2186
    // Push, then a second clone commits and pushes: we are behind.
2187
    assert!(a.push("origin", false).unwrap()[0].ok);
2188
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
2189
    let b = Repo::clone(&url, &root.join("b"))
2190
        .unwrap()
2191
        .with_home(root.join("home-b"));
2192
    write(&root.join("b"), "g.txt", b"g\n");
2193
    b.commit("g", &[]).unwrap();
2194
    b.push("origin", false).unwrap();
2195
    a.fetch("origin").unwrap();
2196
    let info = a.quick_status().unwrap();
2197
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2198
    assert_eq!(info.format("%A%D"), "-1");
2199
    let _ = origin;
2200
}
2201
2202
#[test]
2203
fn lazy_blobs_are_fetched_on_first_read() {
2204
    hermetic();
2205
    let dir = tempfile::tempdir().unwrap();
2206
    let root = dir.path();
2207
    let origin_dir = root.join("origin");
2208
    let origin = Repo::init(&origin_dir)
2209
        .unwrap()
2210
        .with_home(root.join("home"));
2211
    let url = origin_dir.to_string_lossy().to_string();
2212
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2213
    write(&origin_dir, "big.bin", &big);
2214
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2215
    write(&origin_dir, "t.txt", b"t\n");
2216
    let h = origin.commit("blobs", &[]).unwrap();
2217
    let big_ref = Repo::blob_ref(&big);
2218
2219
    // Fetch only (no checkout) with a filter: the big blob stays absent.
2220
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2221
        .unwrap()
2222
        .with_home(root.join("home"));
2223
    let a = {
2224
        let mut a = a;
2225
        a.config.set("remote.origin.url", &url).unwrap();
2226
        a.config.set("filter.max-blob", "100K").unwrap();
2227
        a.save_config().unwrap();
2228
        a
2229
    };
2230
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2231
    a.fetch("origin").unwrap();
2232
    assert!(a.store().has(&h));
2233
    assert!(!a.store().has(&big_ref), "withheld");
2234
    assert!(
2235
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2236
        "small blob came along"
2237
    );
2238
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2239
2240
    // status and commit do not need it: adopt the state, edit a text file, commit.
2241
    let (op_ref, op) = a.head_op().unwrap();
2242
    let mut view = op.view.clone();
2243
    view.bookmarks.insert(
2244
        "main".into(),
2245
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2246
    );
2247
    a.record_op(&[op_ref], "adopt", view).unwrap();
2248
    // Checkout reads the blob lazily, which fetches it.
2249
    a.checkout(&[h], true, "checkout").unwrap();
2250
    assert!(a.store().has(&big_ref), "fetched on first read");
2251
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2252
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2253
    write(&root.join("a"), "t.txt", b"t2\n");
2254
    a.commit("text edit", &[]).unwrap();
2255
2256
    // clone --max-blob records the filter; the checkout fetches lazily.
2257
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
2258
    assert_eq!(b.config.max_blob, Some(1024));
2259
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2260
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2261
    assert!(parse_size("lots").is_err());
2262
}
2263
2264
#[test]
2265
fn sparse_checkout_materializes_only_chosen_paths() {
2266
    hermetic();
2267
    let dir = tempfile::tempdir().unwrap();
2268
    let root = dir.path();
2269
    let origin_dir = root.join("origin");
2270
    let origin = Repo::init(&origin_dir)
2271
        .unwrap()
2272
        .with_home(root.join("home"));
2273
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2274
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2275
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2276
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2277
    write(&origin_dir, "docs/logo.png", &logo);
2278
    write(&origin_dir, "README.md", b"# top\n");
2279
    let h1 = origin.commit("tree", &[]).unwrap();
2280
    let url = origin_dir.to_string_lossy().to_string();
2281
2282
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2283
        .unwrap()
2284
        .with_home(root.join("home"));
2285
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2286
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2287
    assert!(root.join("a/src/main.rs").exists());
2288
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
2289
    assert!(
2290
        !a.store().has(&Repo::blob_ref(&logo)),
2291
        "out-of-scope blob never fetched"
2292
    );
2293
    assert!(
2294
        !a.snapshot("status").unwrap().changed,
2295
        "out-of-scope files are not removals"
2296
    );
2297
    assert!(!a.quick_status().unwrap().dirty);
2298
2299
    // Edits in scope commit normally and keep the rest of the tree intact.
2300
    write(
2301
        &root.join("a"),
2302
        "src/lib.rs",
2303
        b"pub fn a() {}\npub fn b() {}\n",
2304
    );
2305
    let h2 = a.commit("edit lib", &[]).unwrap();
2306
    let st = a.load_state(&[h2]).unwrap().materialize();
2307
    assert!(
2308
        st.files.contains_key("docs/guide.md"),
2309
        "the state still has everything"
2310
    );
2311
    assert!(a.push("origin", false).unwrap()[0].ok);
2312
    origin.refresh().unwrap();
2313
    // Files created outside the scope are ignored by status.
2314
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2315
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2316
2317
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2318
    let mut a = a;
2319
    a.config.set("filter.paths", "src,docs").unwrap();
2320
    a.save_config().unwrap();
2321
    let r = a
2322
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2323
        .unwrap();
2324
    assert!(r.written >= 2);
2325
    assert_eq!(
2326
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2327
        logo,
2328
        "now fetched lazily"
2329
    );
2330
    assert!(!root.join("a/README.md").exists());
2331
    // Origin sees the change made under a sparse checkout with the full tree intact.
2332
    origin.pull("origin").err();
2333
    let full = origin
2334
        .load_state(&origin.bookmark_heads().unwrap())
2335
        .unwrap()
2336
        .materialize();
2337
    assert!(
2338
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2339
    );
2340
    assert!(full.files.contains_key("README.md"));
2341
    let _ = h1;
2342
}
2343
2344
#[test]
2345
fn shallow_clone_and_deepen() {
2346
    hermetic();
2347
    let dir = tempfile::tempdir().unwrap();
2348
    let root = dir.path();
2349
    let origin_dir = root.join("origin");
2350
    let origin = Repo::init(&origin_dir)
2351
        .unwrap()
2352
        .with_home(root.join("home"));
2353
    let mut hashes = Vec::new();
2354
    for i in 0..8 {
2355
        write(
2356
            &origin_dir,
2357
            "a.txt",
2358
            format!(
2359
                "{}\n",
2360
                (0..=i)
2361
                    .map(|k| k.to_string())
2362
                    .collect::<Vec<_>>()
2363
                    .join("\n")
2364
            )
2365
            .as_bytes(),
2366
        );
2367
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2368
    }
2369
    let url = origin_dir.to_string_lossy().to_string();
2370
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2371
        .unwrap()
2372
        .with_home(root.join("home"));
2373
    assert!(a.is_shallow());
2374
    assert_eq!(
2375
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2376
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2377
    );
2378
    assert!(
2379
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2380
        "three levels present"
2381
    );
2382
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2383
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2384
    assert_eq!(
2385
        a.log().unwrap().len(),
2386
        9,
2387
        "the log shows every change from the checkpoint's metadata"
2388
    );
2389
    assert!(!a.snapshot("status").unwrap().changed);
2390
    assert_eq!(a.quick_status().unwrap().heads, 1);
2391
2392
    // Work continues on top of the shallow history and pushes back.
2393
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2394
    let h_new = a.commit("c8", &[]).unwrap();
2395
    assert!(a.push("origin", false).unwrap()[0].ok);
2396
    origin.refresh().unwrap();
2397
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2398
    // Fetching new work from origin into the shallow clone works too.
2399
    write(&origin_dir, "b.txt", b"b\n");
2400
    origin.pull("origin").err();
2401
    let (_, wc) = origin.working_copy().unwrap();
2402
    let _ = wc;
2403
    origin
2404
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2405
        .unwrap();
2406
    write(&origin_dir, "b.txt", b"b\n");
2407
    let h_b = origin.commit("b", &[]).unwrap();
2408
    let pr = a.pull("origin").unwrap();
2409
    assert!(pr.changed);
2410
    assert!(a.store().has(&h_b));
2411
    assert!(root.join("a/b.txt").exists());
2412
2413
    // Deepening fetches older history until the boundary is gone.
2414
    // Every commit also depends on the change that created the file, so two
2415
    // levels below the boundary hold h4, h3, and the root.
2416
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2417
    assert!(a.store().has(&hashes[3]));
2418
    assert!(a.is_shallow());
2419
    a.deepen("origin", 100).unwrap();
2420
    assert!(!a.is_shallow(), "boundary reached the root");
2421
    assert!(a.store().has(&hashes[0]));
2422
    assert_eq!(
2423
        a.load_state_full(&a.bookmark_heads().unwrap())
2424
            .unwrap()
2425
            .len(),
2426
        10
2427
    );
2428
}
2429
2430
#[test]
2431
fn tags_are_immutable_named_states_and_travel() {
2432
    hermetic();
2433
    let dir = tempfile::tempdir().unwrap();
2434
    let root = dir.path();
2435
    let origin = Repo::init(&root.join("origin")).unwrap();
2436
    let url = root.join("origin").to_string_lossy().to_string();
2437
    let mut a = Repo::clone(&url, &root.join("a"))
2438
        .unwrap()
2439
        .with_home(root.join("home-a"));
2440
    let (key_a, _) = a
2441
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2442
        .unwrap();
2443
    write(&root.join("a"), "f.txt", b"1\n");
2444
    let h1 = a.commit("one", &[]).unwrap();
2445
    write(&root.join("a"), "f.txt", b"1\n2\n");
2446
    let h2 = a.commit("two", &[]).unwrap();
2447
2448
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2449
    assert_eq!(
2450
        (t.heads.clone(), t.signer.as_deref()),
2451
        (vec![h1], Some("Ada"))
2452
    );
2453
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2454
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2455
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2456
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2457
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2458
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2459
    assert_eq!(sa.sigs[0].key, key_a);
2460
    // Checkout by tag.
2461
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2462
        .unwrap();
2463
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2464
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2465
        .unwrap();
2466
2467
    // Push carries the tag; a second attestation for the name is refused.
2468
    let r = a.push("origin", false).unwrap();
2469
    origin.refresh().unwrap();
2470
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2471
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2472
    let mut forged = a
2473
        .tag_refs()
2474
        .unwrap()
2475
        .into_iter()
2476
        .find(|t| t.name == "v1")
2477
        .unwrap();
2478
    forged.state = origin
2479
        .store()
2480
        .put_state(&StateObject::new(vec![h2]))
2481
        .unwrap();
2482
    forged.heads = vec![h2];
2483
    forged.attestation = None;
2484
    let r = origin
2485
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2486
        .unwrap();
2487
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2488
2489
    // A clone gets the tag; a later tag arrives on fetch.
2490
    let b = Repo::clone(&url, &root.join("b"))
2491
        .unwrap()
2492
        .with_home(root.join("home-b"));
2493
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2494
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2495
    a.tag_create("v2", &[h2], "second").unwrap();
2496
    a.push("origin", false).unwrap();
2497
    origin.refresh().unwrap();
2498
    let rep = b.fetch("origin").unwrap();
2499
    assert_eq!(rep.new_tags, 1);
2500
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2501
2502
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2503
    a.policy_init().unwrap();
2504
    a.push("origin", false).unwrap();
2505
    origin.refresh().unwrap();
2506
    let unattested = crate::protocol::TagRef {
2507
        name: "v3".into(),
2508
        state: origin
2509
            .store()
2510
            .put_state(&StateObject::new(vec![h2]))
2511
            .unwrap(),
2512
        heads: vec![h2],
2513
        attestation: None,
2514
    };
2515
    let r = origin
2516
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2517
        .unwrap();
2518
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2519
    a.tag_create("v3", &[h2], "").unwrap();
2520
    let r = a.push("origin", false).unwrap();
2521
    origin.refresh().unwrap();
2522
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2523
    assert!(a.gc(true).is_ok());
2524
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2525
2526
    // After a rotation the policy names only the new key, yet a fresh clone
2527
    // still takes the tags the old key made before it; the old key makes
2528
    // nothing new.
2529
    let rot = a.rotate_identity().unwrap();
2530
    let r = a.push("origin", false).unwrap();
2531
    origin.refresh().unwrap();
2532
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2533
    let c = Repo::clone(&url, &root.join("c"))
2534
        .unwrap()
2535
        .with_home(root.join("home-c"));
2536
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
2537
    let (_, sp) = c.current_policy().unwrap().unwrap();
2538
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
2539
    let made = c.identity(&rot.new).unwrap().created;
2540
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
2541
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
2542
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
2543
}
2544
2545
#[test]
2546
fn multiple_workspaces_share_a_repository() {
2547
    hermetic();
2548
    let dir = tempfile::tempdir().unwrap();
2549
    let root = dir.path();
2550
    let main_dir = root.join("main");
2551
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2552
    write(&main_dir, "a.txt", b"a\n");
2553
    let h1 = repo.commit("a", &[]).unwrap();
2554
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2555
2556
    // A second workspace elsewhere, checked out on the bookmark.
2557
    let ws_dir = root.join("ws2");
2558
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2559
    assert!(ws_dir.join(".oxy").is_file());
2560
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2561
    assert_ne!(ws.workspace(), repo.workspace());
2562
    let list = repo.workspaces().unwrap();
2563
    assert_eq!(list.len(), 2);
2564
    assert!(list
2565
        .iter()
2566
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2567
    assert!(!ws.snapshot("status").unwrap().changed);
2568
2569
    // Work in the second workspace: its own working copy, shared bookmark.
2570
    write(&ws_dir, "b.txt", b"b\n");
2571
    let s = ws.snapshot("status").unwrap();
2572
    assert_eq!(s.statuses.len(), 1);
2573
    assert!(
2574
        !repo.snapshot("status").unwrap().changed,
2575
        "the first workspace is untouched"
2576
    );
2577
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2578
    repo.refresh().unwrap();
2579
    let mut heads = repo.bookmark_heads().unwrap();
2580
    heads.sort();
2581
    let mut want = vec![h1, h2];
2582
    want.sort();
2583
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2584
    assert!(!main_dir.join("b.txt").exists());
2585
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2586
        .unwrap();
2587
    assert!(main_dir.join("b.txt").exists());
2588
2589
    // Reopening from inside the second workspace finds the shared repository.
2590
    let reopened = Repo::open(&ws_dir).unwrap();
2591
    assert_eq!(reopened.workspace(), ws.workspace());
2592
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2593
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2594
2595
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2596
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2597
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2598
    repo.workspace_forget(&ws.workspace()).unwrap();
2599
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2600
    assert!(ws_dir.join("b.txt").exists());
2601
    assert!(
2602
        ws.snapshot("status").is_err(),
2603
        "a forgotten workspace is no longer in the view"
2604
    );
2605
2606
    // The working-copy lock: re-entrant in a thread; a lock whose process
2607
    // is gone is taken over, and a live process's is not, however old.
2608
    let lock = repo.lock_snapshot().unwrap();
2609
    let again = repo.lock_working_copy().unwrap();
2610
    drop(again);
2611
    drop(lock);
2612
    let lock_path = main_dir
2613
        .join(".oxy/workspaces")
2614
        .join(repo.workspace().to_hex())
2615
        .join("lock");
2616
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2617
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2618
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2619
    age(&lock_path);
2620
    assert!(
2621
        !super::workspace::lock_is_stale(&lock_path),
2622
        "a live process keeps its lock"
2623
    );
2624
    fs::write(&lock_path, "4294967295").unwrap();
2625
    age(&lock_path);
2626
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2627
}
2628
2629
#[test]
2630
fn attributes_binary_eol_nocompress_lockable() {
2631
    hermetic();
2632
    let dir = tempfile::tempdir().unwrap();
2633
    let root = dir.path();
2634
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2635
    write(
2636
        root,
2637
        ".oxyattributes",
2638
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2639
    );
2640
    write(root, "plain.dat", b"no nul bytes here\n");
2641
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2642
    write(root, "assets/model.bin", b"\0model");
2643
    let h = repo.commit("attrs", &[]).unwrap();
2644
    let snap = repo.load_state(&[h]).unwrap().materialize();
2645
    assert!(
2646
        snap.files["plain.dat"].mode.opaque,
2647
        "binary attribute forces opaque without NUL bytes"
2648
    );
2649
    assert!(
2650
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2651
        "stored with LF"
2652
    );
2653
    assert!(
2654
        !repo.snapshot("status").unwrap().changed,
2655
        "CRLF on disk equals LF in the state"
2656
    );
2657
    // nocompress chunks pack raw.
2658
    let r = repo.gc(true).unwrap();
2659
    assert!(r.packed.objects > 0);
2660
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2661
    fs::remove_file(root.join("notes.txt")).unwrap();
2662
    repo.checkout(&[h], true, "co").unwrap();
2663
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2664
    assert!(fs::metadata(root.join("assets/model.bin"))
2665
        .unwrap()
2666
        .permissions()
2667
        .readonly());
2668
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2669
    repo.lock_path("assets/model.bin").unwrap();
2670
    assert!(!fs::metadata(root.join("assets/model.bin"))
2671
        .unwrap()
2672
        .permissions()
2673
        .readonly());
2674
    assert!(repo.is_locked("assets/model.bin"));
2675
    write(root, "assets/model.bin", b"\0model2");
2676
    repo.commit("edit model", &[]).unwrap();
2677
    repo.unlock_path("assets/model.bin").unwrap();
2678
    assert!(fs::metadata(root.join("assets/model.bin"))
2679
        .unwrap()
2680
        .permissions()
2681
        .readonly());
2682
    // A later checkout can still overwrite a read-only lockable file.
2683
    repo.checkout(&[h], true, "co").unwrap();
2684
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2685
}
2686
2687
#[cfg(unix)]
2688
#[test]
2689
fn hooks_can_veto_observe_and_add_dependencies() {
2690
    use std::os::unix::fs::PermissionsExt;
2691
    hermetic();
2692
    let dir = tempfile::tempdir().unwrap();
2693
    let root = dir.path();
2694
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2695
    let hooks = root.join(".oxy/hooks");
2696
    fs::create_dir_all(&hooks).unwrap();
2697
    let hook = |name: &str, body: &str| {
2698
        let p = hooks.join(name);
2699
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2700
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2701
    };
2702
    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");
2703
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2704
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2705
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2706
    write(root, ".oxyignore", b".last-*\n");
2707
    write(root, "a.txt", b"a\n");
2708
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2709
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2710
    let h1 = repo.commit("first", &[]).unwrap();
2711
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2712
    assert!(
2713
        pre.contains("\"event\":\"pre-commit\"")
2714
            && pre.contains("\"path\":\"a.txt\"")
2715
            && pre.contains("\"message\":\"first\""),
2716
        "{pre}"
2717
    );
2718
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2719
    assert!(post.contains(&h1.to_hex()), "{post}");
2720
    repo.checkout(&[h1], false, "co").unwrap();
2721
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2722
        .unwrap()
2723
        .contains("post-checkout"));
2724
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2725
    repo.save_config().unwrap();
2726
    let err = repo.push("origin", false).unwrap_err().to_string();
2727
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2728
2729
    // semantic-deps: only when enabled; adds an explicit dependency.
2730
    write(root, "b.txt", b"b\n");
2731
    hook(
2732
        "semantic-deps",
2733
        &format!(
2734
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2735
            h1.to_hex()
2736
        ),
2737
    );
2738
    let h2 = repo.commit("b without hook", &[]).unwrap();
2739
    assert!(
2740
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2741
        "hook disabled by default"
2742
    );
2743
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2744
    repo.save_config().unwrap();
2745
    write(root, "c.txt", b"c\n");
2746
    let h3 = repo.commit("c with hook", &[]).unwrap();
2747
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2748
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2749
    assert!(
2750
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2751
        "{sem}"
2752
    );
2753
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2754
}
2755
2756
#[test]
2757
fn amend_into_older_change_and_split() {
2758
    hermetic();
2759
    let dir = tempfile::tempdir().unwrap();
2760
    let root = dir.path();
2761
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2762
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2763
        .unwrap();
2764
    repo.set_user_config("core.sign", "change").unwrap();
2765
    write(root, "a.txt", b"one\ntwo\n");
2766
    let h0 = repo.commit("base", &[]).unwrap();
2767
    write(root, "a.txt", b"one\nTWO\n");
2768
    let h1 = repo.commit("edit two", &[]).unwrap();
2769
    write(root, "a.txt", b"one\nTWO\nthree\n");
2770
    let h2 = repo.commit("add three", &[]).unwrap();
2771
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2772
2773
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2774
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2775
    let h1b = repo.amend_into(&h1, None).unwrap();
2776
    assert_ne!(h1b, h1);
2777
    let c1b = repo.store().get_change(&h1b).unwrap();
2778
    assert_eq!(c1b.change_id, id1);
2779
    assert_eq!(c1b.deps, vec![h0]);
2780
    assert!(matches!(
2781
        repo.verify_change(&h1b).unwrap(),
2782
        SignatureStatus::Valid { .. }
2783
    ));
2784
    let heads = repo.bookmark_heads().unwrap();
2785
    assert_eq!(heads.len(), 1);
2786
    let top = repo.store().get_change(&heads[0]).unwrap();
2787
    assert_eq!(top.message, "add three");
2788
    assert_eq!(
2789
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2790
        [h0, h1b].into_iter().collect(),
2791
        "depends on the file's creator and the rewritten line"
2792
    );
2793
    let snap = repo.load_state(&heads).unwrap().materialize();
2794
    assert!(
2795
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2796
    );
2797
    assert!(
2798
        !repo.snapshot("status").unwrap().changed,
2799
        "the working copy is clean after folding"
2800
    );
2801
    // Only h1b's own state shows the fix without "three".
2802
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2803
    assert!(
2804
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2805
    );
2806
    assert_eq!(repo.log().unwrap().len(), 4);
2807
2808
    // An edit to a line introduced by h2 cannot fold into h1.
2809
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2810
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2811
    assert!(err.contains("introduced after"), "{err}");
2812
    assert!(
2813
        repo.snapshot("status").unwrap().statuses.len() == 1,
2814
        "nothing was changed by the refusal"
2815
    );
2816
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2817
2818
    // Split the head that touches two files.
2819
    write(root, "b.txt", b"b\n");
2820
    write(root, "c.txt", b"c\n");
2821
    let h3 = repo.commit("b and c", &[]).unwrap();
2822
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2823
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2824
    let c_1 = repo.store().get_change(&p1).unwrap();
2825
    let c_2 = repo.store().get_change(&p2).unwrap();
2826
    assert!(c_1.message.contains("part 1: b.txt"));
2827
    assert_eq!(c_2.change_id, id3);
2828
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2829
    assert!(
2830
        heads.contains(&p1) && heads.contains(&p2),
2831
        "independent parts are both heads"
2832
    );
2833
    let snap = repo
2834
        .load_state(&repo.bookmark_heads().unwrap())
2835
        .unwrap()
2836
        .materialize();
2837
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2838
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2839
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2840
    assert!(!repo.snapshot("status").unwrap().changed);
2841
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2842
    let _ = h2;
2843
}
2844
2845
#[test]
2846
fn identity_lifecycle() {
2847
    hermetic();
2848
    let dir = tempfile::tempdir().unwrap();
2849
    let root = dir.path();
2850
    let origin = Repo::init(&root.join("origin")).unwrap();
2851
    let url = root.join("origin").to_string_lossy().to_string();
2852
    let mut a = Repo::clone(&url, &root.join("a"))
2853
        .unwrap()
2854
        .with_home(root.join("home-a"));
2855
    a.set_user_config("core.sign", "change").unwrap();
2856
    let (key_a, _) = a
2857
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2858
        .unwrap();
2859
    write(&root.join("a"), "a.txt", b"a\n");
2860
    let h1 = a.commit("one", &[]).unwrap();
2861
    assert!(a.policy_init().unwrap().applied);
2862
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2863
    origin.refresh().unwrap();
2864
2865
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2866
    let mut e = Repo::init(&root.join("e"))
2867
        .unwrap()
2868
        .with_home(root.join("home-e"));
2869
    e.set_user_config("core.sign", "change").unwrap();
2870
    e.create_identity_with(
2871
        "Eve",
2872
        "[email protected]",
2873
        IdentityScope::User,
2874
        Some(Hlc::now().wall_ms - 1),
2875
    )
2876
    .unwrap();
2877
    write(&root.join("e"), "e.txt", b"e\n");
2878
    let he = e.commit("late", &[]).unwrap();
2879
    assert!(
2880
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2881
    );
2882
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2883
    let r = e
2884
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2885
        .unwrap();
2886
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2887
    write(&root.join("e"), "e.txt", b"e2\n");
2888
    let he2 = e.commit("in time", &[]).unwrap();
2889
    assert!(
2890
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2891
    );
2892
2893
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2894
    let r = a.rotate_identity().unwrap();
2895
    assert_eq!(r.old, key_a);
2896
    assert_eq!(a.config.author_key, Some(r.new));
2897
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2898
    assert!(r.policy.as_ref().unwrap().applied);
2899
    let (_, sp) = a.current_policy().unwrap().unwrap();
2900
    assert_eq!(
2901
        (sp.policy.serial, sp.policy.roots.clone()),
2902
        (2, vec![r.new])
2903
    );
2904
    assert!(
2905
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2906
        "superseded, not revoked"
2907
    );
2908
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2909
    assert!(
2910
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2911
    );
2912
    write(&root.join("a"), "a.txt", b"a2\n");
2913
    let h2 = a.commit("two", &[]).unwrap();
2914
    assert!(
2915
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2916
    );
2917
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2918
    let res = a.push("origin", false).unwrap();
2919
    origin.refresh().unwrap();
2920
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2921
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2922
    let key_a = r.new;
2923
2924
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2925
    // identity object, so Ada's KeyId changes while her keys stay the same.
2926
    let mut b = Repo::clone(&url, &root.join("b"))
2927
        .unwrap()
2928
        .with_home(root.join("home-b"));
2929
    let (key_b, id_b) = b
2930
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2931
        .unwrap();
2932
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
2933
    assert_eq!(r.old, key_a);
2934
    let key_a2 = r.new;
2935
    assert_eq!(
2936
        a.identity(&key_a2).unwrap().delegates,
2937
        vec![Delegate::full(key_b)]
2938
    );
2939
    assert_eq!(
2940
        a.identity(&key_a2).unwrap().ed25519_pk,
2941
        a.identity(&key_a).unwrap().ed25519_pk
2942
    );
2943
    assert!(
2944
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2945
        "already a delegate"
2946
    );
2947
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2948
    origin.refresh().unwrap();
2949
    write(&root.join("a"), "a.txt", b"a3\n");
2950
    let h3 = a.commit("three", &[]).unwrap();
2951
    assert!(
2952
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2953
        "the same secret signs under the new KeyId"
2954
    );
2955
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2956
    a.set_user_config("core.sign", "seal").unwrap();
2957
    write(&root.join("a"), "a.txt", b"a4\n");
2958
    let h4 = a.commit("four", &[]).unwrap();
2959
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2960
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2961
    a.store()
2962
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2963
        .unwrap();
2964
    assert!(
2965
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2966
    );
2967
    a.set_user_config("core.sign", "change").unwrap();
2968
    // Withdrawing the delegation re-issues the identity again.
2969
    let r = a.delegate_remove(&key_b).unwrap();
2970
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2971
    assert!(a.delegate_remove(&key_b).is_err());
2972
    let key_a3 = r.new;
2973
    let res = a.push("origin", false).unwrap();
2974
    origin.refresh().unwrap();
2975
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2976
2977
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2978
    // both applied under the old threshold of 1. A grant then needs Bob too.
2979
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2980
    assert!(a.policy_root_add(id_b.clone()).is_err());
2981
    assert!(a.policy_set_threshold(3).is_err());
2982
    assert!(a.policy_set_threshold(2).unwrap().applied);
2983
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2984
    origin.refresh().unwrap();
2985
    b.pull("origin").unwrap();
2986
    assert_eq!(
2987
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2988
        2
2989
    );
2990
    let mut c = Repo::init(&root.join("c"))
2991
        .unwrap()
2992
        .with_home(root.join("home-c"));
2993
    let (key_c, id_c) = c
2994
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2995
        .unwrap();
2996
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2997
    let proposal = a.policy_grant(id_c, None).unwrap();
2998
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2999
    assert_eq!(proposal.policy.serial, serial_before + 1);
3000
    assert_eq!(
3001
        a.current_policy().unwrap().unwrap().1.policy.serial,
3002
        serial_before,
3003
        "a proposal changes nothing yet"
3004
    );
3005
    // Bob signs the proposal, handed over as a file, and it applies for him.
3006
    let bytes = proposal.signed().encode();
3007
    let signed = b
3008
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
3009
        .unwrap();
3010
    assert!(signed.applied && signed.sigs.len() == 2);
3011
    assert!(b
3012
        .current_policy()
3013
        .unwrap()
3014
        .unwrap()
3015
        .1
3016
        .policy
3017
        .authorizes(&key_c, "main"));
3018
    assert!(
3019
        b.policy_sign(signed.signed()).is_err(),
3020
        "a stale proposal is refused"
3021
    );
3022
    // Bob publishes it and Ada picks it up.
3023
    assert!(b
3024
        .push("origin", false)
3025
        .unwrap()
3026
        .iter()
3027
        .any(|x| x.name == "policy" && x.ok));
3028
    origin.refresh().unwrap();
3029
    a.pull("origin").unwrap();
3030
    assert_eq!(
3031
        a.current_policy().unwrap().unwrap().1.policy.serial,
3032
        serial_before + 1
3033
    );
3034
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3035
    assert!(a.policy_revoke(&key_a3).is_err());
3036
    let u = a
3037
        .revoke_identity(&key_c, "left the project")
3038
        .unwrap()
3039
        .unwrap();
3040
    assert!(!u.applied);
3041
    assert!(a.is_revoked(&key_c).unwrap());
3042
    assert!(!b.is_revoked(&key_c).unwrap());
3043
    let u = b.policy_sign(u.signed()).unwrap();
3044
    assert!(u.applied && u.policy.is_revoked(&key_c));
3045
    assert!(b.is_revoked(&key_c).unwrap());
3046
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
3047
    assert!(
3048
        b.policy_revoke(&key_a3).is_err(),
3049
        "would leave one root for a threshold of 2"
3050
    );
3051
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3052
    let key_c_own = c.config.author_key.unwrap();
3053
    assert!(c
3054
        .revoke_identity(&key_c_own, "lost laptop")
3055
        .unwrap()
3056
        .is_none());
3057
    assert!(c.is_revoked(&key_c_own).unwrap());
3058
    assert_eq!(key_c_own, key_c);
3059
}
3060
3061
#[test]
3062
fn renames_are_detected_and_tracked_as_moves() {
3063
    hermetic();
3064
    let dir = tempfile::tempdir().unwrap();
3065
    let root = dir.path();
3066
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3067
    write(
3068
        root,
3069
        "src/old.rs",
3070
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3071
    );
3072
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3073
    write(root, "tiny.txt", b"x\n");
3074
    let h1 = repo.commit("base", &[]).unwrap();
3075
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3076
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3077
3078
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3079
    // that shares nothing with the removed file.
3080
    fs::remove_file(root.join("src/old.rs")).unwrap();
3081
    write(
3082
        root,
3083
        "lib/new.rs",
3084
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3085
    );
3086
    fs::remove_file(root.join("img.bin")).unwrap();
3087
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3088
    fs::remove_file(root.join("tiny.txt")).unwrap();
3089
    write(root, "other.txt", b"completely different\n");
3090
    let snap = repo.snapshot("status").unwrap();
3091
    let statuses: Vec<(&str, ChangeStatus)> = snap
3092
        .statuses
3093
        .iter()
3094
        .map(|s| (s.path.as_str(), s.status))
3095
        .collect();
3096
    assert_eq!(
3097
        statuses,
3098
        vec![
3099
            ("assets/img.bin", ChangeStatus::Renamed),
3100
            ("lib/new.rs", ChangeStatus::Renamed),
3101
            ("other.txt", ChangeStatus::Added),
3102
            ("src", ChangeStatus::Removed),
3103
            ("tiny.txt", ChangeStatus::Removed)
3104
        ]
3105
    );
3106
    let h2 = repo.commit("move things", &[]).unwrap();
3107
    let c = repo.store().get_change(&h2).unwrap();
3108
    let moves: Vec<_> = c
3109
        .tree_ops
3110
        .iter()
3111
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3112
        .collect();
3113
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3114
    assert!(c.tree_ops.iter().any(
3115
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3116
    ));
3117
    assert!(c.tree_ops.iter().any(
3118
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3119
    ));
3120
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3121
    assert_eq!(
3122
        snap.files["lib/new.rs"].node, node_old,
3123
        "the node survives the rename"
3124
    );
3125
    assert!(
3126
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3127
    );
3128
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3129
    assert!(render_change(
3130
        &c,
3131
        &repo.load_state(&[h1]).unwrap(),
3132
        &repo.load_state(&[h1]).unwrap().materialize()
3133
    )
3134
    .contains("R src/old.rs -> lib/new.rs"));
3135
    // A fresh checkout reproduces the tree.
3136
    let other = tempfile::tempdir().unwrap();
3137
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3138
    assert_eq!(
3139
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3140
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3141
    );
3142
    assert!(!other.path().join("src").exists());
3143
    assert!(!clone.snapshot("status").unwrap().changed);
3144
    // Similarity is line based, byte weighted.
3145
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3146
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3147
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3148
    assert_eq!(similarity(b"", b"x\n"), 0);
3149
}
3150
3151
#[test]
3152
fn git_fetch_and_push_round_trip() {
3153
    hermetic();
3154
    if std::process::Command::new("git")
3155
        .arg("--version")
3156
        .output()
3157
        .is_err()
3158
    {
3159
        eprintln!("git not installed; skipping");
3160
        return;
3161
    }
3162
    let dir = tempfile::tempdir().unwrap();
3163
    let root = dir.path();
3164
    let git_in = |d: &Path, args: &[&str]| -> String {
3165
        let out = std::process::Command::new("git")
3166
            .arg("-C")
3167
            .arg(d)
3168
            .args([
3169
                "-c",
3170
                "user.name=Grace",
3171
                "-c",
3172
                "[email protected]",
3173
                "-c",
3174
                "commit.gpgsign=false",
3175
            ])
3176
            .args(args)
3177
            .output()
3178
            .unwrap();
3179
        assert!(
3180
            out.status.success(),
3181
            "git {args:?}: {}",
3182
            String::from_utf8_lossy(&out.stderr)
3183
        );
3184
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3185
    };
3186
    // A bare "remote" and a work tree that pushes to it.
3187
    let remote = root.join("remote.git");
3188
    fs::create_dir_all(&remote).unwrap();
3189
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3190
    let work = root.join("work");
3191
    git_in(
3192
        root,
3193
        &[
3194
            "clone",
3195
            "-q",
3196
            remote.to_str().unwrap(),
3197
            work.to_str().unwrap(),
3198
        ],
3199
    );
3200
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3201
    write(&work, "README.md", b"# Project\n");
3202
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3203
    git_in(&work, &["add", "."]);
3204
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3205
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3206
    git_in(&work, &["commit", "-q", "-am", "second"]);
3207
    git_in(&work, &["push", "-q", "origin", "main"]);
3208
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3209
3210
    // Fetch into a fresh oxy repository.
3211
    let o = root.join("oxy");
3212
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3213
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3214
        .unwrap();
3215
    let url = remote.to_string_lossy().to_string();
3216
    let r = repo.git_fetch(&url, "main").unwrap();
3217
    assert_eq!((r.commits, r.heads), (2, 1));
3218
    assert_eq!(
3219
        fs::read(o.join("src/lib.rs")).unwrap(),
3220
        b"pub fn a() {}\npub fn b() {}\n"
3221
    );
3222
    assert!(!repo.snapshot("status").unwrap().changed);
3223
    assert_eq!(
3224
        repo.git_fetch(&url, "main").unwrap().commits,
3225
        0,
3226
        "nothing new"
3227
    );
3228
3229
    // An oxy change, pushed back: one commit on top of the Git tip.
3230
    write(
3231
        &o,
3232
        "src/lib.rs",
3233
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3234
    );
3235
    write(&o, "NOTES.md", b"from oxy\n");
3236
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3237
    let r = repo.git_push(&url, "main").unwrap();
3238
    assert_eq!(r.exported, 1, "{r:?}");
3239
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3240
    assert_eq!(
3241
        git_in(&work, &["log", "--format=%s", "main"]),
3242
        "add c and notes\nsecond\ninitial"
3243
    );
3244
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3245
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3246
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3247
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3248
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3249
    assert_eq!(
3250
        repo.git_push(&url, "main").unwrap().exported,
3251
        0,
3252
        "already pushed"
3253
    );
3254
3255
    // Git moves on; pushing without fetching is refused, fetching brings
3256
    // the commit in and the working copy follows.
3257
    write(&work, "README.md", b"# Project\n\nMore.\n");
3258
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3259
    git_in(&work, &["push", "-q", "origin", "main"]);
3260
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3261
    assert!(repo
3262
        .git_push(&url, "main")
3263
        .unwrap_err()
3264
        .to_string()
3265
        .contains("fetch"));
3266
    let r = repo.git_fetch(&url, "main").unwrap();
3267
    assert_eq!(
3268
        (r.commits, r.heads),
3269
        (1, 2),
3270
        "the Git change and the oxy change commute"
3271
    );
3272
    assert_eq!(
3273
        fs::read(o.join("README.md")).unwrap(),
3274
        b"# Project\n\nMore.\n"
3275
    );
3276
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3277
    assert!(!repo.snapshot("status").unwrap().changed);
3278
    // Another oxy change pushes on top of Git's newest commit.
3279
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3280
    repo.commit("notes again", &[]).unwrap();
3281
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3282
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3283
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
3284
    assert_eq!(
3285
        fs::read(work.join("NOTES.md")).unwrap(),
3286
        b"from oxy\nagain\n"
3287
    );
3288
    assert_eq!(
3289
        git_in(&work, &["log", "--format=%s", "main"])
3290
            .lines()
3291
            .count(),
3292
        5
3293
    );
3294
}
3295
3296
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3297
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3298
#[test]
3299
#[ignore]
3300
fn bench_one_gibibyte_file() {
3301
    hermetic();
3302
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3303
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3304
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3305
        None => tempfile::tempdir().unwrap(),
3306
    };
3307
    let root = dir.path();
3308
    let repo = Repo::init(&root.join("r"))
3309
        .unwrap()
3310
        .with_home(root.join("home"));
3311
    let size = 1usize << 30;
3312
    let mut data = vec![0u8; size];
3313
    let mut x = 0x9e3779b97f4a7c15u64;
3314
    for chunk in data.chunks_mut(8) {
3315
        x ^= x << 13;
3316
        x ^= x >> 7;
3317
        x ^= x << 17;
3318
        let b = x.to_le_bytes();
3319
        chunk.copy_from_slice(&b[..chunk.len()]);
3320
    }
3321
    let t = std::time::Instant::now();
3322
    write(&root.join("r"), "big.bin", &data);
3323
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3324
    let t = std::time::Instant::now();
3325
    let h = repo.commit("big", &[]).unwrap();
3326
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3327
    let t = std::time::Instant::now();
3328
    assert!(!repo.snapshot("status").unwrap().changed);
3329
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3330
    let t = std::time::Instant::now();
3331
    let objects = repo.store().list().unwrap().len();
3332
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3333
    let t = std::time::Instant::now();
3334
    let g = repo.gc(true).unwrap();
3335
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3336
    let t = std::time::Instant::now();
3337
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3338
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3339
    let t = std::time::Instant::now();
3340
    let back = fs::read(root.join("c/big.bin")).unwrap();
3341
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3342
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3343
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3344
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
3345
    eprintln!(
3346
        "store size: {:.1} MiB for 1 GiB of data",
3347
        store_bytes as f64 / (1024.0 * 1024.0)
3348
    );
3349
}
3350
3351
fn walkdir_size(p: &Path) -> u64 {
3352
    let mut total = 0;
3353
    if let Ok(rd) = fs::read_dir(p) {
3354
        for e in rd.flatten() {
3355
            let path = e.path();
3356
            if path.is_dir() {
3357
                total += walkdir_size(&path);
3358
            } else if let Ok(m) = fs::metadata(&path) {
3359
                total += m.len();
3360
            }
3361
        }
3362
    }
3363
    total
3364
}
3365
3366
/// An opaque file whose size and mtime match the manifest is not read on
3367
/// the next snapshot: its blob comes from the manifest's stat cache.
3368
#[cfg(unix)]
3369
#[test]
3370
fn stat_cache_skips_reading_unchanged_opaque_files() {
3371
    use std::os::unix::fs::PermissionsExt;
3372
    hermetic();
3373
    let dir = tempfile::tempdir().unwrap();
3374
    let root = dir.path();
3375
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3376
    let mut big = vec![0u8; 300 * 1024];
3377
    for (i, b) in big.iter_mut().enumerate() {
3378
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3379
    }
3380
    big[0] = 0;
3381
    write(root, "big.bin", &big);
3382
    write(root, "a.txt", b"text\n");
3383
    let h1 = repo.commit("base", &[]).unwrap();
3384
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3385
    assert!(
3386
        m.entries["big.bin"].blob.is_some(),
3387
        "opaque files record their blob"
3388
    );
3389
    assert!(m.entries["a.txt"].blob.is_none());
3390
    let blob = m.entries["big.bin"].blob.unwrap();
3391
    assert!(repo.store().has(&blob));
3392
3393
    // Files modified within two seconds of the manifest are racy and still
3394
    // read; age the file so the cache applies, then snapshot to record it.
3395
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3396
    fs::File::options()
3397
        .write(true)
3398
        .open(root.join("big.bin"))
3399
        .unwrap()
3400
        .set_modified(old)
3401
        .unwrap();
3402
    assert!(!repo.snapshot("status").unwrap().changed);
3403
    // Now the file cannot be read at all; the snapshot succeeds without it.
3404
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3405
    let snap = repo.snapshot("status").unwrap();
3406
    assert!(
3407
        !snap.changed && snap.statuses.is_empty(),
3408
        "{:?}",
3409
        snap.statuses
3410
    );
3411
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3412
    // A real change (new mtime, new content) is seen and committed correctly.
3413
    let mut big2 = big.clone();
3414
    big2[10] ^= 0xff;
3415
    write(root, "big.bin", &big2);
3416
    let snap = repo.snapshot("status").unwrap();
3417
    assert_eq!(
3418
        snap.statuses
3419
            .iter()
3420
            .map(|s| (s.path.as_str(), s.status))
3421
            .collect::<Vec<_>>(),
3422
        vec![("big.bin", ChangeStatus::Modified)]
3423
    );
3424
    let h2 = repo.commit("edit", &[]).unwrap();
3425
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3426
    assert_eq!(
3427
        files["big.bin"].content,
3428
        FileContent::Opaque {
3429
            blobs: vec![Repo::blob_ref(&big2)]
3430
        }
3431
    );
3432
    // Checkout writes a manifest with blobs too, so the next status is cached.
3433
    repo.checkout(&[h1], false, "checkout").unwrap();
3434
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3435
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3436
    assert!(!repo.snapshot("status").unwrap().changed);
3437
}
3438
3439
#[test]
3440
fn status_json_lists_conflicts_with_contributors() {
3441
    hermetic();
3442
    let dir = tempfile::tempdir().unwrap();
3443
    let root = dir.path();
3444
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3445
    write(root, "a.txt", b"one\n");
3446
    let h1 = repo.commit("base", &[]).unwrap();
3447
    write(root, "a.txt", b"one\nleft\n");
3448
    let ha = repo.commit("left", &[]).unwrap();
3449
    repo.checkout(&[h1], true, "checkout").unwrap();
3450
    write(root, "a.txt", b"one\nright\n");
3451
    let hb = repo.commit("right", &[]).unwrap();
3452
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3453
    let snap = repo.snapshot("status").unwrap();
3454
    assert!(snap.base_snapshot.is_conflicted());
3455
    let json = repo.status_json(&snap).unwrap();
3456
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3457
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3458
    assert!(json.contains("\"conflicted\":true"), "{json}");
3459
    assert!(
3460
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3461
        "{json}"
3462
    );
3463
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3464
    assert!(json.contains("\"resolved\":false"), "{json}");
3465
    assert!(json.starts_with('{') && json.ends_with('}'));
3466
    // Resolve and the report says so; a clean copy has no conflicts.
3467
    write(root, "a.txt", b"one\nleft\nright\n");
3468
    let snap = repo.snapshot("status").unwrap();
3469
    let json = repo.status_json(&snap).unwrap();
3470
    assert!(json.contains("\"resolved\":true"), "{json}");
3471
    repo.commit("resolve", &[]).unwrap();
3472
    let snap = repo.snapshot("status").unwrap();
3473
    let json = repo.status_json(&snap).unwrap();
3474
    assert!(
3475
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3476
        "{json}"
3477
    );
3478
}
3479
3480
#[test]
3481
fn ignore_rules_do_not_untrack_files() {
3482
    hermetic();
3483
    let dir = tempfile::tempdir().unwrap();
3484
    let root = dir.path();
3485
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3486
    write(root, "src.c", b"int x;\n");
3487
    write(root, "build/out.o", b"\0obj");
3488
    write(root, "sub/keep.log", b"keep\n");
3489
    write(root, "sub/junk.log", b"junk\n");
3490
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3491
    let snap = repo.snapshot("status").unwrap();
3492
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3493
    assert_eq!(
3494
        added,
3495
        vec![".oxyignore", "src.c", "sub/keep.log"],
3496
        "anchored, glob, and negated rules"
3497
    );
3498
    let h1 = repo.commit("base", &[]).unwrap();
3499
    // Ignoring a tracked file changes nothing about it.
3500
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3501
    let snap = repo.snapshot("status").unwrap();
3502
    assert_eq!(
3503
        snap.statuses
3504
            .iter()
3505
            .map(|s| s.path.as_str())
3506
            .collect::<Vec<_>>(),
3507
        vec![".oxyignore"]
3508
    );
3509
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3510
    assert!(repo
3511
        .load_state(&[h2])
3512
        .unwrap()
3513
        .materialize()
3514
        .files
3515
        .contains_key("src.c"));
3516
    // Its edits are still seen, by status and by the prompt.
3517
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3518
    write(root, "src.c", b"int x, y;\n");
3519
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3520
    let snap = repo.snapshot("status").unwrap();
3521
    assert_eq!(
3522
        snap.statuses
3523
            .iter()
3524
            .map(|s| (s.path.as_str(), s.status))
3525
            .collect::<Vec<_>>(),
3526
        vec![("src.c", ChangeStatus::Modified)]
3527
    );
3528
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3529
    assert!(
3530
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3531
    );
3532
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3533
    fs::remove_file(root.join("src.c")).unwrap();
3534
    let snap = repo.snapshot("status").unwrap();
3535
    assert_eq!(
3536
        snap.statuses
3537
            .iter()
3538
            .map(|s| (s.path.as_str(), s.status))
3539
            .collect::<Vec<_>>(),
3540
        vec![("src.c", ChangeStatus::Removed)]
3541
    );
3542
    repo.checkout(&[h3], true, "checkout").unwrap();
3543
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3544
    assert!(!repo.snapshot("status").unwrap().changed);
3545
    let _ = h1;
3546
}
3547
3548
#[test]
3549
fn split_works_on_non_heads_by_node() {
3550
    hermetic();
3551
    let dir = tempfile::tempdir().unwrap();
3552
    let root = dir.path();
3553
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3554
    write(root, "a.txt", b"one\n");
3555
    write(root, "junk/x.lock", b"lock\n");
3556
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3557
    write(root, "a.txt", b"one\ntwo\n");
3558
    let h2 = repo.commit("more work", &[]).unwrap();
3559
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3560
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3561
    // h1 is not a head: split it by node.
3562
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3563
    assert_ne!(h1b, h1);
3564
    assert_eq!(
3565
        repo.store().get_change(&h1b).unwrap().change_id,
3566
        id1,
3567
        "the rest keeps the ChangeId"
3568
    );
3569
    let junk = repo.store().get_change(&hj).unwrap();
3570
    assert!(junk.tree_ops.iter().all(
3571
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3572
    ));
3573
    let heads = repo.bookmark_heads().unwrap();
3574
    assert!(
3575
        heads.contains(&hj),
3576
        "the split-off part is a head of its own"
3577
    );
3578
    let snap = repo.load_state(&heads).unwrap().materialize();
3579
    assert!(
3580
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3581
        "the dependent was rewritten onto the new hash"
3582
    );
3583
    assert!(snap.files.contains_key("junk/x.lock"));
3584
    let h2b = heads
3585
        .iter()
3586
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3587
        .copied()
3588
        .unwrap();
3589
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3590
    assert!(!repo.snapshot("status").unwrap().changed);
3591
    // Abandoning the split-off head removes the junk from history.
3592
    repo.abandon(&hj).unwrap();
3593
    let heads = repo.bookmark_heads().unwrap();
3594
    let snap = repo.load_state(&heads).unwrap().materialize();
3595
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3596
    assert!(snap.files.contains_key("a.txt"));
3597
    // A dependent that touches the split-off paths blocks the split.
3598
    write(root, "junk/y.lock", b"y\n");
3599
    let hb = repo.commit("junk base", &[]).unwrap();
3600
    write(root, "junk/y.lock", b"yy\n");
3601
    write(root, "b.txt", b"b\n");
3602
    repo.commit("touches junk", &[]).unwrap();
3603
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3604
    assert!(err.contains("depends on the split-off paths"), "{err}");
3605
}
3606
3607
#[test]
3608
fn bookmarks_switch_merge_and_push() {
3609
    hermetic();
3610
    let dir = tempfile::tempdir().unwrap();
3611
    let root = dir.path();
3612
    let origin = Repo::init(&root.join("origin")).unwrap();
3613
    let url = root.join("origin").to_string_lossy().to_string();
3614
    let mut repo = Repo::clone(&url, &root.join("r"))
3615
        .unwrap()
3616
        .with_home(root.join("home"));
3617
    let r = root.join("r");
3618
    write(&r, "a.txt", b"a\n");
3619
    let h_a = repo.commit("a", &[]).unwrap();
3620
    assert!(repo.push("origin", false).unwrap()[0].ok);
3621
    origin.refresh().unwrap();
3622
3623
    // A bookmark at the working copy's base, then work on it.
3624
    assert!(repo.bookmark_create("bad name..", None).is_err());
3625
    assert!(repo.bookmark_create("-x", None).is_err());
3626
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3627
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3628
    repo.bookmark_switch("feature", false).unwrap();
3629
    assert_eq!(repo.config.bookmark, "feature");
3630
    write(&r, "a.txt", b"a\nb\n");
3631
    write(&r, "b.txt", b"b\n");
3632
    let h_b = repo.commit("b on feature", &[]).unwrap();
3633
    assert_eq!(
3634
        repo.bookmark_heads().unwrap(),
3635
        vec![h_b],
3636
        "b edits a.txt, so it depends on a"
3637
    );
3638
    assert_eq!(
3639
        repo.resolve_heads("main").unwrap(),
3640
        vec![h_a],
3641
        "main is untouched"
3642
    );
3643
    assert_eq!(
3644
        repo.resolve_change("feature").unwrap(),
3645
        h_b,
3646
        "a one-head bookmark names its change"
3647
    );
3648
    // Reopening keeps the workspace's bookmark.
3649
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3650
    assert_eq!(reopened.config.bookmark, "feature");
3651
    // Back to main: b.txt goes away; work there.
3652
    repo.bookmark_switch("main", false).unwrap();
3653
    assert!(!r.join("b.txt").exists());
3654
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3655
    write(&r, "c.txt", b"c\n");
3656
    let h_c = repo.commit("c on main", &[]).unwrap();
3657
    let list = repo.bookmarks().unwrap();
3658
    assert_eq!(
3659
        list.iter()
3660
            .map(|b| (b.name.as_str(), b.current))
3661
            .collect::<Vec<_>>(),
3662
        vec![("feature", false), ("main", true)]
3663
    );
3664
    assert_eq!(
3665
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3666
        Some(1),
3667
        "c is not on origin yet"
3668
    );
3669
    // Merge feature into main: the union, both heads, no merge change.
3670
    let m = repo.merge("feature").unwrap();
3671
    assert!(m.changed && m.checked_out);
3672
    let mut want = vec![h_b, h_c];
3673
    want.sort();
3674
    assert_eq!(m.heads, want);
3675
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3676
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3677
    assert!(repo.merge("main").is_err());
3678
    // The other bookmark can be pushed by name and appears at origin.
3679
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3680
    origin.refresh().unwrap();
3681
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3682
    assert!(repo.push("origin", false).unwrap()[0].ok);
3683
    origin.refresh().unwrap();
3684
    assert_eq!(
3685
        repo.bookmarks()
3686
            .unwrap()
3687
            .iter()
3688
            .find(|b| b.name == "main")
3689
            .unwrap()
3690
            .ahead,
3691
        Some(0)
3692
    );
3693
    // A second workspace inherits the current bookmark and can switch independently.
3694
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3695
    assert_eq!(ws.config.bookmark, "main");
3696
    let mut ws = ws;
3697
    ws.bookmark_switch("feature", false).unwrap();
3698
    assert_eq!(
3699
        Repo::open(&r).unwrap().config.bookmark,
3700
        "main",
3701
        "the first workspace is unaffected"
3702
    );
3703
    assert!(
3704
        repo.bookmark_delete("feature").is_err(),
3705
        "current bookmark of another workspace"
3706
    );
3707
    ws.bookmark_switch("main", false).unwrap();
3708
    // Set and delete.
3709
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3710
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3711
    repo.bookmark_delete("feature").unwrap();
3712
    assert!(repo.resolve_heads("feature").is_err());
3713
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3714
    assert!(
3715
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3716
        "changes of a deleted bookmark remain"
3717
    );
3718
}
3719
3720
#[test]
3721
fn oxygen_subrepos_pin_follow_and_update() {
3722
    hermetic();
3723
    let dir = tempfile::tempdir().unwrap();
3724
    let root = dir.path();
3725
    // A library repository with two commits, and a bare-ish origin for it.
3726
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3727
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3728
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3729
        .unwrap()
3730
        .with_home(root.join("home"));
3731
    write(&root.join("lib"), "lib.txt", b"v1\n");
3732
    let l1 = lib.commit("lib v1", &[]).unwrap();
3733
    assert!(lib.push("origin", false).unwrap()[0].ok);
3734
    let _ = lib_origin;
3735
3736
    // The application (a clone of its own origin) adds it as a subrepo.
3737
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3738
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3739
    let _ = app_origin;
3740
    let app_dir = root.join("app");
3741
    let app = Repo::clone(&app_url, &app_dir)
3742
        .unwrap()
3743
        .with_home(root.join("home"));
3744
    write(&app_dir, "main.txt", b"app\n");
3745
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3746
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3747
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3748
    let snap = app.snapshot("status").unwrap();
3749
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3750
    assert_eq!(
3751
        paths,
3752
        vec![".oxymodules", "libs/lib", "main.txt"],
3753
        "the nested files are not walked"
3754
    );
3755
    let a1 = app.commit("app with lib", &[]).unwrap();
3756
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3757
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3758
    assert!(!files.contains_key("libs/lib/lib.txt"));
3759
    assert!(!app.snapshot("status").unwrap().changed);
3760
    let subs = app.subrepos().unwrap();
3761
    assert_eq!(subs.len(), 1);
3762
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3763
3764
    // Advance the nested repository: the parent sees a modified pin.
3765
    let nested = Repo::open(&app_dir.join("libs/lib"))
3766
        .unwrap()
3767
        .with_home(root.join("home"));
3768
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3769
    let l2 = nested.commit("lib v2", &[]).unwrap();
3770
    assert!(nested.push("origin", false).unwrap()[0].ok);
3771
    let snap = app.snapshot("status").unwrap();
3772
    assert_eq!(
3773
        snap.statuses
3774
            .iter()
3775
            .map(|s| (s.path.as_str(), s.status))
3776
            .collect::<Vec<_>>(),
3777
        vec![("libs/lib", ChangeStatus::Modified)]
3778
    );
3779
    let a2 = app.commit("bump lib", &[]).unwrap();
3780
    // Checking out the older app state brings the nested working copy back
3781
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3782
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3783
    assert!(
3784
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3785
        "{:?}",
3786
        r.notes
3787
    );
3788
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3789
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3790
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3791
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3792
    assert!(!app.snapshot("status").unwrap().changed);
3793
    // A dirty nested repository is left alone and reported.
3794
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3795
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3796
    assert!(
3797
        r.notes.iter().any(|n| n.contains("uncommitted")),
3798
        "{:?}",
3799
        r.notes
3800
    );
3801
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3802
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3803
    let r = app.submodule_update(false, &[]).unwrap();
3804
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3805
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3806
    let _ = l2;
3807
3808
    // A fresh clone of the app has the pin but no nested repository until update --init.
3809
    assert!(app.push("origin", false).unwrap()[0].ok);
3810
    let clone_dir = root.join("app-clone");
3811
    let clone = Repo::clone(&app_url, &clone_dir)
3812
        .unwrap()
3813
        .with_home(root.join("home"));
3814
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3815
    assert_eq!(
3816
        clone.submodule_update(false, &[]).unwrap(),
3817
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3818
    );
3819
    assert_eq!(
3820
        clone.submodule_update(true, &[]).unwrap(),
3821
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3822
    );
3823
    assert_eq!(
3824
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3825
        b"v2\n"
3826
    );
3827
    assert!(!clone.snapshot("status").unwrap().changed);
3828
    // Removing the subrepo leaves the directory and drops the node.
3829
    clone.submodule_remove("libs/lib").unwrap();
3830
    let snap = clone.snapshot("status").unwrap();
3831
    assert!(
3832
        snap.statuses
3833
            .iter()
3834
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3835
        "{:?}",
3836
        snap.statuses
3837
    );
3838
    let c = clone.commit("drop lib", &[]).unwrap();
3839
    assert!(!clone
3840
        .load_state(&[c])
3841
        .unwrap()
3842
        .materialize()
3843
        .files
3844
        .contains_key("libs/lib"));
3845
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3846
    assert!(
3847
        !clone.snapshot("status").unwrap().changed,
3848
        "an unregistered nested repository is ignored"
3849
    );
3850
}
3851
3852
#[test]
3853
fn git_submodules_import_and_export_as_gitlinks() {
3854
    hermetic();
3855
    if std::process::Command::new("git")
3856
        .arg("--version")
3857
        .output()
3858
        .is_err()
3859
    {
3860
        eprintln!("git not installed; skipping");
3861
        return;
3862
    }
3863
    let dir = tempfile::tempdir().unwrap();
3864
    let root = dir.path();
3865
    let git_in = |d: &Path, args: &[&str]| -> String {
3866
        let out = std::process::Command::new("git")
3867
            .arg("-C")
3868
            .arg(d)
3869
            .args([
3870
                "-c",
3871
                "user.name=Grace",
3872
                "-c",
3873
                "[email protected]",
3874
                "-c",
3875
                "commit.gpgsign=false",
3876
                "-c",
3877
                "protocol.file.allow=always",
3878
            ])
3879
            .args(args)
3880
            .output()
3881
            .unwrap();
3882
        assert!(
3883
            out.status.success(),
3884
            "git {args:?}: {}",
3885
            String::from_utf8_lossy(&out.stderr)
3886
        );
3887
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3888
    };
3889
    let sub = root.join("sub");
3890
    fs::create_dir_all(&sub).unwrap();
3891
    git_in(&sub, &["init", "-q", "-b", "main"]);
3892
    write(&sub, "s.txt", b"sub\n");
3893
    git_in(&sub, &["add", "."]);
3894
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3895
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3896
    let g = root.join("main.git");
3897
    fs::create_dir_all(&g).unwrap();
3898
    git_in(&g, &["init", "-q", "-b", "main"]);
3899
    write(&g, "README.md", b"# app\n");
3900
    git_in(&g, &["add", "."]);
3901
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3902
    git_in(
3903
        &g,
3904
        &[
3905
            "submodule",
3906
            "add",
3907
            "-q",
3908
            sub.to_str().unwrap(),
3909
            "vendor/sub",
3910
        ],
3911
    );
3912
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3913
3914
    let dest = root.join("oxy");
3915
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3916
    let rep = repo.import_git(&g, "main").unwrap();
3917
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3918
    let files = repo
3919
        .load_state(&repo.bookmark_heads().unwrap())
3920
        .unwrap()
3921
        .materialize()
3922
        .files;
3923
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3924
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3925
        panic!()
3926
    };
3927
    assert_eq!(
3928
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3929
        crate::subrepo::Pin::Git {
3930
            sha: sub_sha.clone(),
3931
            branch: "HEAD".into()
3932
        }
3933
    );
3934
    let modules =
3935
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3936
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3937
    assert!(modules.entries["vendor/sub"].git);
3938
    assert!(
3939
        files.contains_key(".gitmodules"),
3940
        "the Git file is kept for round trips"
3941
    );
3942
    assert!(
3943
        !dest.join("vendor/sub/.git").exists(),
3944
        "not cloned until update --init"
3945
    );
3946
    assert!(!repo.snapshot("status").unwrap().changed);
3947
    // update --init clones it at the pinned commit; status is unchanged.
3948
    assert_eq!(
3949
        repo.submodule_update(true, &[]).unwrap(),
3950
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3951
    );
3952
    assert_eq!(
3953
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3954
        sub_sha
3955
    );
3956
    assert!(!repo.snapshot("status").unwrap().changed);
3957
    // Export writes the gitlink and .gitmodules back.
3958
    let mirror = root.join("mirror.git");
3959
    let rep = repo.git_export(&mirror).unwrap();
3960
    assert_eq!(rep.skipped_subrepos, 0);
3961
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3962
    assert!(
3963
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3964
        "{ls}"
3965
    );
3966
    assert_eq!(
3967
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3968
        ".gitmodules\nREADME.md\nvendor"
3969
    );
3970
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3971
    assert_eq!(
3972
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3973
        orig_tree,
3974
        "tree round trip"
3975
    );
3976
}
3977
3978
#[test]
3979
fn partial_commits_by_path_and_by_hunk() {
3980
    hermetic();
3981
    let dir = tempfile::tempdir().unwrap();
3982
    let root = dir.path();
3983
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3984
    write(root, "a.txt", b"1\n2\n3\n");
3985
    write(root, "b.txt", b"b\n");
3986
    let h0 = repo.commit("base", &[]).unwrap();
3987
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3988
    write(root, "b.txt", b"b\nbb\n");
3989
    write(root, "c.txt", b"c\n");
3990
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3991
    let h1 = repo
3992
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3993
        .unwrap();
3994
    let c1 = repo.store().get_change(&h1).unwrap();
3995
    assert!(
3996
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3997
        "{:?}",
3998
        c1.tree_ops
3999
    );
4000
    assert_eq!(c1.deps, vec![h0]);
4001
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
4002
    assert!(
4003
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
4004
    );
4005
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
4006
    assert!(!files.contains_key("c.txt"));
4007
    let snap = repo.snapshot("status").unwrap();
4008
    assert_eq!(
4009
        snap.statuses
4010
            .iter()
4011
            .map(|s| (s.path.as_str(), s.status))
4012
            .collect::<Vec<_>>(),
4013
        vec![
4014
            ("b.txt", ChangeStatus::Modified),
4015
            ("c.txt", ChangeStatus::Added)
4016
        ]
4017
    );
4018
    assert_eq!(
4019
        fs::read(root.join("b.txt")).unwrap(),
4020
        b"b\nbb\n",
4021
        "disk untouched"
4022
    );
4023
    // By hunk: pick the b.txt insert; c.txt's addition is left.
4024
    let (_, hunks) = repo.hunks().unwrap();
4025
    let b_hunk = hunks
4026
        .iter()
4027
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
4028
        .unwrap()
4029
        .index;
4030
    let h2 = repo
4031
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4032
        .unwrap();
4033
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4034
    assert!(
4035
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4036
    );
4037
    assert!(!files.contains_key("c.txt"));
4038
    let snap = repo.snapshot("status").unwrap();
4039
    assert_eq!(
4040
        snap.statuses
4041
            .iter()
4042
            .map(|s| s.path.as_str())
4043
            .collect::<Vec<_>>(),
4044
        vec!["c.txt"]
4045
    );
4046
    // Choosing only the content hunk of a file in a new directory pulls in
4047
    // the directory and file additions it needs.
4048
    write(root, "d/e.txt", b"e\n");
4049
    let (_, hunks) = repo.hunks().unwrap();
4050
    let e_insert = hunks
4051
        .iter()
4052
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4053
        .unwrap()
4054
        .index;
4055
    let h3 = repo
4056
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4057
        .unwrap();
4058
    let c3 = repo.store().get_change(&h3).unwrap();
4059
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4060
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4061
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
4062
    // Choosing a new file's addition hunk brings its content along.
4063
    write(root, "f/g.txt", b"g\n");
4064
    let (_, hunks) = repo.hunks().unwrap();
4065
    let g_add = hunks
4066
        .iter()
4067
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4068
        .unwrap()
4069
        .index;
4070
    let h4 = repo
4071
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4072
        .unwrap();
4073
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4074
    assert!(
4075
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4076
    );
4077
    assert!(!repo
4078
        .snapshot("status")
4079
        .unwrap()
4080
        .statuses
4081
        .iter()
4082
        .any(|s| s.path == "f/g.txt"));
4083
    // Everything left commits normally; the working copy is then clean.
4084
    repo.commit("the rest", &[]).unwrap();
4085
    assert!(!repo.snapshot("status").unwrap().changed);
4086
    let files = repo
4087
        .load_state(&repo.bookmark_heads().unwrap())
4088
        .unwrap()
4089
        .materialize()
4090
        .files;
4091
    assert!(files.contains_key("c.txt"));
4092
}
4093
4094
#[test]
4095
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4096
    hermetic();
4097
    let dir = tempfile::tempdir().unwrap();
4098
    let root = dir.path();
4099
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4100
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4101
        .unwrap();
4102
    write(root, "a.txt", b"one\n");
4103
    let h1 = repo.commit("first", &[]).unwrap();
4104
    write(root, "a.txt", b"one\ntwo\n");
4105
    let h2 = repo.commit("second", &[]).unwrap();
4106
    let b = repo.blame("a.txt").unwrap();
4107
    assert_eq!(
4108
        b.iter()
4109
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4110
            .collect::<Vec<_>>(),
4111
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4112
    );
4113
    assert!(b.iter().all(|l| l.author == "Ada"));
4114
    assert_eq!(
4115
        b[0].change_id,
4116
        repo.store().get_change(&h1).unwrap().change_id
4117
    );
4118
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4119
    repo.commit("rename", &[]).unwrap();
4120
    let b = repo.blame("b.txt").unwrap();
4121
    assert_eq!(
4122
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4123
        vec![h1, h2],
4124
        "the node survives the rename"
4125
    );
4126
    assert!(repo.blame("a.txt").is_err());
4127
}
4128
4129
#[test]
4130
fn bisect_finds_the_first_bad_change() {
4131
    hermetic();
4132
    let dir = tempfile::tempdir().unwrap();
4133
    let root = dir.path();
4134
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4135
    let mut content = String::new();
4136
    let mut hashes = Vec::new();
4137
    for i in 1..=8 {
4138
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4139
        write(root, "f.txt", content.as_bytes());
4140
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4141
    }
4142
    // Each step appends after the previous line, so the chain is linear.
4143
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4144
    repo.bisect_start().unwrap();
4145
    assert!(matches!(
4146
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4147
        BisectStep::NeedMarks { good: 1, bad: 0 }
4148
    ));
4149
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4150
    assert!(
4151
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4152
        "{step:?}"
4153
    );
4154
    // Automated: bad when the bug line is present.
4155
    let step = repo
4156
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4157
        .unwrap();
4158
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4159
    assert_eq!(
4160
        repo.bisect_status().unwrap(),
4161
        Some(BisectStep::Found { culprit: hashes[4] })
4162
    );
4163
    repo.bisect_reset().unwrap();
4164
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4165
    assert!(repo.bisect_status().unwrap().is_none());
4166
    assert!(!repo.snapshot("status").unwrap().changed);
4167
    // Manual marks and a skip.
4168
    repo.bisect_start().unwrap();
4169
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4170
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4171
    let mut skipped_once = false;
4172
    let mut guard = 0;
4173
    while let BisectStep::Testing { .. } = step {
4174
        guard += 1;
4175
        assert!(guard < 20);
4176
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4177
        if !skipped_once && text.contains("line 6") {
4178
            // An untestable state away from the boundary: the search routes around it.
4179
            skipped_once = true;
4180
            step = repo.bisect_mark(None, &[]).unwrap();
4181
            continue;
4182
        }
4183
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4184
    }
4185
    assert!(skipped_once);
4186
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4187
    repo.bisect_reset().unwrap();
4188
    // Skipping the culprit itself leaves it among the candidates reported.
4189
    repo.bisect_start().unwrap();
4190
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4191
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4192
    let mut guard = 0;
4193
    while let BisectStep::Testing { heads, .. } = &step {
4194
        guard += 1;
4195
        assert!(guard < 20);
4196
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4197
        let is_culprit_state =
4198
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4199
        step = if is_culprit_state {
4200
            repo.bisect_mark(None, &[]).unwrap()
4201
        } else {
4202
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4203
        };
4204
    }
4205
    match step {
4206
        BisectStep::Inconclusive { candidates } => assert!(
4207
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4208
            "{candidates:?}"
4209
        ),
4210
        other => panic!("{other:?}"),
4211
    }
4212
    repo.bisect_reset().unwrap();
4213
}
4214
4215
#[test]
4216
fn squash_folds_a_change_into_its_dependency() {
4217
    hermetic();
4218
    let dir = tempfile::tempdir().unwrap();
4219
    let root = dir.path();
4220
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4221
    write(root, "a.txt", b"1\n");
4222
    let a = repo.commit("A", &[]).unwrap();
4223
    write(root, "a.txt", b"1\n2\n");
4224
    let c = repo.commit("C", &[]).unwrap();
4225
    write(root, "a.txt", b"1\n2\n3\n");
4226
    let e = repo.commit("E", &[]).unwrap();
4227
    write(root, "b.txt", b"b\n");
4228
    let b = repo.commit("B", &[]).unwrap();
4229
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4230
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4231
    // E depends on C which A lacks: refused, naming it.
4232
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4233
    assert!(err.contains(&c.short(12)), "{err}");
4234
    // C into A: A' has both, C is gone, E follows and still reads the same.
4235
    let a2 = repo.squash(&c, &a).unwrap();
4236
    let a2c = repo.store().get_change(&a2).unwrap();
4237
    assert_eq!(a2c.change_id, id_a);
4238
    assert!(a2c.deps.is_empty());
4239
    let heads = repo.bookmark_heads().unwrap();
4240
    let st = repo.load_state(&heads).unwrap();
4241
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4242
    let e2 = st
4243
        .changes()
4244
        .find(|(_, m)| m.change_id == id_e)
4245
        .map(|(h, _)| *h)
4246
        .unwrap();
4247
    assert_eq!(
4248
        repo.store().get_change(&e2).unwrap().deps,
4249
        vec![a2],
4250
        "E now depends on A' alone"
4251
    );
4252
    let files = st.materialize().files;
4253
    assert!(
4254
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4255
    );
4256
    assert!(files.contains_key("b.txt"));
4257
    assert!(st.contains(&b));
4258
    assert!(!repo.snapshot("status").unwrap().changed);
4259
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4260
    // Undo restores the three original changes.
4261
    repo.undo().unwrap();
4262
    repo.undo().unwrap();
4263
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4264
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4265
}
4266
4267
#[test]
4268
fn rebase_re_expresses_a_change_against_another_base() {
4269
    hermetic();
4270
    let dir = tempfile::tempdir().unwrap();
4271
    let root = dir.path();
4272
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4273
    write(root, "a.txt", b"1\n2\n");
4274
    let a = repo.commit("A", &[]).unwrap();
4275
    write(root, "a.txt", b"1\n2\n3\n");
4276
    let c = repo.commit("C: append 3", &[]).unwrap();
4277
    write(root, "a.txt", b"1\n2\n3\n4\n");
4278
    let e = repo.commit("E: append 4", &[]).unwrap();
4279
    // A different base: A plus a change that prepends a line.
4280
    repo.checkout(&[a], true, "checkout").unwrap();
4281
    write(root, "a.txt", b"0\n1\n2\n");
4282
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4283
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4284
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4285
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4286
    let c2 = repo.rebase(&c, &[d]).unwrap();
4287
    let c2c = repo.store().get_change(&c2).unwrap();
4288
    assert_eq!(c2c.change_id, id_c);
4289
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4290
    let heads = repo.bookmark_heads().unwrap();
4291
    let st = repo.load_state(&heads).unwrap();
4292
    assert!(!st.contains(&c) && st.contains(&d));
4293
    let e2 = st
4294
        .changes()
4295
        .find(|(_, m)| m.change_id == id_e)
4296
        .map(|(h, _)| *h)
4297
        .unwrap();
4298
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
4299
    assert!(
4300
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4301
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4302
    );
4303
    let files = st.materialize().files;
4304
    assert!(
4305
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4306
        "{:?}",
4307
        files["a.txt"].content
4308
    );
4309
    assert!(!files["a.txt"].is_conflicted());
4310
    // Rebasing onto a state that already contains the change is refused.
4311
    assert!(repo.rebase(&c2, &[c2]).is_err());
4312
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
4313
    assert!(
4314
        err.contains("lacks dependencies"),
4315
        "E needs C, which D's state does not have: {err}"
4316
    );
4317
}
4318
4319
#[test]
4320
fn unsigned_tags_keep_their_message() {
4321
    hermetic();
4322
    let dir = tempfile::tempdir().unwrap();
4323
    let root = dir.path();
4324
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4325
    write(root, "a.txt", b"a\n");
4326
    repo.commit("a", &[]).unwrap();
4327
    assert!(repo.secret_key().unwrap().is_none());
4328
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4329
        .unwrap();
4330
    let tags = repo.tags().unwrap();
4331
    assert_eq!(
4332
        (
4333
            tags[0].name.as_str(),
4334
            tags[0].message.as_str(),
4335
            tags[0].signer.as_deref()
4336
        ),
4337
        ("v1", "first release", None)
4338
    );
4339
    assert!(
4340
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4341
        "an unsigned attestation is not advertised"
4342
    );
4343
}
4344
4345
#[test]
4346
fn fsck_passes_a_sound_repository_and_names_each_fault() {
4347
    // Files on disk are what this tests: tampering with them, and the
4348
    // directory store's crash points.
4349
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4350
        return;
4351
    }
4352
    hermetic();
4353
    let dir = tempfile::tempdir().unwrap();
4354
    let root = dir.path();
4355
    let origin_path = root.join("origin");
4356
    let origin = Repo::init(&origin_path).unwrap();
4357
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4358
        .unwrap()
4359
        .with_home(root.join("home-a"));
4360
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4361
        .unwrap();
4362
    write(&root.join("a"), "f.txt", b"one\n");
4363
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4364
    let h1 = a.commit("first", &[]).unwrap();
4365
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4366
    let h2 = a.commit("second", &[]).unwrap();
4367
    a.tag_create("v1", &[h2], "first release").unwrap();
4368
    a.checkpoint().unwrap();
4369
    assert!(a.push("origin", false).unwrap()[0].ok);
4370
    origin.refresh().unwrap();
4371
4372
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4373
    for repo in [&a, &origin] {
4374
        let rep = repo.fsck().unwrap();
4375
        assert_eq!(rep.problems, vec![], "{rep:?}");
4376
        // The two commits, plus the working copy's change in `a`.
4377
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4378
        assert!(rep.ops > 1 && rep.objects > 5);
4379
    }
4380
    assert!(origin.fsck().unwrap().attestations >= 1);
4381
4382
    // A flipped byte in a stored object is corruption, named by hash.
4383
    let c1 = a.store().path_for(&h1);
4384
    let pristine = fs::read(&c1).unwrap();
4385
    let mut bytes = pristine.clone();
4386
    *bytes.last_mut().unwrap() ^= 1;
4387
    fs::write(&c1, &bytes).unwrap();
4388
    let rep = a.fsck().unwrap();
4389
    assert!(rep.errors() >= 1);
4390
    assert!(
4391
        rep.problems
4392
            .iter()
4393
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4394
        "{rep:?}"
4395
    );
4396
    fs::write(&c1, &pristine).unwrap();
4397
    assert_eq!(a.fsck().unwrap().errors(), 0);
4398
4399
    // A missing change is named with what needed it.
4400
    fs::remove_file(&c1).unwrap();
4401
    let rep = a.fsck().unwrap();
4402
    assert!(
4403
        rep.problems.iter().any(|p| p.severity == Severity::Error
4404
            && p.object == Some(h1)
4405
            && p.what.contains("change missing, needed by change")),
4406
        "{rep:?}"
4407
    );
4408
    fs::write(&c1, &pristine).unwrap();
4409
4410
    // A missing blob is an error in a full clone.
4411
    let c2 = a.store().get_change(&h1).unwrap();
4412
    let blob = c2
4413
        .edits
4414
        .iter()
4415
        .find_map(|e| match e {
4416
            Edit::Replace { new: Some(b), .. } => Some(*b),
4417
            _ => None,
4418
        })
4419
        .expect("the binary file is a blob");
4420
    let bp = a.store().path_for(&blob);
4421
    let blob_bytes = fs::read(&bp).unwrap();
4422
    fs::remove_file(&bp).unwrap();
4423
    let rep = a.fsck().unwrap();
4424
    assert!(
4425
        rep.problems
4426
            .iter()
4427
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4428
        "{rep:?}"
4429
    );
4430
    fs::write(&bp, &blob_bytes).unwrap();
4431
4432
    // A broken op log head is reported, not a crash.
4433
    let head = root.join("a/.oxy/ops/head");
4434
    let saved = fs::read(&head).unwrap();
4435
    fs::write(&head, b"not a hash").unwrap();
4436
    let rep = a.fsck().unwrap();
4437
    assert!(
4438
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4439
        "{rep:?}"
4440
    );
4441
    fs::write(&head, saved).unwrap();
4442
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4443
}
4444
4445
/// Copy a directory tree (for restoring a pristine repository).
4446
fn copy_tree(from: &Path, to: &Path) {
4447
    fs::create_dir_all(to).unwrap();
4448
    for e in fs::read_dir(from).unwrap() {
4449
        let e = e.unwrap();
4450
        let target = to.join(e.file_name());
4451
        if e.file_type().unwrap().is_dir() {
4452
            copy_tree(&e.path(), &target);
4453
        } else {
4454
            fs::copy(e.path(), &target).unwrap();
4455
        }
4456
    }
4457
}
4458
4459
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4460
/// would, and check that both repositories still open, pass `fsck`, and
4461
/// accept the same operation again.
4462
#[test]
4463
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4464
    // Files on disk are what this tests: tampering with them, and the
4465
    // directory store's crash points.
4466
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4467
        return;
4468
    }
4469
    use crate::durable::failpoint;
4470
    hermetic();
4471
    let dir = tempfile::tempdir().unwrap();
4472
    let pristine = dir.path().join("pristine");
4473
    let origin_path = pristine.join("origin");
4474
    Repo::init(&origin_path).unwrap();
4475
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4476
        .unwrap()
4477
        .with_home(dir.path().join("home"));
4478
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4479
        .unwrap();
4480
    write(&pristine.join("a"), "f.txt", b"one\n");
4481
    a.commit("first", &[]).unwrap();
4482
    assert!(a.push("origin", false).unwrap()[0].ok);
4483
    drop(a);
4484
4485
    type Op = fn(&Repo) -> Result<()>;
4486
    let edit_and_commit: Op = |r| {
4487
        write(r.root(), "f.txt", b"one\ntwo\n");
4488
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4489
        r.commit("second", &[]).map(|_| ())
4490
    };
4491
    let push: Op = |r| {
4492
        let res = r.push("origin", false)?;
4493
        if res.iter().all(|x| x.ok) {
4494
            Ok(())
4495
        } else {
4496
            Err(RepoError::Msg(format!("{res:?}")))
4497
        }
4498
    };
4499
4500
    for (name, prepare, op) in [
4501
        ("commit", None, edit_and_commit),
4502
        ("push", Some(edit_and_commit), push),
4503
    ] {
4504
        let mut steps = 0;
4505
        for n in 1.. {
4506
            let run = dir.path().join(format!("{name}-{n}"));
4507
            copy_tree(&pristine, &run);
4508
            // Clones record their remote by path; point it at this copy.
4509
            let open = |p: &Path| {
4510
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4511
                r.config
4512
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4513
                    .unwrap();
4514
                r.save_config().unwrap();
4515
                r
4516
            };
4517
            let a = open(&run.join("a"));
4518
            if let Some(prep) = prepare {
4519
                prep(&a).unwrap();
4520
            }
4521
            failpoint::crash_after(n);
4522
            let outcome = op(&a);
4523
            let crashed = failpoint::disarm();
4524
            drop(a);
4525
            if !crashed {
4526
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4527
                steps = n - 1;
4528
                break;
4529
            }
4530
            assert!(
4531
                outcome.is_err(),
4532
                "{name}: a crash at step {n} was swallowed"
4533
            );
4534
            for repo in ["a", "origin"] {
4535
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4536
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4537
                });
4538
                let rep = r.fsck().unwrap();
4539
                assert_eq!(
4540
                    rep.errors(),
4541
                    0,
4542
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4543
                    rep.problems
4544
                );
4545
            }
4546
            // The interrupted operation can simply be run again.
4547
            let a = open(&run.join("a"));
4548
            // A crash after the commit point leaves the commit done.
4549
            let landed = a
4550
                .bookmark_heads()
4551
                .unwrap()
4552
                .iter()
4553
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4554
            let again = match (name, landed) {
4555
                ("commit", true) => Ok(()),
4556
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4557
                _ => op(&a),
4558
            };
4559
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4560
            assert_eq!(a.fsck().unwrap().errors(), 0);
4561
            fs::remove_dir_all(&run).unwrap();
4562
        }
4563
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4564
    }
4565
}
4566
4567
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4568
/// running at the same time lose nothing: every commit ends up on the
4569
/// bookmark, locally and on the remote, and the repository passes fsck.
4570
#[test]
4571
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4572
    hermetic();
4573
    let dir = tempfile::tempdir().unwrap();
4574
    let root = dir.path();
4575
    let origin = root.join("origin");
4576
    Repo::init_bare_unbound(&origin).unwrap();
4577
    let main = root.join("main");
4578
    let mut repo = Repo::init(&main).unwrap();
4579
    repo.config
4580
        .set("remote.origin.url", &origin.to_string_lossy())
4581
        .unwrap();
4582
    repo.save_config().unwrap();
4583
    write(&main, "seed.txt", b"seed\n");
4584
    repo.commit("seed", &[]).unwrap();
4585
    let second = root.join("second");
4586
    repo.workspace_add(&second, None).unwrap();
4587
    drop(repo);
4588
4589
    const EACH: usize = 15;
4590
    std::thread::scope(|s| {
4591
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4592
            s.spawn(move || {
4593
                let r = Repo::open(&dir).unwrap();
4594
                for i in 0..EACH {
4595
                    write(
4596
                        &dir,
4597
                        &format!("{tag}-{i}.txt"),
4598
                        format!("{tag} {i}\n").as_bytes(),
4599
                    );
4600
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4601
                    if push && i % 5 == 4 {
4602
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4603
                        let _ = r.push("origin", false);
4604
                    }
4605
                }
4606
            });
4607
        }
4608
    });
4609
4610
    let repo = Repo::open(&main).unwrap();
4611
    let heads = repo.bookmark_heads().unwrap();
4612
    let state = repo.load_state(&heads).unwrap();
4613
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4614
    for tag in ["a", "b"] {
4615
        for i in 0..EACH {
4616
            assert!(
4617
                messages.contains(&format!("{tag} {i}")),
4618
                "lost commit {tag} {i}; have {messages:?}"
4619
            );
4620
        }
4621
    }
4622
    let rep = repo.fsck().unwrap();
4623
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4624
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4625
    let hosted = Repo::open(&origin).unwrap();
4626
    let hosted_heads = hosted.bookmark_heads().unwrap();
4627
    assert_eq!(
4628
        hosted.load_state(&hosted_heads).unwrap().len(),
4629
        state.len(),
4630
        "the remote has every commit"
4631
    );
4632
}
4633
4634
/// Two operations recorded from the same parent (what two processes do
4635
/// when they race) are merged: both bookmarks' heads survive, and a
4636
/// change made on one side only is kept.
4637
#[test]
4638
fn operations_from_the_same_parent_are_merged() {
4639
    hermetic();
4640
    let dir = tempfile::tempdir().unwrap();
4641
    let root = dir.path();
4642
    let repo = Repo::init(root).unwrap();
4643
    write(root, "a.txt", b"a\n");
4644
    let a = repo.commit("a", &[]).unwrap();
4645
    write(root, "b.txt", b"b\n");
4646
    let b = repo.commit("b", &[]).unwrap();
4647
    let (x, op) = repo.head_op().unwrap();
4648
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4649
4650
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4651
    let mut one = op.view.clone();
4652
    one.bookmarks.insert("main".into(), state(vec![a]));
4653
    one.bookmarks.insert("topic".into(), state(vec![a]));
4654
    let mut two = op.view.clone();
4655
    two.bookmarks.insert("main".into(), state(vec![b]));
4656
    repo.record_op(&[x], "one", one).unwrap();
4657
    let merged = repo.record_op(&[x], "two", two).unwrap();
4658
4659
    let (head, op) = repo.head_op().unwrap();
4660
    assert_eq!(head, merged);
4661
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4662
    assert!(op.command.contains("merged with a concurrent operation"));
4663
    let mut main = repo
4664
        .store()
4665
        .get_state(&op.view.bookmarks["main"])
4666
        .unwrap()
4667
        .heads;
4668
    main.sort();
4669
    let mut want = vec![a, b];
4670
    want.sort();
4671
    assert_eq!(main, want, "both sides' heads are kept");
4672
    assert!(
4673
        op.view.bookmarks.contains_key("topic"),
4674
        "a one-sided change survives"
4675
    );
4676
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4677
}
4678
4679
#[test]
4680
fn failed_requests_come_with_a_next_step() {
4681
    use crate::protocol::hint_for;
4682
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4683
        .unwrap()
4684
        .contains("token"));
4685
    assert!(hint_for("…: HTTP 403: forbidden")
4686
        .unwrap()
4687
        .contains("repo:write"));
4688
    assert!(hint_for("…: HTTP 404: no such repository")
4689
        .unwrap()
4690
        .contains("owner and repository name"));
4691
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4692
        .unwrap()
4693
        .contains("oxyhub-ca.pem"));
4694
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4695
        .unwrap()
4696
        .contains("running"));
4697
    assert!(hint_for("Dns Failed: failed to lookup address information")
4698
        .unwrap()
4699
        .contains("resolve"));
4700
    assert_eq!(hint_for("something else entirely"), None);
4701
}
4702
4703
#[test]
4704
fn doctor_names_problems_and_what_to_do() {
4705
    hermetic();
4706
    let dir = tempfile::tempdir().unwrap();
4707
    let root = dir.path();
4708
    let origin = root.join("origin");
4709
    Repo::init_bare_unbound(&origin).unwrap();
4710
    let mut repo = Repo::init(&root.join("r"))
4711
        .unwrap()
4712
        .with_home(root.join("home"));
4713
    let find = |r: &DoctorReport, area: &str, h: Health| {
4714
        r.checks
4715
            .iter()
4716
            .find(|c| c.area == area && c.health == h)
4717
            .cloned()
4718
    };
4719
4720
    let r = repo.doctor(true);
4721
    assert!(find(&r, "identity", Health::Warn)
4722
        .unwrap()
4723
        .hint
4724
        .unwrap()
4725
        .contains("oxy identity create"));
4726
    assert!(find(&r, "repository", Health::Ok).is_some());
4727
4728
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4729
        .unwrap();
4730
    repo.config.set("author.name", "Ada").unwrap();
4731
    repo.config.set("author.email", "[email protected]").unwrap();
4732
    repo.config
4733
        .set("remote.origin.url", &origin.to_string_lossy())
4734
        .unwrap();
4735
    repo.config
4736
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4737
        .unwrap();
4738
    repo.config.set("remote.down.token", "t").unwrap();
4739
    repo.config
4740
        .set("remote.badca.url", "https://example.invalid/a/b")
4741
        .unwrap();
4742
    repo.config
4743
        .set(
4744
            "remote.badca.ca",
4745
            &root.join("missing.pem").to_string_lossy(),
4746
        )
4747
        .unwrap();
4748
    repo.save_config().unwrap();
4749
4750
    let r = repo.doctor(true);
4751
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4752
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4753
    assert!(find(&r, "remote origin", Health::Ok)
4754
        .unwrap()
4755
        .message
4756
        .contains("first push binds it"));
4757
    let down = find(&r, "remote down", Health::Fail).unwrap();
4758
    assert!(
4759
        down.hint.as_deref().unwrap_or("").contains("running"),
4760
        "{down:?}"
4761
    );
4762
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4763
    assert!(
4764
        badca.hint.unwrap().contains("remote.badca.ca"),
4765
        "the remote's own name is in the hint"
4766
    );
4767
    assert_eq!(r.worst(), Health::Fail);
4768
4769
    // Offline, nothing is contacted.
4770
    let r = repo.doctor(false);
4771
    assert!(find(&r, "remote down", Health::Fail).is_none());
4772
    assert!(find(&r, "remote down", Health::Ok)
4773
        .unwrap()
4774
        .message
4775
        .contains("not contacted"));
4776
}
4777
4778
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4779
/// after it. Inserting after `b` and then deleting `b`, one commit after
4780
/// the other, must not leave a delete/insert conflict.
4781
#[test]
4782
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4783
    hermetic();
4784
    let dir = tempfile::tempdir().unwrap();
4785
    let root = dir.path();
4786
    let repo = Repo::init(root).unwrap();
4787
    write(root, "f", b"a\nb\nc\n");
4788
    repo.commit("base", &[]).unwrap();
4789
    write(root, "f", b"a\nb\nx\nc\n");
4790
    let insert = repo.commit("insert x after b", &[]).unwrap();
4791
    write(root, "f", b"a\nx\nc\n");
4792
    let delete = repo.commit("delete b", &[]).unwrap();
4793
    assert!(
4794
        repo.store()
4795
            .get_change(&delete)
4796
            .unwrap()
4797
            .deps
4798
            .contains(&insert),
4799
        "the deletion depends on the insertion below the deleted line"
4800
    );
4801
    let heads = repo.bookmark_heads().unwrap();
4802
    assert_eq!(heads, vec![delete]);
4803
    let snap = repo.load_state(&heads).unwrap().materialize();
4804
    assert!(!snap.is_conflicted());
4805
    assert!(
4806
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4807
    );
4808
}
4809
4810
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4811
/// replacement depends on the change that set the blob it replaces.
4812
#[test]
4813
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4814
    hermetic();
4815
    let dir = tempfile::tempdir().unwrap();
4816
    let root = dir.path();
4817
    let repo = Repo::init(root).unwrap();
4818
    write(root, "bin", b"\0A");
4819
    let v1 = repo.commit("v1", &[]).unwrap();
4820
    write(root, "bin", b"\0B");
4821
    let v2 = repo.commit("v2", &[]).unwrap();
4822
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4823
    write(root, "bin", b"\0A");
4824
    let v3 = repo.commit("back to A", &[]).unwrap();
4825
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4826
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4827
    let state = repo.load_state(&[v3]).unwrap();
4828
    let snap = state.materialize();
4829
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4830
        panic!("opaque")
4831
    };
4832
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4833
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4834
}
4835
4836
/// Spec §23: a binary file changed on two branches and merged in Git to
4837
/// one side's version comes back as that version at the merge, and the
4838
/// import verifies commit by commit.
4839
#[test]
4840
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4841
    hermetic();
4842
    if std::process::Command::new("git")
4843
        .arg("--version")
4844
        .output()
4845
        .is_err()
4846
    {
4847
        eprintln!("git not installed; skipping");
4848
        return;
4849
    }
4850
    let dir = tempfile::tempdir().unwrap();
4851
    let root = dir.path();
4852
    let g = root.join("src.git");
4853
    fs::create_dir_all(&g).unwrap();
4854
    let git = |args: &[&str]| -> String {
4855
        let out = std::process::Command::new("git")
4856
            .arg("-C")
4857
            .arg(&g)
4858
            .args([
4859
                "-c",
4860
                "user.name=Grace",
4861
                "-c",
4862
                "[email protected]",
4863
                "-c",
4864
                "commit.gpgsign=false",
4865
            ])
4866
            .args(args)
4867
            .output()
4868
            .unwrap();
4869
        assert!(
4870
            out.status.success(),
4871
            "git {args:?}: {}",
4872
            String::from_utf8_lossy(&out.stderr)
4873
        );
4874
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4875
    };
4876
    git(&["init", "-q", "-b", "main"]);
4877
    write(&g, "logo.bin", b"\0base");
4878
    write(&g, "notes.txt", b"a\nb\nc\n");
4879
    git(&["add", "."]);
4880
    git(&["commit", "-qm", "base"]);
4881
    git(&["checkout", "-qb", "side"]);
4882
    write(&g, "logo.bin", b"\0side");
4883
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4884
    git(&["commit", "-qam", "side"]);
4885
    git(&["checkout", "-q", "main"]);
4886
    write(&g, "logo.bin", b"\0main");
4887
    git(&["commit", "-qam", "main"]);
4888
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4889
    let _ = std::process::Command::new("git")
4890
        .arg("-C")
4891
        .arg(&g)
4892
        .args([
4893
            "-c",
4894
            "user.name=G",
4895
            "-c",
4896
            "user.email=g@e",
4897
            "merge",
4898
            "-q",
4899
            "side",
4900
        ])
4901
        .output();
4902
    write(&g, "logo.bin", b"\0main");
4903
    git(&["add", "."]);
4904
    git(&["commit", "-qm", "merge side"]);
4905
    // Then a revert of the binary to its first version.
4906
    write(&g, "logo.bin", b"\0base");
4907
    git(&["commit", "-qam", "back to base"]);
4908
4909
    let repo = Repo::init(&root.join("o")).unwrap();
4910
    let rep = repo.import_git(&g, "main").unwrap();
4911
    assert_eq!(rep.merges, 1);
4912
    let v = repo.verify_git_import(&g, "main").unwrap();
4913
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4914
    assert_eq!(v.commits, 5);
4915
    let snap = repo
4916
        .load_state(&repo.bookmark_heads().unwrap())
4917
        .unwrap()
4918
        .materialize();
4919
    assert!(!snap.is_conflicted());
4920
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4921
        panic!("opaque")
4922
    };
4923
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4924
}
4925
4926
/// Spec §7.7 on a file system without executable bits or symlinks: the
4927
/// recorded bit is kept, and a symlink checked out as a plain file holding
4928
/// its target is still that symlink.
4929
#[cfg(unix)]
4930
#[test]
4931
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4932
    use crate::portable::Platform;
4933
    use std::os::unix::fs::PermissionsExt;
4934
    hermetic();
4935
    let dir = tempfile::tempdir().unwrap();
4936
    let root = dir.path();
4937
    let repo = Repo::init(root).unwrap();
4938
    write(root, "run.sh", b"#!/bin/sh\n");
4939
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4940
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4941
    repo.commit("script and link", &[]).unwrap();
4942
    drop(repo);
4943
4944
    // What checking out on Windows leaves: no exec bit, the link as a file.
4945
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4946
    fs::remove_file(root.join("link")).unwrap();
4947
    write(root, "link", b"run.sh");
4948
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4949
    let s = win.snapshot("oxy status").unwrap();
4950
    assert!(
4951
        s.statuses.is_empty(),
4952
        "nothing changed on Windows: {:?}",
4953
        statuses(&s)
4954
    );
4955
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4956
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4957
    write(root, "link", b"other");
4958
    let h = win.commit("edit on Windows", &[]).unwrap();
4959
    let snap = win.load_state(&[h]).unwrap().materialize();
4960
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4961
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4962
    // The same working copy read as Linux sees the lost bit and the plain file.
4963
    let linux = Repo::open(root).unwrap();
4964
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4965
}
4966
4967
/// Paths that collide on case-insensitive or Windows file systems are
4968
/// named at checkout there, and by doctor everywhere.
4969
#[test]
4970
fn paths_other_platforms_cannot_hold_are_reported() {
4971
    use crate::portable::Platform;
4972
    hermetic();
4973
    let dir = tempfile::tempdir().unwrap();
4974
    let root = dir.path();
4975
    let repo = Repo::init(root).unwrap();
4976
    write(root, "README.md", b"a\n");
4977
    write(root, "readme.md", b"b\n");
4978
    write(root, "src/aux.c", b"int x;\n");
4979
    let h = repo.commit("unportable", &[]).unwrap();
4980
    let r = repo.doctor(false);
4981
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4982
    assert_eq!(port.health, Health::Warn);
4983
    assert!(
4984
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4985
        "{}",
4986
        port.message
4987
    );
4988
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4989
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4990
    assert!(
4991
        rep.notes
4992
            .iter()
4993
            .any(|n| n.contains("README.md and readme.md")),
4994
        "{:?}",
4995
        rep.notes
4996
    );
4997
    assert!(
4998
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4999
        "macOS allows aux.c"
5000
    );
5001
}
5002
5003
#[test]
5004
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
5005
    hermetic();
5006
    let dir = tempfile::tempdir().unwrap();
5007
    let repo = Repo::init(dir.path()).unwrap();
5008
    write(dir.path(), "a.txt", b"one\n");
5009
    write(dir.path(), "other.txt", b"x\n");
5010
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
5011
    repo.snapshot("t").unwrap();
5012
    let c1 = repo.commit("first", &[]).unwrap();
5013
    write(dir.path(), "other.txt", b"y\n");
5014
    repo.snapshot("t").unwrap();
5015
    repo.commit("other only", &[]).unwrap();
5016
    write(dir.path(), "a.txt", b"one\ntwo\n");
5017
    repo.snapshot("t").unwrap();
5018
    let c3 = repo.commit("second line", &[]).unwrap();
5019
    write(dir.path(), "other.txt", b"z\n");
5020
    repo.snapshot("t").unwrap();
5021
    repo.commit("other again", &[]).unwrap();
5022
5023
    let heads = repo.bookmark_heads().unwrap();
5024
    let state = repo.load_state(&heads).unwrap();
5025
    let full: Vec<ChangeHash> = repo
5026
        .log_for_path_in("a.txt", &heads)
5027
        .unwrap()
5028
        .iter()
5029
        .map(|e| e.hash)
5030
        .collect();
5031
    assert_eq!(
5032
        full,
5033
        vec![c3, c1],
5034
        "newest first, only changes touching the path"
5035
    );
5036
    let newest: Vec<ChangeHash> = repo
5037
        .log_for_path_of(&state, "a.txt", Some(1))
5038
        .unwrap()
5039
        .iter()
5040
        .map(|e| e.hash)
5041
        .collect();
5042
    assert_eq!(newest, vec![c3], "stops at the first");
5043
    assert_eq!(
5044
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5045
        2
5046
    );
5047
    assert!(repo
5048
        .log_for_path_of(&state, "missing.txt", Some(1))
5049
        .is_err());
5050
    assert_eq!(
5051
        repo.log_state(&heads).unwrap().len(),
5052
        repo.log_of(&state).len()
5053
    );
5054
5055
    let tree = state.tree().view();
5056
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5057
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5058
    assert_eq!(
5059
        via_state
5060
            .iter()
5061
            .map(|l| (l.hash, l.text.clone()))
5062
            .collect::<Vec<_>>(),
5063
        via_heads
5064
            .iter()
5065
            .map(|l| (l.hash, l.text.clone()))
5066
            .collect::<Vec<_>>()
5067
    );
5068
    assert_eq!(
5069
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5070
        vec![c1, c3]
5071
    );
5072
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5073
}
5074
5075
/// A text file whose stat matches the manifest and whose recorded hash is
5076
/// the base's content is taken from the base without reading it; anything
5077
/// else is read, so no edit is missed (spec §12.3).
5078
#[cfg(unix)]
5079
#[test]
5080
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5081
    use std::os::unix::fs::PermissionsExt;
5082
    hermetic();
5083
    let dir = tempfile::tempdir().unwrap();
5084
    let root = dir.path();
5085
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5086
    write(root, "a.txt", b"one\ntwo\n");
5087
    write(root, "b.txt", b"bee\n");
5088
    repo.commit("base", &[]).unwrap();
5089
    let age = |p: &str| {
5090
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5091
        fs::File::options()
5092
            .write(true)
5093
            .open(root.join(p))
5094
            .unwrap()
5095
            .set_modified(old)
5096
            .unwrap();
5097
    };
5098
    age("a.txt");
5099
    age("b.txt");
5100
    assert!(
5101
        !repo.snapshot("status").unwrap().changed,
5102
        "records the aged stat"
5103
    );
5104
5105
    // Clean and equal to the base: not read at all.
5106
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5107
    let snap = repo.snapshot("status").unwrap();
5108
    assert!(
5109
        !snap.changed && snap.statuses.is_empty(),
5110
        "{:?}",
5111
        snap.statuses
5112
    );
5113
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5114
5115
    // An uncommitted edit that is older than the manifest: stat-clean, but
5116
    // its hash is not the base's, so it is read and stays visible.
5117
    write(root, "b.txt", b"bee edited\n");
5118
    age("b.txt");
5119
    let first = repo.snapshot("status").unwrap();
5120
    assert_eq!(
5121
        statuses(&first),
5122
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5123
    );
5124
    let again = repo.snapshot("status").unwrap();
5125
    assert_eq!(
5126
        statuses(&again),
5127
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5128
        "still seen once stat-clean"
5129
    );
5130
    assert!(!again.changed, "and the working copy hashes the same");
5131
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5132
    assert!(
5133
        repo.snapshot("status").is_err(),
5134
        "an edited file must be read, never taken from the base"
5135
    );
5136
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5137
5138
    // A same-size edit made just now is racy and read.
5139
    write(root, "a.txt", b"one\nTWO\n");
5140
    assert_eq!(
5141
        statuses(&repo.snapshot("status").unwrap()),
5142
        vec![
5143
            ("a.txt".to_string(), ChangeStatus::Modified),
5144
            ("b.txt".to_string(), ChangeStatus::Modified)
5145
        ]
5146
    );
5147
    // Committing makes the edits the base: both are clean and served from it again.
5148
    repo.commit("edits", &[]).unwrap();
5149
    age("a.txt");
5150
    age("b.txt");
5151
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5152
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5153
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5154
    let snap = repo.snapshot("status").unwrap();
5155
    assert!(!snap.changed && snap.statuses.is_empty());
5156
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5157
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5158
}
5159
5160
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5161
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5162
/// file is unchanged, and loading through the checkpoint equals a full load.
5163
#[test]
5164
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5165
    hermetic();
5166
    let dir = tempfile::tempdir().unwrap();
5167
    let root = dir.path();
5168
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5169
    let long: String = (0..300)
5170
        .map(|i| format!("line {i} of a long file\n"))
5171
        .collect();
5172
    write(root, "long.txt", long.as_bytes());
5173
    write(root, "short.txt", b"short\n");
5174
    repo.commit("base", &[]).unwrap();
5175
    let (r1, _, _) = repo.checkpoint().unwrap();
5176
    let cp1 = crate::objects::Checkpoint::decode(
5177
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5178
    )
5179
    .unwrap();
5180
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5181
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5182
5183
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5184
    repo.gc(true).unwrap();
5185
    assert!(repo.store().has(&graphs1[0]));
5186
    let report = repo.fsck().unwrap();
5187
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5188
5189
    // Loading through the checkpoint equals a full load.
5190
    write(root, "short.txt", b"short, edited\n");
5191
    repo.commit("edit the short file", &[]).unwrap();
5192
    let heads = repo.bookmark_heads().unwrap();
5193
    let fast = repo.load_state(&heads).unwrap();
5194
    let full = repo.load_state_full(&heads).unwrap();
5195
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5196
5197
    // The next checkpoint shares the unchanged long file's graph.
5198
    let (r2, _, _) = repo.checkpoint().unwrap();
5199
    let cp2 = crate::objects::Checkpoint::decode(
5200
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5201
    )
5202
    .unwrap();
5203
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5204
5205
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5206
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5207
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5208
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5209
5210
    // A version 1 checkpoint written by an older oxy still loads.
5211
    let state = repo.load_state_full(&heads).unwrap();
5212
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5213
    let cp_old = crate::objects::Checkpoint {
5214
        heads: cp2.heads.clone(),
5215
        count: cp2.count,
5216
        payload: old,
5217
    };
5218
    let r_old = repo
5219
        .store()
5220
        .put(ObjectType::Checkpoint, &cp_old.encode())
5221
        .unwrap();
5222
    repo.install_checkpoint("main", &r_old).unwrap();
5223
    assert_eq!(
5224
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5225
        full.checkpoint_payload()
5226
    );
5227
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5228
5229
    // A lost graph blob fails the load loudly rather than dropping the
5230
    // file, and fsck reports it (a fresh repository, objects still loose).
5231
    let dir2 = tempfile::tempdir().unwrap();
5232
    let root2 = dir2.path();
5233
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5234
    write(root2, "long.txt", long.as_bytes());
5235
    repo2.commit("base", &[]).unwrap();
5236
    let (r, _, _) = repo2.checkpoint().unwrap();
5237
    let cp = crate::objects::Checkpoint::decode(
5238
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5239
    )
5240
    .unwrap();
5241
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5242
    repo2.store().remove_loose_for_test(&graph).unwrap();
5243
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5244
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5245
}
5246
5247
/// A new repository has not stored the user's identity yet (that happens
5248
/// at the first signed change); looking it up falls back to the key
5249
/// directory, and a file there that does not hash to the key is refused.
5250
#[test]
5251
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5252
    hermetic();
5253
    let dir = tempfile::tempdir().unwrap();
5254
    let home = dir.path().join("home");
5255
    let mut first = Repo::init(&dir.path().join("a"))
5256
        .unwrap()
5257
        .with_home(home.clone());
5258
    let (key, _) = first
5259
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5260
        .unwrap();
5261
    let fresh = Repo::init(&dir.path().join("b"))
5262
        .unwrap()
5263
        .with_home(home.clone());
5264
    assert!(!fresh.store().has(&key), "nothing stored yet");
5265
    let id = fresh.identity(&key).unwrap();
5266
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5267
    // A key file that is not this identity is an error, not a wrong answer.
5268
    let keys = fresh.keys_dir.clone();
5269
    let (other, _) = first
5270
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5271
        .unwrap();
5272
    fs::copy(
5273
        keys.join(format!("{}.identity", other.to_hex())),
5274
        keys.join(format!("{}.identity", key.to_hex())),
5275
    )
5276
    .unwrap();
5277
    assert!(fresh
5278
        .identity(&key)
5279
        .unwrap_err()
5280
        .to_string()
5281
        .contains("does not hold identity"));
5282
}
5283
5284
/// Status snapshots (spec §12.3): a text file whose stat matches the
5285
/// manifest, and whose base graph key is the one the manifest recorded it
5286
/// equal to, is neither read nor rendered; any edit, and any change to the
5287
/// file's graph in the base, brings it back.
5288
#[cfg(unix)]
5289
#[test]
5290
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5291
    use std::os::unix::fs::PermissionsExt;
5292
    hermetic();
5293
    let dir = tempfile::tempdir().unwrap();
5294
    let root = dir.path();
5295
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5296
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5297
        write(root, p, c.as_bytes());
5298
    }
5299
    repo.commit("base", &[]).unwrap();
5300
    let age = |p: &str| {
5301
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5302
        fs::File::options()
5303
            .write(true)
5304
            .open(root.join(p))
5305
            .unwrap()
5306
            .set_modified(old)
5307
            .unwrap();
5308
    };
5309
    let lock = |p: &str, mode: u32| {
5310
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5311
    };
5312
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5313
        age(p);
5314
    }
5315
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5316
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5317
    assert!(
5318
        m.entries.values().all(|e| e.graph.is_some()),
5319
        "keys recorded"
5320
    );
5321
5322
    // Unreadable files prove they are not read; the status snapshot does
5323
    // not render them either, and its base lacks their graphs.
5324
    lock("a.txt", 0o000);
5325
    lock("b.txt", 0o000);
5326
    let snap = repo.snapshot_status("status").unwrap();
5327
    assert!(!snap.changed && snap.statuses.is_empty());
5328
    assert_eq!(
5329
        snap.base_snapshot
5330
            .unrendered
5331
            .iter()
5332
            .cloned()
5333
            .collect::<Vec<_>>(),
5334
        vec!["a.txt", "b.txt", "d/c.txt"]
5335
    );
5336
    assert!(!snap.base.is_full());
5337
    assert!(!snap.base_snapshot.is_conflicted());
5338
    // A full snapshot does not read them either, but renders everything.
5339
    let full = repo.snapshot("status").unwrap();
5340
    assert!(full.statuses.is_empty() && full.base.is_full());
5341
    assert!(full.base_snapshot.unrendered.is_empty());
5342
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5343
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5344
5345
    // An edit is seen; the file is rendered, the others still are not.
5346
    write(root, "d/c.txt", b"sea edited\n");
5347
    let snap = repo.snapshot_status("status").unwrap();
5348
    assert_eq!(
5349
        statuses(&snap),
5350
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5351
    );
5352
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5353
    // So is a mode change of an unread file.
5354
    lock("b.txt", 0o100);
5355
    assert_eq!(
5356
        statuses(&repo.snapshot_status("status").unwrap()),
5357
        vec![
5358
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5359
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5360
        ]
5361
    );
5362
    lock("b.txt", 0o000);
5363
5364
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5365
    // stays unread, c.txt is read once and then skipped too.
5366
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5367
        .unwrap();
5368
    age("d/c.txt");
5369
    let snap = repo.snapshot_status("status").unwrap();
5370
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5371
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5372
    lock("d/c.txt", 0o000);
5373
    let snap = repo.snapshot_status("status").unwrap();
5374
    assert!(snap.statuses.is_empty());
5375
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5376
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5377
        lock(p, 0o644);
5378
    }
5379
}
5380
5381
/// Attributes decide how a file compares with the base, so a changed
5382
/// `.oxyattributes` makes every text file be compared again.
5383
#[cfg(unix)]
5384
#[test]
5385
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5386
    hermetic();
5387
    let dir = tempfile::tempdir().unwrap();
5388
    let root = dir.path();
5389
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5390
    write(root, "a.txt", b"crlf\r\n");
5391
    repo.commit("base", &[]).unwrap();
5392
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5393
    fs::File::options()
5394
        .write(true)
5395
        .open(root.join("a.txt"))
5396
        .unwrap()
5397
        .set_modified(old)
5398
        .unwrap();
5399
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5400
    assert!(repo
5401
        .snapshot_status("status")
5402
        .unwrap()
5403
        .base_snapshot
5404
        .unrendered
5405
        .contains("a.txt"));
5406
    // With eol=lf, a.txt as stored no longer equals the base.
5407
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5408
    let snap = repo.snapshot_status("status").unwrap();
5409
    assert_eq!(
5410
        statuses(&snap),
5411
        vec![
5412
            (".oxyattributes".to_string(), ChangeStatus::Added),
5413
            ("a.txt".to_string(), ChangeStatus::Modified)
5414
        ]
5415
    );
5416
}
5417
5418
/// Bookmarks with `/` in their names: pushing records their
5419
/// attestations, and checkpoints are kept for them, beside `feature`
5420
/// itself.
5421
#[test]
5422
fn bookmarks_with_slashes_push_and_checkpoint() {
5423
    hermetic();
5424
    let dir = tempfile::tempdir().unwrap();
5425
    let root = dir.path();
5426
    let origin = Repo::init(&root.join("origin")).unwrap();
5427
    let url = root.join("origin").to_string_lossy().to_string();
5428
    let mut repo = Repo::clone(&url, &root.join("r"))
5429
        .unwrap()
5430
        .with_home(root.join("home"));
5431
    // With an identity, pushes carry reference attestations: the case
5432
    // that failed, since the attestation is a file named after the bookmark.
5433
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5434
        .unwrap();
5435
    let r = root.join("r");
5436
    write(&r, "a.txt", b"a\n");
5437
    let h_a = repo.commit("a", &[]).unwrap();
5438
    assert!(repo.push("origin", false).unwrap()[0].ok);
5439
    origin.refresh().unwrap();
5440
    repo.bookmark_create("feature", None).unwrap();
5441
    repo.bookmark_create("feature/x", None).unwrap();
5442
    repo.bookmark_switch("feature/x", false).unwrap();
5443
    write(&r, "b.txt", b"b\n");
5444
    let h_b = repo.commit("b", &[]).unwrap();
5445
    for name in ["feature", "feature/x"] {
5446
        let res = repo.push_bookmark("origin", name, false).unwrap();
5447
        origin.refresh().unwrap();
5448
        assert!(res[0].ok, "{name}: {res:?}");
5449
    }
5450
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5451
    assert_eq!(
5452
        origin.resolve_heads("feature/x").unwrap(),
5453
        repo.resolve_heads("feature/x").unwrap()
5454
    );
5455
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5456
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5457
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5458
5459
    // A checkpoint of feature/x is found again when loading its state.
5460
    let (cp, _, _) = repo.checkpoint().unwrap();
5461
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5462
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5463
    let heads = repo.resolve_heads("feature/x").unwrap();
5464
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5465
}
5466
5467
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5468
/// never the remote's own bookmark, and a bookmark created again later is
5469
/// accepted although the deletion's attestation stays the latest.
5470
#[test]
5471
fn bookmarks_are_deleted_on_a_remote() {
5472
    hermetic();
5473
    let dir = tempfile::tempdir().unwrap();
5474
    let root = dir.path();
5475
    let origin = Repo::init(&root.join("origin")).unwrap();
5476
    let url = root.join("origin").to_string_lossy().to_string();
5477
    let mut repo = Repo::clone(&url, &root.join("r"))
5478
        .unwrap()
5479
        .with_home(root.join("home"));
5480
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5481
        .unwrap();
5482
    let r = root.join("r");
5483
    write(&r, "a.txt", b"a\n");
5484
    repo.commit("a", &[]).unwrap();
5485
    assert!(repo.push("origin", false).unwrap()[0].ok);
5486
    origin.refresh().unwrap();
5487
    repo.bookmark_create("feature/x", None).unwrap();
5488
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5489
    origin.refresh().unwrap();
5490
    assert!(origin.resolve_heads("feature/x").is_ok());
5491
5492
    let res = repo.push_delete("origin", "feature/x").unwrap();
5493
    origin.refresh().unwrap();
5494
    assert!(res[0].ok, "{res:?}");
5495
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5496
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5497
    assert!(
5498
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5499
        "the deletion is attested"
5500
    );
5501
    assert!(
5502
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5503
        "the local bookmark stays"
5504
    );
5505
    assert!(!repo
5506
        .view()
5507
        .unwrap()
5508
        .remotes
5509
        .get("origin")
5510
        .is_some_and(|m| m.contains_key("feature/x")));
5511
5512
    // Pushing it again creates it again, past the deletion's serial.
5513
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5514
    origin.refresh().unwrap();
5515
    assert!(res[0].ok, "{res:?}");
5516
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5517
5518
    // Nothing to delete, and never the remote's own bookmark.
5519
    assert!(repo.push_delete("origin", "nope").is_err());
5520
    let res = repo.push_delete("origin", "main").unwrap();
5521
    origin.refresh().unwrap();
5522
    assert!(
5523
        !res[0].ok && res[0].reason.contains("default bookmark"),
5524
        "{res:?}"
5525
    );
5526
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5527
}
5528
5529
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5530
/// when the target has the same versions of the files it touches, and is
5531
/// refused, untouched, when it has others.
5532
#[test]
5533
fn switching_bookmarks_carries_uncommitted_work() {
5534
    hermetic();
5535
    let dir = tempfile::tempdir().unwrap();
5536
    let root = dir.path();
5537
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5538
    write(root, "a.txt", b"a\n");
5539
    write(root, "b.txt", b"b\n");
5540
    write(root, "gone.txt", b"gone\n");
5541
    repo.commit("base", &[]).unwrap();
5542
    repo.bookmark_create("feature", None).unwrap();
5543
    // Started on main, belongs on feature: edit, add, remove.
5544
    write(root, "a.txt", b"a\nmore\n");
5545
    write(root, "new.txt", b"new\n");
5546
    fs::remove_file(root.join("gone.txt")).unwrap();
5547
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5548
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5549
    assert_eq!(repo.config.bookmark, "feature");
5550
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5551
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5552
    assert!(!root.join("gone.txt").exists());
5553
    let snap = repo.snapshot("status").unwrap();
5554
    assert_eq!(
5555
        statuses(&snap),
5556
        vec![
5557
            ("a.txt".to_string(), ChangeStatus::Modified),
5558
            ("gone.txt".to_string(), ChangeStatus::Removed),
5559
            ("new.txt".to_string(), ChangeStatus::Added)
5560
        ]
5561
    );
5562
    repo.commit("the work", &[]).unwrap();
5563
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5564
5565
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5566
    repo.bookmark_switch("main", false).unwrap();
5567
    write(root, "b.txt", b"b on main\n");
5568
    repo.commit("b on main", &[]).unwrap();
5569
    repo.bookmark_switch("feature", false).unwrap();
5570
    write(root, "b.txt", b"b edited\n");
5571
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5572
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5573
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5574
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5575
}
5576
5577
/// Merging and checking out (feedback 3): a working copy without changes
5578
/// follows a merge whichever state it sat on; a refused checkout names
5579
/// what is in the way; `checkout --carry` takes the work along.
5580
#[test]
5581
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5582
    hermetic();
5583
    let dir = tempfile::tempdir().unwrap();
5584
    let root = dir.path();
5585
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5586
    write(root, "a.txt", b"a\n");
5587
    let h1 = repo.commit("a", &[]).unwrap();
5588
    write(root, "b.txt", b"b\n");
5589
    repo.commit("b", &[]).unwrap();
5590
    repo.bookmark_create("feature", None).unwrap();
5591
    repo.bookmark_switch("feature", false).unwrap();
5592
    write(root, "c.txt", b"c\n");
5593
    repo.commit("c on feature", &[]).unwrap();
5594
    repo.bookmark_switch("main", false).unwrap();
5595
    // The working copy sits on an older state than main's heads.
5596
    repo.checkout(&[h1], false, "checkout").unwrap();
5597
    assert!(!root.join("b.txt").exists());
5598
    let m = repo.merge("feature").unwrap();
5599
    assert!(m.checked_out, "a clean working copy follows the merge");
5600
    for f in ["a.txt", "b.txt", "c.txt"] {
5601
        assert!(root.join(f).exists(), "{f}");
5602
    }
5603
5604
    // A refusal says which paths are in the way and what to do.
5605
    fs::remove_file(root.join("b.txt")).unwrap();
5606
    write(root, "a.txt", b"a edited\n");
5607
    let err = repo
5608
        .checkout(&[h1], false, "checkout")
5609
        .unwrap_err()
5610
        .to_string();
5611
    assert!(
5612
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5613
        "{err}"
5614
    );
5615
    // --carry takes them along: h1 has a.txt as the base has it, and the
5616
    // removed b.txt is already as h1 has it (none), so that is no conflict
5617
    // either (oxygen#100).
5618
    let (_, carried) = repo
5619
        .checkout_carry(&[h1], "the first change", "checkout")
5620
        .unwrap();
5621
    assert_eq!(carried, vec!["a.txt"]);
5622
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5623
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5624
}
5625
5626
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5627
/// user identity not stored in a new repository yet is fine while its
5628
/// secret key is there; an added subrepo is listed as not committed yet.
5629
#[test]
5630
fn a_new_repository_is_healthy_before_its_first_commit() {
5631
    hermetic();
5632
    let dir = tempfile::tempdir().unwrap();
5633
    let root = dir.path();
5634
    let home = root.join("home");
5635
    let mut first = Repo::init(&root.join("first"))
5636
        .unwrap()
5637
        .with_home(home.clone());
5638
    let (key, _) = first
5639
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5640
        .unwrap();
5641
    let repo = Repo::init(&root.join("second"))
5642
        .unwrap()
5643
        .with_home(home.clone());
5644
    // Only the secret key: no identity object anywhere this repository sees.
5645
    let keys = repo.keys_dir.clone();
5646
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5647
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5648
    let r = repo.doctor(true);
5649
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5650
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5651
    assert!(id.message.contains("first signed change"), "{}", id.message);
5652
5653
    // A subrepo added and not committed yet is listed, pinned where it is.
5654
    let lib = root.join("lib");
5655
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5656
    write(&lib, "x.txt", b"x\n");
5657
    l.commit("x", &[]).unwrap();
5658
    let second = root.join("second");
5659
    write(&second, "a.txt", b"a\n");
5660
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5661
        .unwrap();
5662
    let subs = repo.subrepos().unwrap();
5663
    assert_eq!(subs.len(), 1);
5664
    assert_eq!(
5665
        (subs[0].path.as_str(), subs[0].committed),
5666
        ("deps/lib", false)
5667
    );
5668
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5669
    repo.commit("add lib", &[]).unwrap();
5670
    let subs = repo.subrepos().unwrap();
5671
    assert!(subs[0].committed, "committed now");
5672
}
5673
5674
/// Commit, diff, hunks and discard use the partial snapshot: a file
5675
/// unchanged since the manifest is neither read nor rendered, and showing
5676
/// a change renders only what it edits, the same as from a full base.
5677
#[cfg(unix)]
5678
#[test]
5679
fn commits_and_diffs_leave_unchanged_files_alone() {
5680
    use std::os::unix::fs::PermissionsExt;
5681
    hermetic();
5682
    let dir = tempfile::tempdir().unwrap();
5683
    let root = dir.path();
5684
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5685
    write(root, "big.txt", b"lots\nof\nlines\n");
5686
    write(root, "a.txt", b"one\ntwo\n");
5687
    repo.commit("base", &[]).unwrap();
5688
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5689
    for f in ["big.txt", "a.txt"] {
5690
        fs::File::options()
5691
            .write(true)
5692
            .open(root.join(f))
5693
            .unwrap()
5694
            .set_modified(old)
5695
            .unwrap();
5696
    }
5697
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5698
    // big.txt cannot be read at all from here on.
5699
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5700
5701
    write(root, "a.txt", b"one\nTWO\nthree\n");
5702
    let diff = repo.diff_files(None).unwrap();
5703
    assert_eq!(
5704
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5705
        ["a.txt"]
5706
    );
5707
    let (_, hunks) = repo.hunks().unwrap();
5708
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5709
    let h = repo.commit("edit a", &[]).unwrap();
5710
5711
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5712
    let c = repo.store().get_change(&h).unwrap();
5713
    let full = repo.load_state(&c.deps).unwrap();
5714
    let want = render_change(&c, &full, &full.materialize());
5715
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5716
    let (base, snap) = repo.change_base(&c).unwrap();
5717
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5718
5719
    // Discarding works the same way.
5720
    write(root, "a.txt", b"scratch\n");
5721
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5722
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5723
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5724
}
5725
5726
/// A replace conflict (spec §9.3) is settled by a change that writes one
5727
/// candidate, or new bytes, at the path when the caller names it; a plain
5728
/// snapshot of a checkout never settles it on its own.
5729
#[test]
5730
fn replace_conflicts_are_settled_when_asked() {
5731
    hermetic();
5732
    let dir = tempfile::tempdir().unwrap();
5733
    let root = dir.path();
5734
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5735
    let blob = |n: u8| {
5736
        let mut v = vec![0u8; 64];
5737
        v[1] = n;
5738
        v
5739
    };
5740
    write(root, "img.bin", &blob(1));
5741
    repo.commit("add img", &[]).unwrap();
5742
    repo.bookmark_create("other", None).unwrap();
5743
    write(root, "img.bin", &blob(2));
5744
    repo.commit("img two", &[]).unwrap();
5745
    repo.bookmark_switch("other", false).unwrap();
5746
    write(root, "img.bin", &blob(3));
5747
    repo.commit("img three", &[]).unwrap();
5748
    repo.bookmark_switch("main", false).unwrap();
5749
    repo.merge("other").unwrap();
5750
    let heads = repo.bookmark_heads().unwrap();
5751
    let merged = repo.load_state(&heads).unwrap().materialize();
5752
    assert!(
5753
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5754
        "a replace conflict"
5755
    );
5756
    // A snapshot of the checkout records nothing.
5757
    assert!(repo
5758
        .snapshot("status")
5759
        .unwrap()
5760
        .statuses
5761
        .iter()
5762
        .all(|s| s.path != "img.bin"));
5763
5764
    // Keeping candidate 3 settles it.
5765
    let author = repo.author();
5766
    let edits = [FileEdit {
5767
        path: "img.bin".into(),
5768
        content: Some(blob(3)),
5769
    }];
5770
    let c = repo
5771
        .build_change(&heads, &edits, "keep three", author)
5772
        .unwrap();
5773
    assert_eq!(c.kind, ChangeKind::Resolution);
5774
    let mut st = repo.load_state(&heads).unwrap();
5775
    for d in &c.deps {
5776
        assert!(st.contains(d));
5777
    }
5778
    assert!(
5779
        heads.iter().all(|h| c.deps.contains(h)),
5780
        "depends on both contributors"
5781
    );
5782
    st.add(c).unwrap();
5783
    let after = st.materialize();
5784
    assert!(!after.is_conflicted());
5785
    assert_eq!(
5786
        after.files["img.bin"].content,
5787
        FileContent::Opaque {
5788
            blobs: vec![Repo::blob_ref(&blob(3))]
5789
        }
5790
    );
5791
5792
    // New bytes settle it too.
5793
    let edits = [FileEdit {
5794
        path: "img.bin".into(),
5795
        content: Some(blob(9)),
5796
    }];
5797
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5798
    let mut st = repo.load_state(&heads).unwrap();
5799
    st.add(c).unwrap();
5800
    assert_eq!(
5801
        st.materialize().files["img.bin"].content,
5802
        FileContent::Opaque {
5803
            blobs: vec![Repo::blob_ref(&blob(9))]
5804
        }
5805
    );
5806
}
5807
5808
/// The history of a range of lines (spec §27): the changes that wrote
5809
/// or deleted its atoms, or deleted atoms from between them; edits outside
5810
/// the range and changes the range's lines survived are not in it.
5811
#[test]
5812
fn line_ranges_have_exact_histories() {
5813
    hermetic();
5814
    let dir = tempfile::tempdir().unwrap();
5815
    let root = dir.path();
5816
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5817
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5818
    let base = repo.commit("add f", &[]).unwrap();
5819
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5820
    let outside = repo.commit("change the import", &[]).unwrap();
5821
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5822
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5823
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5824
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5825
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5826
    let after = repo.commit("add b after a", &[]).unwrap();
5827
    let heads = repo.bookmark_heads().unwrap();
5828
5829
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5830
    let hist: Vec<ChangeHash> = repo
5831
        .line_history(&heads, "f.rs", 2, 4)
5832
        .unwrap()
5833
        .iter()
5834
        .map(|e| e.hash)
5835
        .collect();
5836
    for (h, what) in [
5837
        (base, "wrote it"),
5838
        (inside, "edited a line"),
5839
        (deleted, "deleted a line from inside"),
5840
    ] {
5841
        assert!(hist.contains(&h), "{what}");
5842
    }
5843
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5844
        assert!(!hist.contains(&h), "{what}");
5845
    }
5846
    assert_eq!(hist[0], deleted, "newest first");
5847
    // One line: only what touched it.
5848
    let one: Vec<ChangeHash> = repo
5849
        .line_history(&heads, "f.rs", 1, 1)
5850
        .unwrap()
5851
        .iter()
5852
        .map(|e| e.hash)
5853
        .collect();
5854
    assert!(one.contains(&outside) && !one.contains(&inside));
5855
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5856
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5857
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5858
}
5859
5860
#[test]
5861
fn receipts_are_kept_with_their_state_and_verified() {
5862
    use crate::receipt::{Receipt, SignedReceipt};
5863
    hermetic();
5864
    let dir = tempfile::tempdir().unwrap();
5865
    let root = dir.path();
5866
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5867
    write(root, "a.txt", b"1\n");
5868
    repo.commit("A", &[]).unwrap();
5869
    let heads = repo.bookmark_heads().unwrap();
5870
    let state = repo
5871
        .store()
5872
        .put_state(&StateObject::new(heads.clone()))
5873
        .unwrap();
5874
    let out = repo.store_blob(b"built\n").unwrap();
5875
    let receipt = Receipt {
5876
        job_name: "build".into(),
5877
        pipeline_hash: ObjectRef([1; 32]),
5878
        scope_tree_hash: ObjectRef([2; 32]),
5879
        inputs: vec![],
5880
        environment: ObjectRef([3; 32]),
5881
        outputs: vec![out],
5882
        exit_code: 0,
5883
        duration_ms: 42,
5884
    };
5885
    let sk = SecretKey::generate();
5886
    let runner = sk.identity("earth-1", "runner@earth", 1);
5887
    let sr = SignedReceipt::sign(
5888
        receipt.clone(),
5889
        repo.id().unwrap(),
5890
        state,
5891
        "demo#1",
5892
        &runner,
5893
        &sk,
5894
    );
5895
5896
    let r = repo.add_receipt(&sr).unwrap();
5897
    let found = repo.receipts(&heads).unwrap();
5898
    assert_eq!(found.len(), 1);
5899
    assert_eq!(found[0].attest, r);
5900
    assert_eq!(found[0].signed, sr);
5901
    assert!(found[0].problem.is_none() && !found[0].revoked);
5902
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5903
5904
    // Another repository's receipt, or a forged one, is refused.
5905
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5906
    assert!(repo
5907
        .add_receipt(&elsewhere)
5908
        .unwrap_err()
5909
        .to_string()
5910
        .contains("another repository"));
5911
    let mut forged = sr.clone();
5912
    forged.receipt.exit_code = 1;
5913
    assert!(repo
5914
        .add_receipt(&forged)
5915
        .unwrap_err()
5916
        .to_string()
5917
        .contains("does not verify"));
5918
5919
    // A receipt signed by a short-lived key keeps its certificate and the
5920
    // issuer's identity, and reads back with them (oxygenhub#241).
5921
    let hub_sk = SecretKey::generate();
5922
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
5923
    let job_sk = SecretKey::generate();
5924
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
5925
    let mut test_receipt = receipt.clone();
5926
    test_receipt.job_name = "test".into();
5927
    let plain = SignedReceipt::sign(
5928
        test_receipt,
5929
        repo.id().unwrap(),
5930
        state,
5931
        "demo#2",
5932
        &job,
5933
        &job_sk,
5934
    );
5935
    let now = plain.attest.hlc.wall_ms;
5936
    let cert = crate::cert::SignedCertificate::sign(
5937
        crate::cert::Certificate {
5938
            key: job.clone(),
5939
            issuer: hub.hash(),
5940
            subject: "repo:andy/demo:bookmark:main".into(),
5941
            claims: vec![],
5942
            scope: crate::identity::Scope::SEAL,
5943
            not_before: now - 1_000,
5944
            expires: now + 600_000,
5945
            grant: None,
5946
        },
5947
        &hub,
5948
        &hub_sk,
5949
    );
5950
    let certified = plain.with_certificate(cert, hub.clone());
5951
    repo.add_receipt(&certified).unwrap();
5952
    let found = repo.receipts(&heads).unwrap();
5953
    let got = found
5954
        .iter()
5955
        .find(|i| i.signed.receipt.job_name == "test")
5956
        .unwrap();
5957
    assert_eq!(got.signed, certified);
5958
    assert!(got.problem.is_none(), "{:?}", got.problem);
5959
5960
    // gc keeps the receipts, their runners, the certificate and its issuer,
5961
    // and the output while the state lives.
5962
    repo.gc(true).unwrap();
5963
    let found = repo.receipts(&heads).unwrap();
5964
    assert_eq!(found.len(), 2);
5965
    let got = found
5966
        .iter()
5967
        .find(|i| i.signed.receipt.job_name == "test")
5968
        .unwrap();
5969
    assert_eq!(got.signed, certified, "the certificate survives gc");
5970
    assert!(got.problem.is_none());
5971
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5972
    assert!(repo.fsck().unwrap().problems.is_empty());
5973
}
5974
5975
#[test]
5976
fn approvals_are_kept_with_their_state_and_survive_gc() {
5977
    hermetic();
5978
    let dir = tempfile::tempdir().unwrap();
5979
    let root = dir.path();
5980
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5981
    write(root, "a.txt", b"1\n");
5982
    repo.commit("A", &[]).unwrap();
5983
    let heads = repo.bookmark_heads().unwrap();
5984
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
5985
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
5986
    let sk = SecretKey::generate();
5987
    let andy = sk.identity("Andy", "[email protected]", 1);
5988
    let statement = crate::approval::Statement {
5989
        repo: repo.id().unwrap(),
5990
        run: "https://hub.example/andy/infra/flow/8".into(),
5991
        job: "apply".into(),
5992
        job_hash: ObjectRef([1; 32]),
5993
        state,
5994
        inputs: vec![plan],
5995
        environment: "prod".into(),
5996
        approve: true,
5997
    };
5998
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
5999
    let r = repo.add_approval(&sa).unwrap();
6000
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6001
    // Another repository's approval, or a changed one, is refused.
6002
    let elsewhere = crate::approval::SignedApproval::sign(
6003
        &crate::approval::Statement {
6004
            repo: [0; 16],
6005
            ..statement.clone()
6006
        },
6007
        &andy,
6008
        &sk,
6009
    );
6010
    assert!(repo
6011
        .add_approval(&elsewhere)
6012
        .unwrap_err()
6013
        .to_string()
6014
        .contains("another repository"));
6015
    let mut forged = sa.clone();
6016
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
6017
        *environment = "dev".into();
6018
    }
6019
    assert!(repo
6020
        .add_approval(&forged)
6021
        .unwrap_err()
6022
        .to_string()
6023
        .contains("does not verify"));
6024
    // gc keeps it, its signature and its signer while the state lives.
6025
    repo.gc(true).unwrap();
6026
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6027
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
6028
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
6029
    assert!(repo.fsck().unwrap().problems.is_empty());
6030
}
6031
6032
#[test]
6033
fn status_leaves_an_unchanged_manifest_alone() {
6034
    hermetic();
6035
    let dir = tempfile::tempdir().unwrap();
6036
    let root = dir.path();
6037
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6038
    write(root, "a.txt", b"1\n");
6039
    write(root, "b.txt", b"2\n");
6040
    repo.commit("A", &[]).unwrap();
6041
    // Files last touched well outside the racy window.
6042
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6043
    for f in ["a.txt", "b.txt"] {
6044
        fs::File::options()
6045
            .write(true)
6046
            .open(root.join(f))
6047
            .unwrap()
6048
            .set_modified(old)
6049
            .unwrap();
6050
    }
6051
    repo.snapshot_status("status").unwrap();
6052
    let path = repo.manifest_path();
6053
    let first = fs::read(&path).unwrap();
6054
    repo.snapshot_status("status").unwrap();
6055
    assert_eq!(
6056
        fs::read(&path).unwrap(),
6057
        first,
6058
        "an unchanged tree does not rewrite the manifest"
6059
    );
6060
    // A change rewrites it.
6061
    write(root, "a.txt", b"1\n2\n");
6062
    repo.snapshot_status("status").unwrap();
6063
    assert_ne!(fs::read(&path).unwrap(), first);
6064
}
6065
6066
#[test]
6067
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6068
    hermetic();
6069
    let dir = tempfile::tempdir().unwrap();
6070
    let root = dir.path();
6071
    let origin_path = root.join("origin");
6072
    Repo::init(&origin_path).unwrap();
6073
    let origin_url = origin_path.to_string_lossy().to_string();
6074
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6075
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6076
    write(&root.join("a"), "big.txt", big.as_bytes());
6077
    write(&root.join("a"), "small.txt", b"small\n");
6078
    let h1 = a.commit("large", &[]).unwrap();
6079
    let (_, body) = a.store().get(&h1).unwrap();
6080
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6081
    assert!(a.push("origin", false).unwrap()[0].ok);
6082
6083
    // A clone reads the text from the blobs that came with the change.
6084
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6085
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6086
    // An edit in the middle of the stored insert is an ordinary change.
6087
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6088
    write(&root.join("b"), "big.txt", edited.as_bytes());
6089
    let h2 = b.commit("edit", &[]).unwrap();
6090
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6091
    assert!(b.push("origin", false).unwrap()[0].ok);
6092
    assert!(a.pull("origin").unwrap().checked_out);
6093
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6094
    assert_eq!(
6095
        a.fsck().unwrap().errors(),
6096
        0,
6097
        "{:?}",
6098
        a.fsck().unwrap().problems
6099
    );
6100
6101
    // With zero retention gc keeps the text blobs of every kept change.
6102
    let mut a = Repo::open(&root.join("a")).unwrap();
6103
    a.config.set("core.op-retention", "0").unwrap();
6104
    a.save_config().unwrap();
6105
    let a = Repo::open(&root.join("a")).unwrap();
6106
    a.gc(true).unwrap();
6107
    let a = Repo::open(&root.join("a")).unwrap();
6108
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6109
    assert_eq!(
6110
        a.fsck().unwrap().errors(),
6111
        0,
6112
        "{:?}",
6113
        a.fsck().unwrap().problems
6114
    );
6115
    // And a clone of the packed repository reads them from its packs.
6116
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6117
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6118
    drop(c);
6119
}
6120
6121
#[test]
6122
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6123
    hermetic();
6124
    let dir = tempfile::tempdir().unwrap();
6125
    let root = dir.path();
6126
    let repo = Repo::init(root).unwrap();
6127
    write(root, "a.txt", b"a\n");
6128
    let a = repo.commit("a", &[]).unwrap();
6129
    write(root, "b.txt", b"b\n");
6130
    repo.commit("b", &[]).unwrap();
6131
    let (x, op) = repo.head_op().unwrap();
6132
    let ws = *op.view.workspaces.keys().next().unwrap();
6133
    let mut one = op.view.clone();
6134
    one.workspaces.insert(ws, a);
6135
    let mut two = op.view.clone();
6136
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6137
    let first = repo.record_op(&[x], "one", one).unwrap();
6138
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6139
    assert!(
6140
        e.to_string()
6141
            .contains("changed this working copy at the same time"),
6142
        "{e}"
6143
    );
6144
    assert_eq!(
6145
        repo.head_op().unwrap().0,
6146
        first,
6147
        "the second is not recorded"
6148
    );
6149
}
6150
6151
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6152
/// rewrote the working copy recorded the half-written files as edits, and
6153
/// its view replaced the switch's.
6154
#[test]
6155
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6156
    hermetic();
6157
    let dir = tempfile::tempdir().unwrap();
6158
    let root = dir.path().to_path_buf();
6159
    let mut repo = Repo::init(&root).unwrap();
6160
    write(&root, "keep.txt", b"keep\n");
6161
    repo.commit("base", &[]).unwrap();
6162
    repo.bookmark_create("small", None).unwrap();
6163
    for i in 0..300 {
6164
        write(
6165
            &root,
6166
            &format!("many/f{i}.txt"),
6167
            format!("file {i}\n").as_bytes(),
6168
        );
6169
    }
6170
    repo.commit("many", &[]).unwrap();
6171
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6172
    let watcher = {
6173
        let (root, stop) = (root.clone(), stop.clone());
6174
        std::thread::spawn(move || {
6175
            let r = Repo::open(&root).unwrap();
6176
            let mut ran = 0;
6177
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6178
                if r.snapshot_status("oxy status").is_ok() {
6179
                    ran += 1;
6180
                }
6181
            }
6182
            ran
6183
        })
6184
    };
6185
    for i in 0..20 {
6186
        let to = if i % 2 == 0 { "small" } else { "main" };
6187
        repo.bookmark_switch(to, false).unwrap();
6188
    }
6189
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6190
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6191
    // Back on main, clean, with every file where main has it.
6192
    let repo = Repo::open(&root).unwrap();
6193
    let s = repo.snapshot_status("oxy status").unwrap();
6194
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6195
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6196
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6197
    assert!(root.join("many/f299.txt").exists());
6198
}
6199
6200
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6201
/// put a subrepo that was ahead of its pin back at the pin and moved the
6202
/// subrepo's own bookmark backwards.
6203
#[test]
6204
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6205
    hermetic();
6206
    let dir = tempfile::tempdir().unwrap();
6207
    let root = dir.path();
6208
    Repo::init(&root.join("lib-origin")).unwrap();
6209
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6210
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6211
    write(&root.join("lib"), "lib.txt", b"v1\n");
6212
    lib.commit("lib v1", &[]).unwrap();
6213
    assert!(lib.push("origin", false).unwrap()[0].ok);
6214
6215
    let app_dir = root.join("app");
6216
    let mut app = Repo::init(&app_dir).unwrap();
6217
    write(&app_dir, "main.txt", b"app\n");
6218
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6219
    app.commit("app with lib", &[]).unwrap();
6220
    app.bookmark_create("feature", None).unwrap();
6221
6222
    // New work in the subrepo, not yet pinned by the parent.
6223
    let nested_dir = app_dir.join("libs/lib");
6224
    let nested = Repo::open(&nested_dir).unwrap();
6225
    write(&nested_dir, "new.txt", b"new\n");
6226
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6227
    drop(nested);
6228
6229
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6230
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6231
    let nested = Repo::open(&nested_dir).unwrap();
6232
    assert!(
6233
        nested.bookmark_heads().unwrap().contains(&l2),
6234
        "its bookmark kept its work"
6235
    );
6236
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6237
    let s = app.snapshot("status").unwrap();
6238
    assert_eq!(
6239
        statuses(&s),
6240
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6241
    );
6242
}
6243
6244
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6245
/// moving `main` to a change this clone had pushed on another bookmark,
6246
/// the first `pull` said "Already up to date" while `main` was behind.
6247
#[test]
6248
fn pull_takes_a_remote_move_to_changes_already_here() {
6249
    hermetic();
6250
    let dir = tempfile::tempdir().unwrap();
6251
    let root = dir.path();
6252
    let origin_path = root.join("origin");
6253
    let origin = Repo::init(&origin_path).unwrap();
6254
    let url = origin_path.to_string_lossy().to_string();
6255
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6256
    write(&root.join("b"), "base.txt", b"base\n");
6257
    b.commit("base", &[]).unwrap();
6258
    assert!(b.push("origin", false).unwrap()[0].ok);
6259
    origin.refresh().unwrap();
6260
6261
    // A feature bookmark with one change, pushed.
6262
    b.bookmark_create("feat", None).unwrap();
6263
    b.bookmark_switch("feat", false).unwrap();
6264
    write(&root.join("b"), "x.txt", b"x\n");
6265
    let x = b.commit("x", &[]).unwrap();
6266
    assert!(b.push("origin", false).unwrap()[0].ok);
6267
    origin.refresh().unwrap();
6268
    b.bookmark_switch("main", false).unwrap();
6269
6270
    // The remote lands it: its main moves to the feature's state.
6271
    let feat = origin
6272
        .store()
6273
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6274
        .unwrap()
6275
        .heads;
6276
    origin.bookmark_set("main", &feat).unwrap();
6277
6278
    let r = b.pull("origin").unwrap();
6279
    assert!(r.changed, "{r:?}");
6280
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6281
    let main = b
6282
        .bookmarks()
6283
        .unwrap()
6284
        .into_iter()
6285
        .find(|m| m.name == "main")
6286
        .unwrap();
6287
    assert_eq!(main.behind, Some(0), "{main:?}");
6288
}
6289
6290
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6291
/// to one only the remote has makes a local bookmark from it; a pull moves
6292
/// every local bookmark the remote has too; a clone checks out the remote's
6293
/// default bookmark.
6294
#[test]
6295
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6296
    hermetic();
6297
    let dir = tempfile::tempdir().unwrap();
6298
    let root = dir.path();
6299
    let origin_path = root.join("origin");
6300
    let mut origin = Repo::init(&origin_path).unwrap();
6301
    let url = origin_path.to_string_lossy().to_string();
6302
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6303
    write(&root.join("a"), "base.txt", b"base\n");
6304
    a.commit("base", &[]).unwrap();
6305
    assert!(a.push("origin", false).unwrap()[0].ok);
6306
    a.bookmark_create("develop", None).unwrap();
6307
    a.bookmark_switch("develop", false).unwrap();
6308
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6309
    let d1 = a.commit("d1", &[]).unwrap();
6310
    assert!(a.push("origin", false).unwrap()[0].ok);
6311
6312
    // A clone has main only; origin/develop is a name all the same.
6313
    let c_root = root.join("c");
6314
    let mut c = Repo::clone(&url, &c_root).unwrap();
6315
    assert_eq!(c.config.bookmark, "main");
6316
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6317
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6318
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6319
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6320
6321
    // Switching makes the local bookmark from origin's.
6322
    c.bookmark_switch("develop", false).unwrap();
6323
    assert_eq!(c.config.bookmark, "develop");
6324
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6325
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6326
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6327
    assert!(c.bookmark_switch("nowhere", false).is_err());
6328
6329
    // Both bookmarks move on the remote; one pull takes both.
6330
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6331
    let d2 = a.commit("d2", &[]).unwrap();
6332
    assert!(a.push("origin", false).unwrap()[0].ok);
6333
    a.bookmark_switch("main", false).unwrap();
6334
    write(&root.join("a"), "m.txt", b"m\n");
6335
    let m = a.commit("m", &[]).unwrap();
6336
    assert!(a.push("origin", false).unwrap()[0].ok);
6337
    let r = c.pull("origin").unwrap();
6338
    assert!(r.changed && r.checked_out, "{r:?}");
6339
    assert_eq!(r.heads, vec![d2]);
6340
    assert_eq!(r.others, vec!["main".to_string()]);
6341
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6342
    assert_eq!(
6343
        fs::read(c_root.join("base.txt")).unwrap(),
6344
        b"base\nd1\nd2\n"
6345
    );
6346
    let again = c.pull("origin").unwrap();
6347
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6348
6349
    // A clone checks out the remote's default bookmark.
6350
    origin.config.set("workspace.bookmark", "develop").unwrap();
6351
    origin.save_config().unwrap();
6352
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6353
    assert_eq!(e.config.bookmark, "develop");
6354
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6355
    let reopened = Repo::open(&root.join("e")).unwrap();
6356
    assert_eq!(reopened.config.bookmark, "develop");
6357
    // REMOTE/NAME names the remote's bookmark to switch to.
6358
    let mut e = reopened;
6359
    e.bookmark_switch("origin/main", false).unwrap();
6360
    assert_eq!(e.config.bookmark, "main");
6361
    assert!(e.bookmark_heads().unwrap().contains(&m));
6362
}
6363
6364
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6365
/// op restore goes back to an operation, files included, and undo takes
6366
/// the restore back whole; op revert undoes one operation alone; each
6367
/// operation's changes are described from the views.
6368
#[test]
6369
fn operations_can_be_read_restored_and_reverted() {
6370
    hermetic();
6371
    let dir = tempfile::tempdir().unwrap();
6372
    let root = dir.path();
6373
    let repo = Repo::init(root).unwrap();
6374
    write(root, "a.txt", b"a\n");
6375
    let first = repo.commit("first", &[]).unwrap();
6376
    write(root, "a.txt", b"a\nb\n");
6377
    let second = repo.commit("second", &[]).unwrap();
6378
    let at_second = repo.head_op().unwrap().0.to_hex();
6379
    repo.bookmark_create("keep", None).unwrap();
6380
    let created = repo.head_op().unwrap().0.to_hex();
6381
    write(root, "n.txt", b"n\n");
6382
    let third = repo.commit("third", &[]).unwrap();
6383
6384
    // What each operation changed.
6385
    let ops = repo.op_log().unwrap();
6386
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6387
    assert!(
6388
        changes
6389
            .iter()
6390
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6391
        "{changes:?}"
6392
    );
6393
    assert!(changes
6394
        .iter()
6395
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6396
6397
    // Reading at an earlier operation.
6398
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6399
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6400
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6401
    write(root, "z.txt", b"z\n");
6402
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6403
    fs::remove_file(root.join("z.txt")).unwrap();
6404
    assert!(repo.resolve_op("zz").is_err());
6405
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
6406
6407
    // Restore goes back, files and all; undo takes it back whole.
6408
    repo.op_restore(&at_second, false).unwrap();
6409
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
6410
    assert!(!root.join("n.txt").exists());
6411
    repo.undo().unwrap();
6412
    let mut heads = repo.bookmark_heads().unwrap();
6413
    heads.sort();
6414
    let mut want = vec![second, third];
6415
    want.sort();
6416
    assert_eq!(heads, want);
6417
    assert!(
6418
        root.join("n.txt").exists(),
6419
        "the files came back with the undo"
6420
    );
6421
6422
    // Revert the bookmark's creation alone: the commit after it stays.
6423
    let r = repo.op_revert(&created).unwrap();
6424
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6425
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6426
    assert!(repo
6427
        .load_state(&repo.bookmark_heads().unwrap())
6428
        .unwrap()
6429
        .contains(&third));
6430
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6431
    let _ = first;
6432
}
6433
6434
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6435
/// from the status cache while every file is as the snapshot left it, and
6436
/// from a snapshot again as soon as one is not.
6437
#[test]
6438
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6439
    hermetic();
6440
    let dir = tempfile::tempdir().unwrap();
6441
    let root = dir.path();
6442
    let repo = Repo::init(root).unwrap();
6443
    write(root, "a.txt", b"a\n");
6444
    write(root, "b.txt", b"b\n");
6445
    repo.commit("base", &[]).unwrap();
6446
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6447
6448
    write(root, "a.txt", b"a\nmore\n");
6449
    assert_eq!(
6450
        repo.status_by_manifest().unwrap(),
6451
        None,
6452
        "no snapshot of the edit yet"
6453
    );
6454
    let snap = repo.snapshot_status("oxy status").unwrap();
6455
    assert_eq!(snap.statuses.len(), 1);
6456
    let cached = repo
6457
        .status_by_manifest()
6458
        .unwrap()
6459
        .expect("answered from the cache");
6460
    assert_eq!(cached.len(), 1);
6461
    assert_eq!(
6462
        (cached[0].path.as_str(), cached[0].status),
6463
        ("a.txt", ChangeStatus::Modified)
6464
    );
6465
6466
    // Any further change sends status back to a snapshot.
6467
    write(root, "a.txt", b"a\nmore\nand more\n");
6468
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6469
    repo.snapshot_status("oxy status").unwrap();
6470
    assert!(repo.status_by_manifest().unwrap().is_some());
6471
    write(root, "new.txt", b"n\n");
6472
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6473
    fs::remove_file(root.join("new.txt")).unwrap();
6474
    assert!(
6475
        repo.status_by_manifest().unwrap().is_some(),
6476
        "back as it was"
6477
    );
6478
    fs::remove_file(root.join("b.txt")).unwrap();
6479
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6480
    write(root, "b.txt", b"b\n");
6481
6482
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6483
    repo.snapshot_status("oxy status").unwrap();
6484
    repo.commit("more", &[]).unwrap();
6485
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6486
}
6487
6488
/// oxygen#41: while the status cache holds, the working copy's diff is
6489
/// rendered from the stored working-copy change, and says exactly what a
6490
/// snapshot's diff says.
6491
#[test]
6492
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6493
    hermetic();
6494
    let dir = tempfile::tempdir().unwrap();
6495
    let root = dir.path();
6496
    let repo = Repo::init(root).unwrap();
6497
    write(root, "a.txt", b"one\ntwo\nthree\n");
6498
    write(root, "gone.txt", b"bye\n");
6499
    repo.commit("base", &[]).unwrap();
6500
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6501
    write(root, "new.txt", b"hello\n");
6502
    fs::remove_file(root.join("gone.txt")).unwrap();
6503
    let snap = repo.snapshot_status("oxy status").unwrap();
6504
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6505
    assert!(
6506
        repo.status_by_manifest().unwrap().is_some(),
6507
        "the cache holds"
6508
    );
6509
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6510
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6511
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6512
6513
    // Committed, nothing changes: the diff is empty without loading the
6514
    // base (oxygen#94), and the same as rendering it.
6515
    repo.commit("all", &[]).unwrap();
6516
    repo.snapshot_status("oxy status").unwrap();
6517
    assert!(repo.status_by_manifest().unwrap().is_some());
6518
    assert!(repo
6519
        .working_copy_with_base_unless_unchanged()
6520
        .unwrap()
6521
        .is_none());
6522
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6523
    assert_eq!(render_change(&wc, &base, &snapshot), "");
6524
    assert!(repo.diff_files(None).unwrap().is_empty());
6525
}
6526
6527
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6528
/// while none has moved, the check stats the tracked files without listing
6529
/// the tree, and a file added or removed anywhere moves its directory's
6530
/// time, so the tree is listed again.
6531
#[test]
6532
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6533
    hermetic();
6534
    let dir = tempfile::tempdir().unwrap();
6535
    let root = dir.path();
6536
    let repo = Repo::init(root).unwrap();
6537
    write(root, "a.txt", b"a\n");
6538
    write(root, "sub/deep/b.txt", b"b\n");
6539
    repo.commit("base", &[]).unwrap();
6540
    // Out of the racy window: every file and directory a minute old.
6541
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6542
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6543
        fs::File::open(root.join(p))
6544
            .unwrap()
6545
            .set_modified(old)
6546
            .unwrap();
6547
    }
6548
    repo.snapshot_status("oxy status").unwrap();
6549
    repo.write_manifest(false, false).unwrap();
6550
    let m = repo.read_manifest().unwrap().unwrap().2;
6551
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6552
    assert_eq!(
6553
        repo.disk_differs_by_dirs(&m),
6554
        Some(false),
6555
        "no listing needed"
6556
    );
6557
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6558
6559
    // A same-size edit with a new time: found by its stat.
6560
    write(root, "sub/deep/b.txt", b"c\n");
6561
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6562
    write(root, "sub/deep/b.txt", b"b\n");
6563
    fs::File::open(root.join("sub/deep/b.txt"))
6564
        .unwrap()
6565
        .set_modified(old)
6566
        .unwrap();
6567
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6568
6569
    // A new file moves its directory's time: the tree must be listed.
6570
    write(root, "sub/deep/new.txt", b"n\n");
6571
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6572
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6573
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6574
    // A removed one too.
6575
    fs::remove_file(root.join("a.txt")).unwrap();
6576
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6577
}
6578
6579
/// oxygen#41: a commit right after a status takes the snapshot the status
6580
/// left (the status cache holds) rather than walking again, and commits
6581
/// exactly what a snapshot would have.
6582
#[test]
6583
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6584
    hermetic();
6585
    let dir = tempfile::tempdir().unwrap();
6586
    let root = dir.path();
6587
    let repo = Repo::init(root).unwrap();
6588
    write(root, "a.txt", b"a\nb\n");
6589
    write(root, ".oxyattributes", b"*.bin binary\n");
6590
    repo.commit("base", &[]).unwrap();
6591
    write(root, "a.txt", b"a\nB\n");
6592
    write(root, "new.txt", b"new\n");
6593
    let snap = repo.snapshot_status("oxy status").unwrap();
6594
    let cached = repo
6595
        .snapshot_from_cache()
6596
        .unwrap()
6597
        .expect("the cache holds");
6598
    assert_eq!(cached.wc_hash, snap.wc_hash);
6599
    assert_eq!(cached.statuses, snap.statuses);
6600
    assert!(
6601
        !cached.attributes.is_empty(),
6602
        "the .oxyattributes file was read"
6603
    );
6604
    let h = repo.commit("edit", &[]).unwrap();
6605
    let c = repo.store().get_change(&h).unwrap();
6606
    assert_eq!(
6607
        c.tree_ops.len() + c.edits.len(),
6608
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6609
    );
6610
    assert_eq!(
6611
        repo.status_by_manifest().unwrap(),
6612
        Some(vec![]),
6613
        "clean after the commit"
6614
    );
6615
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6616
}
6617
6618
/// oxygen#41: a clean check that verified racy entries restamps the
6619
/// manifest, so later checks can trust them, and a same-size rewrite
6620
/// straight afterwards is still found: entries within two seconds of the
6621
/// new time stay racy.
6622
#[test]
6623
fn a_verified_clean_check_restamps_the_manifest_safely() {
6624
    hermetic();
6625
    let dir = tempfile::tempdir().unwrap();
6626
    let root = dir.path();
6627
    let repo = Repo::init(root).unwrap();
6628
    write(root, "a.txt", b"one\n");
6629
    repo.commit("one", &[]).unwrap();
6630
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6631
    assert!(repo.clean_by_manifest().unwrap());
6632
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6633
    assert!(after > before, "restamped");
6634
    write(root, "a.txt", b"two\n");
6635
    assert!(
6636
        !repo.clean_by_manifest().unwrap(),
6637
        "a same-size rewrite is still seen"
6638
    );
6639
}
6640
6641
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6642
/// stored insert's text blob only when it builds that file's graph, and
6643
/// builds the same graph a full load does.
6644
#[test]
6645
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6646
    hermetic();
6647
    let dir = tempfile::tempdir().unwrap();
6648
    let root = dir.path();
6649
    let repo = Repo::init(root).unwrap();
6650
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6651
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6652
    write(root, "big.txt", big.as_bytes());
6653
    write(root, "other.txt", other.as_bytes());
6654
    let h = repo.commit("two large files", &[]).unwrap();
6655
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6656
    let h2 = repo.commit("append", &[]).unwrap();
6657
6658
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6659
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6660
        FileContent::Text { bytes, .. } => bytes.clone(),
6661
        other => panic!("{other:?}"),
6662
    };
6663
    // Built on demand, every graph renders as the full load's.
6664
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6665
    let big_node = full.files["big.txt"].node;
6666
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6667
    repo.load_all_graphs(&mut hist).unwrap();
6668
    let rendered = hist.materialize();
6669
    for p in ["big.txt", "other.txt"] {
6670
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6671
    }
6672
6673
    // Without other.txt's text blob, history still loads and big.txt still
6674
    // builds: nothing read the other text.
6675
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6676
    assert_eq!(texts.len(), 2);
6677
    let content = |r: &ObjectRef| -> Vec<u8> {
6678
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6679
        blob.chunks
6680
            .iter()
6681
            .flat_map(|c| repo.store().get(c).unwrap().1)
6682
            .collect()
6683
    };
6684
    let other_text = texts
6685
        .iter()
6686
        .filter_map(|t| match t {
6687
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6688
            _ => None,
6689
        })
6690
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6691
        .unwrap();
6692
    repo.store().remove_loose_for_test(&other_text).unwrap();
6693
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6694
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6695
    assert!(repo
6696
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6697
        .is_err());
6698
}
6699
6700
/// oxygen#35: the first status after a commit read and rendered every
6701
/// file (79 s and more than 14 GB on the Linux tree), because the
6702
/// manifest had no graph keys for files the commit added.
6703
#[test]
6704
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6705
    use std::os::unix::fs::PermissionsExt;
6706
    hermetic();
6707
    let dir = tempfile::tempdir().unwrap();
6708
    let root = dir.path();
6709
    let repo = Repo::init(root).unwrap();
6710
    let files = ["a.txt", "b.txt", "d/c.txt"];
6711
    for p in files {
6712
        write(root, p, format!("{p}\n").as_bytes());
6713
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6714
        fs::File::options()
6715
            .write(true)
6716
            .open(root.join(p))
6717
            .unwrap()
6718
            .set_modified(old)
6719
            .unwrap();
6720
    }
6721
    repo.commit("added", &[]).unwrap();
6722
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6723
    assert!(
6724
        m.entries.values().all(|e| e.graph.is_some()),
6725
        "keys recorded at commit"
6726
    );
6727
    // Unreadable files prove the next status reads none of them.
6728
    for p in files {
6729
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6730
    }
6731
    let snap = repo.snapshot_status("status").unwrap();
6732
    for p in files {
6733
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6734
    }
6735
    assert!(!snap.changed && snap.statuses.is_empty());
6736
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6737
}
6738
6739
/// oxygen#35: a checkout reads, renders and writes only the files whose
6740
/// graphs differ, and renders the rest a batch at a time.
6741
#[test]
6742
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6743
    use std::os::unix::fs::PermissionsExt;
6744
    hermetic();
6745
    let dir = tempfile::tempdir().unwrap();
6746
    let root = dir.path();
6747
    let origin = root.join("origin");
6748
    let mut repo = Repo::init(&origin).unwrap();
6749
    // More files than one batch holds.
6750
    let n = 2100;
6751
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6752
    for i in 0..n {
6753
        let p = format!("f/{i:04}.txt");
6754
        write(&origin, &p, format!("file {i}\n").as_bytes());
6755
        fs::File::options()
6756
            .write(true)
6757
            .open(origin.join(&p))
6758
            .unwrap()
6759
            .set_modified(old)
6760
            .unwrap();
6761
    }
6762
    repo.commit("many", &[]).unwrap();
6763
    repo.bookmark_create("feature", None).unwrap();
6764
    repo.bookmark_switch("feature", false).unwrap();
6765
    write(&origin, "f/0007.txt", b"changed\n");
6766
    repo.commit("one change", &[]).unwrap();
6767
6768
    // Switching back to main must not read the unchanged files.
6769
    for i in 0..n {
6770
        if i != 7 {
6771
            let p = origin.join(format!("f/{i:04}.txt"));
6772
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6773
        }
6774
    }
6775
    let r = repo.bookmark_switch("main", false).unwrap();
6776
    for i in 0..n {
6777
        let p = origin.join(format!("f/{i:04}.txt"));
6778
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6779
    }
6780
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6781
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6782
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6783
6784
    // A clone renders every file, across batches.
6785
    let c = root.join("clone");
6786
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6787
    for i in [0, 2047, 2048, n - 1] {
6788
        assert_eq!(
6789
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6790
            format!("file {i}\n").as_bytes()
6791
        );
6792
    }
6793
    let cloned = Repo::open(&c).unwrap();
6794
    assert!(cloned
6795
        .snapshot_status("status")
6796
        .unwrap()
6797
        .statuses
6798
        .is_empty());
6799
}
6800
6801
/// A file written just before the manifest (inside the racy window) is
6802
/// checked by its hash: trusted when equal, caught when edited in place
6803
/// with the same size and time.
6804
#[test]
6805
fn a_racy_manifest_entry_is_checked_by_hash() {
6806
    hermetic();
6807
    let dir = tempfile::tempdir().unwrap();
6808
    let root = dir.path();
6809
    let repo = Repo::init(root).unwrap();
6810
    write(root, "a.txt", b"one\n");
6811
    repo.commit("fresh", &[]).unwrap();
6812
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6813
    let t = fs::metadata(root.join("a.txt"))
6814
        .unwrap()
6815
        .modified()
6816
        .unwrap();
6817
    write(root, "a.txt", b"two\n");
6818
    fs::File::options()
6819
        .write(true)
6820
        .open(root.join("a.txt"))
6821
        .unwrap()
6822
        .set_modified(t)
6823
        .unwrap();
6824
    assert!(
6825
        !repo.clean_by_manifest().unwrap(),
6826
        "same size and time, other bytes"
6827
    );
6828
    assert_eq!(
6829
        statuses(&repo.snapshot_status("status").unwrap()),
6830
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6831
    );
6832
}
6833
6834
/// A fetch on one machine moves changes as stored, text blobs among the
6835
/// objects; a change whose text blob did not come is refused, not stored.
6836
#[test]
6837
fn a_raw_bundle_without_a_changes_text_is_refused() {
6838
    hermetic();
6839
    let dir = tempfile::tempdir().unwrap();
6840
    let root = dir.path();
6841
    let a = Repo::init(&root.join("a")).unwrap();
6842
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6843
    write(&root.join("a"), "big.txt", big.as_bytes());
6844
    let h = a.commit("big", &[]).unwrap();
6845
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6846
    assert_eq!(bundle.raw_changes.len(), 1);
6847
    assert!(bundle.changes.is_empty());
6848
    let b = Repo::init(&root.join("b")).unwrap();
6849
    let mut without = bundle.clone();
6850
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6851
    let e = b.import_bundle(&without, false).unwrap_err();
6852
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6853
    assert!(!b.store().has(&h));
6854
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6855
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6856
}
6857
6858
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6859
/// again was a second node for one Git path, so a file moved into it on
6860
/// another line, where the first node still stood, ended up in two places.
6861
/// An import now brings the directory back rather than make a new one.
6862
#[test]
6863
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6864
    hermetic();
6865
    if std::process::Command::new("git")
6866
        .arg("--version")
6867
        .output()
6868
        .is_err()
6869
    {
6870
        eprintln!("git not installed; skipping");
6871
        return;
6872
    }
6873
    let dir = tempfile::tempdir().unwrap();
6874
    let root = dir.path();
6875
    let g = root.join("src.git");
6876
    fs::create_dir_all(&g).unwrap();
6877
    let git = |args: &[&str]| -> String {
6878
        let out = std::process::Command::new("git")
6879
            .arg("-C")
6880
            .arg(&g)
6881
            .args([
6882
                "-c",
6883
                "user.name=Grace",
6884
                "-c",
6885
                "[email protected]",
6886
                "-c",
6887
                "commit.gpgsign=false",
6888
            ])
6889
            .args(args)
6890
            .output()
6891
            .unwrap();
6892
        assert!(
6893
            out.status.success(),
6894
            "git {args:?}: {}",
6895
            String::from_utf8_lossy(&out.stderr)
6896
        );
6897
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6898
    };
6899
    git(&["init", "-q", "-b", "main"]);
6900
    write(&g, "d/a.txt", b"a\n");
6901
    write(&g, "c/x.txt", b"x\n");
6902
    git(&["add", "."]);
6903
    git(&["commit", "-qm", "base"]);
6904
    // One line: move x into d while d still stands.
6905
    git(&["checkout", "-qb", "side"]);
6906
    git(&["mv", "c/x.txt", "d/x.txt"]);
6907
    git(&["commit", "-qm", "x into d"]);
6908
    // The other: d goes, comes back, and x moves into it too.
6909
    git(&["checkout", "-q", "main"]);
6910
    git(&["rm", "-q", "d/a.txt"]);
6911
    git(&["commit", "-qm", "d goes"]);
6912
    write(&g, "d/b.txt", b"b\n");
6913
    git(&["add", "."]);
6914
    git(&["commit", "-qm", "d comes back"]);
6915
    git(&["mv", "c/x.txt", "d/x.txt"]);
6916
    git(&["commit", "-qm", "x into d again"]);
6917
    git(&["merge", "-q", "--no-edit", "side"]);
6918
6919
    let repo = Repo::init(&root.join("o")).unwrap();
6920
    repo.import_git(&g, "main").unwrap();
6921
    let v = repo.verify_git_import(&g, "main").unwrap();
6922
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6923
    let st = repo
6924
        .load_state_history(&repo.bookmark_heads().unwrap())
6925
        .unwrap();
6926
    let view = st.tree().view();
6927
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6928
    // The directory is the one the first commit made.
6929
    // Commits made in one second tie on time: find the first by its message.
6930
    let first = repo
6931
        .log()
6932
        .unwrap()
6933
        .into_iter()
6934
        .find(|e| e.change.message.starts_with("base"))
6935
        .unwrap();
6936
    let base = repo
6937
        .load_state_history(&[first.hash])
6938
        .unwrap()
6939
        .tree()
6940
        .view();
6941
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6942
}
6943
6944
/// oxygen#30, the rest: a placement left under a directory another line
6945
/// removed is out of sight, so no diff reaches it; the merge that settles
6946
/// where the file is retires it.
6947
#[test]
6948
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6949
    hermetic();
6950
    if std::process::Command::new("git")
6951
        .arg("--version")
6952
        .output()
6953
        .is_err()
6954
    {
6955
        eprintln!("git not installed; skipping");
6956
        return;
6957
    }
6958
    let dir = tempfile::tempdir().unwrap();
6959
    let root = dir.path();
6960
    let g = root.join("src.git");
6961
    fs::create_dir_all(&g).unwrap();
6962
    let run = |args: &[&str]| {
6963
        std::process::Command::new("git")
6964
            .arg("-C")
6965
            .arg(&g)
6966
            .args([
6967
                "-c",
6968
                "user.name=Grace",
6969
                "-c",
6970
                "[email protected]",
6971
                "-c",
6972
                "commit.gpgsign=false",
6973
            ])
6974
            .args(args)
6975
            .output()
6976
            .unwrap()
6977
    };
6978
    let git = |args: &[&str]| {
6979
        let out = run(args);
6980
        assert!(
6981
            out.status.success(),
6982
            "git {args:?}: {}",
6983
            String::from_utf8_lossy(&out.stderr)
6984
        );
6985
    };
6986
    git(&["init", "-q", "-b", "main"]);
6987
    write(&g, "c/x.txt", b"x\n");
6988
    write(&g, "keep.txt", b"k\n");
6989
    git(&["add", "."]);
6990
    git(&["commit", "-qm", "base"]);
6991
    // One line renames the file within c; the other moves it out of c,
6992
    // which goes.
6993
    git(&["checkout", "-qb", "side"]);
6994
    git(&["mv", "c/x.txt", "c/y.txt"]);
6995
    git(&["commit", "-qm", "rename within c"]);
6996
    git(&["checkout", "-q", "main"]);
6997
    fs::create_dir_all(g.join("n")).unwrap();
6998
    git(&["mv", "c/x.txt", "n/x.txt"]);
6999
    git(&["commit", "-qm", "move out of c"]);
7000
    // Git cannot merge the two renames; the merge keeps n/x.txt.
7001
    let _ = run(&["merge", "-q", "side"]);
7002
    let _ = run(&[
7003
        "rm",
7004
        "-q",
7005
        "--cached",
7006
        "--ignore-unmatch",
7007
        "c/y.txt",
7008
        "c/x.txt",
7009
    ]);
7010
    let _ = std::fs::remove_dir_all(g.join("c"));
7011
    write(&g, "n/x.txt", b"x\n");
7012
    git(&["add", "-A"]);
7013
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
7014
7015
    let repo = Repo::init(&root.join("o")).unwrap();
7016
    repo.import_git(&g, "main").unwrap();
7017
    let v = repo.verify_git_import(&g, "main").unwrap();
7018
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7019
    let st = repo
7020
        .load_state_history(&repo.bookmark_heads().unwrap())
7021
        .unwrap();
7022
    let view = st.tree().view();
7023
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7024
    assert!(view.entries.contains_key("n/x.txt"));
7025
}
7026
7027
/// oxygen#30, orphans: a file added on one line into a directory the other
7028
/// line removed is placed where the tree cannot show it; Git's merge keeps
7029
/// the file, and the import's merge leaves exactly one of it.
7030
#[test]
7031
fn git_import_merge_leaves_no_orphan_behind() {
7032
    hermetic();
7033
    if std::process::Command::new("git")
7034
        .arg("--version")
7035
        .output()
7036
        .is_err()
7037
    {
7038
        eprintln!("git not installed; skipping");
7039
        return;
7040
    }
7041
    let dir = tempfile::tempdir().unwrap();
7042
    let root = dir.path();
7043
    let g = root.join("src.git");
7044
    fs::create_dir_all(&g).unwrap();
7045
    let git = |args: &[&str]| {
7046
        let out = std::process::Command::new("git")
7047
            .arg("-C")
7048
            .arg(&g)
7049
            .args([
7050
                "-c",
7051
                "user.name=Grace",
7052
                "-c",
7053
                "[email protected]",
7054
                "-c",
7055
                "commit.gpgsign=false",
7056
            ])
7057
            .args(args)
7058
            .output()
7059
            .unwrap();
7060
        assert!(
7061
            out.status.success(),
7062
            "git {args:?}: {}",
7063
            String::from_utf8_lossy(&out.stderr)
7064
        );
7065
    };
7066
    git(&["init", "-q", "-b", "main"]);
7067
    write(&g, "d/f.txt", b"f\n");
7068
    write(&g, "keep.txt", b"k\n");
7069
    git(&["add", "."]);
7070
    git(&["commit", "-qm", "base"]);
7071
    git(&["checkout", "-qb", "side"]);
7072
    write(&g, "d/new.txt", b"new\n");
7073
    git(&["add", "."]);
7074
    git(&["commit", "-qm", "add into d"]);
7075
    git(&["checkout", "-q", "main"]);
7076
    git(&["rm", "-q", "d/f.txt"]);
7077
    git(&["commit", "-qm", "d goes"]);
7078
    git(&["merge", "-q", "--no-edit", "side"]);
7079
7080
    let repo = Repo::init(&root.join("o")).unwrap();
7081
    repo.import_git(&g, "main").unwrap();
7082
    let v = repo.verify_git_import(&g, "main").unwrap();
7083
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7084
    let st = repo
7085
        .load_state_history(&repo.bookmark_heads().unwrap())
7086
        .unwrap();
7087
    let view = st.tree().view();
7088
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7089
    assert!(view.entries.contains_key("d/new.txt"));
7090
}
7091
7092
/// fsck checks a change's text as the blobs it is stored in, without
7093
/// decoding it: a missing text blob is an error named for the change.
7094
#[test]
7095
fn fsck_names_a_missing_text_blob() {
7096
    hermetic();
7097
    let dir = tempfile::tempdir().unwrap();
7098
    let root = dir.path();
7099
    let repo = Repo::init(root).unwrap();
7100
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7101
    write(root, "big.txt", big.as_bytes());
7102
    let h = repo.commit("big", &[]).unwrap();
7103
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7104
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7105
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7106
        panic!("a stored text")
7107
    };
7108
    repo.store().remove_loose_for_test(&b).unwrap();
7109
    let rep = repo.fsck().unwrap();
7110
    assert!(rep.errors() > 0);
7111
    assert!(
7112
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7113
        "{:?}",
7114
        rep.problems
7115
    );
7116
}
7117
7118
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7119
/// reached with that remote's token and CA (a private subrepo then clones
7120
/// for anyone who can read the parent); another hub gets none of them.
7121
#[test]
7122
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7123
    hermetic();
7124
    let dir = tempfile::tempdir().unwrap();
7125
    let mut repo = Repo::init(dir.path()).unwrap();
7126
    repo.config
7127
        .set(
7128
            "remote.origin.url",
7129
            "https://Hub.example:7343/doomsdayone/metalgear",
7130
        )
7131
        .unwrap();
7132
    repo.config.set("remote.origin.token", "secret").unwrap();
7133
    repo.config
7134
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7135
        .unwrap();
7136
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7137
    assert_eq!(same.token.as_deref(), Some("secret"));
7138
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7139
    for other in [
7140
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7141
        "https://hub.example/doomsdayone/rstar-api",
7142
        "http://hub.example:7343/doomsdayone/rstar-api",
7143
    ] {
7144
        let o = repo.credentials_for(other);
7145
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7146
    }
7147
}
7148
7149
/// oxygen#47: a remote with no token of its own uses the user's credential
7150
/// store for its hub, and a nested checkout finds its parent's remote
7151
/// token there instead of keeping a copy.
7152
#[test]
7153
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7154
    hermetic();
7155
    let home = tempfile::tempdir().unwrap();
7156
    let dir = tempfile::tempdir().unwrap();
7157
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7158
    parent
7159
        .config
7160
        .set("remote.origin.url", "https://hub.example/o/parent")
7161
        .unwrap();
7162
    parent.save_config().unwrap();
7163
    assert_eq!(parent.remote_options("origin").token, None);
7164
    crate::credentials::Credentials::at(home.path())
7165
        .save("https://hub.example", "stored", Some("andy"), None)
7166
        .unwrap();
7167
    assert_eq!(
7168
        parent.remote_options("origin").token.as_deref(),
7169
        Some("stored")
7170
    );
7171
7172
    let empty_home = tempfile::tempdir().unwrap();
7173
    let nested = dir.path().join("deps").join("child");
7174
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7175
    child
7176
        .config
7177
        .set("remote.origin.url", "https://hub.example/o/child")
7178
        .unwrap();
7179
    child.save_config().unwrap();
7180
    assert_eq!(child.remote_options("origin").token, None);
7181
    parent
7182
        .config
7183
        .set("remote.origin.token", "checkout")
7184
        .unwrap();
7185
    parent.save_config().unwrap();
7186
    assert_eq!(
7187
        child.remote_options("origin").token.as_deref(),
7188
        Some("checkout")
7189
    );
7190
    // Another hub's checkout token is not borrowed.
7191
    child
7192
        .config
7193
        .set("remote.origin.url", "https://other.example/o/child")
7194
        .unwrap();
7195
    assert_eq!(child.remote_options("origin").token, None);
7196
}
7197
7198
#[test]
7199
fn the_metadata_cache_survives_a_torn_tail() {
7200
    hermetic();
7201
    let dir = tempfile::tempdir().unwrap();
7202
    let root = dir.path();
7203
    let repo = Repo::init(root).unwrap();
7204
    write(root, "a.txt", b"1\n");
7205
    let h = repo.commit("first", &[]).unwrap();
7206
    let meta = repo.store().get_change_meta(&h).unwrap();
7207
    let cache = repo.store().dir().join("metas");
7208
    let len = fs::metadata(&cache).unwrap().len();
7209
    assert!(len > 0, "a change read is cached");
7210
    // A torn record at the end: the cache reads up to it and cuts it off.
7211
    fs::OpenOptions::new()
7212
        .append(true)
7213
        .open(&cache)
7214
        .unwrap()
7215
        .write_all(&[7; 20])
7216
        .unwrap();
7217
    let again = Repo::open(root).unwrap();
7218
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7219
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7220
}
7221
7222
#[test]
7223
fn a_manifest_that_does_not_check_reads_as_none() {
7224
    hermetic();
7225
    let dir = tempfile::tempdir().unwrap();
7226
    let root = dir.path();
7227
    let repo = Repo::init(root).unwrap();
7228
    write(root, "a.txt", b"1\n");
7229
    repo.commit("first", &[]).unwrap();
7230
    let path = repo.manifest_path();
7231
    let mut bytes = fs::read(&path).unwrap();
7232
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7233
    let last = bytes.len() - 1;
7234
    bytes[last] ^= 1;
7235
    fs::write(&path, &bytes).unwrap();
7236
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7237
    // The next status reads the files and writes it again.
7238
    let again = Repo::open(root).unwrap();
7239
    assert!(!again.snapshot("status").unwrap().changed);
7240
    assert!(again.read_manifest().unwrap().is_some());
7241
}
7242
7243
#[test]
7244
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7245
    hermetic();
7246
    let dir = tempfile::tempdir().unwrap();
7247
    let root = dir.path();
7248
    let repo = Repo::init(root).unwrap();
7249
    write(root, "a.txt", b"1\n");
7250
    write(root, "b.txt", b"2\n");
7251
    // b.txt outside the racy window, so snapshots take it as unchanged.
7252
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7253
    fs::File::options()
7254
        .write(true)
7255
        .open(root.join("b.txt"))
7256
        .unwrap()
7257
        .set_modified(old)
7258
        .unwrap();
7259
    repo.commit("first", &[]).unwrap();
7260
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7261
    repo.snapshot_status("status").unwrap();
7262
    write(root, "a.txt", b"1\n2\n");
7263
    repo.commit("second", &[]).unwrap();
7264
    assert!(
7265
        repo.clean_by_manifest().unwrap(),
7266
        "after a commit of one file"
7267
    );
7268
    // Edited, seen by a status, edited again, then committed: the status
7269
    // left the first edit's stat, which the commit must not keep.
7270
    write(root, "a.txt", b"1\n2\n3\n");
7271
    repo.snapshot_status("status").unwrap();
7272
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7273
    repo.commit("third", &[]).unwrap();
7274
    assert!(
7275
        repo.clean_by_manifest().unwrap(),
7276
        "after an edit a status saw"
7277
    );
7278
}
7279
7280
#[test]
7281
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7282
    hermetic();
7283
    let dir = tempfile::tempdir().unwrap();
7284
    let root = dir.path();
7285
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7286
    write(root, "a.txt", b"1\n2\n");
7287
    let a = repo.commit("A", &[]).unwrap();
7288
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7289
    write(root, "a.txt", b"1\nX\n");
7290
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7291
    repo.bookmark_switch("develop", false).unwrap();
7292
    write(root, "a.txt", b"1\nY\n");
7293
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7294
    repo.bookmark_switch("main", false).unwrap();
7295
7296
    let err = repo.rebase(&c, &[d]).unwrap_err();
7297
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7298
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7299
    assert!(r.changed && r.checked_out);
7300
    let snap = repo.snapshot_status("status").unwrap();
7301
    assert!(
7302
        snap.base_snapshot.is_conflicted(),
7303
        "the conflict is in the working copy"
7304
    );
7305
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7306
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7307
7308
    write(root, "a.txt", b"1\nXY\n");
7309
    repo.commit("Resolve", &[]).unwrap();
7310
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7311
    assert!(st.contains(&c) && st.contains(&d));
7312
    let files = st.materialize().files;
7313
    assert!(!files["a.txt"].is_conflicted());
7314
    assert!(
7315
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7316
    );
7317
7318
    // A change the current bookmark does not hold is refused.
7319
    repo.bookmark_switch("develop", false).unwrap();
7320
    write(root, "b.txt", b"b\n");
7321
    let e = repo.commit("E", &[]).unwrap();
7322
    repo.bookmark_switch("main", false).unwrap();
7323
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7324
    assert!(
7325
        err.to_string().contains("not on the current bookmark"),
7326
        "{err}"
7327
    );
7328
}
7329
7330
#[test]
7331
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7332
    hermetic();
7333
    let dir = tempfile::tempdir().unwrap();
7334
    let root = dir.path();
7335
    let repo = Repo::init(root).unwrap();
7336
    write(root, "a.txt", b"a\n");
7337
    write(root, "kept.log", b"tracked\n");
7338
    repo.commit("first", &[]).unwrap();
7339
    write(root, "build.log", b"made\n");
7340
    let snap = repo.snapshot_status("status").unwrap();
7341
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7342
    // A rule written afterwards leaves the added file out again, while the
7343
    // committed one stays tracked.
7344
    write(root, ".gitignore", b"*.log\n");
7345
    let snap = repo.snapshot_status("status").unwrap();
7346
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7347
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7348
    write(root, "kept.log", b"tracked, edited\n");
7349
    let snap = repo.snapshot_status("status").unwrap();
7350
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7351
}
7352
7353
#[test]
7354
fn shed_graphs_come_back_the_same() {
7355
    hermetic();
7356
    let dir = tempfile::tempdir().unwrap();
7357
    let root = dir.path();
7358
    let repo = Repo::init(root).unwrap();
7359
    write(root, "a.txt", b"1\n2\n3\n");
7360
    write(root, "b.txt", b"x\n");
7361
    repo.commit("first", &[]).unwrap();
7362
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7363
    repo.commit("second", &[]).unwrap();
7364
    let heads = repo.bookmark_heads().unwrap();
7365
    let mut st = repo.load_state_history(&heads).unwrap();
7366
    let view = st.tree().view();
7367
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7368
        .iter()
7369
        .map(|p| view.entries[*p].node)
7370
        .collect();
7371
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7372
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7373
    assert_eq!(st.built_count(), 2);
7374
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7375
    assert_eq!((shed, st.built_count()), (2, 0));
7376
    // A later change applies on top of the shed history.
7377
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7378
    let h3 = repo.commit("third", &[]).unwrap();
7379
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7380
    st.add_known(h3, skeleton, texts);
7381
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7382
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7383
    assert_eq!(after[1], before[1]);
7384
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7385
}
7386
7387
#[test]
7388
fn many_edited_files_diff_in_parallel() {
7389
    // Enough edited files that the builder diffs them in parallel; the
7390
    // commit must hold exactly what is on disk, and a second snapshot
7391
    // must find nothing left to commit.
7392
    hermetic();
7393
    let dir = tempfile::tempdir().unwrap();
7394
    let root = dir.path();
7395
    let repo = Repo::init(root).unwrap();
7396
    let text = |i: usize, round: usize| {
7397
        let mut s = String::new();
7398
        for line in 0..50 {
7399
            if round > 0 && line % 7 == i % 7 {
7400
                s.push_str(&format!("edited {round} {i} {line}\n"));
7401
            } else {
7402
                s.push_str(&format!("file {i} line {line}\n"));
7403
            }
7404
        }
7405
        if round > 0 && i.is_multiple_of(3) {
7406
            s.push_str("appended\n");
7407
        }
7408
        s
7409
    };
7410
    for i in 0..40 {
7411
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7412
    }
7413
    repo.commit("first", &[]).unwrap();
7414
    for i in 0..40 {
7415
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7416
    }
7417
    let h = repo.commit("edit every file", &[]).unwrap();
7418
    let snap = repo.load_state(&[h]).unwrap().materialize();
7419
    for i in 0..40 {
7420
        let want = text(i, 1);
7421
        assert!(
7422
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
7423
            "d/f{i}.txt as committed"
7424
        );
7425
    }
7426
    assert!(
7427
        repo.commit("nothing", &[]).is_err(),
7428
        "nothing left to commit"
7429
    );
7430
}
7431
7432
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7433
/// is known (fetch printed "up to date" while main was behind), a change
7434
/// only fetched resolves and says where it is, and a checkout whose only
7435
/// remote is not `origin` uses that one.
7436
#[test]
7437
fn a_fetched_change_shows_as_behind_and_resolves() {
7438
    hermetic();
7439
    let dir = tempfile::tempdir().unwrap();
7440
    let root = dir.path();
7441
    let origin = Repo::init(&root.join("origin")).unwrap();
7442
    drop(origin);
7443
    let url = root.join("origin").to_string_lossy().to_string();
7444
    let a = Repo::clone(&url, &root.join("a"))
7445
        .unwrap()
7446
        .with_home(root.join("home-a"));
7447
    write(&root.join("a"), "f.txt", b"one\n");
7448
    a.commit("one", &[]).unwrap();
7449
    a.push("origin", false).unwrap();
7450
    let b = Repo::clone(&url, &root.join("b"))
7451
        .unwrap()
7452
        .with_home(root.join("home-b"));
7453
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7454
7455
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7456
    let h2 = a.commit("two", &[]).unwrap();
7457
    a.push("origin", false).unwrap();
7458
    b.fetch("origin").unwrap();
7459
    // Fetched, not pulled: one behind, the change found and placed.
7460
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7461
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7462
    assert_eq!(
7463
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7464
            .unwrap(),
7465
        h2
7466
    );
7467
    assert_eq!(
7468
        b.remote_only_location(&h2).unwrap().as_deref(),
7469
        Some("origin/main")
7470
    );
7471
    // Fetching again changes nothing: still behind, which is what the
7472
    // CLI now says rather than "up to date".
7473
    b.fetch("origin").unwrap();
7474
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7475
    b.pull("origin").unwrap();
7476
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7477
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7478
7479
    // One remote, not called origin: it is the default.
7480
    let mut c = Repo::init(&root.join("c")).unwrap();
7481
    assert_eq!(c.default_remote(), "origin");
7482
    c.config.set("remote.earth.url", &url).unwrap();
7483
    assert_eq!(c.default_remote(), "earth");
7484
    c.config.set("remote.origin.url", &url).unwrap();
7485
    assert_eq!(c.default_remote(), "origin");
7486
}
7487
7488
/// oxygen#57: a clone from a relative local path records the remote as an
7489
/// absolute path, so fetch still finds it from inside the clone.
7490
#[test]
7491
fn a_clone_from_a_relative_path_records_it_absolute() {
7492
    hermetic();
7493
    let dir = tempfile::tempdir().unwrap();
7494
    let root = dir.path();
7495
    Repo::init(&root.join("origin")).unwrap();
7496
    let rel = crate::protocol::stored_url("relative/repo");
7497
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7498
    assert_eq!(
7499
        crate::protocol::stored_url("https://hub.example/o/n"),
7500
        "https://hub.example/o/n"
7501
    );
7502
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7503
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7504
    // A bucket is kept as written: it is not a path.
7505
    assert_eq!(
7506
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7507
        "s3://bucket/prefix?profile=p"
7508
    );
7509
    let url = root.join("origin").to_string_lossy().to_string();
7510
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7511
    assert_eq!(b.config.remotes["origin"], url);
7512
    b.fetch("origin").unwrap();
7513
}
7514
7515
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7516
/// and gets its subrepos at their pins from this workspace's copies, with
7517
/// their remotes pointing where the subrepos come from.
7518
#[test]
7519
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7520
    hermetic();
7521
    let dir = tempfile::tempdir().unwrap();
7522
    let root = dir.path();
7523
    Repo::init(&root.join("lib-origin")).unwrap();
7524
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7525
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7526
        .unwrap()
7527
        .with_home(root.join("home"));
7528
    write(&root.join("lib"), "lib.txt", b"v1\n");
7529
    let l1 = lib.commit("lib v1", &[]).unwrap();
7530
    assert!(lib.push("origin", false).unwrap()[0].ok);
7531
7532
    let app_dir = root.join("app");
7533
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7534
    write(&app_dir, "main.txt", b"app\n");
7535
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7536
    app.commit("app with lib", &[]).unwrap();
7537
    // A second bookmark, and the main workspace on another.
7538
    app.bookmark_create("develop", None).unwrap();
7539
    app.bookmark_create("feature", None).unwrap();
7540
    let mut app = app;
7541
    app.bookmark_switch("feature", false).unwrap();
7542
    assert_eq!(app.config.bookmark, "feature");
7543
7544
    // The library's origin goes away: the subrepo must come from here.
7545
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7546
    let heads = app.resolve_heads("develop").unwrap();
7547
    let ws = app
7548
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7549
        .unwrap();
7550
    assert_eq!(
7551
        ws.config.bookmark, "develop",
7552
        "the new workspace is on develop"
7553
    );
7554
    assert_eq!(
7555
        app.config.bookmark, "feature",
7556
        "and this one stays on its own"
7557
    );
7558
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7559
    assert_eq!(
7560
        sub.config.remotes["origin"], lib_url,
7561
        "its origin is the subrepo's URL"
7562
    );
7563
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7564
    assert_eq!(
7565
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7566
        b"v1\n"
7567
    );
7568
}
7569
7570
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7571
/// operators and the predicates, over a small graph with two heads and
7572
/// a rename.
7573
#[test]
7574
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7575
    hermetic();
7576
    let dir = tempfile::tempdir().unwrap();
7577
    let root = dir.path();
7578
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7579
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7580
        .unwrap();
7581
    write(root, "src/a.rs", b"one\n");
7582
    let a = repo.commit("first: add a", &[]).unwrap();
7583
    write(root, "src/a.rs", b"one\ntwo\n");
7584
    let b = repo.commit("second: grow a", &[]).unwrap();
7585
    // A second head, independent of b: a new file on top of a.
7586
    repo.checkout(&[a], false, "checkout a").unwrap();
7587
    write(root, "docs/notes.md", b"notes\n");
7588
    let c = repo.commit("third: notes", &[]).unwrap();
7589
    // Back to both heads, then rename a.rs: the node keeps its identity.
7590
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7591
        .unwrap();
7592
    fs::remove_file(root.join("src/a.rs")).unwrap();
7593
    write(root, "src/z.rs", b"one\ntwo\n");
7594
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7595
    let wc = repo.working_copy().unwrap().0;
7596
    // A saved revset is checked when set.
7597
    repo.set_user_config("revset.mine", "author(me) & ::main")
7598
        .unwrap();
7599
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7600
    let set = |src: &str| -> Vec<ChangeHash> {
7601
        let mut v = repo.revset(src).unwrap().hashes;
7602
        v.sort();
7603
        v
7604
    };
7605
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7606
        let mut v = hs.to_vec();
7607
        v.sort();
7608
        v
7609
    };
7610
7611
    // Changes commute: a new file depends on nothing and the rename on the
7612
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7613
    // copy on the three heads b, c, d.
7614
    let heads = sorted(&repo.bookmark_heads().unwrap());
7615
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7616
    assert!(heads.contains(&d) && heads.contains(&c));
7617
    // Symbols and closures.
7618
    assert_eq!(set("main"), heads);
7619
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7620
    assert_eq!(set("@"), vec![wc]);
7621
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7622
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7623
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7624
    assert_eq!(
7625
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7626
        sorted(&[a, b])
7627
    );
7628
    // Ranges: what main has beyond b, and `..` forms.
7629
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7630
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7631
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7632
    // Operators and precedence: ~ binds tighter than &, & than |.
7633
    assert_eq!(
7634
        set(&format!("::main ~ #{}", d.short(12))),
7635
        sorted(&[a, b, c])
7636
    );
7637
    assert_eq!(
7638
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7639
        sorted(&[b, c])
7640
    );
7641
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7642
    // Relations.
7643
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7644
    head_deps.sort();
7645
    head_deps.dedup();
7646
    assert_eq!(set("deps(main)"), head_deps);
7647
    let on_a: Vec<ChangeHash> = [b, c, d]
7648
        .into_iter()
7649
        .filter(|h| meta(h).deps.contains(&a))
7650
        .collect();
7651
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7652
    assert_eq!(set("heads(::main)"), heads);
7653
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7654
    assert_eq!(
7655
        set(&format!(
7656
            "heads(#{} | #{} | #{})",
7657
            a.short(12),
7658
            b.short(12),
7659
            c.short(12)
7660
        )),
7661
        sorted(&[b, c])
7662
    );
7663
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7664
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7665
    assert_eq!(set("none()"), vec![]);
7666
    // Predicates: author by name, email, key prefix and `me`.
7667
    let key = repo.config.author_key.unwrap();
7668
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7669
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7670
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7671
    assert_eq!(set("author(me) & ::main").len(), 4);
7672
    assert_eq!(set("author(nobody)"), vec![]);
7673
    assert_eq!(set("description(notes)"), vec![c]);
7674
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7675
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7676
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7677
    // touches follows the node through the rename, in the current state.
7678
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7679
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7680
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7681
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7682
    // Newest first in the result order.
7683
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7684
    // The saved revset, and errors that say what is wrong.
7685
    assert_eq!(set("mine()").len(), 4);
7686
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7687
    assert!(e.contains("unknown function nosuch()"), "{e}");
7688
    let e = repo.revset("main &").unwrap_err().to_string();
7689
    assert!(e.contains("at character"), "{e}");
7690
    let e = repo.revset("zzzz").unwrap_err().to_string();
7691
    assert!(e.contains("no change matches"), "{e}");
7692
    let e = repo
7693
        .revset_with_budget("::main", std::time::Duration::ZERO)
7694
        .unwrap_err()
7695
        .to_string();
7696
    assert!(e.contains("budget"), "{e}");
7697
    // The log entries carry the bookmark's heads and the working copy.
7698
    let entries = repo.log_revset("::@").unwrap();
7699
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7700
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7701
    // push); then a signed change, a tag, and a revocation.
7702
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7703
    assert_eq!(set("signed_by(me)"), vec![]);
7704
    repo.sign_change(&d).unwrap();
7705
    assert_eq!(set("signed_by(me)"), vec![d]);
7706
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7707
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7708
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7709
    assert_eq!(set("delegated()"), vec![]);
7710
    assert_eq!(set("revoked()"), vec![]);
7711
    assert_eq!(set("attested(tag)"), vec![]);
7712
    repo.tag_create("v1", &[b], "first").unwrap();
7713
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7714
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7715
    assert_eq!(set("attested(receipt)"), vec![]);
7716
    assert_eq!(set("built(test)"), vec![]);
7717
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7718
    assert!(e.contains("tag, receipt or ref"), "{e}");
7719
    repo.revoke_identity(&key, "test").unwrap();
7720
    assert_eq!(set("revoked()"), vec![d]);
7721
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7722
    // independent(X, IN): what could ship without X. c and d neither
7723
    // depend on b nor are depended on by it; a is below, the working copy
7724
    // above.
7725
    assert_eq!(
7726
        set(&format!("independent(#{}, ::@)", b.short(12))),
7727
        sorted(&[c, d])
7728
    );
7729
    assert_eq!(
7730
        set(&format!("independent(#{}, ::main)", a.short(12))),
7731
        vec![c]
7732
    );
7733
    // conflicts(S): nothing conflicts yet; then two edits of one line.
7734
    assert_eq!(set("conflicts()"), vec![]);
7735
    assert_eq!(set("conflicts(main)"), vec![]);
7736
    // (The saved revset above edited the user config under the root:
7737
    // discard it.)
7738
    repo.checkout(&[a], true, "checkout a").unwrap();
7739
    write(root, "src/a.rs", b"one\nTWO\n");
7740
    let e = repo
7741
        .commit("fifth: the other edit of line two", &[])
7742
        .unwrap();
7743
    repo.checkout(&repo.bookmark_heads().unwrap(), true, "checkout main")
7744
        .unwrap();
7745
    let conflicted = repo.revset("conflicts()").unwrap().hashes;
7746
    assert!(
7747
        conflicted.contains(&e) && conflicted.contains(&b),
7748
        "{conflicted:?} should hold b and e"
7749
    );
7750
    assert!(!conflicted.contains(&c));
7751
    assert_eq!(set("conflicts() & author(nobody)"), vec![]);
7752
}
7753
7754
#[test]
7755
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7756
    let dir = tempfile::tempdir().unwrap();
7757
    let root = dir.path();
7758
    let home = root.join("home");
7759
    // Ada's identity lives in the user file; repository `a` pins the same
7760
    // key in its own file, repository `b` names none.
7761
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7762
    let (key, _) = a
7763
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7764
        .unwrap();
7765
    a.config.set("author.key", &key.to_hex()).unwrap();
7766
    a.save_config().unwrap();
7767
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7768
    let r = a
7769
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7770
        .unwrap();
7771
    assert_eq!(
7772
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7773
        r.new.to_hex(),
7774
        "the user file follows"
7775
    );
7776
    assert_eq!(
7777
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7778
        r.new.to_hex(),
7779
        "the pinning repository follows"
7780
    );
7781
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7782
    assert_eq!(
7783
        b.config.author_key,
7784
        Some(r.new),
7785
        "a checkout without a pin follows the user file"
7786
    );
7787
    // A repository-scoped identity leaves the user file alone.
7788
    let other_home = root.join("home2");
7789
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7790
    let (ck, _) = c
7791
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7792
        .unwrap();
7793
    assert!(!other_home.join("config.toml").exists());
7794
    let r2 = c.rotate_identity().unwrap();
7795
    assert_ne!(r2.new, ck);
7796
    assert_eq!(
7797
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7798
        r2.new.to_hex()
7799
    );
7800
    assert!(
7801
        !other_home.join("config.toml").exists(),
7802
        "a repository-scoped identity stays repository-scoped"
7803
    );
7804
    // Several delegates in one rotation; a repeat is refused.
7805
    let (d1, d2) = (
7806
        SecretKey::generate().identity("D1", "d1@x", 1),
7807
        SecretKey::generate().identity("D2", "d2@x", 1),
7808
    );
7809
    let r3 = c
7810
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7811
        .unwrap();
7812
    assert_eq!(r3.identity.delegates.len(), 2);
7813
    assert!(c
7814
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7815
        .is_err());
7816
}
7817
7818
/// Two unrelated histories that both add the same file, joined by two
7819
/// independent merges on two branches, then those branches merged: Git
7820
/// merges identical additions cleanly, and the import must too (#71,
7821
/// found in VS Code's history).
7822
#[test]
7823
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7824
    // Batches of one: every merge renders apart from the state, where a
7825
    // file whose graph the state had built came out empty (#71).
7826
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7827
    hermetic();
7828
    if std::process::Command::new("git")
7829
        .arg("--version")
7830
        .output()
7831
        .is_err()
7832
    {
7833
        eprintln!("git not installed; skipping");
7834
        return;
7835
    }
7836
    let dir = tempfile::tempdir().unwrap();
7837
    let root = dir.path();
7838
    let g = root.join("src.git");
7839
    fs::create_dir_all(&g).unwrap();
7840
    let git = |args: &[&str]| -> String {
7841
        let out = std::process::Command::new("git")
7842
            .arg("-C")
7843
            .arg(&g)
7844
            .args([
7845
                "-c",
7846
                "user.name=Grace",
7847
                "-c",
7848
                "[email protected]",
7849
                "-c",
7850
                "commit.gpgsign=false",
7851
            ])
7852
            .args(args)
7853
            .output()
7854
            .unwrap();
7855
        assert!(
7856
            out.status.success(),
7857
            "git {args:?}: {}",
7858
            String::from_utf8_lossy(&out.stderr)
7859
        );
7860
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7861
    };
7862
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7863
    // History A: main.
7864
    git(&["init", "-q", "-b", "main"]);
7865
    write(&g, "gulpfile.js", text);
7866
    write(&g, "a.txt", b"a\n");
7867
    git(&["add", "."]);
7868
    git(&["commit", "-q", "-m", "A root"]);
7869
    // History B: an unrelated root adding the same file, identical.
7870
    git(&["checkout", "-q", "--orphan", "fork"]);
7871
    git(&["rm", "-q", "-r", "--cached", "."]);
7872
    for f in ["gulpfile.js", "a.txt"] {
7873
        let _ = fs::remove_file(g.join(f));
7874
    }
7875
    write(&g, "gulpfile.js", text);
7876
    write(&g, "b.txt", b"b\n");
7877
    git(&["add", "."]);
7878
    git(&["commit", "-q", "-m", "B root"]);
7879
    // Two branches from main, each joining B on its own.
7880
    git(&["checkout", "-q", "-b", "one", "main"]);
7881
    git(&[
7882
        "merge",
7883
        "-q",
7884
        "--no-ff",
7885
        "--allow-unrelated-histories",
7886
        "-m",
7887
        "join on one",
7888
        "fork",
7889
    ]);
7890
    git(&["checkout", "-q", "-b", "two", "main"]);
7891
    write(&g, "a.txt", b"a\ntwo\n");
7892
    git(&["commit", "-q", "-am", "work on two"]);
7893
    git(&[
7894
        "merge",
7895
        "-q",
7896
        "--no-ff",
7897
        "--allow-unrelated-histories",
7898
        "-m",
7899
        "join on two",
7900
        "fork",
7901
    ]);
7902
    // Then the two joins meet, and the file is reformatted after.
7903
    git(&["checkout", "-q", "main"]);
7904
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7905
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7906
    write(
7907
        &g,
7908
        "gulpfile.js",
7909
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7910
    );
7911
    git(&["commit", "-q", "-am", "after"]);
7912
7913
    let dest = root.join("dest");
7914
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7915
    repo.import_git(&g, "main").unwrap();
7916
    let v = repo.verify_git_import(&g, "main").unwrap();
7917
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7918
    assert_eq!(
7919
        fs::read(dest.join("gulpfile.js")).unwrap(),
7920
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7921
    );
7922
}
7923
7924
/// As above, but the two joins keep different copies (each branch had a
7925
/// different version when it joined), and later work edits each copy:
7926
/// the shape of VS Code's c67ef57cda90 (#71).
7927
#[test]
7928
fn git_import_joins_where_each_join_kept_a_different_copy() {
7929
    // Batches of one: every merge renders apart from the state, where a
7930
    // file whose graph the state had built came out empty (#71).
7931
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7932
    hermetic();
7933
    if std::process::Command::new("git")
7934
        .arg("--version")
7935
        .output()
7936
        .is_err()
7937
    {
7938
        eprintln!("git not installed; skipping");
7939
        return;
7940
    }
7941
    let dir = tempfile::tempdir().unwrap();
7942
    let root = dir.path();
7943
    let g = root.join("src.git");
7944
    fs::create_dir_all(&g).unwrap();
7945
    let run = |args: &[&str]| {
7946
        std::process::Command::new("git")
7947
            .arg("-C")
7948
            .arg(&g)
7949
            .args([
7950
                "-c",
7951
                "user.name=Grace",
7952
                "-c",
7953
                "[email protected]",
7954
                "-c",
7955
                "commit.gpgsign=false",
7956
            ])
7957
            .args(args)
7958
            .output()
7959
            .unwrap()
7960
    };
7961
    let git = |args: &[&str]| -> String {
7962
        let out = run(args);
7963
        assert!(
7964
            out.status.success(),
7965
            "git {args:?}: {}",
7966
            String::from_utf8_lossy(&out.stderr)
7967
        );
7968
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7969
    };
7970
    git(&["init", "-q", "-b", "main"]);
7971
    write(
7972
        &g,
7973
        "gulpfile.js",
7974
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7975
    );
7976
    git(&["add", "."]);
7977
    git(&["commit", "-q", "-m", "A root"]);
7978
    write(
7979
        &g,
7980
        "gulpfile.js",
7981
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7982
    );
7983
    git(&["commit", "-q", "-am", "whitespace"]);
7984
    git(&["checkout", "-q", "--orphan", "fork"]);
7985
    git(&["rm", "-q", "-r", "--cached", "."]);
7986
    let _ = fs::remove_file(g.join("gulpfile.js"));
7987
    write(
7988
        &g,
7989
        "gulpfile.js",
7990
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7991
    );
7992
    git(&["add", "."]);
7993
    git(&["commit", "-q", "-m", "B root"]);
7994
    // Branch one joins B keeping main's copy; branch two keeps B's.
7995
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7996
        git(&["checkout", "-q", "-b", branch, "main"]);
7997
        let _ = run(&[
7998
            "merge",
7999
            "-q",
8000
            "--no-ff",
8001
            "--allow-unrelated-histories",
8002
            "-m",
8003
            "join",
8004
            "fork",
8005
        ]);
8006
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
8007
        git(&["add", "gulpfile.js"]);
8008
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
8009
    }
8010
    // Each branch then edits its copy.
8011
    git(&["checkout", "-q", "one"]);
8012
    write(
8013
        &g,
8014
        "gulpfile.js",
8015
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
8016
    );
8017
    git(&["commit", "-q", "-am", "tslint on one"]);
8018
    git(&["checkout", "-q", "two"]);
8019
    write(
8020
        &g,
8021
        "gulpfile.js",
8022
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
8023
    );
8024
    write(&g, "extra.txt", b"x\n");
8025
    write(&g, "more.txt", b"m\n");
8026
    git(&["add", "."]);
8027
    git(&["commit", "-q", "-am", "fmt on two"]);
8028
    // They meet: resolved by hand.
8029
    git(&["checkout", "-q", "one"]);
8030
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8031
    write(
8032
        &g,
8033
        "gulpfile.js",
8034
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
8035
    );
8036
    git(&["add", "gulpfile.js"]);
8037
    git(&["commit", "-q", "-m", "merge two into one"]);
8038
8039
    let dest = root.join("dest");
8040
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8041
    repo.import_git(&g, "one").unwrap();
8042
    let v = repo.verify_git_import(&g, "one").unwrap();
8043
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8044
}
8045
8046
/// oxygen#68: on a store that is not this disk's directory, the operation
8047
/// head is the store's reference record, moved by compare-and-swap. Two
8048
/// handles recording from the same head both get through, merged; a swap
8049
/// from a stale version is refused; a second repository cannot start on a
8050
/// store that already holds one.
8051
#[test]
8052
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8053
    use crate::strata::{MemoryStore, Store as _};
8054
    let backend = std::sync::Arc::new(MemoryStore::new());
8055
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8056
    let dir = tempfile::tempdir().unwrap();
8057
    let a = Repo::init(dir.path()).unwrap();
8058
    assert!(
8059
        !dir.path().join(".oxy/ops/head").exists(),
8060
        "the head is not a file"
8061
    );
8062
    let (h0, op0) = a.head_op().unwrap();
8063
    let record = backend
8064
        .read_ref(HEAD_RECORD)
8065
        .unwrap()
8066
        .expect("the head is the store's record");
8067
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8068
8069
    let b = Repo::open(dir.path()).unwrap();
8070
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8071
    let mut va = op0.view.clone();
8072
    va.bookmarks.insert("from-a".into(), state);
8073
    let mut vb = op0.view.clone();
8074
    vb.bookmarks.insert("from-b".into(), state);
8075
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8076
    assert_eq!(b.head_ref().unwrap(), rb);
8077
    // a recorded from h0 too: the head moved, so the two are merged.
8078
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8079
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8080
    assert_eq!(head, ra);
8081
    assert!(
8082
        op.command.ends_with("(merged with a concurrent operation)"),
8083
        "{}",
8084
        op.command
8085
    );
8086
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8087
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8088
8089
    // A swap from a version that is no longer current moves nothing.
8090
    let (h, v) = a.read_head().unwrap();
8091
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8092
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8093
    a.refresh().unwrap();
8094
    assert_eq!(a.head_ref().unwrap(), rb);
8095
8096
    let other = tempfile::tempdir().unwrap();
8097
    let err = Repo::init(other.path())
8098
        .err()
8099
        .expect("the store already holds a log")
8100
        .to_string();
8101
    assert!(
8102
        err.contains("already holds a repository's operation log"),
8103
        "{err}"
8104
    );
8105
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8106
}
8107
8108
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8109
/// objects and operation head there, with `.oxy/cache` in front: it works
8110
/// as one on disk does, reopens, and survives losing its cache.
8111
#[test]
8112
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8113
    hermetic();
8114
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8115
        return;
8116
    }
8117
    let dir = tempfile::tempdir().unwrap();
8118
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8119
    let url = format!("dir://{}", bucket.display());
8120
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8121
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8122
    write(&root, "a.txt", b"one\n");
8123
    let h1 = repo.commit("First", &[]).unwrap();
8124
    write(&root, "a.txt", b"one\ntwo\n");
8125
    let h2 = repo.commit("Second", &[]).unwrap();
8126
    assert!(
8127
        !root.join(".oxy/ops/head").exists(),
8128
        "the head is in the store"
8129
    );
8130
    assert!(bucket.join("ops/head").is_file());
8131
    assert!(root.join(".oxy/cache").is_dir());
8132
    drop(repo);
8133
8134
    // Reopened, and again with no cache at all: everything comes from the store.
8135
    for drop_cache in [false, true] {
8136
        if drop_cache {
8137
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8138
        }
8139
        let repo = Repo::open(&root).unwrap();
8140
        let log: Vec<String> = repo
8141
            .op_log()
8142
            .unwrap()
8143
            .into_iter()
8144
            .map(|(_, op)| op.command)
8145
            .collect();
8146
        assert!(log.len() >= 3, "{log:?}");
8147
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8148
        let heads = repo
8149
            .store()
8150
            .get_state(&repo.view().unwrap().bookmarks["main"])
8151
            .unwrap()
8152
            .heads;
8153
        assert_eq!(heads, vec![h2]);
8154
        assert_eq!(
8155
            repo.load_state(&heads).unwrap().materialize().files.len(),
8156
            1
8157
        );
8158
    }
8159
8160
    // A second repository cannot start on the same store.
8161
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8162
        .err()
8163
        .unwrap()
8164
        .to_string();
8165
    assert!(
8166
        err.contains("already holds a repository's operation log"),
8167
        "{err}"
8168
    );
8169
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8170
        .err()
8171
        .unwrap()
8172
        .to_string();
8173
    assert!(err.contains("cannot open that kind of store"), "{err}");
8174
}
8175
8176
/// oxygen#75: the prompt's quick check agrees with status in a repository
8177
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8178
/// another state, clean again once that pin is committed. (It compared the
8179
/// subrepo's directory as if it were a file, so it was always dirty.)
8180
#[test]
8181
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8182
    hermetic();
8183
    let dir = tempfile::tempdir().unwrap();
8184
    let root = dir.path();
8185
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8186
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8187
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8188
        .unwrap()
8189
        .with_home(root.join("home"));
8190
    write(&root.join("lib"), "lib.txt", b"v1\n");
8191
    lib.commit("lib v1", &[]).unwrap();
8192
    assert!(lib.push("origin", false).unwrap()[0].ok);
8193
    let app_dir = root.join("app");
8194
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8195
    write(&app_dir, "main.txt", b"app\n");
8196
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8197
    app.commit("app with lib", &[]).unwrap();
8198
    // Out of the racy window, so the stat-only path decides.
8199
    std::thread::sleep(std::time::Duration::from_millis(2100));
8200
    let reopen = || Repo::open(&app_dir).unwrap();
8201
    assert_eq!(
8202
        reopen().quick_dirty().unwrap(),
8203
        Some(false),
8204
        "clean, as status says"
8205
    );
8206
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8207
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8208
    nested.commit("lib v2", &[]).unwrap();
8209
    assert_eq!(
8210
        reopen().quick_dirty().unwrap(),
8211
        Some(true),
8212
        "the subrepo moved"
8213
    );
8214
    reopen().commit("pin lib v2", &[]).unwrap();
8215
    std::thread::sleep(std::time::Duration::from_millis(2100));
8216
    assert_eq!(
8217
        reopen().quick_dirty().unwrap(),
8218
        Some(false),
8219
        "the new pin is committed"
8220
    );
8221
}
8222
8223
#[test]
8224
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8225
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8226
    hermetic();
8227
    let dir = tempfile::tempdir().unwrap();
8228
    let root = dir.path();
8229
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8230
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8231
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8232
        .unwrap()
8233
        .with_home(root.join("home"));
8234
    write(&root.join("lib"), "lib.txt", b"v1\n");
8235
    lib.commit("lib v1", &[]).unwrap();
8236
    assert!(lib.push("origin", false).unwrap()[0].ok);
8237
    let app_dir = root.join("app");
8238
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8239
    write(
8240
        &app_dir,
8241
        ".oxymodules",
8242
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8243
    );
8244
    let unpinned = app.unpinned_modules().unwrap();
8245
    assert_eq!(unpinned.len(), 1);
8246
    assert_eq!(unpinned[0].0, "libs/lib");
8247
    assert_eq!(unpinned[0].1.url, lib_url);
8248
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8249
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8250
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8251
}
8252
8253
#[test]
8254
fn the_bookmark_revset_function_names_only_bookmarks() {
8255
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8256
    hermetic();
8257
    let dir = tempfile::tempdir().unwrap();
8258
    let repo = Repo::init(dir.path()).unwrap();
8259
    write(dir.path(), "a.txt", b"a\n");
8260
    let a = repo.commit("A", &[]).unwrap();
8261
    write(dir.path(), "b.txt", b"b\n");
8262
    let b = repo.commit("B", &[]).unwrap();
8263
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8264
    heads.sort();
8265
    let mut want = repo.bookmark_heads().unwrap();
8266
    want.sort();
8267
    assert_eq!(heads, want);
8268
    assert!(heads.contains(&b));
8269
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8270
    // A change prefix is a symbol, not a bookmark.
8271
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8272
    assert!(repo.revset(&prefix).is_ok());
8273
    let e = repo
8274
        .revset(&format!("bookmark({prefix})"))
8275
        .unwrap_err()
8276
        .to_string();
8277
    assert!(e.contains("no such bookmark"), "{e}");
8278
}
8279
8280
#[test]
8281
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8282
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8283
    // pinning the subrepo, and the nested repository on disk at that pin.
8284
    hermetic();
8285
    let dir = tempfile::tempdir().unwrap();
8286
    let root = dir.path();
8287
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8288
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8289
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8290
        .unwrap()
8291
        .with_home(root.join("home"));
8292
    write(&root.join("lib"), "lib.txt", b"v1\n");
8293
    lib.commit("lib v1", &[]).unwrap();
8294
    assert!(lib.push("origin", false).unwrap()[0].ok);
8295
    let app_dir = root.join("app");
8296
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8297
    write(&app_dir, "main.txt", b"app\n");
8298
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8299
    // The stale state: registered in .oxymodules, never pinned.
8300
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8301
    app.commit("initial", &[]).unwrap();
8302
    let stale = app.bookmark_heads().unwrap();
8303
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8304
    app.commit("pin lib", &[]).unwrap();
8305
    let newer = app.bookmark_heads().unwrap();
8306
    app.checkout(&stale, false, "test").unwrap();
8307
    write(&app_dir, "notes.txt", b"mine\n");
8308
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8309
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8310
    assert!(app_dir.join("notes.txt").exists());
8311
}
8312
8313
#[test]
8314
fn a_bookmark_only_behind_its_remote_catches_up() {
8315
    // oxygen#74: switch takes the remote's state rather than a stale one.
8316
    hermetic();
8317
    let dir = tempfile::tempdir().unwrap();
8318
    let root = dir.path();
8319
    let _origin = Repo::init(&root.join("origin")).unwrap();
8320
    let url = root.join("origin").to_string_lossy().to_string();
8321
    let one = Repo::clone(&url, &root.join("one"))
8322
        .unwrap()
8323
        .with_home(root.join("home"));
8324
    write(&root.join("one"), "a.txt", b"a\n");
8325
    one.commit("A", &[]).unwrap();
8326
    assert!(one.push("origin", false).unwrap()[0].ok);
8327
    let two = Repo::clone(&url, &root.join("two"))
8328
        .unwrap()
8329
        .with_home(root.join("home"));
8330
    write(&root.join("two"), "b.txt", b"b\n");
8331
    two.commit("B", &[]).unwrap();
8332
    assert!(two.push("origin", false).unwrap()[0].ok);
8333
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8334
    one.fetch("origin").unwrap();
8335
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8336
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8337
    // Local work the remote lacks: left alone.
8338
    write(&root.join("one"), "c.txt", b"c\n");
8339
    one.commit("C", &[]).unwrap();
8340
    write(&root.join("two"), "d.txt", b"d\n");
8341
    two.commit("D", &[]).unwrap();
8342
    assert!(two.push("origin", false).unwrap()[0].ok);
8343
    one.fetch("origin").unwrap();
8344
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8345
}
8346
8347
#[test]
8348
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8349
    // oxygen#83: remotes earth and gcs, origin removed.
8350
    hermetic();
8351
    let dir = tempfile::tempdir().unwrap();
8352
    let root = dir.path();
8353
    let _up = Repo::init(&root.join("up")).unwrap();
8354
    let url = root.join("up").to_string_lossy().to_string();
8355
    let other = Repo::clone(&url, &root.join("other"))
8356
        .unwrap()
8357
        .with_home(root.join("home"));
8358
    write(&root.join("other"), "a.txt", b"a\n");
8359
    other.commit("a", &[]).unwrap();
8360
    assert!(other.push("origin", false).unwrap()[0].ok);
8361
    let mut one = Repo::clone(&url, &root.join("one"))
8362
        .unwrap()
8363
        .with_home(root.join("home"));
8364
    one.config.set("remote.earth.url", &url).unwrap();
8365
    one.config.set("remote.gcs.url", &url).unwrap();
8366
    one.config.set("remote.origin.url", "").unwrap();
8367
    one.save_config().unwrap();
8368
    write(&root.join("other"), "b.txt", b"b\n");
8369
    other.commit("b", &[]).unwrap();
8370
    assert!(other.push("origin", false).unwrap()[0].ok);
8371
    one.fetch("earth").unwrap();
8372
    let b = one
8373
        .bookmarks()
8374
        .unwrap()
8375
        .into_iter()
8376
        .find(|b| b.name == "main")
8377
        .unwrap();
8378
    assert_eq!(
8379
        (b.remote.as_deref(), b.behind),
8380
        (Some("earth"), Some(1)),
8381
        "a stale origin copy is not used"
8382
    );
8383
    assert_eq!(
8384
        one.default_remote(),
8385
        "origin",
8386
        "no default chosen among several"
8387
    );
8388
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8389
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8390
    one.config.set("core.remote", "earth").unwrap();
8391
    assert_eq!(one.default_remote(), "earth");
8392
}
8393
8394
#[test]
8395
fn a_missing_author_identity_says_how_to_fix_it() {
8396
    // oxygen#82: an agent home's author.key naming an identity the
8397
    // repository does not hold.
8398
    hermetic();
8399
    let dir = tempfile::tempdir().unwrap();
8400
    let mut repo = Repo::init(dir.path()).unwrap();
8401
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8402
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8403
    let e = repo.identity(&missing).unwrap_err().to_string();
8404
    assert!(
8405
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8406
        "{e}"
8407
    );
8408
    assert!(e.contains("this repository's config"), "{e}");
8409
}
8410
8411
#[test]
8412
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8413
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8414
    // the working copy, a pull with nothing new left it there, and status
8415
    // said "clean".
8416
    hermetic();
8417
    let dir = tempfile::tempdir().unwrap();
8418
    let root = dir.path();
8419
    let _up = Repo::init(&root.join("up")).unwrap();
8420
    let url = root.join("up").to_string_lossy().to_string();
8421
    let other = Repo::clone(&url, &root.join("other"))
8422
        .unwrap()
8423
        .with_home(root.join("home"));
8424
    write(&root.join("other"), "a.txt", b"a\n");
8425
    other.commit("a", &[]).unwrap();
8426
    assert!(other.push("origin", false).unwrap()[0].ok);
8427
    let one = Repo::clone(&url, &root.join("one"))
8428
        .unwrap()
8429
        .with_home(root.join("home"));
8430
    write(&root.join("other"), "b.txt", b"b\n");
8431
    other.commit("b", &[]).unwrap();
8432
    assert!(other.push("origin", false).unwrap()[0].ok);
8433
    one.fetch("origin").unwrap();
8434
    // The bookmark moves; the working copy does not.
8435
    let theirs = one.resolve_heads("origin/main").unwrap();
8436
    one.bookmark_set("main", &theirs).unwrap();
8437
    assert!(!root.join("one/b.txt").exists());
8438
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8439
    let r = one.pull("origin").unwrap();
8440
    assert!(
8441
        !r.changed && r.checked_out,
8442
        "nothing new, but the working copy caught up"
8443
    );
8444
    assert!(root.join("one/b.txt").exists());
8445
    assert_eq!(one.working_copy_behind().unwrap(), None);
8446
}
8447
8448
#[test]
8449
fn touched_nodes_cache_answers_as_the_changes_do() {
8450
    hermetic();
8451
    let dir = tempfile::tempdir().unwrap();
8452
    let repo = Repo::init(dir.path()).unwrap();
8453
    write(dir.path(), "a.txt", b"one\n");
8454
    write(dir.path(), "b.txt", b"x\n");
8455
    repo.snapshot("t").unwrap();
8456
    let c1 = repo.commit("first", &[]).unwrap();
8457
    write(dir.path(), "b.txt", b"y\n");
8458
    repo.snapshot("t").unwrap();
8459
    repo.commit("b only", &[]).unwrap();
8460
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8461
    write(dir.path(), "c.txt", b"one\ntwo\n");
8462
    repo.snapshot("t").unwrap();
8463
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8464
    // Uncommitted work, so the working copy touches a file too.
8465
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8466
    repo.snapshot("t").unwrap();
8467
8468
    let path = dir.path().join(".oxy/index/touched");
8469
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8470
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8471
    assert!(path.exists(), "the first query writes the cache");
8472
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8473
    assert_eq!(cold, warm, "the cache answers as the changes do");
8474
    let (wc, _) = repo.working_copy().unwrap();
8475
    assert_eq!(
8476
        cold,
8477
        vec![wc, c3, c1],
8478
        "renames followed, the working copy included"
8479
    );
8480
8481
    // Working-copy changes are not kept: they are replaced by every snapshot.
8482
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8483
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8484
    assert!(cached.contains(&c1) && cached.contains(&c3));
8485
8486
    // A damaged cache is ignored, not trusted.
8487
    let mut bytes = fs::read(&path).unwrap();
8488
    let last = bytes.len() - 40;
8489
    bytes[last] ^= 1;
8490
    fs::write(&path, &bytes).unwrap();
8491
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8492
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8493
    assert_eq!(hashes(touches), vec![c3, c1]);
8494
}
8495
8496
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8497
/// file back where it was leave two placements at one place, which the
8498
/// tree shows as one file. Removing it, and then its directory, retires
8499
/// both, so no copy is left under a directory that is gone.
8500
#[test]
8501
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8502
    hermetic();
8503
    if std::process::Command::new("git")
8504
        .arg("--version")
8505
        .output()
8506
        .is_err()
8507
    {
8508
        eprintln!("git not installed; skipping");
8509
        return;
8510
    }
8511
    let dir = tempfile::tempdir().unwrap();
8512
    let root = dir.path();
8513
    let g = root.join("src.git");
8514
    fs::create_dir_all(&g).unwrap();
8515
    let git = |args: &[&str]| {
8516
        let out = std::process::Command::new("git")
8517
            .arg("-C")
8518
            .arg(&g)
8519
            .args([
8520
                "-c",
8521
                "user.name=Grace",
8522
                "-c",
8523
                "[email protected]",
8524
                "-c",
8525
                "commit.gpgsign=false",
8526
            ])
8527
            .args(args)
8528
            .output()
8529
            .unwrap();
8530
        assert!(
8531
            out.status.success(),
8532
            "git {args:?}: {}",
8533
            String::from_utf8_lossy(&out.stderr)
8534
        );
8535
    };
8536
    git(&["init", "-q", "-b", "main"]);
8537
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8538
    write(&g, "keep.txt", b"k\n");
8539
    git(&["add", "."]);
8540
    git(&["commit", "-qm", "base"]);
8541
    fs::create_dir_all(g.join("d/sub")).unwrap();
8542
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8543
    git(&["commit", "-qm", "into sub"]);
8544
    git(&["checkout", "-qb", "side"]);
8545
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8546
    git(&["commit", "-qm", "back, on side"]);
8547
    git(&["checkout", "-q", "main"]);
8548
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8549
    git(&["commit", "-qm", "back, on main"]);
8550
    git(&["merge", "-q", "--no-edit", "side"]);
8551
    git(&["rm", "-rq", "d"]);
8552
    git(&["commit", "-qm", "d goes"]);
8553
8554
    let repo = Repo::init(&root.join("o")).unwrap();
8555
    repo.import_git(&g, "main").unwrap();
8556
    let v = repo.verify_git_import(&g, "main").unwrap();
8557
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8558
    let st = repo
8559
        .load_state_history(&repo.bookmark_heads().unwrap())
8560
        .unwrap();
8561
    let view = st.tree().view();
8562
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8563
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8564
}
8565
8566
/// oxygen#94: a state index's file histories are read, and checked by
8567
/// their own hashes, only when a file is built. One found damaged is an
8568
/// error that says so, the index is removed, and the next read rebuilds it.
8569
#[test]
8570
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8571
    hermetic();
8572
    let dir = tempfile::tempdir().unwrap();
8573
    let repo = Repo::init(dir.path()).unwrap();
8574
    for i in 0..6 {
8575
        write(
8576
            dir.path(),
8577
            &format!("f{i}.txt"),
8578
            format!("one {i}\n").as_bytes(),
8579
        );
8580
    }
8581
    repo.snapshot("t").unwrap();
8582
    repo.commit("first", &[]).unwrap();
8583
    for i in 0..6 {
8584
        write(
8585
            dir.path(),
8586
            &format!("f{i}.txt"),
8587
            format!("one {i}\ntwo\n").as_bytes(),
8588
        );
8589
    }
8590
    repo.snapshot("t").unwrap();
8591
    repo.commit("second", &[]).unwrap();
8592
    let want: Vec<Vec<u8>> = (0..6)
8593
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8594
        .collect();
8595
    // The index of the working copy's base, holding every file's history
8596
    // (a few changes behind, an index is replayed onto, not rewritten).
8597
    let (_, wc) = repo.working_copy().unwrap();
8598
    let base = repo.load_state_history(&wc.deps).unwrap();
8599
    repo.write_state_index(&wc.deps, &base);
8600
    for (i, w) in want.iter().enumerate() {
8601
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8602
    }
8603
    let index = repo.state_indexes();
8604
    assert!(!index.is_empty(), "a state index was written");
8605
    // The histories are last in the file: damage the last of them.
8606
    let mut bytes = fs::read(&index[0]).unwrap();
8607
    let last = bytes.len() - 1;
8608
    bytes[last] ^= 0x40;
8609
    fs::write(&index[0], &bytes).unwrap();
8610
8611
    let reads: Vec<_> = (0..6)
8612
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8613
        .collect();
8614
    let damaged: Vec<String> = reads
8615
        .iter()
8616
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8617
        .collect();
8618
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8619
    assert!(
8620
        damaged[0].contains("state index was damaged")
8621
            && damaged[0].contains("run the command again"),
8622
        "{}",
8623
        damaged[0]
8624
    );
8625
    // Every file reads right again, from an index rebuilt from history.
8626
    for (i, w) in want.iter().enumerate() {
8627
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8628
    }
8629
}
8630
8631
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8632
/// objects alone and in dependency order, and the last moves the bookmark.
8633
/// The remote ends with every change and the same state, and says how each
8634
/// part went.
8635
#[test]
8636
fn a_long_push_goes_in_parts() {
8637
    hermetic();
8638
    let dir = tempfile::tempdir().unwrap();
8639
    let root = dir.path();
8640
    let origin = root.join("origin");
8641
    Repo::init_bare_unbound(&origin).unwrap();
8642
    let main = root.join("main");
8643
    let mut repo = Repo::init(&main).unwrap();
8644
    repo.config
8645
        .set("remote.origin.url", &origin.to_string_lossy())
8646
        .unwrap();
8647
    // One byte: every change is a part of its own.
8648
    repo.config.set("push.batch-bytes", "1").unwrap();
8649
    repo.save_config().unwrap();
8650
    for i in 0..6 {
8651
        write(
8652
            &main,
8653
            &format!("f{i}.txt"),
8654
            format!("file {i}\n").as_bytes(),
8655
        );
8656
        repo.commit(&format!("c{i}"), &[]).unwrap();
8657
    }
8658
    let mut parts = Vec::new();
8659
    let results = repo
8660
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8661
        .unwrap();
8662
    assert!(
8663
        results.iter().any(|r| r.ok && r.name == "main"),
8664
        "{results:?}"
8665
    );
8666
    assert_eq!(parts.len(), 6, "{parts:?}");
8667
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8668
8669
    let remote = Repo::open(&origin).unwrap();
8670
    let heads = repo.bookmark_heads().unwrap();
8671
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8672
    assert_eq!(
8673
        remote.log_state(&heads).unwrap().len(),
8674
        repo.log_state(&heads).unwrap().len()
8675
    );
8676
    // A push of objects alone reports how it went, as `objects`.
8677
    let got = remote
8678
        .receive_push(Bundle::default(), vec![], None, vec![])
8679
        .unwrap();
8680
    assert_eq!(got.len(), 1);
8681
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8682
}
8683
8684
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8685
/// own commits (Git author email = its email, any case) with its key, and
8686
/// leaves anyone else's with the zero key; the history verifies as before.
8687
#[test]
8688
fn git_import_claims_your_own_commits() {
8689
    hermetic();
8690
    if std::process::Command::new("git")
8691
        .arg("--version")
8692
        .output()
8693
        .is_err()
8694
    {
8695
        eprintln!("git not installed; skipping");
8696
        return;
8697
    }
8698
    let dir = tempfile::tempdir().unwrap();
8699
    let root = dir.path();
8700
    let g = root.join("src.git");
8701
    fs::create_dir_all(&g).unwrap();
8702
    let git = |who: &str, args: &[&str]| {
8703
        let (name, email) = who.split_once(' ').unwrap();
8704
        let out = std::process::Command::new("git")
8705
            .arg("-C")
8706
            .arg(&g)
8707
            .args([
8708
                "-c",
8709
                &format!("user.name={name}"),
8710
                "-c",
8711
                &format!("user.email={email}"),
8712
                "-c",
8713
                "commit.gpgsign=false",
8714
            ])
8715
            .args(args)
8716
            .output()
8717
            .unwrap();
8718
        assert!(
8719
            out.status.success(),
8720
            "git {args:?}: {}",
8721
            String::from_utf8_lossy(&out.stderr)
8722
        );
8723
    };
8724
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8725
    write(&g, "a.txt", b"a\n");
8726
    git("Grace [email protected]", &["add", "."]);
8727
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8728
    write(&g, "b.txt", b"b\n");
8729
    git("Ada [email protected]", &["add", "."]);
8730
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8731
8732
    let mut repo = Repo::init(&root.join("o")).unwrap();
8733
    let (key, _) = repo
8734
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8735
        .unwrap();
8736
    repo.config.set("git.claim", "true").unwrap();
8737
    repo.save_config().unwrap();
8738
    let repo = Repo::open(&root.join("o")).unwrap();
8739
    repo.import_git(&g, "main").unwrap();
8740
    let v = repo.verify_git_import(&g, "main").unwrap();
8741
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8742
    let heads = repo.bookmark_heads().unwrap();
8743
    let by_message: std::collections::HashMap<String, KeyId> = repo
8744
        .log_state(&heads)
8745
        .unwrap()
8746
        .into_iter()
8747
        .map(|e| {
8748
            (
8749
                e.change.message.lines().next().unwrap_or("").to_string(),
8750
                e.change.author,
8751
            )
8752
        })
8753
        .collect();
8754
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8755
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8756
}
8757
8758
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8759
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8760
#[test]
8761
fn removing_a_remote_leaves_nothing_of_it() {
8762
    hermetic();
8763
    let dir = tempfile::tempdir().unwrap();
8764
    let origin = dir.path().join("origin");
8765
    Repo::init_bare_unbound(&origin).unwrap();
8766
    let main = dir.path().join("main");
8767
    let mut repo = Repo::init(&main).unwrap();
8768
    repo.config
8769
        .set("remote.origin.url", &origin.to_string_lossy())
8770
        .unwrap();
8771
    repo.config
8772
        .set("remote.origin.token", "secret-ish")
8773
        .unwrap();
8774
    repo.config
8775
        .set("remote.keep.url", &origin.to_string_lossy())
8776
        .unwrap();
8777
    repo.save_config().unwrap();
8778
    write(&main, "a.txt", b"a\n");
8779
    repo.commit("a", &[]).unwrap();
8780
    assert!(repo.push("origin", false).unwrap()[0].ok);
8781
    assert!(
8782
        repo.view().unwrap().remotes.contains_key("origin"),
8783
        "a tracking bookmark"
8784
    );
8785
8786
    repo.remove_remote("origin").unwrap();
8787
    let again = Repo::open(&main).unwrap();
8788
    assert!(
8789
        !again
8790
            .config
8791
            .repo_layer()
8792
            .keys()
8793
            .any(|k| k.starts_with("remote.origin.")),
8794
        "{:?}",
8795
        again.config.repo_layer()
8796
    );
8797
    assert!(!again.config.remotes.contains_key("origin"));
8798
    assert!(
8799
        !again.view().unwrap().remotes.contains_key("origin"),
8800
        "its tracking bookmarks go"
8801
    );
8802
    assert!(
8803
        again.config.remotes.contains_key("keep"),
8804
        "another remote stays"
8805
    );
8806
    let mut again = again;
8807
    assert!(
8808
        again.remove_remote("origin").is_err(),
8809
        "a second removal is refused"
8810
    );
8811
}
8812
8813
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
8814
/// unreachable from history, so gc prunes it, unless the host names it:
8815
/// then it and its chunks stay, and it reads back whole.
8816
#[test]
8817
fn gc_keeps_the_blobs_a_host_names() {
8818
    hermetic();
8819
    let dir = tempfile::tempdir().unwrap();
8820
    let repo = Repo::init(dir.path()).unwrap();
8821
    write(dir.path(), "a.txt", b"a\n");
8822
    repo.commit("a", &[]).unwrap();
8823
    // Large enough to be several chunks.
8824
    let body: Vec<u8> = (0..400_000u32)
8825
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
8826
        .collect();
8827
    let kept = repo.store_blob(&body).unwrap();
8828
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
8829
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
8830
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
8831
    assert!(!repo.store().has(&lost), "not named: pruned");
8832
    repo.gc(true).unwrap();
8833
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
8834
}
8835
8836
/// oxygen#99: undo in one workspace undoes that workspace's last command,
8837
/// never another workspace's, says what it undid, and goes further back
8838
/// when run again.
8839
#[test]
8840
fn undo_is_scoped_to_its_workspace() {
8841
    hermetic();
8842
    let dir = tempfile::tempdir().unwrap();
8843
    let root = dir.path().join("main");
8844
    let a = Repo::init(&root).unwrap();
8845
    write(&root, "base.txt", b"base\n");
8846
    let base = a.commit("base", &[]).unwrap();
8847
    a.bookmark_create("feature", None).unwrap();
8848
    let ws_dir = dir.path().join("ws");
8849
    let heads = a.resolve_heads("feature").unwrap();
8850
    let b = a
8851
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
8852
        .unwrap();
8853
8854
    // A commits on main, then B commits on feature: B's is the newest.
8855
    write(&root, "a.txt", b"a\n");
8856
    let ca = a.commit("from a", &[]).unwrap();
8857
    write(&ws_dir, "b.txt", b"b\n");
8858
    let cb = b.commit("from b", &[]).unwrap();
8859
8860
    // A's undo undoes A's commit and leaves B's.
8861
    let u = a.undo().unwrap();
8862
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8863
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
8864
    assert!(!u.changes.is_empty());
8865
    let view = a.view().unwrap();
8866
    // (Independent changes commute, so a bookmark's heads may hold base too.)
8867
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
8868
    assert!(
8869
        a.heads_of(&view, "feature").unwrap().contains(&cb),
8870
        "B's commit stands"
8871
    );
8872
    assert!(
8873
        a.store().get_change(&ca).is_ok(),
8874
        "the change itself is still in the store"
8875
    );
8876
    // A's working copy was clean, so its files followed; B's are untouched.
8877
    assert!(!root.join("a.txt").exists());
8878
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
8879
    assert!(ws_dir.join("b.txt").exists());
8880
8881
    // B's undo still finds B's own commit, under A's undo.
8882
    let u = b.undo().unwrap();
8883
    assert_eq!(u.command, "oxy commit -m \"from b\"");
8884
    assert!(!b
8885
        .heads_of(&b.view().unwrap(), "feature")
8886
        .unwrap()
8887
        .contains(&cb));
8888
    assert_eq!(
8889
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
8890
        vec![base],
8891
        "A's undo stands"
8892
    );
8893
8894
    // A's next undo goes past the commit it already undid, to adding B's
8895
    // workspace: refused, since B has worked there since.
8896
    let e = a.undo().unwrap_err().to_string();
8897
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
8898
}
8899
8900
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
8901
/// own commit's head, and the other workspace's head stays.
8902
#[test]
8903
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
8904
    hermetic();
8905
    let dir = tempfile::tempdir().unwrap();
8906
    let root = dir.path().join("main");
8907
    let a = Repo::init(&root).unwrap();
8908
    write(&root, "base.txt", b"base\n");
8909
    a.commit("base", &[]).unwrap();
8910
    let ws_dir = dir.path().join("ws");
8911
    let b = a.workspace_add(&ws_dir, None).unwrap();
8912
    write(&root, "a.txt", b"a\n");
8913
    let ca = a.commit("from a", &[]).unwrap();
8914
    write(&ws_dir, "b.txt", b"b\n");
8915
    let cb = b.commit("from b", &[]).unwrap();
8916
    let u = a.undo().unwrap();
8917
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8918
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
8919
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
8920
}
8921
8922
/// oxygen#99: an undo that would also take back what another workspace
8923
/// did since to the same bookmark is refused, naming it.
8924
#[test]
8925
fn undo_refuses_to_take_back_another_workspaces_work() {
8926
    hermetic();
8927
    let dir = tempfile::tempdir().unwrap();
8928
    let root = dir.path().join("main");
8929
    let a = Repo::init(&root).unwrap();
8930
    write(&root, "base.txt", b"base\n");
8931
    a.commit("base", &[]).unwrap();
8932
    let ws_dir = dir.path().join("ws");
8933
    let b = a.workspace_add(&ws_dir, None).unwrap();
8934
    // Both on main: A commits, then B builds on it, editing A's file.
8935
    write(&root, "a.txt", b"a\n");
8936
    a.commit("from a", &[]).unwrap();
8937
    b.refresh().unwrap();
8938
    let heads = b.resolve_heads("main").unwrap();
8939
    b.checkout(&heads, false, "oxy checkout").unwrap();
8940
    write(&ws_dir, "a.txt", b"a, then b\n");
8941
    b.commit("from b", &[]).unwrap();
8942
    let e = a.undo().unwrap_err().to_string();
8943
    assert!(
8944
        e.contains("bookmark main") && e.contains("builds on"),
8945
        "{e}"
8946
    );
8947
    assert!(e.contains("oxy op restore"), "{e}");
8948
}
8949
8950
/// oxygen#99: undoing a commit that was already pushed says so: the remote
8951
/// still has it.
8952
#[test]
8953
fn undo_says_when_the_commit_was_pushed() {
8954
    hermetic();
8955
    let dir = tempfile::tempdir().unwrap();
8956
    let root = dir.path();
8957
    Repo::init(&root.join("origin")).unwrap();
8958
    let url = root.join("origin").to_string_lossy().to_string();
8959
    let repo = Repo::clone(&url, &root.join("work"))
8960
        .unwrap()
8961
        .with_home(root.join("home"));
8962
    write(&root.join("work"), "a.txt", b"a\n");
8963
    repo.commit("a", &[]).unwrap();
8964
    assert!(repo.push("origin", false).unwrap()[0].ok);
8965
    // The push itself is passed over: the remote keeps what it was sent.
8966
    let u = repo.undo().unwrap();
8967
    assert_eq!(u.command, "oxy commit -m \"a\"");
8968
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
8969
}
8970
8971
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
8972
/// out of the snapshot and named; tracked files and files already in the
8973
/// working copy are not.
8974
#[test]
8975
fn large_new_files_are_left_out_of_snapshots() {
8976
    hermetic();
8977
    let dir = tempfile::tempdir().unwrap();
8978
    let root = dir.path();
8979
    let mut repo = Repo::init(root).unwrap();
8980
    repo.config.max_new_file = 1024;
8981
    write(root, "small.txt", b"small\n");
8982
    write(root, "big.bin", &vec![0u8; 4096]);
8983
    let s = repo.snapshot("oxy status").unwrap();
8984
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8985
    assert_eq!(paths, ["small.txt"]);
8986
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
8987
    repo.commit("small", &[]).unwrap();
8988
8989
    // A tracked file may grow past the limit.
8990
    write(root, "small.txt", &vec![b'x'; 4096]);
8991
    let s = repo.snapshot("oxy status").unwrap();
8992
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
8993
    // With no limit the big file is taken in, and stays once it is.
8994
    repo.config.max_new_file = 0;
8995
    let s = repo.snapshot("oxy status").unwrap();
8996
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
8997
    repo.config.max_new_file = 1024;
8998
    let s = repo.snapshot("oxy status").unwrap();
8999
    assert!(
9000
        s.statuses.iter().any(|p| p.path == "big.bin"),
9001
        "already in the working copy"
9002
    );
9003
    assert!(repo.skipped_large().is_empty());
9004
}
9005
9006
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
9007
/// snapshots expire, and kept while they have not.
9008
#[test]
9009
fn gc_prunes_what_only_expired_snapshots_held() {
9010
    hermetic();
9011
    let dir = tempfile::tempdir().unwrap();
9012
    let root = dir.path();
9013
    let mut repo = Repo::init(root).unwrap();
9014
    repo.config.gc_grace_days = 0;
9015
    write(root, "a.txt", b"a\n");
9016
    repo.commit("a", &[]).unwrap();
9017
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
9018
    write(root, "image.tar", &image);
9019
    repo.snapshot("oxy status").unwrap();
9020
    std::fs::remove_file(root.join("image.tar")).unwrap();
9021
    repo.snapshot("oxy status").unwrap();
9022
    let blob = Repo::blob_ref(&image);
9023
    assert!(repo.store().has(&blob));
9024
    repo.gc(true).unwrap();
9025
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
9026
    repo.config.snapshot_retention_days = 0;
9027
    repo.gc(true).unwrap();
9028
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
9029
    assert_eq!(
9030
        repo.file_at("a.txt", None).unwrap(),
9031
        b"a\n",
9032
        "committed files stay"
9033
    );
9034
}
9035
9036
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
9037
/// already has is no conflict: the switch goes through, nothing is lost,
9038
/// and other carried work still comes along.
9039
#[test]
9040
fn carrying_work_the_target_already_has_is_no_conflict() {
9041
    hermetic();
9042
    let dir = tempfile::tempdir().unwrap();
9043
    let root = dir.path();
9044
    let mut repo = Repo::init(root).unwrap();
9045
    write(root, "a.txt", b"one\n");
9046
    write(root, "b.txt", b"b\n");
9047
    repo.commit("one", &[]).unwrap();
9048
    repo.bookmark_create("landed", None).unwrap();
9049
    // On landed, a.txt becomes "two" (as a proposal landing would).
9050
    repo.bookmark_switch("landed", false).unwrap();
9051
    write(root, "a.txt", b"two\n");
9052
    repo.commit("two", &[]).unwrap();
9053
    repo.bookmark_switch("main", false).unwrap();
9054
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
9055
    // The same edit, uncommitted, on main; and another edit besides.
9056
    write(root, "a.txt", b"two\n");
9057
    write(root, "b.txt", b"b, edited\n");
9058
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
9059
    assert_eq!(
9060
        carried,
9061
        vec!["b.txt".to_string()],
9062
        "only the work landed lacks is carried"
9063
    );
9064
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
9065
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
9066
    let s = repo.snapshot("oxy status").unwrap();
9067
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9068
    assert_eq!(paths, ["b.txt"]);
9069
9070
    // A real difference is still refused.
9071
    repo.bookmark_switch("main", true).unwrap();
9072
    write(root, "a.txt", b"three\n");
9073
    let e = repo
9074
        .bookmark_switch_carry("landed")
9075
        .unwrap_err()
9076
        .to_string();
9077
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
9078
}
9079
9080
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
9081
/// resolves, so JSON output feeds back into commands.
9082
#[test]
9083
fn a_full_hash_resolves_without_its_hash_sign() {
9084
    hermetic();
9085
    let dir = tempfile::tempdir().unwrap();
9086
    let root = dir.path();
9087
    let repo = Repo::init(root).unwrap();
9088
    write(root, "a.txt", b"a\n");
9089
    let h = repo.commit("a", &[]).unwrap();
9090
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
9091
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
9092
    assert!(repo
9093
        .resolve_change(&"0".repeat(64))
9094
        .unwrap_err()
9095
        .to_string()
9096
        .contains("no change matches"));
9097
}
9098
9099
#[test]
9100
fn a_pin_change_moves_only_the_pin() {
9101
    hermetic();
9102
    let dir = tempfile::tempdir().unwrap();
9103
    let root = dir.path();
9104
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9105
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9106
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9107
        .unwrap()
9108
        .with_home(root.join("home"));
9109
    write(&root.join("lib"), "lib.txt", b"v1\n");
9110
    lib.commit("lib v1", &[]).unwrap();
9111
    assert!(lib.push("origin", false).unwrap()[0].ok);
9112
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
9113
    let app_dir = root.join("app");
9114
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
9115
        .unwrap()
9116
        .with_home(root.join("home"));
9117
    write(&app_dir, "main.txt", b"app\n");
9118
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9119
    let a1 = app.commit("app with lib", &[]).unwrap();
9120
    // The library moves on.
9121
    write(&root.join("lib"), "more.txt", b"v2\n");
9122
    let l2 = lib.commit("lib v2", &[]).unwrap();
9123
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
9124
        panic!("an Oxygen pin")
9125
    };
9126
    let pin2 = crate::subrepo::Pin::Oxy {
9127
        repo,
9128
        heads: vec![l2],
9129
        bookmark,
9130
    };
9131
    let author = app.store().get_change(&a1).unwrap().author;
9132
    let change = app
9133
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
9134
        .unwrap();
9135
    let mut state = app.load_state(&[a1]).unwrap();
9136
    state.add(change).unwrap();
9137
    let files = state.materialize().files;
9138
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
9139
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
9140
        panic!("a pin is opaque")
9141
    };
9142
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
9143
    assert_eq!(read, pin2, "the new pin");
9144
    assert!(
9145
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
9146
        "nothing else changes"
9147
    );
9148
    // Only a subrepo's pin can be moved this way.
9149
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
9150
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
9151
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
9152
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
9153
}
9154
9155
/// oxygenhub#249: a handle reads the operation head once and keeps it,
9156
/// so one command or request never mixes two heads; another handle's
9157
/// operation shows only after `refresh`. Its own operations move it, and
9158
/// one recorded from the head it kept merges with what landed since, as
9159
/// any concurrent operation does.
9160
#[test]
9161
fn one_handle_keeps_one_head_until_it_refreshes() {
9162
    hermetic();
9163
    let dir = tempfile::tempdir().unwrap();
9164
    let root = dir.path();
9165
    let writer = Repo::init(root).unwrap();
9166
    write(root, "a.txt", b"one\n");
9167
    let h1 = writer.commit("one", &[]).unwrap();
9168
    let reader = Repo::open(root).unwrap();
9169
    let before = reader.view().unwrap();
9170
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9171
    write(root, "a.txt", b"two\n");
9172
    let h2 = writer.commit("two", &[]).unwrap();
9173
    assert_eq!(
9174
        writer.bookmark_heads().unwrap(),
9175
        vec![h2],
9176
        "its own operation"
9177
    );
9178
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
9179
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9180
    reader.refresh().unwrap();
9181
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
9182
9183
    // A handle recording from an older head merges with the newer one.
9184
    let stale = Repo::open(root).unwrap();
9185
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
9186
    write(root, "a.txt", b"three\n");
9187
    let h3 = writer.commit("three", &[]).unwrap();
9188
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
9189
    let view = stale.view().unwrap();
9190
    assert!(view.bookmarks.contains_key("feature"));
9191
    assert_eq!(
9192
        stale.bookmark_heads().unwrap(),
9193
        vec![h3],
9194
        "merged, not lost"
9195
    );
9196
    let fresh = Repo::open(root).unwrap();
9197
    assert_eq!(fresh.view().unwrap(), view);
9198
}
9199
9200
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
9201
#[test]
9202
fn over_a_store_one_handle_keeps_one_head() {
9203
    hermetic();
9204
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
9205
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9206
    let dir = tempfile::tempdir().unwrap();
9207
    let a = Repo::init(dir.path()).unwrap();
9208
    let (h0, _) = a.head_op().unwrap();
9209
    let b = Repo::open(dir.path()).unwrap();
9210
    assert_eq!(b.head_op().unwrap().0, h0);
9211
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9212
    let mut view = a.view().unwrap();
9213
    view.bookmarks.insert("x".into(), state);
9214
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
9215
    assert_eq!(a.head_op().unwrap().0, r);
9216
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
9217
    b.refresh().unwrap();
9218
    assert_eq!(b.head_op().unwrap().0, r);
9219
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9220
}
9221
9222
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
9223
/// reader opened before reads on, then and after the next gc deletes the
9224
/// retired files once their hour is up. Younger ones are kept.
9225
#[test]
9226
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
9227
    hermetic();
9228
    let dir = tempfile::tempdir().unwrap();
9229
    let root = dir.path();
9230
    let repo = Repo::init(root).unwrap();
9231
    let mut heads = Vec::new();
9232
    for i in 0..4 {
9233
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
9234
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
9235
    }
9236
    let reader = Repo::open(root).unwrap();
9237
    assert_eq!(reader.log().unwrap().len(), 5);
9238
    let r = repo.gc(true).unwrap();
9239
    assert_eq!(r.retired, crate::store::RetiredReport::default());
9240
    assert_eq!(repo.store().loose_count().unwrap(), 0);
9241
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
9242
    // Nothing is an hour old yet: a gc keeps it all.
9243
    let r = repo.gc(true).unwrap();
9244
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9245
    assert!(r.retired.kept > 0, "{r:?}");
9246
    write(root, "f9.txt", b"9\n");
9247
    heads.push(repo.commit("c9", &[]).unwrap());
9248
    crate::store::reader_tests::age_retired(
9249
        repo.store(),
9250
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
9251
    );
9252
    let r = repo.gc(true).unwrap();
9253
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
9254
    assert_eq!(r.retired.kept, 0, "{r:?}");
9255
    let r = repo.gc(true).unwrap();
9256
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
9257
    assert!(r.retired.kept > 0, "what the last gc retired is young");
9258
    // The reader opened before all of it still reads everything, from
9259
    // the packs it finds when what it loaded is gone.
9260
    assert_eq!(reader.log().unwrap().len(), 5);
9261
    for h in &heads[..4] {
9262
        reader.store().get_change(h).unwrap();
9263
    }
9264
    reader.refresh().unwrap();
9265
    assert_eq!(reader.log().unwrap().len(), 6);
9266
    let fresh = Repo::open(root).unwrap();
9267
    assert_eq!(
9268
        fresh.store().pack_count(),
9269
        1,
9270
        "retired packs are not loaded"
9271
    );
9272
}
9273
9274
/// oxygenhub#249: a repository opens when its store's pack listing names
9275
/// an index that is not there (deleted between the listing and the read).
9276
#[test]
9277
fn a_repository_opens_when_a_listed_index_is_gone() {
9278
    hermetic();
9279
    let backend = crate::store::reader_tests::racing(true);
9280
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
9281
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
9282
    let dir = tempfile::tempdir().unwrap();
9283
    let repo = Repo::init(dir.path()).unwrap();
9284
    write(dir.path(), "a.txt", b"a\n");
9285
    let h = repo.commit("a", &[]).unwrap();
9286
    repo.gc(true).unwrap();
9287
    let again = Repo::open(dir.path()).unwrap();
9288
    assert_eq!(again.store().pack_count(), 1);
9289
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
9290
    // And when one is deleted between the listing and the read: a copy of
9291
    // the live pack, whose index goes as the store opens.
9292
    use crate::strata::Store as _;
9293
    let idx = backend
9294
        .list("pack-")
9295
        .unwrap()
9296
        .into_iter()
9297
        .map(|e| e.key)
9298
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
9299
        .unwrap();
9300
    let stem = idx.trim_end_matches(".idx");
9301
    for ext in ["pack", "idx"] {
9302
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
9303
        backend
9304
            .put_new(&format!("pack-copy.{ext}"), &bytes)
9305
            .unwrap();
9306
    }
9307
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
9308
    let again = Repo::open(dir.path()).unwrap();
9309
    assert_eq!(again.store().pack_count(), 1);
9310
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
9311
    assert!(!backend.has("pack-copy.idx").unwrap());
9312
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9313
}