OXYGENHUB
◆ v0.4.5 oxygen / crates / oxy-core / src / repo / tests.rs
337.5 KiB · Rust · last changed Grants let certified keys act for an author (keyless step 5a) 18 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
    assert!(results[0].ok, "{}", results[0].reason);
516
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
517
    // The change was sealed at push and the reference attested.
518
    assert!(
519
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
520
    );
521
    assert_eq!(
522
        origin.verify_change(&h1).unwrap(),
523
        SignatureStatus::Unsigned
524
    );
525
    let serial_of = |att: &SignedAttest| match att.attest.body {
526
        AttestBody::Ref { serial, .. } => serial,
527
        _ => unreachable!(),
528
    };
529
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
530
    // A bookmark new to the remote starts at the clock (past any deleted
531
    // namesake's serial); later updates count up from there.
532
    let first = serial_of(&att);
533
    assert!(first > 1_000_000_000_000, "{first}");
534
    let again = a.push("origin", false).unwrap();
535
    assert!(again[0].ok && again[0].reason.contains("up to date"));
536
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
537
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
538
539
    // B clones and sees the file and the seal.
540
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
541
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
542
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
543
    assert!(matches!(
544
        b.authenticate_change(&h1).unwrap(),
545
        SignatureStatus::Valid { sealed: true, .. }
546
    ));
547
548
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
549
    write(&root.join("b"), "f.txt", b"a\nb\n");
550
    let h2 = b.commit("second", &[]).unwrap();
551
    assert!(b.push("origin", false).unwrap()[0].ok);
552
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
553
554
    // A commits an independent change; push is refused until A pulls.
555
    write(&root.join("a"), "g.txt", b"g\n");
556
    let h3 = a.commit("third", &[]).unwrap();
557
    assert!(a.push("origin", false).is_err());
558
    let pr = a.pull("origin").unwrap();
559
    assert!(pr.changed && pr.checked_out);
560
    let mut want = vec![h2, h3];
561
    want.sort();
562
    assert_eq!(pr.heads, want);
563
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
564
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
565
    let results = a.push("origin", false).unwrap();
566
    assert!(results[0].ok, "{}", results[0].reason);
567
    let mut origin_heads = origin.bookmark_heads().unwrap();
568
    origin_heads.sort();
569
    assert_eq!(origin_heads, want);
570
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
571
    assert_eq!(serial_of(&att), first + 1);
572
573
    // B pulls and ends up identical.
574
    let pr = b.pull("origin").unwrap();
575
    assert_eq!(pr.heads, want);
576
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
577
    assert!(!b.snapshot("status").unwrap().changed);
578
579
    // Concurrent edits of the same line: the union is a reified conflict.
580
    write(&root.join("a"), "f.txt", b"a\nA\n");
581
    a.commit("a-edit", &[]).unwrap();
582
    a.push("origin", false).unwrap();
583
    write(&root.join("b"), "f.txt", b"a\nB\n");
584
    b.commit("b-edit", &[]).unwrap();
585
    let pr = b.pull("origin").unwrap();
586
    assert!(pr.changed && pr.checked_out);
587
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
588
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
589
    write(&root.join("b"), "f.txt", b"a\nAB\n");
590
    let hr = b.commit("resolve", &[]).unwrap();
591
    assert_eq!(
592
        b.store().get_change(&hr).unwrap().kind,
593
        ChangeKind::Resolution
594
    );
595
    assert!(b.push("origin", false).unwrap()[0].ok);
596
    a.pull("origin").unwrap();
597
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
598
    // The resolution depends on the conflicting edits, but nothing depends
599
    // on "third" (it only added g.txt), so it stays a head beside it.
600
    let mut want = vec![hr, h3];
601
    want.sort();
602
    assert_eq!(a.bookmark_heads().unwrap(), want);
603
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
604
}
605
606
#[test]
607
fn receive_push_rejects_bad_updates() {
608
    hermetic();
609
    let dir = tempfile::tempdir().unwrap();
610
    let root = dir.path();
611
    let origin = Repo::init(&root.join("origin")).unwrap();
612
    let url = root.join("origin").to_string_lossy().to_string();
613
    let mut a = Repo::clone(&url, &root.join("a"))
614
        .unwrap()
615
        .with_home(root.join("home"));
616
    let (key, _) = a
617
        .create_identity("Ada", "a@b", IdentityScope::Repo)
618
        .unwrap();
619
    write(&root.join("a"), "f.txt", b"x\n");
620
    let h1 = a.commit("one", &[]).unwrap();
621
    assert!(a.push("origin", false).unwrap()[0].ok);
622
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
623
    let s1 = origin
624
        .store()
625
        .put_state(&StateObject::new(vec![h1]))
626
        .unwrap();
627
628
    // Missing head.
629
    let ghost = origin
630
        .store()
631
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
632
        .unwrap();
633
    let r = origin
634
        .receive_push(
635
            Bundle::default(),
636
            vec![RefUpdate {
637
                name: "main".into(),
638
                old_state: s1,
639
                new_state: ghost,
640
                force: false,
641
                attestation: None,
642
            }],
643
            None,
644
            vec![],
645
        )
646
        .unwrap();
647
    assert!(
648
        !r[0].ok && r[0].reason.contains("missing"),
649
        "{}",
650
        r[0].reason
651
    );
652
653
    // Stale old_state.
654
    let r = origin
655
        .receive_push(
656
            Bundle::default(),
657
            vec![RefUpdate {
658
                name: "main".into(),
659
                old_state: empty,
660
                new_state: s1,
661
                force: false,
662
                attestation: None,
663
            }],
664
            None,
665
            vec![],
666
        )
667
        .unwrap();
668
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
669
670
    // Non-fast-forward without force is refused; with force it passes.
671
    let r = origin
672
        .receive_push(
673
            Bundle::default(),
674
            vec![RefUpdate {
675
                name: "main".into(),
676
                old_state: s1,
677
                new_state: empty,
678
                force: false,
679
                attestation: None,
680
            }],
681
            None,
682
            vec![],
683
        )
684
        .unwrap();
685
    assert!(
686
        !r[0].ok && r[0].reason.contains("fast-forward"),
687
        "{}",
688
        r[0].reason
689
    );
690
    let r = origin
691
        .receive_push(
692
            Bundle::default(),
693
            vec![RefUpdate {
694
                name: "main".into(),
695
                old_state: s1,
696
                new_state: empty,
697
                force: true,
698
                attestation: None,
699
            }],
700
            None,
701
            vec![],
702
        )
703
        .unwrap();
704
    assert!(r[0].ok);
705
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
706
707
    // Attestation with a stale serial is a rollback and is refused.
708
    let sa = a
709
        .sign_attest(&Attest {
710
            repo: a.id().unwrap(),
711
            hlc: Hlc::now(),
712
            body: AttestBody::Ref {
713
                name: "main".into(),
714
                old_state: empty,
715
                new_state: s1,
716
                serial: 1,
717
            },
718
        })
719
        .unwrap();
720
    let r = origin
721
        .receive_push(
722
            Bundle::default(),
723
            vec![RefUpdate {
724
                name: "main".into(),
725
                old_state: empty,
726
                new_state: s1,
727
                force: false,
728
                attestation: Some(sa.clone()),
729
            }],
730
            None,
731
            vec![],
732
        )
733
        .unwrap();
734
    assert!(
735
        !r[0].ok && r[0].reason.contains("serial"),
736
        "{}",
737
        r[0].reason
738
    );
739
    // An attestation for a different update is refused too.
740
    let sa2 = a
741
        .sign_attest(&Attest {
742
            repo: a.id().unwrap(),
743
            hlc: Hlc::now(),
744
            body: AttestBody::Ref {
745
                name: "main".into(),
746
                old_state: s1,
747
                new_state: empty,
748
                serial: 5,
749
            },
750
        })
751
        .unwrap();
752
    let r = origin
753
        .receive_push(
754
            Bundle::default(),
755
            vec![RefUpdate {
756
                name: "main".into(),
757
                old_state: empty,
758
                new_state: s1,
759
                force: false,
760
                attestation: Some(sa2),
761
            }],
762
            None,
763
            vec![],
764
        )
765
        .unwrap();
766
    assert!(
767
        !r[0].ok && r[0].reason.contains("describe"),
768
        "{}",
769
        r[0].reason
770
    );
771
    let _ = key;
772
}
773
774
#[test]
775
fn user_config_supplies_defaults_and_clones_sign() {
776
    hermetic();
777
    let dir = tempfile::tempdir().unwrap();
778
    let root = dir.path();
779
    let home = root.join("home");
780
    let origin = Repo::init(&root.join("origin")).unwrap();
781
    let url = root.join("origin").to_string_lossy().to_string();
782
783
    // Identity at user scope: the repository file stays free of author keys.
784
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
785
    let (key, _) = a
786
        .create_identity("Ada", "[email protected]", IdentityScope::User)
787
        .unwrap();
788
    assert!(!a.config.repo_layer().contains_key("author.key"));
789
    assert_eq!(a.config.author_key, Some(key));
790
    assert!(home.join("config.toml").exists());
791
    a.set_user_config("core.sign", "change").unwrap();
792
    assert!(a.config.sign_changes);
793
794
    // Repository settings override user settings and are the only ones saved.
795
    a.config.set("core.sign", "seal").unwrap();
796
    a.save_config().unwrap();
797
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
798
    assert!(!again.config.sign_changes);
799
    assert_eq!(again.config.author_key, Some(key));
800
    assert_eq!(
801
        read_config_file(&root.join("a/.oxy/config"))
802
            .unwrap()
803
            .get("core.sign")
804
            .map(String::as_str),
805
        Some("seal")
806
    );
807
808
    // A fresh clone made by this user signs with the user-level identity,
809
    // even though the clone's store has never seen the identity object.
810
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
811
    assert!(b.config.sign_changes);
812
    write(&root.join("b"), "f.txt", b"f\n");
813
    let h = b.commit("signed from a clone", &[]).unwrap();
814
    assert!(
815
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
816
    );
817
    assert!(b.push("origin", false).unwrap()[0].ok);
818
    assert!(matches!(
819
        origin.verify_change(&h).unwrap(),
820
        SignatureStatus::Valid { .. }
821
    ));
822
}
823
824
#[test]
825
fn format1_repositories_are_migrated_on_open() {
826
    hermetic();
827
    use crate::oplog::{Format1Op, Format1View};
828
    let dir = tempfile::tempdir().unwrap();
829
    let root = dir.path();
830
    let repo = Repo::init(root).unwrap();
831
    write(root, "a.txt", b"a\n");
832
    let h1 = repo.commit("one", &[]).unwrap();
833
    let (wc_hash, _) = repo.working_copy().unwrap();
834
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
835
    let mut v1 = Format1View::default();
836
    v1.bookmarks.insert("main".into(), vec![]);
837
    v1.workspaces.insert(repo.workspace(), wc_hash);
838
    let init = Format1Op {
839
        parents: vec![],
840
        hlc: Hlc::default(),
841
        command: "oxy init".into(),
842
        view: v1.clone(),
843
    };
844
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
845
    v1.bookmarks.insert("main".into(), vec![h1]);
846
    let commit = Format1Op {
847
        parents: vec![init_ref],
848
        hlc: Hlc::default(),
849
        command: "oxy commit".into(),
850
        view: v1,
851
    };
852
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
853
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
854
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
855
    drop(repo);
856
857
    let repo = Repo::open(root).unwrap();
858
    assert_eq!(
859
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
860
        FORMAT_LINE
861
    );
862
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
863
    let ops = repo.op_log().unwrap();
864
    assert_eq!(
865
        ops.iter()
866
            .map(|(_, o)| o.command.as_str())
867
            .collect::<Vec<_>>(),
868
        ["oxy commit", "oxy init"]
869
    );
870
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
871
    assert!(!repo.snapshot("status").unwrap().changed);
872
    // Reopening again is a no-op.
873
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
874
}
875
876
#[test]
877
fn undo_skips_snapshot_operations() {
878
    hermetic();
879
    let dir = tempfile::tempdir().unwrap();
880
    let root = dir.path();
881
    let repo = Repo::init(root).unwrap();
882
    write(root, "a.txt", b"a\n");
883
    let h1 = repo.commit("a", &[]).unwrap();
884
    // A later command snapshots new edits on top of the commit.
885
    write(root, "b.txt", b"b\n");
886
    let s = repo.snapshot("oxy status").unwrap();
887
    assert!(s.changed);
888
    assert!(repo.head_op().unwrap().1.is_snapshot());
889
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
890
    // Undo must undo the commit, not the snapshot.
891
    repo.undo().unwrap();
892
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
893
    let s = repo.snapshot("oxy status").unwrap();
894
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
895
    assert_eq!(
896
        paths,
897
        ["a.txt", "b.txt"],
898
        "both files are back in the working copy"
899
    );
900
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
901
    // Only snapshots remain above `init`, so there is nothing left to undo.
902
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
903
    assert!(repo.undo().is_err());
904
}
905
906
#[test]
907
fn independent_changes_commute_and_make_multiple_heads() {
908
    hermetic();
909
    let dir = tempfile::tempdir().unwrap();
910
    let root = dir.path();
911
    let repo = Repo::init(root).unwrap();
912
    write(root, "a.txt", b"a\n");
913
    let h1 = repo.commit("a", &[]).unwrap();
914
    write(root, "b.txt", b"b\n");
915
    let h2 = repo.commit("b", &[]).unwrap();
916
    let c2 = repo.store().get_change(&h2).unwrap();
917
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
918
    let mut heads = repo.bookmark_heads().unwrap();
919
    heads.sort();
920
    let mut want = vec![h1, h2];
921
    want.sort();
922
    assert_eq!(heads, want);
923
    // Editing a.txt depends on h1 only.
924
    write(root, "a.txt", b"a\na2\n");
925
    let h3 = repo.commit("a2", &[]).unwrap();
926
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
927
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
928
    assert_eq!(heads, [h2, h3].into_iter().collect());
929
    // Explicit dependency.
930
    write(root, "c.txt", b"c\n");
931
    let h4 = repo.commit("c", &[h2]).unwrap();
932
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
933
}
934
935
#[test]
936
fn mode_change_and_text_binary_switch() {
937
    hermetic();
938
    let dir = tempfile::tempdir().unwrap();
939
    let root = dir.path();
940
    let repo = Repo::init(root).unwrap();
941
    write(root, "run.sh", b"#!/bin/sh\n");
942
    repo.commit("add script", &[]).unwrap();
943
    #[cfg(unix)]
944
    {
945
        use std::os::unix::fs::PermissionsExt;
946
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
947
        let s = repo.snapshot("status").unwrap();
948
        assert_eq!(
949
            statuses(&s),
950
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
951
        );
952
        let h = repo.commit("exec", &[]).unwrap();
953
        let snap = repo.load_state(&[h]).unwrap().materialize();
954
        assert!(snap.files["run.sh"].mode.exec);
955
    }
956
    // Text → binary → text.
957
    write(root, "run.sh", b"\0binary");
958
    let h = repo.commit("binary", &[]).unwrap();
959
    let snap = repo.load_state(&[h]).unwrap().materialize();
960
    assert!(snap.files["run.sh"].mode.opaque);
961
    write(root, "run.sh", b"text again\n");
962
    let h = repo.commit("text", &[]).unwrap();
963
    let snap = repo.load_state(&[h]).unwrap().materialize();
964
    assert!(!snap.files["run.sh"].mode.opaque);
965
    assert!(
966
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
967
    );
968
    assert!(!snap.is_conflicted());
969
}
970
971
/// oxygen#87: a binary file given new contents and the executable bit in
972
/// one commit kept the contents and lost the bit.
973
#[cfg(unix)]
974
#[test]
975
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
976
    use std::os::unix::fs::PermissionsExt;
977
    hermetic();
978
    let dir = tempfile::tempdir().unwrap();
979
    let root = dir.path();
980
    let repo = Repo::init(root).unwrap();
981
    write(root, "tool.exe", b"MZ\0one");
982
    repo.commit("add", &[]).unwrap();
983
    write(root, "tool.exe", b"MZ\0two");
984
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
985
    let h = repo.commit("update and +x", &[]).unwrap();
986
    let snap = repo.load_state(&[h]).unwrap().materialize();
987
    let f = &snap.files["tool.exe"];
988
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
989
    assert!(
990
        repo.snapshot("status").unwrap().statuses.is_empty(),
991
        "nothing left to commit"
992
    );
993
}
994
995
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
996
/// key whose certificate an issuer gave pushes when the policy grants its
997
/// subject, and a fetch accepts what it attested; an expired certificate,
998
/// or a subject the policy does not grant, may not move the bookmark.
999
#[test]
1000
fn a_certified_key_pushes_under_a_subject_grant() {
1001
    use crate::cert::{Certificate, SignedCertificate};
1002
    use crate::identity::Scope;
1003
    hermetic();
1004
    let dir = tempfile::tempdir().unwrap();
1005
    let root = dir.path();
1006
    let _origin = Repo::init(&root.join("origin")).unwrap();
1007
    let url = root.join("origin").to_string_lossy().to_string();
1008
    let mut a = Repo::clone(&url, &root.join("a"))
1009
        .unwrap()
1010
        .with_home(root.join("home-a"));
1011
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1012
        .unwrap();
1013
    write(&root.join("a"), "a.txt", b"a\n");
1014
    a.commit("a", &[]).unwrap();
1015
    a.policy_init().unwrap();
1016
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1017
    let hub_sk = SecretKey::generate();
1018
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1019
    a.policy_grant_subject(
1020
        "agent:claude@ada",
1021
        hub.clone(),
1022
        Scope::CHANGES | Scope::REFS,
1023
        None,
1024
    )
1025
    .unwrap();
1026
    assert!(a
1027
        .push("origin", false)
1028
        .unwrap()
1029
        .iter()
1030
        .any(|r| r.name == "policy" && r.ok));
1031
1032
    let now = Hlc::now().wall_ms;
1033
    // An agent repository whose key the hub certified for `subject`, from
1034
    // `from` to `to`.
1035
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1036
        let mut r = Repo::clone(&url, &root.join(name))
1037
            .unwrap()
1038
            .with_home(root.join(format!("home-{name}")));
1039
        let (_, id) = r
1040
            .create_identity(name, "[email protected]", IdentityScope::User)
1041
            .unwrap();
1042
        let cert = SignedCertificate::sign(
1043
            Certificate {
1044
                key: id,
1045
                issuer: hub.hash(),
1046
                subject: subject.into(),
1047
                claims: vec![],
1048
                scope: Scope::CHANGES | Scope::REFS,
1049
                not_before: from,
1050
                expires: to,
1051
                grant: None,
1052
            },
1053
            &hub,
1054
            &hub_sk,
1055
        );
1056
        r.store().put_identity(&hub).unwrap();
1057
        r.store().put_certificate(&cert).unwrap();
1058
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1059
        r.commit("work", &[]).unwrap();
1060
        r
1061
    };
1062
1063
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1064
    let r = claude.push("origin", false).unwrap();
1065
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1066
    // Ada's fetch accepts the bookmark the certified key attested.
1067
    a.pull("origin").unwrap();
1068
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1069
        .store()
1070
        .get_change(h)
1071
        .map(|c| c.message == "work")
1072
        .unwrap_or(false)));
1073
1074
    // Step 4c: a host with an acceptor key records when it accepted the
1075
    // certified update and serves it; a fetch checks the certificate at
1076
    // that time only when the certificate's issuer signed it for exactly
1077
    // this attestation, else at the attestation's own time.
1078
    let host = Repo::open(&root.join("origin"))
1079
        .unwrap()
1080
        .with_acceptor(hub.clone(), hub_sk.clone());
1081
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1082
    host.record_acceptance(&attest_ref).unwrap();
1083
    let served = host.remote_refs().unwrap();
1084
    let acc = served
1085
        .refs
1086
        .iter()
1087
        .find(|r| r.name == "main")
1088
        .unwrap()
1089
        .accepted
1090
        .clone()
1091
        .expect("served with the refs");
1092
    let signer = sa.sigs[0].key;
1093
    assert_eq!(
1094
        a.certified_time(&signer, &sa, Some(&acc)),
1095
        acc.attest.hlc.wall_ms
1096
    );
1097
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1098
    let stranger_sk = SecretKey::generate();
1099
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1100
    let mut forged = acc.clone();
1101
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1102
    assert_eq!(
1103
        a.certified_time(&signer, &sa, Some(&forged)),
1104
        sa.attest.hlc.wall_ms,
1105
        "not the issuer's"
1106
    );
1107
    let mut elsewhere = acc.clone();
1108
    elsewhere.attest.body = AttestBody::Accepted {
1109
        attest: ObjectRef([7; 32]),
1110
    };
1111
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1112
    assert_eq!(
1113
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1114
        sa.attest.hlc.wall_ms,
1115
        "another attestation's"
1116
    );
1117
    a.pull("origin").unwrap();
1118
    // gc keeps the acceptance with the attestation.
1119
    host.gc(true).unwrap();
1120
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1121
1122
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1123
    let r = late.push("origin", false).unwrap();
1124
    assert!(
1125
        !r[0].ok && r[0].reason.contains("may not update"),
1126
        "an expired certificate: {r:?}"
1127
    );
1128
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1129
    let r = other.push("origin", false).unwrap();
1130
    assert!(
1131
        !r[0].ok && r[0].reason.contains("may not update"),
1132
        "a subject not granted: {r:?}"
1133
    );
1134
}
1135
1136
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1137
/// subject the author granted, seals changes in the author's name; with
1138
/// no grant, a stranger's, or one that had ended, it is neither the
1139
/// author nor a delegate.
1140
#[test]
1141
fn a_certified_key_acts_for_its_author_under_a_grant() {
1142
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1143
    use crate::identity::{Identity, Scope};
1144
    hermetic();
1145
    let dir = tempfile::tempdir().unwrap();
1146
    let root = dir.path();
1147
    let _origin = Repo::init(&root.join("origin")).unwrap();
1148
    let url = root.join("origin").to_string_lossy().to_string();
1149
    let mut a = Repo::clone(&url, &root.join("a"))
1150
        .unwrap()
1151
        .with_home(root.join("home-a"));
1152
    let (ada, _) = a
1153
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1154
        .unwrap();
1155
    write(&root.join("a"), "a.txt", b"a\n");
1156
    a.commit("a", &[]).unwrap();
1157
    a.policy_init().unwrap();
1158
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1159
    let hub_sk = SecretKey::generate();
1160
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1161
    a.policy_grant_subject(
1162
        "agent:claude@ada",
1163
        hub.clone(),
1164
        Scope::CHANGES | Scope::REFS,
1165
        None,
1166
    )
1167
    .unwrap();
1168
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1169
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1170
    let ada_id = a.identity(&ada).unwrap();
1171
1172
    let now = Hlc::now().wall_ms;
1173
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1174
        SignedGrant::sign(
1175
            Grant {
1176
                grantor: by.hash(),
1177
                subject: "agent:claude@ada".into(),
1178
                issuer: hub.hash(),
1179
                scope: Scope::CHANGES | Scope::SEAL,
1180
                not_before: from,
1181
                expires: to,
1182
            },
1183
            by,
1184
            sk,
1185
        )
1186
    };
1187
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1188
    // certified (with `g` inside) the signer.
1189
    let agent = |name: &str, g: Option<SignedGrant>| {
1190
        let mut r = Repo::clone(&url, &root.join(name))
1191
            .unwrap()
1192
            .with_home(root.join(format!("home-{name}")));
1193
        let (key, id) = r
1194
            .create_identity(name, "[email protected]", IdentityScope::User)
1195
            .unwrap();
1196
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1197
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1198
        let cert = SignedCertificate::sign(
1199
            Certificate {
1200
                key: id,
1201
                issuer: hub.hash(),
1202
                subject: "agent:claude@ada".into(),
1203
                claims: vec![],
1204
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1205
                not_before: now - 60_000,
1206
                expires: now + 600_000,
1207
                grant: g,
1208
            },
1209
            &hub,
1210
            &hub_sk,
1211
        );
1212
        r.store().put_identity(&hub).unwrap();
1213
        r.store().put_certificate(&cert).unwrap();
1214
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1215
        let h = r.commit("work", &[]).unwrap();
1216
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1217
        (r, key, h)
1218
    };
1219
1220
    let (claude, key, h) = agent(
1221
        "claude",
1222
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1223
    );
1224
    let r = claude.push("origin", false).unwrap();
1225
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1226
    let host = Repo::open(&root.join("origin")).unwrap();
1227
    assert!(matches!(
1228
        host.authenticate_change(&h).unwrap(),
1229
        SignatureStatus::Valid { key: k, sealed: true, .. } if k == key
1230
    ));
1231
    a.pull("origin").unwrap();
1232
    assert!(matches!(
1233
        a.authenticate_change(&h).unwrap(),
1234
        SignatureStatus::Valid { key: k, .. } if k == key
1235
    ));
1236
1237
    let (none, _, _) = agent("none", None);
1238
    let r = none.push("origin", false).unwrap();
1239
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1240
    let mallory_sk = SecretKey::generate();
1241
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1242
    let (stranger, _, _) = agent(
1243
        "stranger",
1244
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1245
    );
1246
    let r = stranger.push("origin", false).unwrap();
1247
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1248
    let (ended, _, eh) = agent(
1249
        "ended",
1250
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1251
    );
1252
    let r = ended.push("origin", false).unwrap();
1253
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1254
    assert!(matches!(
1255
        ended.authenticate_change(&eh).unwrap(),
1256
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1257
    ));
1258
}
1259
1260
#[test]
1261
fn trust_policy_governs_pushes_and_fetches() {
1262
    hermetic();
1263
    let dir = tempfile::tempdir().unwrap();
1264
    let root = dir.path();
1265
    let origin = Repo::init(&root.join("origin")).unwrap();
1266
    let url = root.join("origin").to_string_lossy().to_string();
1267
1268
    // A is the root. Before the policy, an unsigned push from B is fine.
1269
    let mut a = Repo::clone(&url, &root.join("a"))
1270
        .unwrap()
1271
        .with_home(root.join("home-a"));
1272
    let (key_a, _) = a
1273
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1274
        .unwrap();
1275
    let mut b = Repo::clone(&url, &root.join("b"))
1276
        .unwrap()
1277
        .with_home(root.join("home-b"));
1278
    write(&root.join("b"), "b.txt", b"b\n");
1279
    b.commit("unsigned before policy", &[]).unwrap();
1280
    assert!(b.push("origin", false).unwrap()[0].ok);
1281
1282
    // A creates the policy and pushes it; origin now enforces it.
1283
    write(&root.join("a"), "a.txt", b"a\n");
1284
    a.commit("a", &[]).unwrap();
1285
    let sp = a.policy_init().unwrap();
1286
    assert_eq!(sp.policy.serial, 1);
1287
    a.pull("origin").unwrap();
1288
    let results = a.push("origin", false).unwrap();
1289
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1290
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1291
1292
    // B pulls the policy. Without an identity B cannot push at all.
1293
    b.pull("origin").unwrap();
1294
    assert!(
1295
        b.current_policy().unwrap().is_some(),
1296
        "the policy arrived with the fetch"
1297
    );
1298
    assert!(b.push("origin", false).is_err());
1299
    // With an identity the policy does not list, the push is rejected by origin.
1300
    let (key_b, id_b) = b
1301
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1302
        .unwrap();
1303
    write(&root.join("b"), "b.txt", b"b2\n");
1304
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1305
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1306
    let r = b.push("origin", false).unwrap();
1307
    assert!(
1308
        !r[0].ok && r[0].reason.contains("may not update"),
1309
        "{:?}",
1310
        r
1311
    );
1312
1313
    // A grants B (identity handed over as a file) and publishes the policy.
1314
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1315
    assert_eq!(sp.policy.serial, 2);
1316
    let r = a.push("origin", false).unwrap();
1317
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1318
    // B must fetch the new policy before pushing.
1319
    assert!(b
1320
        .push("origin", false)
1321
        .unwrap_or_else(|e| vec![RefResult {
1322
            name: "main".into(),
1323
            ok: false,
1324
            reason: e.to_string()
1325
        }])
1326
        .iter()
1327
        .all(|x| !x.ok));
1328
    b.pull("origin").unwrap();
1329
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1330
    let r = b.push("origin", false).unwrap();
1331
    assert!(r[0].ok, "{:?}", r);
1332
    // Origin verified B's change under the policy.
1333
    let heads = origin.bookmark_heads().unwrap();
1334
    for h in &heads {
1335
        let c = origin.store().get_change(h).unwrap();
1336
        if c.author == key_b {
1337
            origin
1338
                .change_allowed(
1339
                    h,
1340
                    &origin.current_policy().unwrap().unwrap().1.policy,
1341
                    "main",
1342
                )
1343
                .unwrap();
1344
        }
1345
    }
1346
1347
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1348
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1349
    forged.serial = 3;
1350
    forged.roots = vec![key_b];
1351
    let fh = forged.hash();
1352
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1353
    let forged = SignedPolicy {
1354
        policy: forged,
1355
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1356
    };
1357
    let r = origin
1358
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1359
        .unwrap();
1360
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1361
    let stale = a.current_policy().unwrap().unwrap().1;
1362
    let mut old = stale.clone();
1363
    old.policy.serial = 1;
1364
    let r = origin
1365
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1366
        .unwrap();
1367
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1368
1369
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1370
    a.pull("origin").unwrap();
1371
    a.policy_revoke(&key_b).unwrap();
1372
    let r = a.push("origin", false).unwrap();
1373
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1374
    b.pull("origin").unwrap();
1375
    write(&root.join("b"), "b.txt", b"b3\n");
1376
    b.commit("b3", &[]).unwrap();
1377
    let r = b.push("origin", false).unwrap();
1378
    assert!(!r[0].ok, "{:?}", r);
1379
1380
    // A clone by a third party receives and verifies everything.
1381
    let c = Repo::clone(&url, &root.join("c"))
1382
        .unwrap()
1383
        .with_home(root.join("home-c"));
1384
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1385
    assert!(c
1386
        .current_policy()
1387
        .unwrap()
1388
        .unwrap()
1389
        .1
1390
        .policy
1391
        .roots
1392
        .contains(&key_a));
1393
    assert!(!c.snapshot("status").unwrap().changed);
1394
}
1395
1396
/// oxygen#66: a gc says what it is doing, phase by phase.
1397
#[test]
1398
fn gc_reports_its_phases() {
1399
    hermetic();
1400
    let dir = tempfile::tempdir().unwrap();
1401
    let repo = Repo::init(dir.path()).unwrap();
1402
    for i in 0..3 {
1403
        write(
1404
            dir.path(),
1405
            &format!("f{i}.txt"),
1406
            format!("{i}\n").as_bytes(),
1407
        );
1408
        repo.commit(&format!("c{i}"), &[]).unwrap();
1409
    }
1410
    let mut phases = Vec::new();
1411
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1412
        .unwrap();
1413
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1414
    assert!(
1415
        phases.iter().any(|p| p.starts_with("pruning")),
1416
        "{phases:?}"
1417
    );
1418
    assert!(
1419
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1420
        "{phases:?}"
1421
    );
1422
    assert!(
1423
        phases
1424
            .iter()
1425
            .any(|p| p.starts_with("writing the index of ")),
1426
        "{phases:?}"
1427
    );
1428
}
1429
1430
#[test]
1431
fn gc_packs_objects_and_history_still_works() {
1432
    hermetic();
1433
    let dir = tempfile::tempdir().unwrap();
1434
    let root = dir.path();
1435
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1436
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1437
        .unwrap();
1438
    repo.set_user_config("core.sign", "change").unwrap();
1439
    write(root, "a.txt", b"one\n");
1440
    let h1 = repo.commit("one", &[]).unwrap();
1441
    write(root, "a.txt", b"two\n");
1442
    write(root, "big.bin", &vec![0u8; 100_000]);
1443
    let h2 = repo.commit("two", &[]).unwrap();
1444
    // Several snapshots leave superseded working-copy versions behind.
1445
    for i in 0..5 {
1446
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1447
        repo.snapshot("status").unwrap();
1448
    }
1449
    write(root, "a.txt", b"two\n");
1450
    repo.snapshot("status").unwrap();
1451
    let before = repo.store().list().unwrap();
1452
    assert!(repo.store().loose_count().unwrap() > 0);
1453
1454
    // With the default retention every operation's view is a root: nothing prunes.
1455
    let r = repo.gc(true).unwrap();
1456
    assert_eq!(r.packed.objects, before.len());
1457
    assert_eq!(r.pruned.objects, 0);
1458
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1459
    assert_eq!(repo.store().list().unwrap(), before);
1460
1461
    // With zero retention only the current view is a root: superseded
1462
    // working copies go, everything reachable stays.
1463
    repo.config.set("core.op-retention", "0").unwrap();
1464
    repo.save_config().unwrap();
1465
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1466
    let r = repo.gc(true).unwrap();
1467
    assert!(r.pruned.objects >= 5, "{r:?}");
1468
    let after = repo.store().list().unwrap();
1469
    assert!(after.len() < before.len());
1470
    assert!(after.contains(&h1) && after.contains(&h2));
1471
    for (_, op) in repo.op_log().unwrap() {
1472
        assert!(!op.command.is_empty(), "operation objects are all kept");
1473
    }
1474
    // Everything still works from the pruned, packed store.
1475
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1476
    assert!(matches!(
1477
        repo.verify_change(&h2).unwrap(),
1478
        SignatureStatus::Valid { .. }
1479
    ));
1480
    assert_eq!(repo.log().unwrap().len(), 3);
1481
    repo.checkout(&[h1], false, "checkout").unwrap();
1482
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1483
    repo.checkout(&[h2], false, "checkout").unwrap();
1484
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1485
    assert!(!repo.snapshot("status").unwrap().changed);
1486
    // Grace period defers pruning of young garbage.
1487
    write(root, "a.txt", b"three\n");
1488
    repo.commit("three", &[]).unwrap();
1489
    let r = repo.gc(false).unwrap();
1490
    assert_eq!(r.pruned.objects, 0);
1491
    assert!(r.pruned.deferred > 0);
1492
    let r = repo.gc(true).unwrap();
1493
    assert!(r.pruned.objects > 0);
1494
    assert_eq!(repo.log().unwrap().len(), 4);
1495
    // Restoring the default retention makes the old views roots again; the
1496
    // working copies they name were pruned, which gc tolerates.
1497
    repo.config.set("core.op-retention", "90").unwrap();
1498
    repo.save_config().unwrap();
1499
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1500
    let r = repo.gc(false).unwrap();
1501
    assert_eq!(r.pruned.objects, 0);
1502
    assert_eq!(repo.log().unwrap().len(), 4);
1503
}
1504
1505
#[test]
1506
fn describe_amend_abandon_heads() {
1507
    hermetic();
1508
    let dir = tempfile::tempdir().unwrap();
1509
    let root = dir.path();
1510
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1511
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1512
        .unwrap();
1513
    repo.set_user_config("core.sign", "change").unwrap();
1514
    write(root, "a.txt", b"one\n");
1515
    let h1 = repo.commit("first", &[]).unwrap();
1516
    write(root, "a.txt", b"one\ntwo\n");
1517
    let h2 = repo.commit("secnod", &[]).unwrap();
1518
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1519
1520
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1521
    let h2b = repo.describe(&h2, "second").unwrap();
1522
    assert_ne!(h2b, h2);
1523
    let c = repo.store().get_change(&h2b).unwrap();
1524
    assert_eq!(
1525
        (c.change_id, c.message.as_str(), c.deps.clone()),
1526
        (id2, "second", vec![h1])
1527
    );
1528
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1529
    assert!(matches!(
1530
        repo.verify_change(&h2b).unwrap(),
1531
        SignatureStatus::Valid { .. }
1532
    ));
1533
    let s = repo.snapshot("status").unwrap();
1534
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1535
    assert_eq!(
1536
        repo.resolve_change(&id2.short(8)).unwrap(),
1537
        h2b,
1538
        "the old object is no longer reachable from the log"
1539
    );
1540
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1541
    let h1b = repo.describe(&h1, "first, described").unwrap();
1542
    assert_ne!(h1b, h1);
1543
    let heads = repo.bookmark_heads().unwrap();
1544
    assert_eq!(heads.len(), 1);
1545
    let top = repo.store().get_change(&heads[0]).unwrap();
1546
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1547
    assert!(
1548
        matches!(
1549
            repo.verify_change(&heads[0]).unwrap(),
1550
            SignatureStatus::Valid { .. }
1551
        ),
1552
        "rewritten own change is re-signed"
1553
    );
1554
    let (_, wc) = repo.working_copy().unwrap();
1555
    assert_eq!(
1556
        wc.deps,
1557
        vec![heads[0]],
1558
        "the working copy follows the rewrite"
1559
    );
1560
    assert!(!repo.snapshot("status").unwrap().changed);
1561
    let snap = repo.load_state(&heads).unwrap().materialize();
1562
    assert!(
1563
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1564
    );
1565
1566
    // amend: fold an edit into the head; the result is one change from h1.
1567
    write(root, "a.txt", b"one\ntwo\nthree\n");
1568
    write(root, "b.txt", b"b\n");
1569
    let h2c = repo.amend(None).unwrap();
1570
    let c = repo.store().get_change(&h2c).unwrap();
1571
    assert_eq!(c.change_id, id2);
1572
    assert_eq!(c.message, "second");
1573
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1574
    assert_eq!(
1575
        repo.log().unwrap().len(),
1576
        3,
1577
        "working copy, amended head, first"
1578
    );
1579
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1580
    assert!(
1581
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1582
    );
1583
    assert!(snap.files.contains_key("b.txt"));
1584
    assert!(!repo.snapshot("status").unwrap().changed);
1585
    assert!(
1586
        repo.amend(None).is_err(),
1587
        "clean working copy and no message"
1588
    );
1589
    let h2d = repo.amend(Some("second, amended")).unwrap();
1590
    assert_eq!(
1591
        repo.store().get_change(&h2d).unwrap().message,
1592
        "second, amended"
1593
    );
1594
1595
    // abandon: the head goes, its content stays as uncommitted work.
1596
    repo.abandon(&h2d).unwrap();
1597
    assert_eq!(
1598
        repo.bookmark_heads().unwrap(),
1599
        vec![h1b],
1600
        "the described first change is the head again"
1601
    );
1602
    let s = repo.snapshot("status").unwrap();
1603
    let paths: Vec<_> = s
1604
        .statuses
1605
        .iter()
1606
        .map(|p| (p.path.as_str(), p.status))
1607
        .collect();
1608
    assert_eq!(
1609
        paths,
1610
        vec![
1611
            ("a.txt", ChangeStatus::Modified),
1612
            ("b.txt", ChangeStatus::Added)
1613
        ]
1614
    );
1615
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1616
    let h3 = repo.commit("recommitted", &[]).unwrap();
1617
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1618
    // undo brings the abandoned head back.
1619
    repo.undo().unwrap();
1620
    repo.undo().unwrap();
1621
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1622
1623
    // Abandoning a non-head whose dependent references its atoms reifies
1624
    // the references (here: a.txt vanishes with it, so the dependent's edit
1625
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1626
    let base = repo.bookmark_heads().unwrap()[0];
1627
    let base_change = repo.store().get_change(&base).unwrap();
1628
    let h1_now = base_change.deps[0];
1629
    let notes = repo.abandon(&h1_now).unwrap();
1630
    assert!(
1631
        !notes.is_empty(),
1632
        "the dependent's edit of a.txt was reified"
1633
    );
1634
    let heads = repo.bookmark_heads().unwrap();
1635
    let after = repo.load_state(&heads).unwrap().materialize();
1636
    assert!(
1637
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1638
        "{:?}",
1639
        after.files.keys()
1640
    );
1641
    repo.undo().unwrap();
1642
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1643
    write(root, "c.txt", b"c\n");
1644
    let hc = repo.commit("c", &[]).unwrap();
1645
    write(root, "d.txt", b"d\n");
1646
    let hd = repo.commit("d", &[hc]).unwrap();
1647
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1648
    repo.abandon(&hc).unwrap();
1649
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1650
    assert!(!heads.contains(&hc));
1651
    let d_now = heads
1652
        .iter()
1653
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1654
        .copied()
1655
        .unwrap();
1656
    assert!(
1657
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1658
        "d inherited c's (empty) dependencies"
1659
    );
1660
    let s = repo.snapshot("status").unwrap();
1661
    assert_eq!(
1662
        s.statuses
1663
            .iter()
1664
            .map(|p| p.path.as_str())
1665
            .collect::<Vec<_>>(),
1666
        vec!["c.txt"],
1667
        "c's content is now uncommitted work"
1668
    );
1669
}
1670
1671
#[test]
1672
fn git_export_mirrors_history() {
1673
    hermetic();
1674
    if std::process::Command::new("git")
1675
        .arg("--version")
1676
        .output()
1677
        .is_err()
1678
    {
1679
        eprintln!("git not installed; skipping");
1680
        return;
1681
    }
1682
    let dir = tempfile::tempdir().unwrap();
1683
    let root = dir.path();
1684
    let mut repo = Repo::init(&root.join("r"))
1685
        .unwrap()
1686
        .with_home(root.join("home"));
1687
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1688
        .unwrap();
1689
    let r = root.join("r");
1690
    write(&r, "README.md", b"hello\n");
1691
    write(&r, "src/main.rs", b"fn main() {}\n");
1692
    let h1 = repo.commit("first", &[]).unwrap();
1693
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1694
    write(&r, "logo.png", b"\x89PNG\0\0");
1695
    let h2 = repo.commit("second", &[]).unwrap();
1696
1697
    let git_dir = root.join("mirror.git");
1698
    let rep = repo.git_export(&git_dir).unwrap();
1699
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1700
    let git = |args: &[&str]| -> String {
1701
        let out = std::process::Command::new("git")
1702
            .arg("-C")
1703
            .arg(&git_dir)
1704
            .args(args)
1705
            .output()
1706
            .unwrap();
1707
        assert!(
1708
            out.status.success(),
1709
            "{}",
1710
            String::from_utf8_lossy(&out.stderr)
1711
        );
1712
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1713
    };
1714
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1715
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1716
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1717
    let body = git(&["log", "-1", "--format=%B", "main"]);
1718
    assert!(
1719
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1720
        "{body}"
1721
    );
1722
    assert!(body.contains("Change-Id: "), "{body}");
1723
    assert_eq!(
1724
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1725
        "Ada Lovelace <[email protected]>"
1726
    );
1727
    assert_eq!(
1728
        git(&["ls-tree", "--name-only", "main"]),
1729
        "README.md\nlogo.png\nsrc"
1730
    );
1731
1732
    // Re-export is incremental.
1733
    let rep = repo.git_export(&git_dir).unwrap();
1734
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1735
1736
    // An independent change makes two heads; the next state is one more
1737
    // commit on the linear branch whose tree is the union.
1738
    repo.checkout(&[h1], false, "checkout").unwrap();
1739
    write(&r, "other.txt", b"o\n");
1740
    let h3 = repo.commit("third", &[]).unwrap();
1741
    let rep = repo.git_export(&git_dir).unwrap();
1742
    assert_eq!((rep.exported, rep.heads), (1, 2));
1743
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1744
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1745
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1746
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1747
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1748
    assert_eq!(
1749
        git(&["ls-tree", "--name-only", "main"]),
1750
        "README.md\nlogo.png\nother.txt\nsrc"
1751
    );
1752
    let body = git(&["log", "-1", "--format=%B", "main"]);
1753
    assert!(
1754
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1755
        "{body}"
1756
    );
1757
    // A rewrite is a new state whose one new change is the rewritten one.
1758
    repo.describe(&h3, "third, described").unwrap();
1759
    let rep = repo.git_export(&git_dir).unwrap();
1760
    assert_eq!(rep.exported, 1);
1761
    assert_eq!(
1762
        git(&["log", "-1", "--format=%s", "main"]),
1763
        "third, described"
1764
    );
1765
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1766
    let _ = h2;
1767
}
1768
1769
#[test]
1770
fn git_import_reproduces_trees() {
1771
    git_import_reproduces_trees_with(None);
1772
}
1773
1774
/// The same import with every merge rendered in batches of one file
1775
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1776
#[test]
1777
fn git_import_reproduces_trees_in_batches() {
1778
    git_import_reproduces_trees_with(Some(1));
1779
}
1780
1781
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1782
    crate::repo::git::set_merge_batch_for_tests(batch);
1783
    hermetic();
1784
    if std::process::Command::new("git")
1785
        .arg("--version")
1786
        .output()
1787
        .is_err()
1788
    {
1789
        eprintln!("git not installed; skipping");
1790
        return;
1791
    }
1792
    let dir = tempfile::tempdir().unwrap();
1793
    let root = dir.path();
1794
    let g = root.join("src.git");
1795
    fs::create_dir_all(&g).unwrap();
1796
    let git = |args: &[&str]| -> String {
1797
        let out = std::process::Command::new("git")
1798
            .arg("-C")
1799
            .arg(&g)
1800
            .args([
1801
                "-c",
1802
                "user.name=Grace",
1803
                "-c",
1804
                "[email protected]",
1805
                "-c",
1806
                "commit.gpgsign=false",
1807
            ])
1808
            .args(args)
1809
            .output()
1810
            .unwrap();
1811
        assert!(
1812
            out.status.success(),
1813
            "git {args:?}: {}",
1814
            String::from_utf8_lossy(&out.stderr)
1815
        );
1816
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1817
    };
1818
    git(&["init", "-q", "-b", "main"]);
1819
    write(&g, "README.md", b"# Hi\n");
1820
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1821
    git(&["add", "."]);
1822
    git(&["commit", "-q", "-m", "initial"]);
1823
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1824
    write(&g, "run.sh", b"#!/bin/sh\n");
1825
    #[cfg(unix)]
1826
    {
1827
        use std::os::unix::fs::PermissionsExt;
1828
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1829
    }
1830
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1831
    git(&["add", "."]);
1832
    git(&[
1833
        "commit",
1834
        "-q",
1835
        "-m",
1836
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1837
    ]);
1838
    // A branch that edits README, merged back with a conflict-free merge.
1839
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1840
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1841
    git(&["commit", "-q", "-am", "readme"]);
1842
    git(&["checkout", "-q", "main"]);
1843
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1844
    // A branch from the initial commit inserting at the same place as
1845
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1846
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1847
    git(&["checkout", "-q", "-b", "clash", &initial]);
1848
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1849
    git(&["commit", "-q", "-am", "clash"]);
1850
    git(&["checkout", "-q", "main"]);
1851
    // Expected to stop at the conflict, so its status is ignored; the
1852
    // identity is passed as for every other git call here, or a machine
1853
    // without one refuses to start the merge at all.
1854
    let _ = std::process::Command::new("git")
1855
        .arg("-C")
1856
        .arg(&g)
1857
        .args([
1858
            "-c",
1859
            "user.name=Grace",
1860
            "-c",
1861
            "[email protected]",
1862
            "merge",
1863
            "-q",
1864
            "clash",
1865
        ])
1866
        .output();
1867
    assert!(
1868
        g.join(".git/MERGE_HEAD").exists(),
1869
        "the clash merge stopped at its conflict"
1870
    );
1871
    write(
1872
        &g,
1873
        "src/lib.rs",
1874
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1875
    );
1876
    git(&["add", "."]);
1877
    git(&["commit", "-q", "-m", "resolve clash"]);
1878
    git(&["rm", "-q", "logo.png"]);
1879
    git(&["commit", "-q", "-m", "drop logo"]);
1880
    // A rename with a small edit is imported as a move of the same node.
1881
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1882
    write(
1883
        &g,
1884
        "src/lib2.rs",
1885
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1886
    );
1887
    git(&["add", "."]);
1888
    git(&["commit", "-q", "-m", "rename lib"]);
1889
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1890
    // run.sh is the same as in the first parent's tree, but the merged
1891
    // change touched it, so the importer must compare it, not skip it.
1892
    git(&["checkout", "-q", "-b", "discarded"]);
1893
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1894
    git(&["commit", "-q", "-am", "discarded edit"]);
1895
    git(&["checkout", "-q", "main"]);
1896
    git(&[
1897
        "merge",
1898
        "-q",
1899
        "-s",
1900
        "ours",
1901
        "-m",
1902
        "merge discarded, keeping ours",
1903
        "discarded",
1904
    ]);
1905
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1906
1907
    let dest = root.join("oxy");
1908
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1909
    let rep = repo.import_git(&g, "main").unwrap();
1910
    assert_eq!(rep.commits, expected_count);
1911
    assert_eq!(rep.merges, 3);
1912
    assert_eq!(
1913
        fs::read(dest.join("run.sh")).unwrap(),
1914
        b"#!/bin/sh\n",
1915
        "the ours merge kept main's run.sh"
1916
    );
1917
    let v = repo.verify_git_import(&g, "main").unwrap();
1918
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1919
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1920
    // The working copy equals the Git tree at main.
1921
    assert_eq!(
1922
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1923
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1924
    );
1925
    assert!(!dest.join("src/lib.rs").exists());
1926
    assert_eq!(
1927
        fs::read(dest.join("README.md")).unwrap(),
1928
        b"# Hi\n\nMore.\n"
1929
    );
1930
    assert!(!dest.join("logo.png").exists());
1931
    #[cfg(unix)]
1932
    {
1933
        use std::os::unix::fs::PermissionsExt;
1934
        assert!(
1935
            fs::metadata(dest.join("run.sh"))
1936
                .unwrap()
1937
                .permissions()
1938
                .mode()
1939
                & 0o111
1940
                != 0
1941
        );
1942
    }
1943
    assert!(
1944
        !repo.snapshot("status").unwrap().changed,
1945
        "clean after import"
1946
    );
1947
    let heads = repo.bookmark_heads().unwrap();
1948
    let st = repo.load_state(&heads).unwrap();
1949
    assert!(!st.materialize().is_conflicted());
1950
    assert_eq!(st.len(), expected_count);
1951
    let tip = repo
1952
        .log()
1953
        .unwrap()
1954
        .into_iter()
1955
        .find(|e| e.change.message.starts_with("rename lib"))
1956
        .unwrap();
1957
    let c = repo.store().get_change(&tip.hash).unwrap();
1958
    assert!(
1959
        c.tree_ops
1960
            .iter()
1961
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1962
        "{:?}",
1963
        c.tree_ops
1964
    );
1965
    assert!(!c
1966
        .tree_ops
1967
        .iter()
1968
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1969
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1970
    let log = repo.log().unwrap();
1971
    let second = log
1972
        .iter()
1973
        .find(|e| e.change.message.starts_with("second"))
1974
        .unwrap();
1975
    assert_eq!(
1976
        second.change.change_id,
1977
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1978
    );
1979
    assert!(second
1980
        .change
1981
        .message
1982
        .contains("Git-Author: Grace <[email protected]>"));
1983
    let resolve = log
1984
        .iter()
1985
        .find(|e| e.change.message.starts_with("resolve clash"))
1986
        .unwrap();
1987
    assert_eq!(
1988
        resolve.change.kind,
1989
        ChangeKind::Resolution,
1990
        "a conflicting Git merge becomes a resolution"
1991
    );
1992
    // Re-importing into another fresh repository gives the same ChangeIds.
1993
    let repo2 = Repo::init(&root.join("oxy2"))
1994
        .unwrap()
1995
        .with_home(root.join("home"));
1996
    repo2.import_git(&g, "main").unwrap();
1997
    // New nodes' identifiers derive from the commit (spec §23), so the
1998
    // re-import is not just the same ChangeIds but the same changes.
1999
    assert_eq!(
2000
        repo2.bookmark_heads().unwrap(),
2001
        repo.bookmark_heads().unwrap()
2002
    );
2003
    let ids: BTreeSet<ChangeId> = repo
2004
        .log()
2005
        .unwrap()
2006
        .iter()
2007
        .filter(|e| !e.is_working_copy)
2008
        .map(|e| e.change.change_id)
2009
        .collect();
2010
    let ids2: BTreeSet<ChangeId> = repo2
2011
        .log()
2012
        .unwrap()
2013
        .iter()
2014
        .filter(|e| !e.is_working_copy)
2015
        .map(|e| e.change.change_id)
2016
        .collect();
2017
    assert_eq!(ids, ids2);
2018
    // Round trip back out to Git reproduces the tip tree.
2019
    let mirror = root.join("mirror.git");
2020
    repo.git_export(&mirror).unwrap();
2021
    let out = std::process::Command::new("git")
2022
        .arg("-C")
2023
        .arg(&mirror)
2024
        .args(["show", "main:src/lib2.rs"])
2025
        .output()
2026
        .unwrap();
2027
    assert_eq!(
2028
        String::from_utf8_lossy(&out.stdout),
2029
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2030
    );
2031
    let out = std::process::Command::new("git")
2032
        .arg("-C")
2033
        .arg(&mirror)
2034
        .args(["show", "main:src/lib.rs"])
2035
        .output()
2036
        .unwrap();
2037
    assert!(
2038
        !out.status.success(),
2039
        "the old path is gone from the export"
2040
    );
2041
}
2042
2043
#[test]
2044
fn checkpoints_accelerate_loading_and_stay_correct() {
2045
    hermetic();
2046
    let dir = tempfile::tempdir().unwrap();
2047
    let root = dir.path();
2048
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2049
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2050
    repo.save_config().unwrap();
2051
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2052
    let mut hashes = Vec::new();
2053
    for i in 0..12 {
2054
        write(
2055
            root,
2056
            "a.txt",
2057
            format!(
2058
                "{}\n",
2059
                (0..=i)
2060
                    .map(|k| k.to_string())
2061
                    .collect::<Vec<_>>()
2062
                    .join("\n")
2063
            )
2064
            .as_bytes(),
2065
        );
2066
        write(root, &format!("f{i}.txt"), b"x\n");
2067
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2068
    }
2069
    let (_, cp) = repo
2070
        .latest_checkpoint("main")
2071
        .unwrap()
2072
        .expect("automatic checkpoint");
2073
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2074
    // Loading through the checkpoint equals loading everything.
2075
    let heads = repo.bookmark_heads().unwrap();
2076
    let fast = repo.load_state(&heads).unwrap();
2077
    let full = repo.load_state_full(&heads).unwrap();
2078
    assert_eq!(fast.len(), full.len());
2079
    assert_eq!(fast.heads(), full.heads());
2080
    let (a, b) = (fast.materialize(), full.materialize());
2081
    assert_eq!(
2082
        a.files.keys().collect::<Vec<_>>(),
2083
        b.files.keys().collect::<Vec<_>>()
2084
    );
2085
    for (p, f) in &a.files {
2086
        assert_eq!(f.content, b.files[p].content, "{p}");
2087
    }
2088
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2089
    // A head set that does not contain the checkpoint's heads falls back.
2090
    assert!(repo
2091
        .load_state_checkpointed(&[hashes[0]])
2092
        .unwrap()
2093
        .is_none());
2094
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2095
    // Everything else keeps working on top of the checkpoint.
2096
    assert!(!repo.snapshot("status").unwrap().changed);
2097
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2098
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2099
    let (r, n, bytes) = repo.checkpoint().unwrap();
2100
    assert!(n >= 12 && bytes > 0);
2101
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2102
    write(root, "a.txt", b"after\n");
2103
    let h_after = repo.commit("after", &[]).unwrap();
2104
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2105
    assert!(st.contains(&h_after));
2106
    assert!(
2107
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2108
    );
2109
    assert_eq!(repo.log().unwrap().len(), 14);
2110
    // Checkpoints survive gc.
2111
    repo.gc(true).unwrap();
2112
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
2113
    assert!(repo
2114
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2115
        .unwrap()
2116
        .is_some());
2117
}
2118
2119
#[test]
2120
fn quick_status_for_prompts() {
2121
    hermetic();
2122
    let dir = tempfile::tempdir().unwrap();
2123
    let root = dir.path();
2124
    let origin = Repo::init(&root.join("origin")).unwrap();
2125
    let url = root.join("origin").to_string_lossy().to_string();
2126
    let a = Repo::clone(&url, &root.join("a"))
2127
        .unwrap()
2128
        .with_home(root.join("home"));
2129
    let ops_before = a.op_log().unwrap().len();
2130
    let info = a.quick_status().unwrap();
2131
    assert_eq!(
2132
        (
2133
            info.bookmark.as_str(),
2134
            info.heads,
2135
            info.dirty,
2136
            info.conflicted,
2137
            info.ahead,
2138
            info.behind
2139
        ),
2140
        ("main", 0, false, false, Some(0), Some(0))
2141
    );
2142
    write(&root.join("a"), "f.txt", b"f\n");
2143
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
2144
    assert_eq!(
2145
        a.op_log().unwrap().len(),
2146
        ops_before,
2147
        "quick_status records nothing"
2148
    );
2149
    // A snapshotted but uncommitted change is still dirty.
2150
    a.snapshot("status").unwrap();
2151
    assert!(a.quick_status().unwrap().dirty);
2152
    a.commit("f", &[]).unwrap();
2153
    let info = a.quick_status().unwrap();
2154
    assert!(!info.dirty, "clean right after a commit");
2155
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
2156
    assert_eq!(
2157
        info.format("%b %c%d%x%A%D"),
2158
        format!("main {}+1", info.change_id)
2159
    );
2160
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2161
    // Touching a file without changing it is not dirty; changing content of
2162
    // the same size is.
2163
    let p = root.join("a/f.txt");
2164
    let content = fs::read(&p).unwrap();
2165
    fs::write(&p, &content).unwrap();
2166
    assert!(!a.quick_status().unwrap().dirty);
2167
    fs::write(&p, b"g\n").unwrap();
2168
    assert!(a.quick_status().unwrap().dirty);
2169
    fs::write(&p, b"f\n").unwrap();
2170
    // Push, then a second clone commits and pushes: we are behind.
2171
    assert!(a.push("origin", false).unwrap()[0].ok);
2172
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
2173
    let b = Repo::clone(&url, &root.join("b"))
2174
        .unwrap()
2175
        .with_home(root.join("home-b"));
2176
    write(&root.join("b"), "g.txt", b"g\n");
2177
    b.commit("g", &[]).unwrap();
2178
    b.push("origin", false).unwrap();
2179
    a.fetch("origin").unwrap();
2180
    let info = a.quick_status().unwrap();
2181
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2182
    assert_eq!(info.format("%A%D"), "-1");
2183
    let _ = origin;
2184
}
2185
2186
#[test]
2187
fn lazy_blobs_are_fetched_on_first_read() {
2188
    hermetic();
2189
    let dir = tempfile::tempdir().unwrap();
2190
    let root = dir.path();
2191
    let origin_dir = root.join("origin");
2192
    let origin = Repo::init(&origin_dir)
2193
        .unwrap()
2194
        .with_home(root.join("home"));
2195
    let url = origin_dir.to_string_lossy().to_string();
2196
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2197
    write(&origin_dir, "big.bin", &big);
2198
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2199
    write(&origin_dir, "t.txt", b"t\n");
2200
    let h = origin.commit("blobs", &[]).unwrap();
2201
    let big_ref = Repo::blob_ref(&big);
2202
2203
    // Fetch only (no checkout) with a filter: the big blob stays absent.
2204
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2205
        .unwrap()
2206
        .with_home(root.join("home"));
2207
    let a = {
2208
        let mut a = a;
2209
        a.config.set("remote.origin.url", &url).unwrap();
2210
        a.config.set("filter.max-blob", "100K").unwrap();
2211
        a.save_config().unwrap();
2212
        a
2213
    };
2214
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2215
    a.fetch("origin").unwrap();
2216
    assert!(a.store().has(&h));
2217
    assert!(!a.store().has(&big_ref), "withheld");
2218
    assert!(
2219
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2220
        "small blob came along"
2221
    );
2222
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2223
2224
    // status and commit do not need it: adopt the state, edit a text file, commit.
2225
    let (op_ref, op) = a.head_op().unwrap();
2226
    let mut view = op.view.clone();
2227
    view.bookmarks.insert(
2228
        "main".into(),
2229
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2230
    );
2231
    a.record_op(&[op_ref], "adopt", view).unwrap();
2232
    // Checkout reads the blob lazily, which fetches it.
2233
    a.checkout(&[h], true, "checkout").unwrap();
2234
    assert!(a.store().has(&big_ref), "fetched on first read");
2235
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2236
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2237
    write(&root.join("a"), "t.txt", b"t2\n");
2238
    a.commit("text edit", &[]).unwrap();
2239
2240
    // clone --max-blob records the filter; the checkout fetches lazily.
2241
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
2242
    assert_eq!(b.config.max_blob, Some(1024));
2243
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2244
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2245
    assert!(parse_size("lots").is_err());
2246
}
2247
2248
#[test]
2249
fn sparse_checkout_materializes_only_chosen_paths() {
2250
    hermetic();
2251
    let dir = tempfile::tempdir().unwrap();
2252
    let root = dir.path();
2253
    let origin_dir = root.join("origin");
2254
    let origin = Repo::init(&origin_dir)
2255
        .unwrap()
2256
        .with_home(root.join("home"));
2257
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2258
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2259
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2260
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2261
    write(&origin_dir, "docs/logo.png", &logo);
2262
    write(&origin_dir, "README.md", b"# top\n");
2263
    let h1 = origin.commit("tree", &[]).unwrap();
2264
    let url = origin_dir.to_string_lossy().to_string();
2265
2266
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2267
        .unwrap()
2268
        .with_home(root.join("home"));
2269
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2270
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2271
    assert!(root.join("a/src/main.rs").exists());
2272
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
2273
    assert!(
2274
        !a.store().has(&Repo::blob_ref(&logo)),
2275
        "out-of-scope blob never fetched"
2276
    );
2277
    assert!(
2278
        !a.snapshot("status").unwrap().changed,
2279
        "out-of-scope files are not removals"
2280
    );
2281
    assert!(!a.quick_status().unwrap().dirty);
2282
2283
    // Edits in scope commit normally and keep the rest of the tree intact.
2284
    write(
2285
        &root.join("a"),
2286
        "src/lib.rs",
2287
        b"pub fn a() {}\npub fn b() {}\n",
2288
    );
2289
    let h2 = a.commit("edit lib", &[]).unwrap();
2290
    let st = a.load_state(&[h2]).unwrap().materialize();
2291
    assert!(
2292
        st.files.contains_key("docs/guide.md"),
2293
        "the state still has everything"
2294
    );
2295
    assert!(a.push("origin", false).unwrap()[0].ok);
2296
    // Files created outside the scope are ignored by status.
2297
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2298
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2299
2300
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2301
    let mut a = a;
2302
    a.config.set("filter.paths", "src,docs").unwrap();
2303
    a.save_config().unwrap();
2304
    let r = a
2305
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2306
        .unwrap();
2307
    assert!(r.written >= 2);
2308
    assert_eq!(
2309
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2310
        logo,
2311
        "now fetched lazily"
2312
    );
2313
    assert!(!root.join("a/README.md").exists());
2314
    // Origin sees the change made under a sparse checkout with the full tree intact.
2315
    origin.pull("origin").err();
2316
    let full = origin
2317
        .load_state(&origin.bookmark_heads().unwrap())
2318
        .unwrap()
2319
        .materialize();
2320
    assert!(
2321
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2322
    );
2323
    assert!(full.files.contains_key("README.md"));
2324
    let _ = h1;
2325
}
2326
2327
#[test]
2328
fn shallow_clone_and_deepen() {
2329
    hermetic();
2330
    let dir = tempfile::tempdir().unwrap();
2331
    let root = dir.path();
2332
    let origin_dir = root.join("origin");
2333
    let origin = Repo::init(&origin_dir)
2334
        .unwrap()
2335
        .with_home(root.join("home"));
2336
    let mut hashes = Vec::new();
2337
    for i in 0..8 {
2338
        write(
2339
            &origin_dir,
2340
            "a.txt",
2341
            format!(
2342
                "{}\n",
2343
                (0..=i)
2344
                    .map(|k| k.to_string())
2345
                    .collect::<Vec<_>>()
2346
                    .join("\n")
2347
            )
2348
            .as_bytes(),
2349
        );
2350
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2351
    }
2352
    let url = origin_dir.to_string_lossy().to_string();
2353
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2354
        .unwrap()
2355
        .with_home(root.join("home"));
2356
    assert!(a.is_shallow());
2357
    assert_eq!(
2358
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2359
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2360
    );
2361
    assert!(
2362
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2363
        "three levels present"
2364
    );
2365
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2366
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2367
    assert_eq!(
2368
        a.log().unwrap().len(),
2369
        9,
2370
        "the log shows every change from the checkpoint's metadata"
2371
    );
2372
    assert!(!a.snapshot("status").unwrap().changed);
2373
    assert_eq!(a.quick_status().unwrap().heads, 1);
2374
2375
    // Work continues on top of the shallow history and pushes back.
2376
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2377
    let h_new = a.commit("c8", &[]).unwrap();
2378
    assert!(a.push("origin", false).unwrap()[0].ok);
2379
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2380
    // Fetching new work from origin into the shallow clone works too.
2381
    write(&origin_dir, "b.txt", b"b\n");
2382
    origin.pull("origin").err();
2383
    let (_, wc) = origin.working_copy().unwrap();
2384
    let _ = wc;
2385
    origin
2386
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2387
        .unwrap();
2388
    write(&origin_dir, "b.txt", b"b\n");
2389
    let h_b = origin.commit("b", &[]).unwrap();
2390
    let pr = a.pull("origin").unwrap();
2391
    assert!(pr.changed);
2392
    assert!(a.store().has(&h_b));
2393
    assert!(root.join("a/b.txt").exists());
2394
2395
    // Deepening fetches older history until the boundary is gone.
2396
    // Every commit also depends on the change that created the file, so two
2397
    // levels below the boundary hold h4, h3, and the root.
2398
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2399
    assert!(a.store().has(&hashes[3]));
2400
    assert!(a.is_shallow());
2401
    a.deepen("origin", 100).unwrap();
2402
    assert!(!a.is_shallow(), "boundary reached the root");
2403
    assert!(a.store().has(&hashes[0]));
2404
    assert_eq!(
2405
        a.load_state_full(&a.bookmark_heads().unwrap())
2406
            .unwrap()
2407
            .len(),
2408
        10
2409
    );
2410
}
2411
2412
#[test]
2413
fn tags_are_immutable_named_states_and_travel() {
2414
    hermetic();
2415
    let dir = tempfile::tempdir().unwrap();
2416
    let root = dir.path();
2417
    let origin = Repo::init(&root.join("origin")).unwrap();
2418
    let url = root.join("origin").to_string_lossy().to_string();
2419
    let mut a = Repo::clone(&url, &root.join("a"))
2420
        .unwrap()
2421
        .with_home(root.join("home-a"));
2422
    let (key_a, _) = a
2423
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2424
        .unwrap();
2425
    write(&root.join("a"), "f.txt", b"1\n");
2426
    let h1 = a.commit("one", &[]).unwrap();
2427
    write(&root.join("a"), "f.txt", b"1\n2\n");
2428
    let h2 = a.commit("two", &[]).unwrap();
2429
2430
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2431
    assert_eq!(
2432
        (t.heads.clone(), t.signer.as_deref()),
2433
        (vec![h1], Some("Ada"))
2434
    );
2435
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2436
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2437
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2438
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2439
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2440
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2441
    assert_eq!(sa.sigs[0].key, key_a);
2442
    // Checkout by tag.
2443
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2444
        .unwrap();
2445
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2446
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2447
        .unwrap();
2448
2449
    // Push carries the tag; a second attestation for the name is refused.
2450
    let r = a.push("origin", false).unwrap();
2451
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2452
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2453
    let mut forged = a
2454
        .tag_refs()
2455
        .unwrap()
2456
        .into_iter()
2457
        .find(|t| t.name == "v1")
2458
        .unwrap();
2459
    forged.state = origin
2460
        .store()
2461
        .put_state(&StateObject::new(vec![h2]))
2462
        .unwrap();
2463
    forged.heads = vec![h2];
2464
    forged.attestation = None;
2465
    let r = origin
2466
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2467
        .unwrap();
2468
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2469
2470
    // A clone gets the tag; a later tag arrives on fetch.
2471
    let b = Repo::clone(&url, &root.join("b"))
2472
        .unwrap()
2473
        .with_home(root.join("home-b"));
2474
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2475
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2476
    a.tag_create("v2", &[h2], "second").unwrap();
2477
    a.push("origin", false).unwrap();
2478
    let rep = b.fetch("origin").unwrap();
2479
    assert_eq!(rep.new_tags, 1);
2480
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2481
2482
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2483
    a.policy_init().unwrap();
2484
    a.push("origin", false).unwrap();
2485
    let unattested = crate::protocol::TagRef {
2486
        name: "v3".into(),
2487
        state: origin
2488
            .store()
2489
            .put_state(&StateObject::new(vec![h2]))
2490
            .unwrap(),
2491
        heads: vec![h2],
2492
        attestation: None,
2493
    };
2494
    let r = origin
2495
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2496
        .unwrap();
2497
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2498
    a.tag_create("v3", &[h2], "").unwrap();
2499
    let r = a.push("origin", false).unwrap();
2500
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2501
    assert!(a.gc(true).is_ok());
2502
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2503
2504
    // After a rotation the policy names only the new key, yet a fresh clone
2505
    // still takes the tags the old key made before it; the old key makes
2506
    // nothing new.
2507
    let rot = a.rotate_identity().unwrap();
2508
    let r = a.push("origin", false).unwrap();
2509
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2510
    let c = Repo::clone(&url, &root.join("c"))
2511
        .unwrap()
2512
        .with_home(root.join("home-c"));
2513
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
2514
    let (_, sp) = c.current_policy().unwrap().unwrap();
2515
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
2516
    let made = c.identity(&rot.new).unwrap().created;
2517
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
2518
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
2519
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
2520
}
2521
2522
#[test]
2523
fn multiple_workspaces_share_a_repository() {
2524
    hermetic();
2525
    let dir = tempfile::tempdir().unwrap();
2526
    let root = dir.path();
2527
    let main_dir = root.join("main");
2528
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2529
    write(&main_dir, "a.txt", b"a\n");
2530
    let h1 = repo.commit("a", &[]).unwrap();
2531
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2532
2533
    // A second workspace elsewhere, checked out on the bookmark.
2534
    let ws_dir = root.join("ws2");
2535
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2536
    assert!(ws_dir.join(".oxy").is_file());
2537
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2538
    assert_ne!(ws.workspace(), repo.workspace());
2539
    let list = repo.workspaces().unwrap();
2540
    assert_eq!(list.len(), 2);
2541
    assert!(list
2542
        .iter()
2543
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2544
    assert!(!ws.snapshot("status").unwrap().changed);
2545
2546
    // Work in the second workspace: its own working copy, shared bookmark.
2547
    write(&ws_dir, "b.txt", b"b\n");
2548
    let s = ws.snapshot("status").unwrap();
2549
    assert_eq!(s.statuses.len(), 1);
2550
    assert!(
2551
        !repo.snapshot("status").unwrap().changed,
2552
        "the first workspace is untouched"
2553
    );
2554
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2555
    let mut heads = repo.bookmark_heads().unwrap();
2556
    heads.sort();
2557
    let mut want = vec![h1, h2];
2558
    want.sort();
2559
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2560
    assert!(!main_dir.join("b.txt").exists());
2561
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2562
        .unwrap();
2563
    assert!(main_dir.join("b.txt").exists());
2564
2565
    // Reopening from inside the second workspace finds the shared repository.
2566
    let reopened = Repo::open(&ws_dir).unwrap();
2567
    assert_eq!(reopened.workspace(), ws.workspace());
2568
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2569
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2570
2571
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2572
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2573
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2574
    repo.workspace_forget(&ws.workspace()).unwrap();
2575
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2576
    assert!(ws_dir.join("b.txt").exists());
2577
    assert!(
2578
        ws.snapshot("status").is_err(),
2579
        "a forgotten workspace is no longer in the view"
2580
    );
2581
2582
    // The working-copy lock: re-entrant in a thread; a lock whose process
2583
    // is gone is taken over, and a live process's is not, however old.
2584
    let lock = repo.lock_snapshot().unwrap();
2585
    let again = repo.lock_working_copy().unwrap();
2586
    drop(again);
2587
    drop(lock);
2588
    let lock_path = main_dir
2589
        .join(".oxy/workspaces")
2590
        .join(repo.workspace().to_hex())
2591
        .join("lock");
2592
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2593
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2594
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2595
    age(&lock_path);
2596
    assert!(
2597
        !super::workspace::lock_is_stale(&lock_path),
2598
        "a live process keeps its lock"
2599
    );
2600
    fs::write(&lock_path, "4294967295").unwrap();
2601
    age(&lock_path);
2602
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2603
}
2604
2605
#[test]
2606
fn attributes_binary_eol_nocompress_lockable() {
2607
    hermetic();
2608
    let dir = tempfile::tempdir().unwrap();
2609
    let root = dir.path();
2610
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2611
    write(
2612
        root,
2613
        ".oxyattributes",
2614
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2615
    );
2616
    write(root, "plain.dat", b"no nul bytes here\n");
2617
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2618
    write(root, "assets/model.bin", b"\0model");
2619
    let h = repo.commit("attrs", &[]).unwrap();
2620
    let snap = repo.load_state(&[h]).unwrap().materialize();
2621
    assert!(
2622
        snap.files["plain.dat"].mode.opaque,
2623
        "binary attribute forces opaque without NUL bytes"
2624
    );
2625
    assert!(
2626
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2627
        "stored with LF"
2628
    );
2629
    assert!(
2630
        !repo.snapshot("status").unwrap().changed,
2631
        "CRLF on disk equals LF in the state"
2632
    );
2633
    // nocompress chunks pack raw.
2634
    let r = repo.gc(true).unwrap();
2635
    assert!(r.packed.objects > 0);
2636
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2637
    fs::remove_file(root.join("notes.txt")).unwrap();
2638
    repo.checkout(&[h], true, "co").unwrap();
2639
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2640
    assert!(fs::metadata(root.join("assets/model.bin"))
2641
        .unwrap()
2642
        .permissions()
2643
        .readonly());
2644
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2645
    repo.lock_path("assets/model.bin").unwrap();
2646
    assert!(!fs::metadata(root.join("assets/model.bin"))
2647
        .unwrap()
2648
        .permissions()
2649
        .readonly());
2650
    assert!(repo.is_locked("assets/model.bin"));
2651
    write(root, "assets/model.bin", b"\0model2");
2652
    repo.commit("edit model", &[]).unwrap();
2653
    repo.unlock_path("assets/model.bin").unwrap();
2654
    assert!(fs::metadata(root.join("assets/model.bin"))
2655
        .unwrap()
2656
        .permissions()
2657
        .readonly());
2658
    // A later checkout can still overwrite a read-only lockable file.
2659
    repo.checkout(&[h], true, "co").unwrap();
2660
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2661
}
2662
2663
#[cfg(unix)]
2664
#[test]
2665
fn hooks_can_veto_observe_and_add_dependencies() {
2666
    use std::os::unix::fs::PermissionsExt;
2667
    hermetic();
2668
    let dir = tempfile::tempdir().unwrap();
2669
    let root = dir.path();
2670
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2671
    let hooks = root.join(".oxy/hooks");
2672
    fs::create_dir_all(&hooks).unwrap();
2673
    let hook = |name: &str, body: &str| {
2674
        let p = hooks.join(name);
2675
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2676
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2677
    };
2678
    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");
2679
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2680
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2681
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2682
    write(root, ".oxyignore", b".last-*\n");
2683
    write(root, "a.txt", b"a\n");
2684
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2685
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2686
    let h1 = repo.commit("first", &[]).unwrap();
2687
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2688
    assert!(
2689
        pre.contains("\"event\":\"pre-commit\"")
2690
            && pre.contains("\"path\":\"a.txt\"")
2691
            && pre.contains("\"message\":\"first\""),
2692
        "{pre}"
2693
    );
2694
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2695
    assert!(post.contains(&h1.to_hex()), "{post}");
2696
    repo.checkout(&[h1], false, "co").unwrap();
2697
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2698
        .unwrap()
2699
        .contains("post-checkout"));
2700
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2701
    repo.save_config().unwrap();
2702
    let err = repo.push("origin", false).unwrap_err().to_string();
2703
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2704
2705
    // semantic-deps: only when enabled; adds an explicit dependency.
2706
    write(root, "b.txt", b"b\n");
2707
    hook(
2708
        "semantic-deps",
2709
        &format!(
2710
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2711
            h1.to_hex()
2712
        ),
2713
    );
2714
    let h2 = repo.commit("b without hook", &[]).unwrap();
2715
    assert!(
2716
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2717
        "hook disabled by default"
2718
    );
2719
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2720
    repo.save_config().unwrap();
2721
    write(root, "c.txt", b"c\n");
2722
    let h3 = repo.commit("c with hook", &[]).unwrap();
2723
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2724
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2725
    assert!(
2726
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2727
        "{sem}"
2728
    );
2729
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2730
}
2731
2732
#[test]
2733
fn amend_into_older_change_and_split() {
2734
    hermetic();
2735
    let dir = tempfile::tempdir().unwrap();
2736
    let root = dir.path();
2737
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2738
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2739
        .unwrap();
2740
    repo.set_user_config("core.sign", "change").unwrap();
2741
    write(root, "a.txt", b"one\ntwo\n");
2742
    let h0 = repo.commit("base", &[]).unwrap();
2743
    write(root, "a.txt", b"one\nTWO\n");
2744
    let h1 = repo.commit("edit two", &[]).unwrap();
2745
    write(root, "a.txt", b"one\nTWO\nthree\n");
2746
    let h2 = repo.commit("add three", &[]).unwrap();
2747
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2748
2749
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2750
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2751
    let h1b = repo.amend_into(&h1, None).unwrap();
2752
    assert_ne!(h1b, h1);
2753
    let c1b = repo.store().get_change(&h1b).unwrap();
2754
    assert_eq!(c1b.change_id, id1);
2755
    assert_eq!(c1b.deps, vec![h0]);
2756
    assert!(matches!(
2757
        repo.verify_change(&h1b).unwrap(),
2758
        SignatureStatus::Valid { .. }
2759
    ));
2760
    let heads = repo.bookmark_heads().unwrap();
2761
    assert_eq!(heads.len(), 1);
2762
    let top = repo.store().get_change(&heads[0]).unwrap();
2763
    assert_eq!(top.message, "add three");
2764
    assert_eq!(
2765
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2766
        [h0, h1b].into_iter().collect(),
2767
        "depends on the file's creator and the rewritten line"
2768
    );
2769
    let snap = repo.load_state(&heads).unwrap().materialize();
2770
    assert!(
2771
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2772
    );
2773
    assert!(
2774
        !repo.snapshot("status").unwrap().changed,
2775
        "the working copy is clean after folding"
2776
    );
2777
    // Only h1b's own state shows the fix without "three".
2778
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2779
    assert!(
2780
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2781
    );
2782
    assert_eq!(repo.log().unwrap().len(), 4);
2783
2784
    // An edit to a line introduced by h2 cannot fold into h1.
2785
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2786
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2787
    assert!(err.contains("introduced after"), "{err}");
2788
    assert!(
2789
        repo.snapshot("status").unwrap().statuses.len() == 1,
2790
        "nothing was changed by the refusal"
2791
    );
2792
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2793
2794
    // Split the head that touches two files.
2795
    write(root, "b.txt", b"b\n");
2796
    write(root, "c.txt", b"c\n");
2797
    let h3 = repo.commit("b and c", &[]).unwrap();
2798
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2799
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2800
    let c_1 = repo.store().get_change(&p1).unwrap();
2801
    let c_2 = repo.store().get_change(&p2).unwrap();
2802
    assert!(c_1.message.contains("part 1: b.txt"));
2803
    assert_eq!(c_2.change_id, id3);
2804
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2805
    assert!(
2806
        heads.contains(&p1) && heads.contains(&p2),
2807
        "independent parts are both heads"
2808
    );
2809
    let snap = repo
2810
        .load_state(&repo.bookmark_heads().unwrap())
2811
        .unwrap()
2812
        .materialize();
2813
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2814
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2815
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2816
    assert!(!repo.snapshot("status").unwrap().changed);
2817
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2818
    let _ = h2;
2819
}
2820
2821
#[test]
2822
fn identity_lifecycle() {
2823
    hermetic();
2824
    let dir = tempfile::tempdir().unwrap();
2825
    let root = dir.path();
2826
    let origin = Repo::init(&root.join("origin")).unwrap();
2827
    let url = root.join("origin").to_string_lossy().to_string();
2828
    let mut a = Repo::clone(&url, &root.join("a"))
2829
        .unwrap()
2830
        .with_home(root.join("home-a"));
2831
    a.set_user_config("core.sign", "change").unwrap();
2832
    let (key_a, _) = a
2833
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2834
        .unwrap();
2835
    write(&root.join("a"), "a.txt", b"a\n");
2836
    let h1 = a.commit("one", &[]).unwrap();
2837
    assert!(a.policy_init().unwrap().applied);
2838
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2839
2840
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2841
    let mut e = Repo::init(&root.join("e"))
2842
        .unwrap()
2843
        .with_home(root.join("home-e"));
2844
    e.set_user_config("core.sign", "change").unwrap();
2845
    e.create_identity_with(
2846
        "Eve",
2847
        "[email protected]",
2848
        IdentityScope::User,
2849
        Some(Hlc::now().wall_ms - 1),
2850
    )
2851
    .unwrap();
2852
    write(&root.join("e"), "e.txt", b"e\n");
2853
    let he = e.commit("late", &[]).unwrap();
2854
    assert!(
2855
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2856
    );
2857
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2858
    let r = e
2859
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2860
        .unwrap();
2861
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2862
    write(&root.join("e"), "e.txt", b"e2\n");
2863
    let he2 = e.commit("in time", &[]).unwrap();
2864
    assert!(
2865
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2866
    );
2867
2868
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2869
    let r = a.rotate_identity().unwrap();
2870
    assert_eq!(r.old, key_a);
2871
    assert_eq!(a.config.author_key, Some(r.new));
2872
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2873
    assert!(r.policy.as_ref().unwrap().applied);
2874
    let (_, sp) = a.current_policy().unwrap().unwrap();
2875
    assert_eq!(
2876
        (sp.policy.serial, sp.policy.roots.clone()),
2877
        (2, vec![r.new])
2878
    );
2879
    assert!(
2880
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2881
        "superseded, not revoked"
2882
    );
2883
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2884
    assert!(
2885
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2886
    );
2887
    write(&root.join("a"), "a.txt", b"a2\n");
2888
    let h2 = a.commit("two", &[]).unwrap();
2889
    assert!(
2890
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2891
    );
2892
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2893
    let res = a.push("origin", false).unwrap();
2894
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2895
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2896
    let key_a = r.new;
2897
2898
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2899
    // identity object, so Ada's KeyId changes while her keys stay the same.
2900
    let mut b = Repo::clone(&url, &root.join("b"))
2901
        .unwrap()
2902
        .with_home(root.join("home-b"));
2903
    let (key_b, id_b) = b
2904
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2905
        .unwrap();
2906
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
2907
    assert_eq!(r.old, key_a);
2908
    let key_a2 = r.new;
2909
    assert_eq!(
2910
        a.identity(&key_a2).unwrap().delegates,
2911
        vec![Delegate::full(key_b)]
2912
    );
2913
    assert_eq!(
2914
        a.identity(&key_a2).unwrap().ed25519_pk,
2915
        a.identity(&key_a).unwrap().ed25519_pk
2916
    );
2917
    assert!(
2918
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2919
        "already a delegate"
2920
    );
2921
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2922
    write(&root.join("a"), "a.txt", b"a3\n");
2923
    let h3 = a.commit("three", &[]).unwrap();
2924
    assert!(
2925
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2926
        "the same secret signs under the new KeyId"
2927
    );
2928
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2929
    a.set_user_config("core.sign", "seal").unwrap();
2930
    write(&root.join("a"), "a.txt", b"a4\n");
2931
    let h4 = a.commit("four", &[]).unwrap();
2932
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2933
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2934
    a.store()
2935
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2936
        .unwrap();
2937
    assert!(
2938
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2939
    );
2940
    a.set_user_config("core.sign", "change").unwrap();
2941
    // Withdrawing the delegation re-issues the identity again.
2942
    let r = a.delegate_remove(&key_b).unwrap();
2943
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2944
    assert!(a.delegate_remove(&key_b).is_err());
2945
    let key_a3 = r.new;
2946
    let res = a.push("origin", false).unwrap();
2947
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2948
2949
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2950
    // both applied under the old threshold of 1. A grant then needs Bob too.
2951
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2952
    assert!(a.policy_root_add(id_b.clone()).is_err());
2953
    assert!(a.policy_set_threshold(3).is_err());
2954
    assert!(a.policy_set_threshold(2).unwrap().applied);
2955
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2956
    b.pull("origin").unwrap();
2957
    assert_eq!(
2958
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2959
        2
2960
    );
2961
    let mut c = Repo::init(&root.join("c"))
2962
        .unwrap()
2963
        .with_home(root.join("home-c"));
2964
    let (key_c, id_c) = c
2965
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2966
        .unwrap();
2967
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2968
    let proposal = a.policy_grant(id_c, None).unwrap();
2969
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2970
    assert_eq!(proposal.policy.serial, serial_before + 1);
2971
    assert_eq!(
2972
        a.current_policy().unwrap().unwrap().1.policy.serial,
2973
        serial_before,
2974
        "a proposal changes nothing yet"
2975
    );
2976
    // Bob signs the proposal, handed over as a file, and it applies for him.
2977
    let bytes = proposal.signed().encode();
2978
    let signed = b
2979
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2980
        .unwrap();
2981
    assert!(signed.applied && signed.sigs.len() == 2);
2982
    assert!(b
2983
        .current_policy()
2984
        .unwrap()
2985
        .unwrap()
2986
        .1
2987
        .policy
2988
        .authorizes(&key_c, "main"));
2989
    assert!(
2990
        b.policy_sign(signed.signed()).is_err(),
2991
        "a stale proposal is refused"
2992
    );
2993
    // Bob publishes it and Ada picks it up.
2994
    assert!(b
2995
        .push("origin", false)
2996
        .unwrap()
2997
        .iter()
2998
        .any(|x| x.name == "policy" && x.ok));
2999
    a.pull("origin").unwrap();
3000
    assert_eq!(
3001
        a.current_policy().unwrap().unwrap().1.policy.serial,
3002
        serial_before + 1
3003
    );
3004
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3005
    assert!(a.policy_revoke(&key_a3).is_err());
3006
    let u = a
3007
        .revoke_identity(&key_c, "left the project")
3008
        .unwrap()
3009
        .unwrap();
3010
    assert!(!u.applied);
3011
    assert!(a.is_revoked(&key_c).unwrap());
3012
    assert!(!b.is_revoked(&key_c).unwrap());
3013
    let u = b.policy_sign(u.signed()).unwrap();
3014
    assert!(u.applied && u.policy.is_revoked(&key_c));
3015
    assert!(b.is_revoked(&key_c).unwrap());
3016
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
3017
    assert!(
3018
        b.policy_revoke(&key_a3).is_err(),
3019
        "would leave one root for a threshold of 2"
3020
    );
3021
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3022
    let key_c_own = c.config.author_key.unwrap();
3023
    assert!(c
3024
        .revoke_identity(&key_c_own, "lost laptop")
3025
        .unwrap()
3026
        .is_none());
3027
    assert!(c.is_revoked(&key_c_own).unwrap());
3028
    assert_eq!(key_c_own, key_c);
3029
}
3030
3031
#[test]
3032
fn renames_are_detected_and_tracked_as_moves() {
3033
    hermetic();
3034
    let dir = tempfile::tempdir().unwrap();
3035
    let root = dir.path();
3036
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3037
    write(
3038
        root,
3039
        "src/old.rs",
3040
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3041
    );
3042
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3043
    write(root, "tiny.txt", b"x\n");
3044
    let h1 = repo.commit("base", &[]).unwrap();
3045
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3046
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3047
3048
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3049
    // that shares nothing with the removed file.
3050
    fs::remove_file(root.join("src/old.rs")).unwrap();
3051
    write(
3052
        root,
3053
        "lib/new.rs",
3054
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3055
    );
3056
    fs::remove_file(root.join("img.bin")).unwrap();
3057
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3058
    fs::remove_file(root.join("tiny.txt")).unwrap();
3059
    write(root, "other.txt", b"completely different\n");
3060
    let snap = repo.snapshot("status").unwrap();
3061
    let statuses: Vec<(&str, ChangeStatus)> = snap
3062
        .statuses
3063
        .iter()
3064
        .map(|s| (s.path.as_str(), s.status))
3065
        .collect();
3066
    assert_eq!(
3067
        statuses,
3068
        vec![
3069
            ("assets/img.bin", ChangeStatus::Renamed),
3070
            ("lib/new.rs", ChangeStatus::Renamed),
3071
            ("other.txt", ChangeStatus::Added),
3072
            ("src", ChangeStatus::Removed),
3073
            ("tiny.txt", ChangeStatus::Removed)
3074
        ]
3075
    );
3076
    let h2 = repo.commit("move things", &[]).unwrap();
3077
    let c = repo.store().get_change(&h2).unwrap();
3078
    let moves: Vec<_> = c
3079
        .tree_ops
3080
        .iter()
3081
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3082
        .collect();
3083
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3084
    assert!(c.tree_ops.iter().any(
3085
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3086
    ));
3087
    assert!(c.tree_ops.iter().any(
3088
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3089
    ));
3090
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3091
    assert_eq!(
3092
        snap.files["lib/new.rs"].node, node_old,
3093
        "the node survives the rename"
3094
    );
3095
    assert!(
3096
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3097
    );
3098
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3099
    assert!(render_change(
3100
        &c,
3101
        &repo.load_state(&[h1]).unwrap(),
3102
        &repo.load_state(&[h1]).unwrap().materialize()
3103
    )
3104
    .contains("R src/old.rs -> lib/new.rs"));
3105
    // A fresh checkout reproduces the tree.
3106
    let other = tempfile::tempdir().unwrap();
3107
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3108
    assert_eq!(
3109
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3110
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3111
    );
3112
    assert!(!other.path().join("src").exists());
3113
    assert!(!clone.snapshot("status").unwrap().changed);
3114
    // Similarity is line based, byte weighted.
3115
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3116
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3117
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3118
    assert_eq!(similarity(b"", b"x\n"), 0);
3119
}
3120
3121
#[test]
3122
fn git_fetch_and_push_round_trip() {
3123
    hermetic();
3124
    if std::process::Command::new("git")
3125
        .arg("--version")
3126
        .output()
3127
        .is_err()
3128
    {
3129
        eprintln!("git not installed; skipping");
3130
        return;
3131
    }
3132
    let dir = tempfile::tempdir().unwrap();
3133
    let root = dir.path();
3134
    let git_in = |d: &Path, args: &[&str]| -> String {
3135
        let out = std::process::Command::new("git")
3136
            .arg("-C")
3137
            .arg(d)
3138
            .args([
3139
                "-c",
3140
                "user.name=Grace",
3141
                "-c",
3142
                "[email protected]",
3143
                "-c",
3144
                "commit.gpgsign=false",
3145
            ])
3146
            .args(args)
3147
            .output()
3148
            .unwrap();
3149
        assert!(
3150
            out.status.success(),
3151
            "git {args:?}: {}",
3152
            String::from_utf8_lossy(&out.stderr)
3153
        );
3154
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3155
    };
3156
    // A bare "remote" and a work tree that pushes to it.
3157
    let remote = root.join("remote.git");
3158
    fs::create_dir_all(&remote).unwrap();
3159
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3160
    let work = root.join("work");
3161
    git_in(
3162
        root,
3163
        &[
3164
            "clone",
3165
            "-q",
3166
            remote.to_str().unwrap(),
3167
            work.to_str().unwrap(),
3168
        ],
3169
    );
3170
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3171
    write(&work, "README.md", b"# Project\n");
3172
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3173
    git_in(&work, &["add", "."]);
3174
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3175
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3176
    git_in(&work, &["commit", "-q", "-am", "second"]);
3177
    git_in(&work, &["push", "-q", "origin", "main"]);
3178
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3179
3180
    // Fetch into a fresh oxy repository.
3181
    let o = root.join("oxy");
3182
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3183
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3184
        .unwrap();
3185
    let url = remote.to_string_lossy().to_string();
3186
    let r = repo.git_fetch(&url, "main").unwrap();
3187
    assert_eq!((r.commits, r.heads), (2, 1));
3188
    assert_eq!(
3189
        fs::read(o.join("src/lib.rs")).unwrap(),
3190
        b"pub fn a() {}\npub fn b() {}\n"
3191
    );
3192
    assert!(!repo.snapshot("status").unwrap().changed);
3193
    assert_eq!(
3194
        repo.git_fetch(&url, "main").unwrap().commits,
3195
        0,
3196
        "nothing new"
3197
    );
3198
3199
    // An oxy change, pushed back: one commit on top of the Git tip.
3200
    write(
3201
        &o,
3202
        "src/lib.rs",
3203
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3204
    );
3205
    write(&o, "NOTES.md", b"from oxy\n");
3206
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3207
    let r = repo.git_push(&url, "main").unwrap();
3208
    assert_eq!(r.exported, 1, "{r:?}");
3209
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3210
    assert_eq!(
3211
        git_in(&work, &["log", "--format=%s", "main"]),
3212
        "add c and notes\nsecond\ninitial"
3213
    );
3214
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3215
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3216
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3217
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3218
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3219
    assert_eq!(
3220
        repo.git_push(&url, "main").unwrap().exported,
3221
        0,
3222
        "already pushed"
3223
    );
3224
3225
    // Git moves on; pushing without fetching is refused, fetching brings
3226
    // the commit in and the working copy follows.
3227
    write(&work, "README.md", b"# Project\n\nMore.\n");
3228
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3229
    git_in(&work, &["push", "-q", "origin", "main"]);
3230
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3231
    assert!(repo
3232
        .git_push(&url, "main")
3233
        .unwrap_err()
3234
        .to_string()
3235
        .contains("fetch"));
3236
    let r = repo.git_fetch(&url, "main").unwrap();
3237
    assert_eq!(
3238
        (r.commits, r.heads),
3239
        (1, 2),
3240
        "the Git change and the oxy change commute"
3241
    );
3242
    assert_eq!(
3243
        fs::read(o.join("README.md")).unwrap(),
3244
        b"# Project\n\nMore.\n"
3245
    );
3246
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3247
    assert!(!repo.snapshot("status").unwrap().changed);
3248
    // Another oxy change pushes on top of Git's newest commit.
3249
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3250
    repo.commit("notes again", &[]).unwrap();
3251
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3252
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3253
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
3254
    assert_eq!(
3255
        fs::read(work.join("NOTES.md")).unwrap(),
3256
        b"from oxy\nagain\n"
3257
    );
3258
    assert_eq!(
3259
        git_in(&work, &["log", "--format=%s", "main"])
3260
            .lines()
3261
            .count(),
3262
        5
3263
    );
3264
}
3265
3266
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3267
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3268
#[test]
3269
#[ignore]
3270
fn bench_one_gibibyte_file() {
3271
    hermetic();
3272
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3273
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3274
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3275
        None => tempfile::tempdir().unwrap(),
3276
    };
3277
    let root = dir.path();
3278
    let repo = Repo::init(&root.join("r"))
3279
        .unwrap()
3280
        .with_home(root.join("home"));
3281
    let size = 1usize << 30;
3282
    let mut data = vec![0u8; size];
3283
    let mut x = 0x9e3779b97f4a7c15u64;
3284
    for chunk in data.chunks_mut(8) {
3285
        x ^= x << 13;
3286
        x ^= x >> 7;
3287
        x ^= x << 17;
3288
        let b = x.to_le_bytes();
3289
        chunk.copy_from_slice(&b[..chunk.len()]);
3290
    }
3291
    let t = std::time::Instant::now();
3292
    write(&root.join("r"), "big.bin", &data);
3293
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3294
    let t = std::time::Instant::now();
3295
    let h = repo.commit("big", &[]).unwrap();
3296
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3297
    let t = std::time::Instant::now();
3298
    assert!(!repo.snapshot("status").unwrap().changed);
3299
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3300
    let t = std::time::Instant::now();
3301
    let objects = repo.store().list().unwrap().len();
3302
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3303
    let t = std::time::Instant::now();
3304
    let g = repo.gc(true).unwrap();
3305
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3306
    let t = std::time::Instant::now();
3307
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3308
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3309
    let t = std::time::Instant::now();
3310
    let back = fs::read(root.join("c/big.bin")).unwrap();
3311
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3312
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3313
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3314
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
3315
    eprintln!(
3316
        "store size: {:.1} MiB for 1 GiB of data",
3317
        store_bytes as f64 / (1024.0 * 1024.0)
3318
    );
3319
}
3320
3321
fn walkdir_size(p: &Path) -> u64 {
3322
    let mut total = 0;
3323
    if let Ok(rd) = fs::read_dir(p) {
3324
        for e in rd.flatten() {
3325
            let path = e.path();
3326
            if path.is_dir() {
3327
                total += walkdir_size(&path);
3328
            } else if let Ok(m) = fs::metadata(&path) {
3329
                total += m.len();
3330
            }
3331
        }
3332
    }
3333
    total
3334
}
3335
3336
/// An opaque file whose size and mtime match the manifest is not read on
3337
/// the next snapshot: its blob comes from the manifest's stat cache.
3338
#[cfg(unix)]
3339
#[test]
3340
fn stat_cache_skips_reading_unchanged_opaque_files() {
3341
    use std::os::unix::fs::PermissionsExt;
3342
    hermetic();
3343
    let dir = tempfile::tempdir().unwrap();
3344
    let root = dir.path();
3345
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3346
    let mut big = vec![0u8; 300 * 1024];
3347
    for (i, b) in big.iter_mut().enumerate() {
3348
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3349
    }
3350
    big[0] = 0;
3351
    write(root, "big.bin", &big);
3352
    write(root, "a.txt", b"text\n");
3353
    let h1 = repo.commit("base", &[]).unwrap();
3354
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3355
    assert!(
3356
        m.entries["big.bin"].blob.is_some(),
3357
        "opaque files record their blob"
3358
    );
3359
    assert!(m.entries["a.txt"].blob.is_none());
3360
    let blob = m.entries["big.bin"].blob.unwrap();
3361
    assert!(repo.store().has(&blob));
3362
3363
    // Files modified within two seconds of the manifest are racy and still
3364
    // read; age the file so the cache applies, then snapshot to record it.
3365
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3366
    fs::File::options()
3367
        .write(true)
3368
        .open(root.join("big.bin"))
3369
        .unwrap()
3370
        .set_modified(old)
3371
        .unwrap();
3372
    assert!(!repo.snapshot("status").unwrap().changed);
3373
    // Now the file cannot be read at all; the snapshot succeeds without it.
3374
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3375
    let snap = repo.snapshot("status").unwrap();
3376
    assert!(
3377
        !snap.changed && snap.statuses.is_empty(),
3378
        "{:?}",
3379
        snap.statuses
3380
    );
3381
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3382
    // A real change (new mtime, new content) is seen and committed correctly.
3383
    let mut big2 = big.clone();
3384
    big2[10] ^= 0xff;
3385
    write(root, "big.bin", &big2);
3386
    let snap = repo.snapshot("status").unwrap();
3387
    assert_eq!(
3388
        snap.statuses
3389
            .iter()
3390
            .map(|s| (s.path.as_str(), s.status))
3391
            .collect::<Vec<_>>(),
3392
        vec![("big.bin", ChangeStatus::Modified)]
3393
    );
3394
    let h2 = repo.commit("edit", &[]).unwrap();
3395
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3396
    assert_eq!(
3397
        files["big.bin"].content,
3398
        FileContent::Opaque {
3399
            blobs: vec![Repo::blob_ref(&big2)]
3400
        }
3401
    );
3402
    // Checkout writes a manifest with blobs too, so the next status is cached.
3403
    repo.checkout(&[h1], false, "checkout").unwrap();
3404
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3405
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3406
    assert!(!repo.snapshot("status").unwrap().changed);
3407
}
3408
3409
#[test]
3410
fn status_json_lists_conflicts_with_contributors() {
3411
    hermetic();
3412
    let dir = tempfile::tempdir().unwrap();
3413
    let root = dir.path();
3414
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3415
    write(root, "a.txt", b"one\n");
3416
    let h1 = repo.commit("base", &[]).unwrap();
3417
    write(root, "a.txt", b"one\nleft\n");
3418
    let ha = repo.commit("left", &[]).unwrap();
3419
    repo.checkout(&[h1], true, "checkout").unwrap();
3420
    write(root, "a.txt", b"one\nright\n");
3421
    let hb = repo.commit("right", &[]).unwrap();
3422
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3423
    let snap = repo.snapshot("status").unwrap();
3424
    assert!(snap.base_snapshot.is_conflicted());
3425
    let json = repo.status_json(&snap).unwrap();
3426
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3427
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3428
    assert!(json.contains("\"conflicted\":true"), "{json}");
3429
    assert!(
3430
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3431
        "{json}"
3432
    );
3433
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3434
    assert!(json.contains("\"resolved\":false"), "{json}");
3435
    assert!(json.starts_with('{') && json.ends_with('}'));
3436
    // Resolve and the report says so; a clean copy has no conflicts.
3437
    write(root, "a.txt", b"one\nleft\nright\n");
3438
    let snap = repo.snapshot("status").unwrap();
3439
    let json = repo.status_json(&snap).unwrap();
3440
    assert!(json.contains("\"resolved\":true"), "{json}");
3441
    repo.commit("resolve", &[]).unwrap();
3442
    let snap = repo.snapshot("status").unwrap();
3443
    let json = repo.status_json(&snap).unwrap();
3444
    assert!(
3445
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3446
        "{json}"
3447
    );
3448
}
3449
3450
#[test]
3451
fn ignore_rules_do_not_untrack_files() {
3452
    hermetic();
3453
    let dir = tempfile::tempdir().unwrap();
3454
    let root = dir.path();
3455
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3456
    write(root, "src.c", b"int x;\n");
3457
    write(root, "build/out.o", b"\0obj");
3458
    write(root, "sub/keep.log", b"keep\n");
3459
    write(root, "sub/junk.log", b"junk\n");
3460
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3461
    let snap = repo.snapshot("status").unwrap();
3462
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3463
    assert_eq!(
3464
        added,
3465
        vec![".oxyignore", "src.c", "sub/keep.log"],
3466
        "anchored, glob, and negated rules"
3467
    );
3468
    let h1 = repo.commit("base", &[]).unwrap();
3469
    // Ignoring a tracked file changes nothing about it.
3470
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3471
    let snap = repo.snapshot("status").unwrap();
3472
    assert_eq!(
3473
        snap.statuses
3474
            .iter()
3475
            .map(|s| s.path.as_str())
3476
            .collect::<Vec<_>>(),
3477
        vec![".oxyignore"]
3478
    );
3479
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3480
    assert!(repo
3481
        .load_state(&[h2])
3482
        .unwrap()
3483
        .materialize()
3484
        .files
3485
        .contains_key("src.c"));
3486
    // Its edits are still seen, by status and by the prompt.
3487
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3488
    write(root, "src.c", b"int x, y;\n");
3489
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3490
    let snap = repo.snapshot("status").unwrap();
3491
    assert_eq!(
3492
        snap.statuses
3493
            .iter()
3494
            .map(|s| (s.path.as_str(), s.status))
3495
            .collect::<Vec<_>>(),
3496
        vec![("src.c", ChangeStatus::Modified)]
3497
    );
3498
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3499
    assert!(
3500
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3501
    );
3502
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3503
    fs::remove_file(root.join("src.c")).unwrap();
3504
    let snap = repo.snapshot("status").unwrap();
3505
    assert_eq!(
3506
        snap.statuses
3507
            .iter()
3508
            .map(|s| (s.path.as_str(), s.status))
3509
            .collect::<Vec<_>>(),
3510
        vec![("src.c", ChangeStatus::Removed)]
3511
    );
3512
    repo.checkout(&[h3], true, "checkout").unwrap();
3513
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3514
    assert!(!repo.snapshot("status").unwrap().changed);
3515
    let _ = h1;
3516
}
3517
3518
#[test]
3519
fn split_works_on_non_heads_by_node() {
3520
    hermetic();
3521
    let dir = tempfile::tempdir().unwrap();
3522
    let root = dir.path();
3523
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3524
    write(root, "a.txt", b"one\n");
3525
    write(root, "junk/x.lock", b"lock\n");
3526
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3527
    write(root, "a.txt", b"one\ntwo\n");
3528
    let h2 = repo.commit("more work", &[]).unwrap();
3529
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3530
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3531
    // h1 is not a head: split it by node.
3532
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3533
    assert_ne!(h1b, h1);
3534
    assert_eq!(
3535
        repo.store().get_change(&h1b).unwrap().change_id,
3536
        id1,
3537
        "the rest keeps the ChangeId"
3538
    );
3539
    let junk = repo.store().get_change(&hj).unwrap();
3540
    assert!(junk.tree_ops.iter().all(
3541
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3542
    ));
3543
    let heads = repo.bookmark_heads().unwrap();
3544
    assert!(
3545
        heads.contains(&hj),
3546
        "the split-off part is a head of its own"
3547
    );
3548
    let snap = repo.load_state(&heads).unwrap().materialize();
3549
    assert!(
3550
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3551
        "the dependent was rewritten onto the new hash"
3552
    );
3553
    assert!(snap.files.contains_key("junk/x.lock"));
3554
    let h2b = heads
3555
        .iter()
3556
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3557
        .copied()
3558
        .unwrap();
3559
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3560
    assert!(!repo.snapshot("status").unwrap().changed);
3561
    // Abandoning the split-off head removes the junk from history.
3562
    repo.abandon(&hj).unwrap();
3563
    let heads = repo.bookmark_heads().unwrap();
3564
    let snap = repo.load_state(&heads).unwrap().materialize();
3565
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3566
    assert!(snap.files.contains_key("a.txt"));
3567
    // A dependent that touches the split-off paths blocks the split.
3568
    write(root, "junk/y.lock", b"y\n");
3569
    let hb = repo.commit("junk base", &[]).unwrap();
3570
    write(root, "junk/y.lock", b"yy\n");
3571
    write(root, "b.txt", b"b\n");
3572
    repo.commit("touches junk", &[]).unwrap();
3573
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3574
    assert!(err.contains("depends on the split-off paths"), "{err}");
3575
}
3576
3577
#[test]
3578
fn bookmarks_switch_merge_and_push() {
3579
    hermetic();
3580
    let dir = tempfile::tempdir().unwrap();
3581
    let root = dir.path();
3582
    let origin = Repo::init(&root.join("origin")).unwrap();
3583
    let url = root.join("origin").to_string_lossy().to_string();
3584
    let mut repo = Repo::clone(&url, &root.join("r"))
3585
        .unwrap()
3586
        .with_home(root.join("home"));
3587
    let r = root.join("r");
3588
    write(&r, "a.txt", b"a\n");
3589
    let h_a = repo.commit("a", &[]).unwrap();
3590
    assert!(repo.push("origin", false).unwrap()[0].ok);
3591
3592
    // A bookmark at the working copy's base, then work on it.
3593
    assert!(repo.bookmark_create("bad name..", None).is_err());
3594
    assert!(repo.bookmark_create("-x", None).is_err());
3595
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3596
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3597
    repo.bookmark_switch("feature", false).unwrap();
3598
    assert_eq!(repo.config.bookmark, "feature");
3599
    write(&r, "a.txt", b"a\nb\n");
3600
    write(&r, "b.txt", b"b\n");
3601
    let h_b = repo.commit("b on feature", &[]).unwrap();
3602
    assert_eq!(
3603
        repo.bookmark_heads().unwrap(),
3604
        vec![h_b],
3605
        "b edits a.txt, so it depends on a"
3606
    );
3607
    assert_eq!(
3608
        repo.resolve_heads("main").unwrap(),
3609
        vec![h_a],
3610
        "main is untouched"
3611
    );
3612
    assert_eq!(
3613
        repo.resolve_change("feature").unwrap(),
3614
        h_b,
3615
        "a one-head bookmark names its change"
3616
    );
3617
    // Reopening keeps the workspace's bookmark.
3618
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3619
    assert_eq!(reopened.config.bookmark, "feature");
3620
    // Back to main: b.txt goes away; work there.
3621
    repo.bookmark_switch("main", false).unwrap();
3622
    assert!(!r.join("b.txt").exists());
3623
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3624
    write(&r, "c.txt", b"c\n");
3625
    let h_c = repo.commit("c on main", &[]).unwrap();
3626
    let list = repo.bookmarks().unwrap();
3627
    assert_eq!(
3628
        list.iter()
3629
            .map(|b| (b.name.as_str(), b.current))
3630
            .collect::<Vec<_>>(),
3631
        vec![("feature", false), ("main", true)]
3632
    );
3633
    assert_eq!(
3634
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3635
        Some(1),
3636
        "c is not on origin yet"
3637
    );
3638
    // Merge feature into main: the union, both heads, no merge change.
3639
    let m = repo.merge("feature").unwrap();
3640
    assert!(m.changed && m.checked_out);
3641
    let mut want = vec![h_b, h_c];
3642
    want.sort();
3643
    assert_eq!(m.heads, want);
3644
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3645
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3646
    assert!(repo.merge("main").is_err());
3647
    // The other bookmark can be pushed by name and appears at origin.
3648
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3649
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3650
    assert!(repo.push("origin", false).unwrap()[0].ok);
3651
    assert_eq!(
3652
        repo.bookmarks()
3653
            .unwrap()
3654
            .iter()
3655
            .find(|b| b.name == "main")
3656
            .unwrap()
3657
            .ahead,
3658
        Some(0)
3659
    );
3660
    // A second workspace inherits the current bookmark and can switch independently.
3661
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3662
    assert_eq!(ws.config.bookmark, "main");
3663
    let mut ws = ws;
3664
    ws.bookmark_switch("feature", false).unwrap();
3665
    assert_eq!(
3666
        Repo::open(&r).unwrap().config.bookmark,
3667
        "main",
3668
        "the first workspace is unaffected"
3669
    );
3670
    assert!(
3671
        repo.bookmark_delete("feature").is_err(),
3672
        "current bookmark of another workspace"
3673
    );
3674
    ws.bookmark_switch("main", false).unwrap();
3675
    // Set and delete.
3676
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3677
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3678
    repo.bookmark_delete("feature").unwrap();
3679
    assert!(repo.resolve_heads("feature").is_err());
3680
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3681
    assert!(
3682
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3683
        "changes of a deleted bookmark remain"
3684
    );
3685
}
3686
3687
#[test]
3688
fn oxygen_subrepos_pin_follow_and_update() {
3689
    hermetic();
3690
    let dir = tempfile::tempdir().unwrap();
3691
    let root = dir.path();
3692
    // A library repository with two commits, and a bare-ish origin for it.
3693
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3694
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3695
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3696
        .unwrap()
3697
        .with_home(root.join("home"));
3698
    write(&root.join("lib"), "lib.txt", b"v1\n");
3699
    let l1 = lib.commit("lib v1", &[]).unwrap();
3700
    assert!(lib.push("origin", false).unwrap()[0].ok);
3701
    let _ = lib_origin;
3702
3703
    // The application (a clone of its own origin) adds it as a subrepo.
3704
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3705
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3706
    let _ = app_origin;
3707
    let app_dir = root.join("app");
3708
    let app = Repo::clone(&app_url, &app_dir)
3709
        .unwrap()
3710
        .with_home(root.join("home"));
3711
    write(&app_dir, "main.txt", b"app\n");
3712
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3713
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3714
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3715
    let snap = app.snapshot("status").unwrap();
3716
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3717
    assert_eq!(
3718
        paths,
3719
        vec![".oxymodules", "libs/lib", "main.txt"],
3720
        "the nested files are not walked"
3721
    );
3722
    let a1 = app.commit("app with lib", &[]).unwrap();
3723
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3724
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3725
    assert!(!files.contains_key("libs/lib/lib.txt"));
3726
    assert!(!app.snapshot("status").unwrap().changed);
3727
    let subs = app.subrepos().unwrap();
3728
    assert_eq!(subs.len(), 1);
3729
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3730
3731
    // Advance the nested repository: the parent sees a modified pin.
3732
    let nested = Repo::open(&app_dir.join("libs/lib"))
3733
        .unwrap()
3734
        .with_home(root.join("home"));
3735
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3736
    let l2 = nested.commit("lib v2", &[]).unwrap();
3737
    assert!(nested.push("origin", false).unwrap()[0].ok);
3738
    let snap = app.snapshot("status").unwrap();
3739
    assert_eq!(
3740
        snap.statuses
3741
            .iter()
3742
            .map(|s| (s.path.as_str(), s.status))
3743
            .collect::<Vec<_>>(),
3744
        vec![("libs/lib", ChangeStatus::Modified)]
3745
    );
3746
    let a2 = app.commit("bump lib", &[]).unwrap();
3747
    // Checking out the older app state brings the nested working copy back
3748
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3749
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3750
    assert!(
3751
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3752
        "{:?}",
3753
        r.notes
3754
    );
3755
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3756
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3757
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3758
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3759
    assert!(!app.snapshot("status").unwrap().changed);
3760
    // A dirty nested repository is left alone and reported.
3761
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3762
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3763
    assert!(
3764
        r.notes.iter().any(|n| n.contains("uncommitted")),
3765
        "{:?}",
3766
        r.notes
3767
    );
3768
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3769
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3770
    let r = app.submodule_update(false, &[]).unwrap();
3771
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3772
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3773
    let _ = l2;
3774
3775
    // A fresh clone of the app has the pin but no nested repository until update --init.
3776
    assert!(app.push("origin", false).unwrap()[0].ok);
3777
    let clone_dir = root.join("app-clone");
3778
    let clone = Repo::clone(&app_url, &clone_dir)
3779
        .unwrap()
3780
        .with_home(root.join("home"));
3781
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3782
    assert_eq!(
3783
        clone.submodule_update(false, &[]).unwrap(),
3784
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3785
    );
3786
    assert_eq!(
3787
        clone.submodule_update(true, &[]).unwrap(),
3788
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3789
    );
3790
    assert_eq!(
3791
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3792
        b"v2\n"
3793
    );
3794
    assert!(!clone.snapshot("status").unwrap().changed);
3795
    // Removing the subrepo leaves the directory and drops the node.
3796
    clone.submodule_remove("libs/lib").unwrap();
3797
    let snap = clone.snapshot("status").unwrap();
3798
    assert!(
3799
        snap.statuses
3800
            .iter()
3801
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3802
        "{:?}",
3803
        snap.statuses
3804
    );
3805
    let c = clone.commit("drop lib", &[]).unwrap();
3806
    assert!(!clone
3807
        .load_state(&[c])
3808
        .unwrap()
3809
        .materialize()
3810
        .files
3811
        .contains_key("libs/lib"));
3812
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3813
    assert!(
3814
        !clone.snapshot("status").unwrap().changed,
3815
        "an unregistered nested repository is ignored"
3816
    );
3817
}
3818
3819
#[test]
3820
fn git_submodules_import_and_export_as_gitlinks() {
3821
    hermetic();
3822
    if std::process::Command::new("git")
3823
        .arg("--version")
3824
        .output()
3825
        .is_err()
3826
    {
3827
        eprintln!("git not installed; skipping");
3828
        return;
3829
    }
3830
    let dir = tempfile::tempdir().unwrap();
3831
    let root = dir.path();
3832
    let git_in = |d: &Path, args: &[&str]| -> String {
3833
        let out = std::process::Command::new("git")
3834
            .arg("-C")
3835
            .arg(d)
3836
            .args([
3837
                "-c",
3838
                "user.name=Grace",
3839
                "-c",
3840
                "[email protected]",
3841
                "-c",
3842
                "commit.gpgsign=false",
3843
                "-c",
3844
                "protocol.file.allow=always",
3845
            ])
3846
            .args(args)
3847
            .output()
3848
            .unwrap();
3849
        assert!(
3850
            out.status.success(),
3851
            "git {args:?}: {}",
3852
            String::from_utf8_lossy(&out.stderr)
3853
        );
3854
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3855
    };
3856
    let sub = root.join("sub");
3857
    fs::create_dir_all(&sub).unwrap();
3858
    git_in(&sub, &["init", "-q", "-b", "main"]);
3859
    write(&sub, "s.txt", b"sub\n");
3860
    git_in(&sub, &["add", "."]);
3861
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3862
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3863
    let g = root.join("main.git");
3864
    fs::create_dir_all(&g).unwrap();
3865
    git_in(&g, &["init", "-q", "-b", "main"]);
3866
    write(&g, "README.md", b"# app\n");
3867
    git_in(&g, &["add", "."]);
3868
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3869
    git_in(
3870
        &g,
3871
        &[
3872
            "submodule",
3873
            "add",
3874
            "-q",
3875
            sub.to_str().unwrap(),
3876
            "vendor/sub",
3877
        ],
3878
    );
3879
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3880
3881
    let dest = root.join("oxy");
3882
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3883
    let rep = repo.import_git(&g, "main").unwrap();
3884
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3885
    let files = repo
3886
        .load_state(&repo.bookmark_heads().unwrap())
3887
        .unwrap()
3888
        .materialize()
3889
        .files;
3890
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3891
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3892
        panic!()
3893
    };
3894
    assert_eq!(
3895
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3896
        crate::subrepo::Pin::Git {
3897
            sha: sub_sha.clone(),
3898
            branch: "HEAD".into()
3899
        }
3900
    );
3901
    let modules =
3902
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3903
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3904
    assert!(modules.entries["vendor/sub"].git);
3905
    assert!(
3906
        files.contains_key(".gitmodules"),
3907
        "the Git file is kept for round trips"
3908
    );
3909
    assert!(
3910
        !dest.join("vendor/sub/.git").exists(),
3911
        "not cloned until update --init"
3912
    );
3913
    assert!(!repo.snapshot("status").unwrap().changed);
3914
    // update --init clones it at the pinned commit; status is unchanged.
3915
    assert_eq!(
3916
        repo.submodule_update(true, &[]).unwrap(),
3917
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3918
    );
3919
    assert_eq!(
3920
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3921
        sub_sha
3922
    );
3923
    assert!(!repo.snapshot("status").unwrap().changed);
3924
    // Export writes the gitlink and .gitmodules back.
3925
    let mirror = root.join("mirror.git");
3926
    let rep = repo.git_export(&mirror).unwrap();
3927
    assert_eq!(rep.skipped_subrepos, 0);
3928
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3929
    assert!(
3930
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3931
        "{ls}"
3932
    );
3933
    assert_eq!(
3934
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3935
        ".gitmodules\nREADME.md\nvendor"
3936
    );
3937
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3938
    assert_eq!(
3939
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3940
        orig_tree,
3941
        "tree round trip"
3942
    );
3943
}
3944
3945
#[test]
3946
fn partial_commits_by_path_and_by_hunk() {
3947
    hermetic();
3948
    let dir = tempfile::tempdir().unwrap();
3949
    let root = dir.path();
3950
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3951
    write(root, "a.txt", b"1\n2\n3\n");
3952
    write(root, "b.txt", b"b\n");
3953
    let h0 = repo.commit("base", &[]).unwrap();
3954
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3955
    write(root, "b.txt", b"b\nbb\n");
3956
    write(root, "c.txt", b"c\n");
3957
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3958
    let h1 = repo
3959
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3960
        .unwrap();
3961
    let c1 = repo.store().get_change(&h1).unwrap();
3962
    assert!(
3963
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3964
        "{:?}",
3965
        c1.tree_ops
3966
    );
3967
    assert_eq!(c1.deps, vec![h0]);
3968
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3969
    assert!(
3970
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3971
    );
3972
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3973
    assert!(!files.contains_key("c.txt"));
3974
    let snap = repo.snapshot("status").unwrap();
3975
    assert_eq!(
3976
        snap.statuses
3977
            .iter()
3978
            .map(|s| (s.path.as_str(), s.status))
3979
            .collect::<Vec<_>>(),
3980
        vec![
3981
            ("b.txt", ChangeStatus::Modified),
3982
            ("c.txt", ChangeStatus::Added)
3983
        ]
3984
    );
3985
    assert_eq!(
3986
        fs::read(root.join("b.txt")).unwrap(),
3987
        b"b\nbb\n",
3988
        "disk untouched"
3989
    );
3990
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3991
    let (_, hunks) = repo.hunks().unwrap();
3992
    let b_hunk = hunks
3993
        .iter()
3994
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3995
        .unwrap()
3996
        .index;
3997
    let h2 = repo
3998
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3999
        .unwrap();
4000
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4001
    assert!(
4002
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4003
    );
4004
    assert!(!files.contains_key("c.txt"));
4005
    let snap = repo.snapshot("status").unwrap();
4006
    assert_eq!(
4007
        snap.statuses
4008
            .iter()
4009
            .map(|s| s.path.as_str())
4010
            .collect::<Vec<_>>(),
4011
        vec!["c.txt"]
4012
    );
4013
    // Choosing only the content hunk of a file in a new directory pulls in
4014
    // the directory and file additions it needs.
4015
    write(root, "d/e.txt", b"e\n");
4016
    let (_, hunks) = repo.hunks().unwrap();
4017
    let e_insert = hunks
4018
        .iter()
4019
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4020
        .unwrap()
4021
        .index;
4022
    let h3 = repo
4023
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4024
        .unwrap();
4025
    let c3 = repo.store().get_change(&h3).unwrap();
4026
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4027
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4028
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
4029
    // Choosing a new file's addition hunk brings its content along.
4030
    write(root, "f/g.txt", b"g\n");
4031
    let (_, hunks) = repo.hunks().unwrap();
4032
    let g_add = hunks
4033
        .iter()
4034
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4035
        .unwrap()
4036
        .index;
4037
    let h4 = repo
4038
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4039
        .unwrap();
4040
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4041
    assert!(
4042
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4043
    );
4044
    assert!(!repo
4045
        .snapshot("status")
4046
        .unwrap()
4047
        .statuses
4048
        .iter()
4049
        .any(|s| s.path == "f/g.txt"));
4050
    // Everything left commits normally; the working copy is then clean.
4051
    repo.commit("the rest", &[]).unwrap();
4052
    assert!(!repo.snapshot("status").unwrap().changed);
4053
    let files = repo
4054
        .load_state(&repo.bookmark_heads().unwrap())
4055
        .unwrap()
4056
        .materialize()
4057
        .files;
4058
    assert!(files.contains_key("c.txt"));
4059
}
4060
4061
#[test]
4062
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4063
    hermetic();
4064
    let dir = tempfile::tempdir().unwrap();
4065
    let root = dir.path();
4066
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4067
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4068
        .unwrap();
4069
    write(root, "a.txt", b"one\n");
4070
    let h1 = repo.commit("first", &[]).unwrap();
4071
    write(root, "a.txt", b"one\ntwo\n");
4072
    let h2 = repo.commit("second", &[]).unwrap();
4073
    let b = repo.blame("a.txt").unwrap();
4074
    assert_eq!(
4075
        b.iter()
4076
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4077
            .collect::<Vec<_>>(),
4078
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4079
    );
4080
    assert!(b.iter().all(|l| l.author == "Ada"));
4081
    assert_eq!(
4082
        b[0].change_id,
4083
        repo.store().get_change(&h1).unwrap().change_id
4084
    );
4085
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4086
    repo.commit("rename", &[]).unwrap();
4087
    let b = repo.blame("b.txt").unwrap();
4088
    assert_eq!(
4089
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4090
        vec![h1, h2],
4091
        "the node survives the rename"
4092
    );
4093
    assert!(repo.blame("a.txt").is_err());
4094
}
4095
4096
#[test]
4097
fn bisect_finds_the_first_bad_change() {
4098
    hermetic();
4099
    let dir = tempfile::tempdir().unwrap();
4100
    let root = dir.path();
4101
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4102
    let mut content = String::new();
4103
    let mut hashes = Vec::new();
4104
    for i in 1..=8 {
4105
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4106
        write(root, "f.txt", content.as_bytes());
4107
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4108
    }
4109
    // Each step appends after the previous line, so the chain is linear.
4110
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4111
    repo.bisect_start().unwrap();
4112
    assert!(matches!(
4113
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4114
        BisectStep::NeedMarks { good: 1, bad: 0 }
4115
    ));
4116
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4117
    assert!(
4118
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4119
        "{step:?}"
4120
    );
4121
    // Automated: bad when the bug line is present.
4122
    let step = repo
4123
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4124
        .unwrap();
4125
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4126
    assert_eq!(
4127
        repo.bisect_status().unwrap(),
4128
        Some(BisectStep::Found { culprit: hashes[4] })
4129
    );
4130
    repo.bisect_reset().unwrap();
4131
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4132
    assert!(repo.bisect_status().unwrap().is_none());
4133
    assert!(!repo.snapshot("status").unwrap().changed);
4134
    // Manual marks and a skip.
4135
    repo.bisect_start().unwrap();
4136
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4137
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4138
    let mut skipped_once = false;
4139
    let mut guard = 0;
4140
    while let BisectStep::Testing { .. } = step {
4141
        guard += 1;
4142
        assert!(guard < 20);
4143
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4144
        if !skipped_once && text.contains("line 6") {
4145
            // An untestable state away from the boundary: the search routes around it.
4146
            skipped_once = true;
4147
            step = repo.bisect_mark(None, &[]).unwrap();
4148
            continue;
4149
        }
4150
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4151
    }
4152
    assert!(skipped_once);
4153
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4154
    repo.bisect_reset().unwrap();
4155
    // Skipping the culprit itself leaves it among the candidates reported.
4156
    repo.bisect_start().unwrap();
4157
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4158
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4159
    let mut guard = 0;
4160
    while let BisectStep::Testing { heads, .. } = &step {
4161
        guard += 1;
4162
        assert!(guard < 20);
4163
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4164
        let is_culprit_state =
4165
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4166
        step = if is_culprit_state {
4167
            repo.bisect_mark(None, &[]).unwrap()
4168
        } else {
4169
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4170
        };
4171
    }
4172
    match step {
4173
        BisectStep::Inconclusive { candidates } => assert!(
4174
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4175
            "{candidates:?}"
4176
        ),
4177
        other => panic!("{other:?}"),
4178
    }
4179
    repo.bisect_reset().unwrap();
4180
}
4181
4182
#[test]
4183
fn squash_folds_a_change_into_its_dependency() {
4184
    hermetic();
4185
    let dir = tempfile::tempdir().unwrap();
4186
    let root = dir.path();
4187
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4188
    write(root, "a.txt", b"1\n");
4189
    let a = repo.commit("A", &[]).unwrap();
4190
    write(root, "a.txt", b"1\n2\n");
4191
    let c = repo.commit("C", &[]).unwrap();
4192
    write(root, "a.txt", b"1\n2\n3\n");
4193
    let e = repo.commit("E", &[]).unwrap();
4194
    write(root, "b.txt", b"b\n");
4195
    let b = repo.commit("B", &[]).unwrap();
4196
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4197
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4198
    // E depends on C which A lacks: refused, naming it.
4199
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4200
    assert!(err.contains(&c.short(12)), "{err}");
4201
    // C into A: A' has both, C is gone, E follows and still reads the same.
4202
    let a2 = repo.squash(&c, &a).unwrap();
4203
    let a2c = repo.store().get_change(&a2).unwrap();
4204
    assert_eq!(a2c.change_id, id_a);
4205
    assert!(a2c.deps.is_empty());
4206
    let heads = repo.bookmark_heads().unwrap();
4207
    let st = repo.load_state(&heads).unwrap();
4208
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4209
    let e2 = st
4210
        .changes()
4211
        .find(|(_, m)| m.change_id == id_e)
4212
        .map(|(h, _)| *h)
4213
        .unwrap();
4214
    assert_eq!(
4215
        repo.store().get_change(&e2).unwrap().deps,
4216
        vec![a2],
4217
        "E now depends on A' alone"
4218
    );
4219
    let files = st.materialize().files;
4220
    assert!(
4221
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4222
    );
4223
    assert!(files.contains_key("b.txt"));
4224
    assert!(st.contains(&b));
4225
    assert!(!repo.snapshot("status").unwrap().changed);
4226
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4227
    // Undo restores the three original changes.
4228
    repo.undo().unwrap();
4229
    repo.undo().unwrap();
4230
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4231
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4232
}
4233
4234
#[test]
4235
fn rebase_re_expresses_a_change_against_another_base() {
4236
    hermetic();
4237
    let dir = tempfile::tempdir().unwrap();
4238
    let root = dir.path();
4239
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4240
    write(root, "a.txt", b"1\n2\n");
4241
    let a = repo.commit("A", &[]).unwrap();
4242
    write(root, "a.txt", b"1\n2\n3\n");
4243
    let c = repo.commit("C: append 3", &[]).unwrap();
4244
    write(root, "a.txt", b"1\n2\n3\n4\n");
4245
    let e = repo.commit("E: append 4", &[]).unwrap();
4246
    // A different base: A plus a change that prepends a line.
4247
    repo.checkout(&[a], true, "checkout").unwrap();
4248
    write(root, "a.txt", b"0\n1\n2\n");
4249
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4250
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4251
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4252
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4253
    let c2 = repo.rebase(&c, &[d]).unwrap();
4254
    let c2c = repo.store().get_change(&c2).unwrap();
4255
    assert_eq!(c2c.change_id, id_c);
4256
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4257
    let heads = repo.bookmark_heads().unwrap();
4258
    let st = repo.load_state(&heads).unwrap();
4259
    assert!(!st.contains(&c) && st.contains(&d));
4260
    let e2 = st
4261
        .changes()
4262
        .find(|(_, m)| m.change_id == id_e)
4263
        .map(|(h, _)| *h)
4264
        .unwrap();
4265
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
4266
    assert!(
4267
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4268
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4269
    );
4270
    let files = st.materialize().files;
4271
    assert!(
4272
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4273
        "{:?}",
4274
        files["a.txt"].content
4275
    );
4276
    assert!(!files["a.txt"].is_conflicted());
4277
    // Rebasing onto a state that already contains the change is refused.
4278
    assert!(repo.rebase(&c2, &[c2]).is_err());
4279
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
4280
    assert!(
4281
        err.contains("lacks dependencies"),
4282
        "E needs C, which D's state does not have: {err}"
4283
    );
4284
}
4285
4286
#[test]
4287
fn unsigned_tags_keep_their_message() {
4288
    hermetic();
4289
    let dir = tempfile::tempdir().unwrap();
4290
    let root = dir.path();
4291
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4292
    write(root, "a.txt", b"a\n");
4293
    repo.commit("a", &[]).unwrap();
4294
    assert!(repo.secret_key().unwrap().is_none());
4295
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4296
        .unwrap();
4297
    let tags = repo.tags().unwrap();
4298
    assert_eq!(
4299
        (
4300
            tags[0].name.as_str(),
4301
            tags[0].message.as_str(),
4302
            tags[0].signer.as_deref()
4303
        ),
4304
        ("v1", "first release", None)
4305
    );
4306
    assert!(
4307
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4308
        "an unsigned attestation is not advertised"
4309
    );
4310
}
4311
4312
#[test]
4313
fn fsck_passes_a_sound_repository_and_names_each_fault() {
4314
    // Files on disk are what this tests: tampering with them, and the
4315
    // directory store's crash points.
4316
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4317
        return;
4318
    }
4319
    hermetic();
4320
    let dir = tempfile::tempdir().unwrap();
4321
    let root = dir.path();
4322
    let origin_path = root.join("origin");
4323
    let origin = Repo::init(&origin_path).unwrap();
4324
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4325
        .unwrap()
4326
        .with_home(root.join("home-a"));
4327
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4328
        .unwrap();
4329
    write(&root.join("a"), "f.txt", b"one\n");
4330
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4331
    let h1 = a.commit("first", &[]).unwrap();
4332
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4333
    let h2 = a.commit("second", &[]).unwrap();
4334
    a.tag_create("v1", &[h2], "first release").unwrap();
4335
    a.checkpoint().unwrap();
4336
    assert!(a.push("origin", false).unwrap()[0].ok);
4337
4338
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4339
    for repo in [&a, &origin] {
4340
        let rep = repo.fsck().unwrap();
4341
        assert_eq!(rep.problems, vec![], "{rep:?}");
4342
        // The two commits, plus the working copy's change in `a`.
4343
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4344
        assert!(rep.ops > 1 && rep.objects > 5);
4345
    }
4346
    assert!(origin.fsck().unwrap().attestations >= 1);
4347
4348
    // A flipped byte in a stored object is corruption, named by hash.
4349
    let c1 = a.store().path_for(&h1);
4350
    let pristine = fs::read(&c1).unwrap();
4351
    let mut bytes = pristine.clone();
4352
    *bytes.last_mut().unwrap() ^= 1;
4353
    fs::write(&c1, &bytes).unwrap();
4354
    let rep = a.fsck().unwrap();
4355
    assert!(rep.errors() >= 1);
4356
    assert!(
4357
        rep.problems
4358
            .iter()
4359
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4360
        "{rep:?}"
4361
    );
4362
    fs::write(&c1, &pristine).unwrap();
4363
    assert_eq!(a.fsck().unwrap().errors(), 0);
4364
4365
    // A missing change is named with what needed it.
4366
    fs::remove_file(&c1).unwrap();
4367
    let rep = a.fsck().unwrap();
4368
    assert!(
4369
        rep.problems.iter().any(|p| p.severity == Severity::Error
4370
            && p.object == Some(h1)
4371
            && p.what.contains("change missing, needed by change")),
4372
        "{rep:?}"
4373
    );
4374
    fs::write(&c1, &pristine).unwrap();
4375
4376
    // A missing blob is an error in a full clone.
4377
    let c2 = a.store().get_change(&h1).unwrap();
4378
    let blob = c2
4379
        .edits
4380
        .iter()
4381
        .find_map(|e| match e {
4382
            Edit::Replace { new: Some(b), .. } => Some(*b),
4383
            _ => None,
4384
        })
4385
        .expect("the binary file is a blob");
4386
    let bp = a.store().path_for(&blob);
4387
    let blob_bytes = fs::read(&bp).unwrap();
4388
    fs::remove_file(&bp).unwrap();
4389
    let rep = a.fsck().unwrap();
4390
    assert!(
4391
        rep.problems
4392
            .iter()
4393
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4394
        "{rep:?}"
4395
    );
4396
    fs::write(&bp, &blob_bytes).unwrap();
4397
4398
    // A broken op log head is reported, not a crash.
4399
    let head = root.join("a/.oxy/ops/head");
4400
    let saved = fs::read(&head).unwrap();
4401
    fs::write(&head, b"not a hash").unwrap();
4402
    let rep = a.fsck().unwrap();
4403
    assert!(
4404
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4405
        "{rep:?}"
4406
    );
4407
    fs::write(&head, saved).unwrap();
4408
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4409
}
4410
4411
/// Copy a directory tree (for restoring a pristine repository).
4412
fn copy_tree(from: &Path, to: &Path) {
4413
    fs::create_dir_all(to).unwrap();
4414
    for e in fs::read_dir(from).unwrap() {
4415
        let e = e.unwrap();
4416
        let target = to.join(e.file_name());
4417
        if e.file_type().unwrap().is_dir() {
4418
            copy_tree(&e.path(), &target);
4419
        } else {
4420
            fs::copy(e.path(), &target).unwrap();
4421
        }
4422
    }
4423
}
4424
4425
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4426
/// would, and check that both repositories still open, pass `fsck`, and
4427
/// accept the same operation again.
4428
#[test]
4429
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4430
    // Files on disk are what this tests: tampering with them, and the
4431
    // directory store's crash points.
4432
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4433
        return;
4434
    }
4435
    use crate::durable::failpoint;
4436
    hermetic();
4437
    let dir = tempfile::tempdir().unwrap();
4438
    let pristine = dir.path().join("pristine");
4439
    let origin_path = pristine.join("origin");
4440
    Repo::init(&origin_path).unwrap();
4441
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4442
        .unwrap()
4443
        .with_home(dir.path().join("home"));
4444
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4445
        .unwrap();
4446
    write(&pristine.join("a"), "f.txt", b"one\n");
4447
    a.commit("first", &[]).unwrap();
4448
    assert!(a.push("origin", false).unwrap()[0].ok);
4449
    drop(a);
4450
4451
    type Op = fn(&Repo) -> Result<()>;
4452
    let edit_and_commit: Op = |r| {
4453
        write(r.root(), "f.txt", b"one\ntwo\n");
4454
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4455
        r.commit("second", &[]).map(|_| ())
4456
    };
4457
    let push: Op = |r| {
4458
        let res = r.push("origin", false)?;
4459
        if res.iter().all(|x| x.ok) {
4460
            Ok(())
4461
        } else {
4462
            Err(RepoError::Msg(format!("{res:?}")))
4463
        }
4464
    };
4465
4466
    for (name, prepare, op) in [
4467
        ("commit", None, edit_and_commit),
4468
        ("push", Some(edit_and_commit), push),
4469
    ] {
4470
        let mut steps = 0;
4471
        for n in 1.. {
4472
            let run = dir.path().join(format!("{name}-{n}"));
4473
            copy_tree(&pristine, &run);
4474
            // Clones record their remote by path; point it at this copy.
4475
            let open = |p: &Path| {
4476
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4477
                r.config
4478
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4479
                    .unwrap();
4480
                r.save_config().unwrap();
4481
                r
4482
            };
4483
            let a = open(&run.join("a"));
4484
            if let Some(prep) = prepare {
4485
                prep(&a).unwrap();
4486
            }
4487
            failpoint::crash_after(n);
4488
            let outcome = op(&a);
4489
            let crashed = failpoint::disarm();
4490
            drop(a);
4491
            if !crashed {
4492
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4493
                steps = n - 1;
4494
                break;
4495
            }
4496
            assert!(
4497
                outcome.is_err(),
4498
                "{name}: a crash at step {n} was swallowed"
4499
            );
4500
            for repo in ["a", "origin"] {
4501
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4502
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4503
                });
4504
                let rep = r.fsck().unwrap();
4505
                assert_eq!(
4506
                    rep.errors(),
4507
                    0,
4508
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4509
                    rep.problems
4510
                );
4511
            }
4512
            // The interrupted operation can simply be run again.
4513
            let a = open(&run.join("a"));
4514
            // A crash after the commit point leaves the commit done.
4515
            let landed = a
4516
                .bookmark_heads()
4517
                .unwrap()
4518
                .iter()
4519
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4520
            let again = match (name, landed) {
4521
                ("commit", true) => Ok(()),
4522
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4523
                _ => op(&a),
4524
            };
4525
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4526
            assert_eq!(a.fsck().unwrap().errors(), 0);
4527
            fs::remove_dir_all(&run).unwrap();
4528
        }
4529
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4530
    }
4531
}
4532
4533
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4534
/// running at the same time lose nothing: every commit ends up on the
4535
/// bookmark, locally and on the remote, and the repository passes fsck.
4536
#[test]
4537
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4538
    hermetic();
4539
    let dir = tempfile::tempdir().unwrap();
4540
    let root = dir.path();
4541
    let origin = root.join("origin");
4542
    Repo::init_bare_unbound(&origin).unwrap();
4543
    let main = root.join("main");
4544
    let mut repo = Repo::init(&main).unwrap();
4545
    repo.config
4546
        .set("remote.origin.url", &origin.to_string_lossy())
4547
        .unwrap();
4548
    repo.save_config().unwrap();
4549
    write(&main, "seed.txt", b"seed\n");
4550
    repo.commit("seed", &[]).unwrap();
4551
    let second = root.join("second");
4552
    repo.workspace_add(&second, None).unwrap();
4553
    drop(repo);
4554
4555
    const EACH: usize = 15;
4556
    std::thread::scope(|s| {
4557
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4558
            s.spawn(move || {
4559
                let r = Repo::open(&dir).unwrap();
4560
                for i in 0..EACH {
4561
                    write(
4562
                        &dir,
4563
                        &format!("{tag}-{i}.txt"),
4564
                        format!("{tag} {i}\n").as_bytes(),
4565
                    );
4566
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4567
                    if push && i % 5 == 4 {
4568
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4569
                        let _ = r.push("origin", false);
4570
                    }
4571
                }
4572
            });
4573
        }
4574
    });
4575
4576
    let repo = Repo::open(&main).unwrap();
4577
    let heads = repo.bookmark_heads().unwrap();
4578
    let state = repo.load_state(&heads).unwrap();
4579
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4580
    for tag in ["a", "b"] {
4581
        for i in 0..EACH {
4582
            assert!(
4583
                messages.contains(&format!("{tag} {i}")),
4584
                "lost commit {tag} {i}; have {messages:?}"
4585
            );
4586
        }
4587
    }
4588
    let rep = repo.fsck().unwrap();
4589
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4590
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4591
    let hosted = Repo::open(&origin).unwrap();
4592
    let hosted_heads = hosted.bookmark_heads().unwrap();
4593
    assert_eq!(
4594
        hosted.load_state(&hosted_heads).unwrap().len(),
4595
        state.len(),
4596
        "the remote has every commit"
4597
    );
4598
}
4599
4600
/// Two operations recorded from the same parent (what two processes do
4601
/// when they race) are merged: both bookmarks' heads survive, and a
4602
/// change made on one side only is kept.
4603
#[test]
4604
fn operations_from_the_same_parent_are_merged() {
4605
    hermetic();
4606
    let dir = tempfile::tempdir().unwrap();
4607
    let root = dir.path();
4608
    let repo = Repo::init(root).unwrap();
4609
    write(root, "a.txt", b"a\n");
4610
    let a = repo.commit("a", &[]).unwrap();
4611
    write(root, "b.txt", b"b\n");
4612
    let b = repo.commit("b", &[]).unwrap();
4613
    let (x, op) = repo.head_op().unwrap();
4614
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4615
4616
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4617
    let mut one = op.view.clone();
4618
    one.bookmarks.insert("main".into(), state(vec![a]));
4619
    one.bookmarks.insert("topic".into(), state(vec![a]));
4620
    let mut two = op.view.clone();
4621
    two.bookmarks.insert("main".into(), state(vec![b]));
4622
    repo.record_op(&[x], "one", one).unwrap();
4623
    let merged = repo.record_op(&[x], "two", two).unwrap();
4624
4625
    let (head, op) = repo.head_op().unwrap();
4626
    assert_eq!(head, merged);
4627
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4628
    assert!(op.command.contains("merged with a concurrent operation"));
4629
    let mut main = repo
4630
        .store()
4631
        .get_state(&op.view.bookmarks["main"])
4632
        .unwrap()
4633
        .heads;
4634
    main.sort();
4635
    let mut want = vec![a, b];
4636
    want.sort();
4637
    assert_eq!(main, want, "both sides' heads are kept");
4638
    assert!(
4639
        op.view.bookmarks.contains_key("topic"),
4640
        "a one-sided change survives"
4641
    );
4642
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4643
}
4644
4645
#[test]
4646
fn failed_requests_come_with_a_next_step() {
4647
    use crate::protocol::hint_for;
4648
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4649
        .unwrap()
4650
        .contains("token"));
4651
    assert!(hint_for("…: HTTP 403: forbidden")
4652
        .unwrap()
4653
        .contains("repo:write"));
4654
    assert!(hint_for("…: HTTP 404: no such repository")
4655
        .unwrap()
4656
        .contains("owner and repository name"));
4657
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4658
        .unwrap()
4659
        .contains("oxyhub-ca.pem"));
4660
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4661
        .unwrap()
4662
        .contains("running"));
4663
    assert!(hint_for("Dns Failed: failed to lookup address information")
4664
        .unwrap()
4665
        .contains("resolve"));
4666
    assert_eq!(hint_for("something else entirely"), None);
4667
}
4668
4669
#[test]
4670
fn doctor_names_problems_and_what_to_do() {
4671
    hermetic();
4672
    let dir = tempfile::tempdir().unwrap();
4673
    let root = dir.path();
4674
    let origin = root.join("origin");
4675
    Repo::init_bare_unbound(&origin).unwrap();
4676
    let mut repo = Repo::init(&root.join("r"))
4677
        .unwrap()
4678
        .with_home(root.join("home"));
4679
    let find = |r: &DoctorReport, area: &str, h: Health| {
4680
        r.checks
4681
            .iter()
4682
            .find(|c| c.area == area && c.health == h)
4683
            .cloned()
4684
    };
4685
4686
    let r = repo.doctor(true);
4687
    assert!(find(&r, "identity", Health::Warn)
4688
        .unwrap()
4689
        .hint
4690
        .unwrap()
4691
        .contains("oxy identity create"));
4692
    assert!(find(&r, "repository", Health::Ok).is_some());
4693
4694
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4695
        .unwrap();
4696
    repo.config.set("author.name", "Ada").unwrap();
4697
    repo.config.set("author.email", "[email protected]").unwrap();
4698
    repo.config
4699
        .set("remote.origin.url", &origin.to_string_lossy())
4700
        .unwrap();
4701
    repo.config
4702
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4703
        .unwrap();
4704
    repo.config.set("remote.down.token", "t").unwrap();
4705
    repo.config
4706
        .set("remote.badca.url", "https://example.invalid/a/b")
4707
        .unwrap();
4708
    repo.config
4709
        .set(
4710
            "remote.badca.ca",
4711
            &root.join("missing.pem").to_string_lossy(),
4712
        )
4713
        .unwrap();
4714
    repo.save_config().unwrap();
4715
4716
    let r = repo.doctor(true);
4717
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4718
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4719
    assert!(find(&r, "remote origin", Health::Ok)
4720
        .unwrap()
4721
        .message
4722
        .contains("first push binds it"));
4723
    let down = find(&r, "remote down", Health::Fail).unwrap();
4724
    assert!(
4725
        down.hint.as_deref().unwrap_or("").contains("running"),
4726
        "{down:?}"
4727
    );
4728
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4729
    assert!(
4730
        badca.hint.unwrap().contains("remote.badca.ca"),
4731
        "the remote's own name is in the hint"
4732
    );
4733
    assert_eq!(r.worst(), Health::Fail);
4734
4735
    // Offline, nothing is contacted.
4736
    let r = repo.doctor(false);
4737
    assert!(find(&r, "remote down", Health::Fail).is_none());
4738
    assert!(find(&r, "remote down", Health::Ok)
4739
        .unwrap()
4740
        .message
4741
        .contains("not contacted"));
4742
}
4743
4744
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4745
/// after it. Inserting after `b` and then deleting `b`, one commit after
4746
/// the other, must not leave a delete/insert conflict.
4747
#[test]
4748
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4749
    hermetic();
4750
    let dir = tempfile::tempdir().unwrap();
4751
    let root = dir.path();
4752
    let repo = Repo::init(root).unwrap();
4753
    write(root, "f", b"a\nb\nc\n");
4754
    repo.commit("base", &[]).unwrap();
4755
    write(root, "f", b"a\nb\nx\nc\n");
4756
    let insert = repo.commit("insert x after b", &[]).unwrap();
4757
    write(root, "f", b"a\nx\nc\n");
4758
    let delete = repo.commit("delete b", &[]).unwrap();
4759
    assert!(
4760
        repo.store()
4761
            .get_change(&delete)
4762
            .unwrap()
4763
            .deps
4764
            .contains(&insert),
4765
        "the deletion depends on the insertion below the deleted line"
4766
    );
4767
    let heads = repo.bookmark_heads().unwrap();
4768
    assert_eq!(heads, vec![delete]);
4769
    let snap = repo.load_state(&heads).unwrap().materialize();
4770
    assert!(!snap.is_conflicted());
4771
    assert!(
4772
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4773
    );
4774
}
4775
4776
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4777
/// replacement depends on the change that set the blob it replaces.
4778
#[test]
4779
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4780
    hermetic();
4781
    let dir = tempfile::tempdir().unwrap();
4782
    let root = dir.path();
4783
    let repo = Repo::init(root).unwrap();
4784
    write(root, "bin", b"\0A");
4785
    let v1 = repo.commit("v1", &[]).unwrap();
4786
    write(root, "bin", b"\0B");
4787
    let v2 = repo.commit("v2", &[]).unwrap();
4788
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4789
    write(root, "bin", b"\0A");
4790
    let v3 = repo.commit("back to A", &[]).unwrap();
4791
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4792
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4793
    let state = repo.load_state(&[v3]).unwrap();
4794
    let snap = state.materialize();
4795
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4796
        panic!("opaque")
4797
    };
4798
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4799
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4800
}
4801
4802
/// Spec §23: a binary file changed on two branches and merged in Git to
4803
/// one side's version comes back as that version at the merge, and the
4804
/// import verifies commit by commit.
4805
#[test]
4806
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4807
    hermetic();
4808
    if std::process::Command::new("git")
4809
        .arg("--version")
4810
        .output()
4811
        .is_err()
4812
    {
4813
        eprintln!("git not installed; skipping");
4814
        return;
4815
    }
4816
    let dir = tempfile::tempdir().unwrap();
4817
    let root = dir.path();
4818
    let g = root.join("src.git");
4819
    fs::create_dir_all(&g).unwrap();
4820
    let git = |args: &[&str]| -> String {
4821
        let out = std::process::Command::new("git")
4822
            .arg("-C")
4823
            .arg(&g)
4824
            .args([
4825
                "-c",
4826
                "user.name=Grace",
4827
                "-c",
4828
                "[email protected]",
4829
                "-c",
4830
                "commit.gpgsign=false",
4831
            ])
4832
            .args(args)
4833
            .output()
4834
            .unwrap();
4835
        assert!(
4836
            out.status.success(),
4837
            "git {args:?}: {}",
4838
            String::from_utf8_lossy(&out.stderr)
4839
        );
4840
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4841
    };
4842
    git(&["init", "-q", "-b", "main"]);
4843
    write(&g, "logo.bin", b"\0base");
4844
    write(&g, "notes.txt", b"a\nb\nc\n");
4845
    git(&["add", "."]);
4846
    git(&["commit", "-qm", "base"]);
4847
    git(&["checkout", "-qb", "side"]);
4848
    write(&g, "logo.bin", b"\0side");
4849
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4850
    git(&["commit", "-qam", "side"]);
4851
    git(&["checkout", "-q", "main"]);
4852
    write(&g, "logo.bin", b"\0main");
4853
    git(&["commit", "-qam", "main"]);
4854
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4855
    let _ = std::process::Command::new("git")
4856
        .arg("-C")
4857
        .arg(&g)
4858
        .args([
4859
            "-c",
4860
            "user.name=G",
4861
            "-c",
4862
            "user.email=g@e",
4863
            "merge",
4864
            "-q",
4865
            "side",
4866
        ])
4867
        .output();
4868
    write(&g, "logo.bin", b"\0main");
4869
    git(&["add", "."]);
4870
    git(&["commit", "-qm", "merge side"]);
4871
    // Then a revert of the binary to its first version.
4872
    write(&g, "logo.bin", b"\0base");
4873
    git(&["commit", "-qam", "back to base"]);
4874
4875
    let repo = Repo::init(&root.join("o")).unwrap();
4876
    let rep = repo.import_git(&g, "main").unwrap();
4877
    assert_eq!(rep.merges, 1);
4878
    let v = repo.verify_git_import(&g, "main").unwrap();
4879
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4880
    assert_eq!(v.commits, 5);
4881
    let snap = repo
4882
        .load_state(&repo.bookmark_heads().unwrap())
4883
        .unwrap()
4884
        .materialize();
4885
    assert!(!snap.is_conflicted());
4886
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4887
        panic!("opaque")
4888
    };
4889
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4890
}
4891
4892
/// Spec §7.7 on a file system without executable bits or symlinks: the
4893
/// recorded bit is kept, and a symlink checked out as a plain file holding
4894
/// its target is still that symlink.
4895
#[cfg(unix)]
4896
#[test]
4897
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4898
    use crate::portable::Platform;
4899
    use std::os::unix::fs::PermissionsExt;
4900
    hermetic();
4901
    let dir = tempfile::tempdir().unwrap();
4902
    let root = dir.path();
4903
    let repo = Repo::init(root).unwrap();
4904
    write(root, "run.sh", b"#!/bin/sh\n");
4905
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4906
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4907
    repo.commit("script and link", &[]).unwrap();
4908
    drop(repo);
4909
4910
    // What checking out on Windows leaves: no exec bit, the link as a file.
4911
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4912
    fs::remove_file(root.join("link")).unwrap();
4913
    write(root, "link", b"run.sh");
4914
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4915
    let s = win.snapshot("oxy status").unwrap();
4916
    assert!(
4917
        s.statuses.is_empty(),
4918
        "nothing changed on Windows: {:?}",
4919
        statuses(&s)
4920
    );
4921
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4922
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4923
    write(root, "link", b"other");
4924
    let h = win.commit("edit on Windows", &[]).unwrap();
4925
    let snap = win.load_state(&[h]).unwrap().materialize();
4926
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4927
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4928
    // The same working copy read as Linux sees the lost bit and the plain file.
4929
    let linux = Repo::open(root).unwrap();
4930
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4931
}
4932
4933
/// Paths that collide on case-insensitive or Windows file systems are
4934
/// named at checkout there, and by doctor everywhere.
4935
#[test]
4936
fn paths_other_platforms_cannot_hold_are_reported() {
4937
    use crate::portable::Platform;
4938
    hermetic();
4939
    let dir = tempfile::tempdir().unwrap();
4940
    let root = dir.path();
4941
    let repo = Repo::init(root).unwrap();
4942
    write(root, "README.md", b"a\n");
4943
    write(root, "readme.md", b"b\n");
4944
    write(root, "src/aux.c", b"int x;\n");
4945
    let h = repo.commit("unportable", &[]).unwrap();
4946
    let r = repo.doctor(false);
4947
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4948
    assert_eq!(port.health, Health::Warn);
4949
    assert!(
4950
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4951
        "{}",
4952
        port.message
4953
    );
4954
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4955
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4956
    assert!(
4957
        rep.notes
4958
            .iter()
4959
            .any(|n| n.contains("README.md and readme.md")),
4960
        "{:?}",
4961
        rep.notes
4962
    );
4963
    assert!(
4964
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4965
        "macOS allows aux.c"
4966
    );
4967
}
4968
4969
#[test]
4970
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4971
    hermetic();
4972
    let dir = tempfile::tempdir().unwrap();
4973
    let repo = Repo::init(dir.path()).unwrap();
4974
    write(dir.path(), "a.txt", b"one\n");
4975
    write(dir.path(), "other.txt", b"x\n");
4976
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4977
    repo.snapshot("t").unwrap();
4978
    let c1 = repo.commit("first", &[]).unwrap();
4979
    write(dir.path(), "other.txt", b"y\n");
4980
    repo.snapshot("t").unwrap();
4981
    repo.commit("other only", &[]).unwrap();
4982
    write(dir.path(), "a.txt", b"one\ntwo\n");
4983
    repo.snapshot("t").unwrap();
4984
    let c3 = repo.commit("second line", &[]).unwrap();
4985
    write(dir.path(), "other.txt", b"z\n");
4986
    repo.snapshot("t").unwrap();
4987
    repo.commit("other again", &[]).unwrap();
4988
4989
    let heads = repo.bookmark_heads().unwrap();
4990
    let state = repo.load_state(&heads).unwrap();
4991
    let full: Vec<ChangeHash> = repo
4992
        .log_for_path_in("a.txt", &heads)
4993
        .unwrap()
4994
        .iter()
4995
        .map(|e| e.hash)
4996
        .collect();
4997
    assert_eq!(
4998
        full,
4999
        vec![c3, c1],
5000
        "newest first, only changes touching the path"
5001
    );
5002
    let newest: Vec<ChangeHash> = repo
5003
        .log_for_path_of(&state, "a.txt", Some(1))
5004
        .unwrap()
5005
        .iter()
5006
        .map(|e| e.hash)
5007
        .collect();
5008
    assert_eq!(newest, vec![c3], "stops at the first");
5009
    assert_eq!(
5010
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5011
        2
5012
    );
5013
    assert!(repo
5014
        .log_for_path_of(&state, "missing.txt", Some(1))
5015
        .is_err());
5016
    assert_eq!(
5017
        repo.log_state(&heads).unwrap().len(),
5018
        repo.log_of(&state).len()
5019
    );
5020
5021
    let tree = state.tree().view();
5022
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5023
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5024
    assert_eq!(
5025
        via_state
5026
            .iter()
5027
            .map(|l| (l.hash, l.text.clone()))
5028
            .collect::<Vec<_>>(),
5029
        via_heads
5030
            .iter()
5031
            .map(|l| (l.hash, l.text.clone()))
5032
            .collect::<Vec<_>>()
5033
    );
5034
    assert_eq!(
5035
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5036
        vec![c1, c3]
5037
    );
5038
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5039
}
5040
5041
/// A text file whose stat matches the manifest and whose recorded hash is
5042
/// the base's content is taken from the base without reading it; anything
5043
/// else is read, so no edit is missed (spec §12.3).
5044
#[cfg(unix)]
5045
#[test]
5046
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5047
    use std::os::unix::fs::PermissionsExt;
5048
    hermetic();
5049
    let dir = tempfile::tempdir().unwrap();
5050
    let root = dir.path();
5051
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5052
    write(root, "a.txt", b"one\ntwo\n");
5053
    write(root, "b.txt", b"bee\n");
5054
    repo.commit("base", &[]).unwrap();
5055
    let age = |p: &str| {
5056
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5057
        fs::File::options()
5058
            .write(true)
5059
            .open(root.join(p))
5060
            .unwrap()
5061
            .set_modified(old)
5062
            .unwrap();
5063
    };
5064
    age("a.txt");
5065
    age("b.txt");
5066
    assert!(
5067
        !repo.snapshot("status").unwrap().changed,
5068
        "records the aged stat"
5069
    );
5070
5071
    // Clean and equal to the base: not read at all.
5072
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5073
    let snap = repo.snapshot("status").unwrap();
5074
    assert!(
5075
        !snap.changed && snap.statuses.is_empty(),
5076
        "{:?}",
5077
        snap.statuses
5078
    );
5079
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5080
5081
    // An uncommitted edit that is older than the manifest: stat-clean, but
5082
    // its hash is not the base's, so it is read and stays visible.
5083
    write(root, "b.txt", b"bee edited\n");
5084
    age("b.txt");
5085
    let first = repo.snapshot("status").unwrap();
5086
    assert_eq!(
5087
        statuses(&first),
5088
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5089
    );
5090
    let again = repo.snapshot("status").unwrap();
5091
    assert_eq!(
5092
        statuses(&again),
5093
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5094
        "still seen once stat-clean"
5095
    );
5096
    assert!(!again.changed, "and the working copy hashes the same");
5097
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5098
    assert!(
5099
        repo.snapshot("status").is_err(),
5100
        "an edited file must be read, never taken from the base"
5101
    );
5102
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5103
5104
    // A same-size edit made just now is racy and read.
5105
    write(root, "a.txt", b"one\nTWO\n");
5106
    assert_eq!(
5107
        statuses(&repo.snapshot("status").unwrap()),
5108
        vec![
5109
            ("a.txt".to_string(), ChangeStatus::Modified),
5110
            ("b.txt".to_string(), ChangeStatus::Modified)
5111
        ]
5112
    );
5113
    // Committing makes the edits the base: both are clean and served from it again.
5114
    repo.commit("edits", &[]).unwrap();
5115
    age("a.txt");
5116
    age("b.txt");
5117
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5118
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5119
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5120
    let snap = repo.snapshot("status").unwrap();
5121
    assert!(!snap.changed && snap.statuses.is_empty());
5122
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5123
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5124
}
5125
5126
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5127
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5128
/// file is unchanged, and loading through the checkpoint equals a full load.
5129
#[test]
5130
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5131
    hermetic();
5132
    let dir = tempfile::tempdir().unwrap();
5133
    let root = dir.path();
5134
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5135
    let long: String = (0..300)
5136
        .map(|i| format!("line {i} of a long file\n"))
5137
        .collect();
5138
    write(root, "long.txt", long.as_bytes());
5139
    write(root, "short.txt", b"short\n");
5140
    repo.commit("base", &[]).unwrap();
5141
    let (r1, _, _) = repo.checkpoint().unwrap();
5142
    let cp1 = crate::objects::Checkpoint::decode(
5143
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5144
    )
5145
    .unwrap();
5146
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5147
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5148
5149
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5150
    repo.gc(true).unwrap();
5151
    assert!(repo.store().has(&graphs1[0]));
5152
    let report = repo.fsck().unwrap();
5153
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5154
5155
    // Loading through the checkpoint equals a full load.
5156
    write(root, "short.txt", b"short, edited\n");
5157
    repo.commit("edit the short file", &[]).unwrap();
5158
    let heads = repo.bookmark_heads().unwrap();
5159
    let fast = repo.load_state(&heads).unwrap();
5160
    let full = repo.load_state_full(&heads).unwrap();
5161
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5162
5163
    // The next checkpoint shares the unchanged long file's graph.
5164
    let (r2, _, _) = repo.checkpoint().unwrap();
5165
    let cp2 = crate::objects::Checkpoint::decode(
5166
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5167
    )
5168
    .unwrap();
5169
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5170
5171
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5172
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5173
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5174
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5175
5176
    // A version 1 checkpoint written by an older oxy still loads.
5177
    let state = repo.load_state_full(&heads).unwrap();
5178
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5179
    let cp_old = crate::objects::Checkpoint {
5180
        heads: cp2.heads.clone(),
5181
        count: cp2.count,
5182
        payload: old,
5183
    };
5184
    let r_old = repo
5185
        .store()
5186
        .put(ObjectType::Checkpoint, &cp_old.encode())
5187
        .unwrap();
5188
    repo.install_checkpoint("main", &r_old).unwrap();
5189
    assert_eq!(
5190
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5191
        full.checkpoint_payload()
5192
    );
5193
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5194
5195
    // A lost graph blob fails the load loudly rather than dropping the
5196
    // file, and fsck reports it (a fresh repository, objects still loose).
5197
    let dir2 = tempfile::tempdir().unwrap();
5198
    let root2 = dir2.path();
5199
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5200
    write(root2, "long.txt", long.as_bytes());
5201
    repo2.commit("base", &[]).unwrap();
5202
    let (r, _, _) = repo2.checkpoint().unwrap();
5203
    let cp = crate::objects::Checkpoint::decode(
5204
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5205
    )
5206
    .unwrap();
5207
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5208
    repo2.store().remove_loose_for_test(&graph).unwrap();
5209
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5210
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5211
}
5212
5213
/// A new repository has not stored the user's identity yet (that happens
5214
/// at the first signed change); looking it up falls back to the key
5215
/// directory, and a file there that does not hash to the key is refused.
5216
#[test]
5217
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5218
    hermetic();
5219
    let dir = tempfile::tempdir().unwrap();
5220
    let home = dir.path().join("home");
5221
    let mut first = Repo::init(&dir.path().join("a"))
5222
        .unwrap()
5223
        .with_home(home.clone());
5224
    let (key, _) = first
5225
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5226
        .unwrap();
5227
    let fresh = Repo::init(&dir.path().join("b"))
5228
        .unwrap()
5229
        .with_home(home.clone());
5230
    assert!(!fresh.store().has(&key), "nothing stored yet");
5231
    let id = fresh.identity(&key).unwrap();
5232
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5233
    // A key file that is not this identity is an error, not a wrong answer.
5234
    let keys = fresh.keys_dir.clone();
5235
    let (other, _) = first
5236
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5237
        .unwrap();
5238
    fs::copy(
5239
        keys.join(format!("{}.identity", other.to_hex())),
5240
        keys.join(format!("{}.identity", key.to_hex())),
5241
    )
5242
    .unwrap();
5243
    assert!(fresh
5244
        .identity(&key)
5245
        .unwrap_err()
5246
        .to_string()
5247
        .contains("does not hold identity"));
5248
}
5249
5250
/// Status snapshots (spec §12.3): a text file whose stat matches the
5251
/// manifest, and whose base graph key is the one the manifest recorded it
5252
/// equal to, is neither read nor rendered; any edit, and any change to the
5253
/// file's graph in the base, brings it back.
5254
#[cfg(unix)]
5255
#[test]
5256
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5257
    use std::os::unix::fs::PermissionsExt;
5258
    hermetic();
5259
    let dir = tempfile::tempdir().unwrap();
5260
    let root = dir.path();
5261
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5262
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5263
        write(root, p, c.as_bytes());
5264
    }
5265
    repo.commit("base", &[]).unwrap();
5266
    let age = |p: &str| {
5267
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5268
        fs::File::options()
5269
            .write(true)
5270
            .open(root.join(p))
5271
            .unwrap()
5272
            .set_modified(old)
5273
            .unwrap();
5274
    };
5275
    let lock = |p: &str, mode: u32| {
5276
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5277
    };
5278
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5279
        age(p);
5280
    }
5281
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5282
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5283
    assert!(
5284
        m.entries.values().all(|e| e.graph.is_some()),
5285
        "keys recorded"
5286
    );
5287
5288
    // Unreadable files prove they are not read; the status snapshot does
5289
    // not render them either, and its base lacks their graphs.
5290
    lock("a.txt", 0o000);
5291
    lock("b.txt", 0o000);
5292
    let snap = repo.snapshot_status("status").unwrap();
5293
    assert!(!snap.changed && snap.statuses.is_empty());
5294
    assert_eq!(
5295
        snap.base_snapshot
5296
            .unrendered
5297
            .iter()
5298
            .cloned()
5299
            .collect::<Vec<_>>(),
5300
        vec!["a.txt", "b.txt", "d/c.txt"]
5301
    );
5302
    assert!(!snap.base.is_full());
5303
    assert!(!snap.base_snapshot.is_conflicted());
5304
    // A full snapshot does not read them either, but renders everything.
5305
    let full = repo.snapshot("status").unwrap();
5306
    assert!(full.statuses.is_empty() && full.base.is_full());
5307
    assert!(full.base_snapshot.unrendered.is_empty());
5308
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5309
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5310
5311
    // An edit is seen; the file is rendered, the others still are not.
5312
    write(root, "d/c.txt", b"sea edited\n");
5313
    let snap = repo.snapshot_status("status").unwrap();
5314
    assert_eq!(
5315
        statuses(&snap),
5316
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5317
    );
5318
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5319
    // So is a mode change of an unread file.
5320
    lock("b.txt", 0o100);
5321
    assert_eq!(
5322
        statuses(&repo.snapshot_status("status").unwrap()),
5323
        vec![
5324
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5325
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5326
        ]
5327
    );
5328
    lock("b.txt", 0o000);
5329
5330
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5331
    // stays unread, c.txt is read once and then skipped too.
5332
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5333
        .unwrap();
5334
    age("d/c.txt");
5335
    let snap = repo.snapshot_status("status").unwrap();
5336
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5337
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5338
    lock("d/c.txt", 0o000);
5339
    let snap = repo.snapshot_status("status").unwrap();
5340
    assert!(snap.statuses.is_empty());
5341
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5342
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5343
        lock(p, 0o644);
5344
    }
5345
}
5346
5347
/// Attributes decide how a file compares with the base, so a changed
5348
/// `.oxyattributes` makes every text file be compared again.
5349
#[cfg(unix)]
5350
#[test]
5351
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5352
    hermetic();
5353
    let dir = tempfile::tempdir().unwrap();
5354
    let root = dir.path();
5355
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5356
    write(root, "a.txt", b"crlf\r\n");
5357
    repo.commit("base", &[]).unwrap();
5358
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5359
    fs::File::options()
5360
        .write(true)
5361
        .open(root.join("a.txt"))
5362
        .unwrap()
5363
        .set_modified(old)
5364
        .unwrap();
5365
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5366
    assert!(repo
5367
        .snapshot_status("status")
5368
        .unwrap()
5369
        .base_snapshot
5370
        .unrendered
5371
        .contains("a.txt"));
5372
    // With eol=lf, a.txt as stored no longer equals the base.
5373
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5374
    let snap = repo.snapshot_status("status").unwrap();
5375
    assert_eq!(
5376
        statuses(&snap),
5377
        vec![
5378
            (".oxyattributes".to_string(), ChangeStatus::Added),
5379
            ("a.txt".to_string(), ChangeStatus::Modified)
5380
        ]
5381
    );
5382
}
5383
5384
/// Bookmarks with `/` in their names: pushing records their
5385
/// attestations, and checkpoints are kept for them, beside `feature`
5386
/// itself.
5387
#[test]
5388
fn bookmarks_with_slashes_push_and_checkpoint() {
5389
    hermetic();
5390
    let dir = tempfile::tempdir().unwrap();
5391
    let root = dir.path();
5392
    let origin = Repo::init(&root.join("origin")).unwrap();
5393
    let url = root.join("origin").to_string_lossy().to_string();
5394
    let mut repo = Repo::clone(&url, &root.join("r"))
5395
        .unwrap()
5396
        .with_home(root.join("home"));
5397
    // With an identity, pushes carry reference attestations: the case
5398
    // that failed, since the attestation is a file named after the bookmark.
5399
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5400
        .unwrap();
5401
    let r = root.join("r");
5402
    write(&r, "a.txt", b"a\n");
5403
    let h_a = repo.commit("a", &[]).unwrap();
5404
    assert!(repo.push("origin", false).unwrap()[0].ok);
5405
    repo.bookmark_create("feature", None).unwrap();
5406
    repo.bookmark_create("feature/x", None).unwrap();
5407
    repo.bookmark_switch("feature/x", false).unwrap();
5408
    write(&r, "b.txt", b"b\n");
5409
    let h_b = repo.commit("b", &[]).unwrap();
5410
    for name in ["feature", "feature/x"] {
5411
        let res = repo.push_bookmark("origin", name, false).unwrap();
5412
        assert!(res[0].ok, "{name}: {res:?}");
5413
    }
5414
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5415
    assert_eq!(
5416
        origin.resolve_heads("feature/x").unwrap(),
5417
        repo.resolve_heads("feature/x").unwrap()
5418
    );
5419
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5420
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5421
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5422
5423
    // A checkpoint of feature/x is found again when loading its state.
5424
    let (cp, _, _) = repo.checkpoint().unwrap();
5425
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5426
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5427
    let heads = repo.resolve_heads("feature/x").unwrap();
5428
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5429
}
5430
5431
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5432
/// never the remote's own bookmark, and a bookmark created again later is
5433
/// accepted although the deletion's attestation stays the latest.
5434
#[test]
5435
fn bookmarks_are_deleted_on_a_remote() {
5436
    hermetic();
5437
    let dir = tempfile::tempdir().unwrap();
5438
    let root = dir.path();
5439
    let origin = Repo::init(&root.join("origin")).unwrap();
5440
    let url = root.join("origin").to_string_lossy().to_string();
5441
    let mut repo = Repo::clone(&url, &root.join("r"))
5442
        .unwrap()
5443
        .with_home(root.join("home"));
5444
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5445
        .unwrap();
5446
    let r = root.join("r");
5447
    write(&r, "a.txt", b"a\n");
5448
    repo.commit("a", &[]).unwrap();
5449
    assert!(repo.push("origin", false).unwrap()[0].ok);
5450
    repo.bookmark_create("feature/x", None).unwrap();
5451
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5452
    assert!(origin.resolve_heads("feature/x").is_ok());
5453
5454
    let res = repo.push_delete("origin", "feature/x").unwrap();
5455
    assert!(res[0].ok, "{res:?}");
5456
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5457
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5458
    assert!(
5459
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5460
        "the deletion is attested"
5461
    );
5462
    assert!(
5463
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5464
        "the local bookmark stays"
5465
    );
5466
    assert!(!repo
5467
        .view()
5468
        .unwrap()
5469
        .remotes
5470
        .get("origin")
5471
        .is_some_and(|m| m.contains_key("feature/x")));
5472
5473
    // Pushing it again creates it again, past the deletion's serial.
5474
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5475
    assert!(res[0].ok, "{res:?}");
5476
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5477
5478
    // Nothing to delete, and never the remote's own bookmark.
5479
    assert!(repo.push_delete("origin", "nope").is_err());
5480
    let res = repo.push_delete("origin", "main").unwrap();
5481
    assert!(
5482
        !res[0].ok && res[0].reason.contains("default bookmark"),
5483
        "{res:?}"
5484
    );
5485
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5486
}
5487
5488
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5489
/// when the target has the same versions of the files it touches, and is
5490
/// refused, untouched, when it has others.
5491
#[test]
5492
fn switching_bookmarks_carries_uncommitted_work() {
5493
    hermetic();
5494
    let dir = tempfile::tempdir().unwrap();
5495
    let root = dir.path();
5496
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5497
    write(root, "a.txt", b"a\n");
5498
    write(root, "b.txt", b"b\n");
5499
    write(root, "gone.txt", b"gone\n");
5500
    repo.commit("base", &[]).unwrap();
5501
    repo.bookmark_create("feature", None).unwrap();
5502
    // Started on main, belongs on feature: edit, add, remove.
5503
    write(root, "a.txt", b"a\nmore\n");
5504
    write(root, "new.txt", b"new\n");
5505
    fs::remove_file(root.join("gone.txt")).unwrap();
5506
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5507
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5508
    assert_eq!(repo.config.bookmark, "feature");
5509
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5510
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5511
    assert!(!root.join("gone.txt").exists());
5512
    let snap = repo.snapshot("status").unwrap();
5513
    assert_eq!(
5514
        statuses(&snap),
5515
        vec![
5516
            ("a.txt".to_string(), ChangeStatus::Modified),
5517
            ("gone.txt".to_string(), ChangeStatus::Removed),
5518
            ("new.txt".to_string(), ChangeStatus::Added)
5519
        ]
5520
    );
5521
    repo.commit("the work", &[]).unwrap();
5522
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5523
5524
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5525
    repo.bookmark_switch("main", false).unwrap();
5526
    write(root, "b.txt", b"b on main\n");
5527
    repo.commit("b on main", &[]).unwrap();
5528
    repo.bookmark_switch("feature", false).unwrap();
5529
    write(root, "b.txt", b"b edited\n");
5530
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5531
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5532
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5533
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5534
}
5535
5536
/// Merging and checking out (feedback 3): a working copy without changes
5537
/// follows a merge whichever state it sat on; a refused checkout names
5538
/// what is in the way; `checkout --carry` takes the work along.
5539
#[test]
5540
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5541
    hermetic();
5542
    let dir = tempfile::tempdir().unwrap();
5543
    let root = dir.path();
5544
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5545
    write(root, "a.txt", b"a\n");
5546
    let h1 = repo.commit("a", &[]).unwrap();
5547
    write(root, "b.txt", b"b\n");
5548
    repo.commit("b", &[]).unwrap();
5549
    repo.bookmark_create("feature", None).unwrap();
5550
    repo.bookmark_switch("feature", false).unwrap();
5551
    write(root, "c.txt", b"c\n");
5552
    repo.commit("c on feature", &[]).unwrap();
5553
    repo.bookmark_switch("main", false).unwrap();
5554
    // The working copy sits on an older state than main's heads.
5555
    repo.checkout(&[h1], false, "checkout").unwrap();
5556
    assert!(!root.join("b.txt").exists());
5557
    let m = repo.merge("feature").unwrap();
5558
    assert!(m.checked_out, "a clean working copy follows the merge");
5559
    for f in ["a.txt", "b.txt", "c.txt"] {
5560
        assert!(root.join(f).exists(), "{f}");
5561
    }
5562
5563
    // A refusal says which paths are in the way and what to do.
5564
    fs::remove_file(root.join("b.txt")).unwrap();
5565
    write(root, "a.txt", b"a edited\n");
5566
    let err = repo
5567
        .checkout(&[h1], false, "checkout")
5568
        .unwrap_err()
5569
        .to_string();
5570
    assert!(
5571
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5572
        "{err}"
5573
    );
5574
    // --carry takes them along: h1 has a.txt as the base has it, and the
5575
    // removed b.txt is already as h1 has it (none), so that is no conflict
5576
    // either (oxygen#100).
5577
    let (_, carried) = repo
5578
        .checkout_carry(&[h1], "the first change", "checkout")
5579
        .unwrap();
5580
    assert_eq!(carried, vec!["a.txt"]);
5581
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5582
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5583
}
5584
5585
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5586
/// user identity not stored in a new repository yet is fine while its
5587
/// secret key is there; an added subrepo is listed as not committed yet.
5588
#[test]
5589
fn a_new_repository_is_healthy_before_its_first_commit() {
5590
    hermetic();
5591
    let dir = tempfile::tempdir().unwrap();
5592
    let root = dir.path();
5593
    let home = root.join("home");
5594
    let mut first = Repo::init(&root.join("first"))
5595
        .unwrap()
5596
        .with_home(home.clone());
5597
    let (key, _) = first
5598
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5599
        .unwrap();
5600
    let repo = Repo::init(&root.join("second"))
5601
        .unwrap()
5602
        .with_home(home.clone());
5603
    // Only the secret key: no identity object anywhere this repository sees.
5604
    let keys = repo.keys_dir.clone();
5605
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5606
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5607
    let r = repo.doctor(true);
5608
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5609
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5610
    assert!(id.message.contains("first signed change"), "{}", id.message);
5611
5612
    // A subrepo added and not committed yet is listed, pinned where it is.
5613
    let lib = root.join("lib");
5614
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5615
    write(&lib, "x.txt", b"x\n");
5616
    l.commit("x", &[]).unwrap();
5617
    let second = root.join("second");
5618
    write(&second, "a.txt", b"a\n");
5619
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5620
        .unwrap();
5621
    let subs = repo.subrepos().unwrap();
5622
    assert_eq!(subs.len(), 1);
5623
    assert_eq!(
5624
        (subs[0].path.as_str(), subs[0].committed),
5625
        ("deps/lib", false)
5626
    );
5627
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5628
    repo.commit("add lib", &[]).unwrap();
5629
    let subs = repo.subrepos().unwrap();
5630
    assert!(subs[0].committed, "committed now");
5631
}
5632
5633
/// Commit, diff, hunks and discard use the partial snapshot: a file
5634
/// unchanged since the manifest is neither read nor rendered, and showing
5635
/// a change renders only what it edits, the same as from a full base.
5636
#[cfg(unix)]
5637
#[test]
5638
fn commits_and_diffs_leave_unchanged_files_alone() {
5639
    use std::os::unix::fs::PermissionsExt;
5640
    hermetic();
5641
    let dir = tempfile::tempdir().unwrap();
5642
    let root = dir.path();
5643
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5644
    write(root, "big.txt", b"lots\nof\nlines\n");
5645
    write(root, "a.txt", b"one\ntwo\n");
5646
    repo.commit("base", &[]).unwrap();
5647
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5648
    for f in ["big.txt", "a.txt"] {
5649
        fs::File::options()
5650
            .write(true)
5651
            .open(root.join(f))
5652
            .unwrap()
5653
            .set_modified(old)
5654
            .unwrap();
5655
    }
5656
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5657
    // big.txt cannot be read at all from here on.
5658
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5659
5660
    write(root, "a.txt", b"one\nTWO\nthree\n");
5661
    let diff = repo.diff_files(None).unwrap();
5662
    assert_eq!(
5663
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5664
        ["a.txt"]
5665
    );
5666
    let (_, hunks) = repo.hunks().unwrap();
5667
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5668
    let h = repo.commit("edit a", &[]).unwrap();
5669
5670
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5671
    let c = repo.store().get_change(&h).unwrap();
5672
    let full = repo.load_state(&c.deps).unwrap();
5673
    let want = render_change(&c, &full, &full.materialize());
5674
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5675
    let (base, snap) = repo.change_base(&c).unwrap();
5676
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5677
5678
    // Discarding works the same way.
5679
    write(root, "a.txt", b"scratch\n");
5680
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5681
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5682
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5683
}
5684
5685
/// A replace conflict (spec §9.3) is settled by a change that writes one
5686
/// candidate, or new bytes, at the path when the caller names it; a plain
5687
/// snapshot of a checkout never settles it on its own.
5688
#[test]
5689
fn replace_conflicts_are_settled_when_asked() {
5690
    hermetic();
5691
    let dir = tempfile::tempdir().unwrap();
5692
    let root = dir.path();
5693
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5694
    let blob = |n: u8| {
5695
        let mut v = vec![0u8; 64];
5696
        v[1] = n;
5697
        v
5698
    };
5699
    write(root, "img.bin", &blob(1));
5700
    repo.commit("add img", &[]).unwrap();
5701
    repo.bookmark_create("other", None).unwrap();
5702
    write(root, "img.bin", &blob(2));
5703
    repo.commit("img two", &[]).unwrap();
5704
    repo.bookmark_switch("other", false).unwrap();
5705
    write(root, "img.bin", &blob(3));
5706
    repo.commit("img three", &[]).unwrap();
5707
    repo.bookmark_switch("main", false).unwrap();
5708
    repo.merge("other").unwrap();
5709
    let heads = repo.bookmark_heads().unwrap();
5710
    let merged = repo.load_state(&heads).unwrap().materialize();
5711
    assert!(
5712
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5713
        "a replace conflict"
5714
    );
5715
    // A snapshot of the checkout records nothing.
5716
    assert!(repo
5717
        .snapshot("status")
5718
        .unwrap()
5719
        .statuses
5720
        .iter()
5721
        .all(|s| s.path != "img.bin"));
5722
5723
    // Keeping candidate 3 settles it.
5724
    let author = repo.author();
5725
    let edits = [FileEdit {
5726
        path: "img.bin".into(),
5727
        content: Some(blob(3)),
5728
    }];
5729
    let c = repo
5730
        .build_change(&heads, &edits, "keep three", author)
5731
        .unwrap();
5732
    assert_eq!(c.kind, ChangeKind::Resolution);
5733
    let mut st = repo.load_state(&heads).unwrap();
5734
    for d in &c.deps {
5735
        assert!(st.contains(d));
5736
    }
5737
    assert!(
5738
        heads.iter().all(|h| c.deps.contains(h)),
5739
        "depends on both contributors"
5740
    );
5741
    st.add(c).unwrap();
5742
    let after = st.materialize();
5743
    assert!(!after.is_conflicted());
5744
    assert_eq!(
5745
        after.files["img.bin"].content,
5746
        FileContent::Opaque {
5747
            blobs: vec![Repo::blob_ref(&blob(3))]
5748
        }
5749
    );
5750
5751
    // New bytes settle it too.
5752
    let edits = [FileEdit {
5753
        path: "img.bin".into(),
5754
        content: Some(blob(9)),
5755
    }];
5756
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5757
    let mut st = repo.load_state(&heads).unwrap();
5758
    st.add(c).unwrap();
5759
    assert_eq!(
5760
        st.materialize().files["img.bin"].content,
5761
        FileContent::Opaque {
5762
            blobs: vec![Repo::blob_ref(&blob(9))]
5763
        }
5764
    );
5765
}
5766
5767
/// The history of a range of lines (spec §27): the changes that wrote
5768
/// or deleted its atoms, or deleted atoms from between them; edits outside
5769
/// the range and changes the range's lines survived are not in it.
5770
#[test]
5771
fn line_ranges_have_exact_histories() {
5772
    hermetic();
5773
    let dir = tempfile::tempdir().unwrap();
5774
    let root = dir.path();
5775
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5776
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5777
    let base = repo.commit("add f", &[]).unwrap();
5778
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5779
    let outside = repo.commit("change the import", &[]).unwrap();
5780
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5781
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5782
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5783
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5784
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5785
    let after = repo.commit("add b after a", &[]).unwrap();
5786
    let heads = repo.bookmark_heads().unwrap();
5787
5788
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5789
    let hist: Vec<ChangeHash> = repo
5790
        .line_history(&heads, "f.rs", 2, 4)
5791
        .unwrap()
5792
        .iter()
5793
        .map(|e| e.hash)
5794
        .collect();
5795
    for (h, what) in [
5796
        (base, "wrote it"),
5797
        (inside, "edited a line"),
5798
        (deleted, "deleted a line from inside"),
5799
    ] {
5800
        assert!(hist.contains(&h), "{what}");
5801
    }
5802
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5803
        assert!(!hist.contains(&h), "{what}");
5804
    }
5805
    assert_eq!(hist[0], deleted, "newest first");
5806
    // One line: only what touched it.
5807
    let one: Vec<ChangeHash> = repo
5808
        .line_history(&heads, "f.rs", 1, 1)
5809
        .unwrap()
5810
        .iter()
5811
        .map(|e| e.hash)
5812
        .collect();
5813
    assert!(one.contains(&outside) && !one.contains(&inside));
5814
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5815
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5816
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5817
}
5818
5819
#[test]
5820
fn receipts_are_kept_with_their_state_and_verified() {
5821
    use crate::receipt::{Receipt, SignedReceipt};
5822
    hermetic();
5823
    let dir = tempfile::tempdir().unwrap();
5824
    let root = dir.path();
5825
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5826
    write(root, "a.txt", b"1\n");
5827
    repo.commit("A", &[]).unwrap();
5828
    let heads = repo.bookmark_heads().unwrap();
5829
    let state = repo
5830
        .store()
5831
        .put_state(&StateObject::new(heads.clone()))
5832
        .unwrap();
5833
    let out = repo.store_blob(b"built\n").unwrap();
5834
    let receipt = Receipt {
5835
        job_name: "build".into(),
5836
        pipeline_hash: ObjectRef([1; 32]),
5837
        scope_tree_hash: ObjectRef([2; 32]),
5838
        inputs: vec![],
5839
        environment: ObjectRef([3; 32]),
5840
        outputs: vec![out],
5841
        exit_code: 0,
5842
        duration_ms: 42,
5843
    };
5844
    let sk = SecretKey::generate();
5845
    let runner = sk.identity("earth-1", "runner@earth", 1);
5846
    let sr = SignedReceipt::sign(
5847
        receipt.clone(),
5848
        repo.id().unwrap(),
5849
        state,
5850
        "demo#1",
5851
        &runner,
5852
        &sk,
5853
    );
5854
5855
    let r = repo.add_receipt(&sr).unwrap();
5856
    let found = repo.receipts(&heads).unwrap();
5857
    assert_eq!(found.len(), 1);
5858
    assert_eq!(found[0].attest, r);
5859
    assert_eq!(found[0].signed, sr);
5860
    assert!(found[0].problem.is_none() && !found[0].revoked);
5861
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5862
5863
    // Another repository's receipt, or a forged one, is refused.
5864
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5865
    assert!(repo
5866
        .add_receipt(&elsewhere)
5867
        .unwrap_err()
5868
        .to_string()
5869
        .contains("another repository"));
5870
    let mut forged = sr.clone();
5871
    forged.receipt.exit_code = 1;
5872
    assert!(repo
5873
        .add_receipt(&forged)
5874
        .unwrap_err()
5875
        .to_string()
5876
        .contains("does not verify"));
5877
5878
    // A receipt signed by a short-lived key keeps its certificate and the
5879
    // issuer's identity, and reads back with them (oxygenhub#241).
5880
    let hub_sk = SecretKey::generate();
5881
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
5882
    let job_sk = SecretKey::generate();
5883
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
5884
    let mut test_receipt = receipt.clone();
5885
    test_receipt.job_name = "test".into();
5886
    let plain = SignedReceipt::sign(
5887
        test_receipt,
5888
        repo.id().unwrap(),
5889
        state,
5890
        "demo#2",
5891
        &job,
5892
        &job_sk,
5893
    );
5894
    let now = plain.attest.hlc.wall_ms;
5895
    let cert = crate::cert::SignedCertificate::sign(
5896
        crate::cert::Certificate {
5897
            key: job.clone(),
5898
            issuer: hub.hash(),
5899
            subject: "repo:andy/demo:bookmark:main".into(),
5900
            claims: vec![],
5901
            scope: crate::identity::Scope::SEAL,
5902
            not_before: now - 1_000,
5903
            expires: now + 600_000,
5904
            grant: None,
5905
        },
5906
        &hub,
5907
        &hub_sk,
5908
    );
5909
    let certified = plain.with_certificate(cert, hub.clone());
5910
    repo.add_receipt(&certified).unwrap();
5911
    let found = repo.receipts(&heads).unwrap();
5912
    let got = found
5913
        .iter()
5914
        .find(|i| i.signed.receipt.job_name == "test")
5915
        .unwrap();
5916
    assert_eq!(got.signed, certified);
5917
    assert!(got.problem.is_none(), "{:?}", got.problem);
5918
5919
    // gc keeps the receipts, their runners, the certificate and its issuer,
5920
    // and the output while the state lives.
5921
    repo.gc(true).unwrap();
5922
    let found = repo.receipts(&heads).unwrap();
5923
    assert_eq!(found.len(), 2);
5924
    let got = found
5925
        .iter()
5926
        .find(|i| i.signed.receipt.job_name == "test")
5927
        .unwrap();
5928
    assert_eq!(got.signed, certified, "the certificate survives gc");
5929
    assert!(got.problem.is_none());
5930
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5931
    assert!(repo.fsck().unwrap().problems.is_empty());
5932
}
5933
5934
#[test]
5935
fn approvals_are_kept_with_their_state_and_survive_gc() {
5936
    hermetic();
5937
    let dir = tempfile::tempdir().unwrap();
5938
    let root = dir.path();
5939
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5940
    write(root, "a.txt", b"1\n");
5941
    repo.commit("A", &[]).unwrap();
5942
    let heads = repo.bookmark_heads().unwrap();
5943
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
5944
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
5945
    let sk = SecretKey::generate();
5946
    let andy = sk.identity("Andy", "[email protected]", 1);
5947
    let statement = crate::approval::Statement {
5948
        repo: repo.id().unwrap(),
5949
        run: "https://hub.example/andy/infra/flow/8".into(),
5950
        job: "apply".into(),
5951
        job_hash: ObjectRef([1; 32]),
5952
        state,
5953
        inputs: vec![plan],
5954
        environment: "prod".into(),
5955
        approve: true,
5956
    };
5957
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
5958
    let r = repo.add_approval(&sa).unwrap();
5959
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
5960
    // Another repository's approval, or a changed one, is refused.
5961
    let elsewhere = crate::approval::SignedApproval::sign(
5962
        &crate::approval::Statement {
5963
            repo: [0; 16],
5964
            ..statement.clone()
5965
        },
5966
        &andy,
5967
        &sk,
5968
    );
5969
    assert!(repo
5970
        .add_approval(&elsewhere)
5971
        .unwrap_err()
5972
        .to_string()
5973
        .contains("another repository"));
5974
    let mut forged = sa.clone();
5975
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
5976
        *environment = "dev".into();
5977
    }
5978
    assert!(repo
5979
        .add_approval(&forged)
5980
        .unwrap_err()
5981
        .to_string()
5982
        .contains("does not verify"));
5983
    // gc keeps it, its signature and its signer while the state lives.
5984
    repo.gc(true).unwrap();
5985
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
5986
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
5987
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
5988
    assert!(repo.fsck().unwrap().problems.is_empty());
5989
}
5990
5991
#[test]
5992
fn status_leaves_an_unchanged_manifest_alone() {
5993
    hermetic();
5994
    let dir = tempfile::tempdir().unwrap();
5995
    let root = dir.path();
5996
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5997
    write(root, "a.txt", b"1\n");
5998
    write(root, "b.txt", b"2\n");
5999
    repo.commit("A", &[]).unwrap();
6000
    // Files last touched well outside the racy window.
6001
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6002
    for f in ["a.txt", "b.txt"] {
6003
        fs::File::options()
6004
            .write(true)
6005
            .open(root.join(f))
6006
            .unwrap()
6007
            .set_modified(old)
6008
            .unwrap();
6009
    }
6010
    repo.snapshot_status("status").unwrap();
6011
    let path = repo.manifest_path();
6012
    let first = fs::read(&path).unwrap();
6013
    repo.snapshot_status("status").unwrap();
6014
    assert_eq!(
6015
        fs::read(&path).unwrap(),
6016
        first,
6017
        "an unchanged tree does not rewrite the manifest"
6018
    );
6019
    // A change rewrites it.
6020
    write(root, "a.txt", b"1\n2\n");
6021
    repo.snapshot_status("status").unwrap();
6022
    assert_ne!(fs::read(&path).unwrap(), first);
6023
}
6024
6025
#[test]
6026
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6027
    hermetic();
6028
    let dir = tempfile::tempdir().unwrap();
6029
    let root = dir.path();
6030
    let origin_path = root.join("origin");
6031
    Repo::init(&origin_path).unwrap();
6032
    let origin_url = origin_path.to_string_lossy().to_string();
6033
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6034
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6035
    write(&root.join("a"), "big.txt", big.as_bytes());
6036
    write(&root.join("a"), "small.txt", b"small\n");
6037
    let h1 = a.commit("large", &[]).unwrap();
6038
    let (_, body) = a.store().get(&h1).unwrap();
6039
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6040
    assert!(a.push("origin", false).unwrap()[0].ok);
6041
6042
    // A clone reads the text from the blobs that came with the change.
6043
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6044
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6045
    // An edit in the middle of the stored insert is an ordinary change.
6046
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6047
    write(&root.join("b"), "big.txt", edited.as_bytes());
6048
    let h2 = b.commit("edit", &[]).unwrap();
6049
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6050
    assert!(b.push("origin", false).unwrap()[0].ok);
6051
    assert!(a.pull("origin").unwrap().checked_out);
6052
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6053
    assert_eq!(
6054
        a.fsck().unwrap().errors(),
6055
        0,
6056
        "{:?}",
6057
        a.fsck().unwrap().problems
6058
    );
6059
6060
    // With zero retention gc keeps the text blobs of every kept change.
6061
    let mut a = Repo::open(&root.join("a")).unwrap();
6062
    a.config.set("core.op-retention", "0").unwrap();
6063
    a.save_config().unwrap();
6064
    let a = Repo::open(&root.join("a")).unwrap();
6065
    a.gc(true).unwrap();
6066
    let a = Repo::open(&root.join("a")).unwrap();
6067
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6068
    assert_eq!(
6069
        a.fsck().unwrap().errors(),
6070
        0,
6071
        "{:?}",
6072
        a.fsck().unwrap().problems
6073
    );
6074
    // And a clone of the packed repository reads them from its packs.
6075
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6076
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6077
    drop(c);
6078
}
6079
6080
#[test]
6081
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6082
    hermetic();
6083
    let dir = tempfile::tempdir().unwrap();
6084
    let root = dir.path();
6085
    let repo = Repo::init(root).unwrap();
6086
    write(root, "a.txt", b"a\n");
6087
    let a = repo.commit("a", &[]).unwrap();
6088
    write(root, "b.txt", b"b\n");
6089
    repo.commit("b", &[]).unwrap();
6090
    let (x, op) = repo.head_op().unwrap();
6091
    let ws = *op.view.workspaces.keys().next().unwrap();
6092
    let mut one = op.view.clone();
6093
    one.workspaces.insert(ws, a);
6094
    let mut two = op.view.clone();
6095
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6096
    let first = repo.record_op(&[x], "one", one).unwrap();
6097
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6098
    assert!(
6099
        e.to_string()
6100
            .contains("changed this working copy at the same time"),
6101
        "{e}"
6102
    );
6103
    assert_eq!(
6104
        repo.head_op().unwrap().0,
6105
        first,
6106
        "the second is not recorded"
6107
    );
6108
}
6109
6110
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6111
/// rewrote the working copy recorded the half-written files as edits, and
6112
/// its view replaced the switch's.
6113
#[test]
6114
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6115
    hermetic();
6116
    let dir = tempfile::tempdir().unwrap();
6117
    let root = dir.path().to_path_buf();
6118
    let mut repo = Repo::init(&root).unwrap();
6119
    write(&root, "keep.txt", b"keep\n");
6120
    repo.commit("base", &[]).unwrap();
6121
    repo.bookmark_create("small", None).unwrap();
6122
    for i in 0..300 {
6123
        write(
6124
            &root,
6125
            &format!("many/f{i}.txt"),
6126
            format!("file {i}\n").as_bytes(),
6127
        );
6128
    }
6129
    repo.commit("many", &[]).unwrap();
6130
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6131
    let watcher = {
6132
        let (root, stop) = (root.clone(), stop.clone());
6133
        std::thread::spawn(move || {
6134
            let r = Repo::open(&root).unwrap();
6135
            let mut ran = 0;
6136
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6137
                if r.snapshot_status("oxy status").is_ok() {
6138
                    ran += 1;
6139
                }
6140
            }
6141
            ran
6142
        })
6143
    };
6144
    for i in 0..20 {
6145
        let to = if i % 2 == 0 { "small" } else { "main" };
6146
        repo.bookmark_switch(to, false).unwrap();
6147
    }
6148
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6149
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6150
    // Back on main, clean, with every file where main has it.
6151
    let repo = Repo::open(&root).unwrap();
6152
    let s = repo.snapshot_status("oxy status").unwrap();
6153
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6154
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6155
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6156
    assert!(root.join("many/f299.txt").exists());
6157
}
6158
6159
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6160
/// put a subrepo that was ahead of its pin back at the pin and moved the
6161
/// subrepo's own bookmark backwards.
6162
#[test]
6163
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6164
    hermetic();
6165
    let dir = tempfile::tempdir().unwrap();
6166
    let root = dir.path();
6167
    Repo::init(&root.join("lib-origin")).unwrap();
6168
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6169
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6170
    write(&root.join("lib"), "lib.txt", b"v1\n");
6171
    lib.commit("lib v1", &[]).unwrap();
6172
    assert!(lib.push("origin", false).unwrap()[0].ok);
6173
6174
    let app_dir = root.join("app");
6175
    let mut app = Repo::init(&app_dir).unwrap();
6176
    write(&app_dir, "main.txt", b"app\n");
6177
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6178
    app.commit("app with lib", &[]).unwrap();
6179
    app.bookmark_create("feature", None).unwrap();
6180
6181
    // New work in the subrepo, not yet pinned by the parent.
6182
    let nested_dir = app_dir.join("libs/lib");
6183
    let nested = Repo::open(&nested_dir).unwrap();
6184
    write(&nested_dir, "new.txt", b"new\n");
6185
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6186
    drop(nested);
6187
6188
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6189
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6190
    let nested = Repo::open(&nested_dir).unwrap();
6191
    assert!(
6192
        nested.bookmark_heads().unwrap().contains(&l2),
6193
        "its bookmark kept its work"
6194
    );
6195
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6196
    let s = app.snapshot("status").unwrap();
6197
    assert_eq!(
6198
        statuses(&s),
6199
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6200
    );
6201
}
6202
6203
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6204
/// moving `main` to a change this clone had pushed on another bookmark,
6205
/// the first `pull` said "Already up to date" while `main` was behind.
6206
#[test]
6207
fn pull_takes_a_remote_move_to_changes_already_here() {
6208
    hermetic();
6209
    let dir = tempfile::tempdir().unwrap();
6210
    let root = dir.path();
6211
    let origin_path = root.join("origin");
6212
    let origin = Repo::init(&origin_path).unwrap();
6213
    let url = origin_path.to_string_lossy().to_string();
6214
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6215
    write(&root.join("b"), "base.txt", b"base\n");
6216
    b.commit("base", &[]).unwrap();
6217
    assert!(b.push("origin", false).unwrap()[0].ok);
6218
6219
    // A feature bookmark with one change, pushed.
6220
    b.bookmark_create("feat", None).unwrap();
6221
    b.bookmark_switch("feat", false).unwrap();
6222
    write(&root.join("b"), "x.txt", b"x\n");
6223
    let x = b.commit("x", &[]).unwrap();
6224
    assert!(b.push("origin", false).unwrap()[0].ok);
6225
    b.bookmark_switch("main", false).unwrap();
6226
6227
    // The remote lands it: its main moves to the feature's state.
6228
    let feat = origin
6229
        .store()
6230
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6231
        .unwrap()
6232
        .heads;
6233
    origin.bookmark_set("main", &feat).unwrap();
6234
6235
    let r = b.pull("origin").unwrap();
6236
    assert!(r.changed, "{r:?}");
6237
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6238
    let main = b
6239
        .bookmarks()
6240
        .unwrap()
6241
        .into_iter()
6242
        .find(|m| m.name == "main")
6243
        .unwrap();
6244
    assert_eq!(main.behind, Some(0), "{main:?}");
6245
}
6246
6247
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6248
/// to one only the remote has makes a local bookmark from it; a pull moves
6249
/// every local bookmark the remote has too; a clone checks out the remote's
6250
/// default bookmark.
6251
#[test]
6252
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6253
    hermetic();
6254
    let dir = tempfile::tempdir().unwrap();
6255
    let root = dir.path();
6256
    let origin_path = root.join("origin");
6257
    let mut origin = Repo::init(&origin_path).unwrap();
6258
    let url = origin_path.to_string_lossy().to_string();
6259
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6260
    write(&root.join("a"), "base.txt", b"base\n");
6261
    a.commit("base", &[]).unwrap();
6262
    assert!(a.push("origin", false).unwrap()[0].ok);
6263
    a.bookmark_create("develop", None).unwrap();
6264
    a.bookmark_switch("develop", false).unwrap();
6265
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6266
    let d1 = a.commit("d1", &[]).unwrap();
6267
    assert!(a.push("origin", false).unwrap()[0].ok);
6268
6269
    // A clone has main only; origin/develop is a name all the same.
6270
    let c_root = root.join("c");
6271
    let mut c = Repo::clone(&url, &c_root).unwrap();
6272
    assert_eq!(c.config.bookmark, "main");
6273
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6274
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6275
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6276
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6277
6278
    // Switching makes the local bookmark from origin's.
6279
    c.bookmark_switch("develop", false).unwrap();
6280
    assert_eq!(c.config.bookmark, "develop");
6281
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6282
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6283
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6284
    assert!(c.bookmark_switch("nowhere", false).is_err());
6285
6286
    // Both bookmarks move on the remote; one pull takes both.
6287
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6288
    let d2 = a.commit("d2", &[]).unwrap();
6289
    assert!(a.push("origin", false).unwrap()[0].ok);
6290
    a.bookmark_switch("main", false).unwrap();
6291
    write(&root.join("a"), "m.txt", b"m\n");
6292
    let m = a.commit("m", &[]).unwrap();
6293
    assert!(a.push("origin", false).unwrap()[0].ok);
6294
    let r = c.pull("origin").unwrap();
6295
    assert!(r.changed && r.checked_out, "{r:?}");
6296
    assert_eq!(r.heads, vec![d2]);
6297
    assert_eq!(r.others, vec!["main".to_string()]);
6298
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6299
    assert_eq!(
6300
        fs::read(c_root.join("base.txt")).unwrap(),
6301
        b"base\nd1\nd2\n"
6302
    );
6303
    let again = c.pull("origin").unwrap();
6304
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6305
6306
    // A clone checks out the remote's default bookmark.
6307
    origin.config.set("workspace.bookmark", "develop").unwrap();
6308
    origin.save_config().unwrap();
6309
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6310
    assert_eq!(e.config.bookmark, "develop");
6311
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6312
    let reopened = Repo::open(&root.join("e")).unwrap();
6313
    assert_eq!(reopened.config.bookmark, "develop");
6314
    // REMOTE/NAME names the remote's bookmark to switch to.
6315
    let mut e = reopened;
6316
    e.bookmark_switch("origin/main", false).unwrap();
6317
    assert_eq!(e.config.bookmark, "main");
6318
    assert!(e.bookmark_heads().unwrap().contains(&m));
6319
}
6320
6321
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6322
/// op restore goes back to an operation, files included, and undo takes
6323
/// the restore back whole; op revert undoes one operation alone; each
6324
/// operation's changes are described from the views.
6325
#[test]
6326
fn operations_can_be_read_restored_and_reverted() {
6327
    hermetic();
6328
    let dir = tempfile::tempdir().unwrap();
6329
    let root = dir.path();
6330
    let repo = Repo::init(root).unwrap();
6331
    write(root, "a.txt", b"a\n");
6332
    let first = repo.commit("first", &[]).unwrap();
6333
    write(root, "a.txt", b"a\nb\n");
6334
    let second = repo.commit("second", &[]).unwrap();
6335
    let at_second = repo.head_op().unwrap().0.to_hex();
6336
    repo.bookmark_create("keep", None).unwrap();
6337
    let created = repo.head_op().unwrap().0.to_hex();
6338
    write(root, "n.txt", b"n\n");
6339
    let third = repo.commit("third", &[]).unwrap();
6340
6341
    // What each operation changed.
6342
    let ops = repo.op_log().unwrap();
6343
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6344
    assert!(
6345
        changes
6346
            .iter()
6347
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6348
        "{changes:?}"
6349
    );
6350
    assert!(changes
6351
        .iter()
6352
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6353
6354
    // Reading at an earlier operation.
6355
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6356
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6357
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6358
    write(root, "z.txt", b"z\n");
6359
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6360
    fs::remove_file(root.join("z.txt")).unwrap();
6361
    assert!(repo.resolve_op("zz").is_err());
6362
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
6363
6364
    // Restore goes back, files and all; undo takes it back whole.
6365
    repo.op_restore(&at_second, false).unwrap();
6366
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
6367
    assert!(!root.join("n.txt").exists());
6368
    repo.undo().unwrap();
6369
    let mut heads = repo.bookmark_heads().unwrap();
6370
    heads.sort();
6371
    let mut want = vec![second, third];
6372
    want.sort();
6373
    assert_eq!(heads, want);
6374
    assert!(
6375
        root.join("n.txt").exists(),
6376
        "the files came back with the undo"
6377
    );
6378
6379
    // Revert the bookmark's creation alone: the commit after it stays.
6380
    let r = repo.op_revert(&created).unwrap();
6381
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6382
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6383
    assert!(repo
6384
        .load_state(&repo.bookmark_heads().unwrap())
6385
        .unwrap()
6386
        .contains(&third));
6387
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6388
    let _ = first;
6389
}
6390
6391
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6392
/// from the status cache while every file is as the snapshot left it, and
6393
/// from a snapshot again as soon as one is not.
6394
#[test]
6395
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6396
    hermetic();
6397
    let dir = tempfile::tempdir().unwrap();
6398
    let root = dir.path();
6399
    let repo = Repo::init(root).unwrap();
6400
    write(root, "a.txt", b"a\n");
6401
    write(root, "b.txt", b"b\n");
6402
    repo.commit("base", &[]).unwrap();
6403
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6404
6405
    write(root, "a.txt", b"a\nmore\n");
6406
    assert_eq!(
6407
        repo.status_by_manifest().unwrap(),
6408
        None,
6409
        "no snapshot of the edit yet"
6410
    );
6411
    let snap = repo.snapshot_status("oxy status").unwrap();
6412
    assert_eq!(snap.statuses.len(), 1);
6413
    let cached = repo
6414
        .status_by_manifest()
6415
        .unwrap()
6416
        .expect("answered from the cache");
6417
    assert_eq!(cached.len(), 1);
6418
    assert_eq!(
6419
        (cached[0].path.as_str(), cached[0].status),
6420
        ("a.txt", ChangeStatus::Modified)
6421
    );
6422
6423
    // Any further change sends status back to a snapshot.
6424
    write(root, "a.txt", b"a\nmore\nand more\n");
6425
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6426
    repo.snapshot_status("oxy status").unwrap();
6427
    assert!(repo.status_by_manifest().unwrap().is_some());
6428
    write(root, "new.txt", b"n\n");
6429
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6430
    fs::remove_file(root.join("new.txt")).unwrap();
6431
    assert!(
6432
        repo.status_by_manifest().unwrap().is_some(),
6433
        "back as it was"
6434
    );
6435
    fs::remove_file(root.join("b.txt")).unwrap();
6436
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6437
    write(root, "b.txt", b"b\n");
6438
6439
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6440
    repo.snapshot_status("oxy status").unwrap();
6441
    repo.commit("more", &[]).unwrap();
6442
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6443
}
6444
6445
/// oxygen#41: while the status cache holds, the working copy's diff is
6446
/// rendered from the stored working-copy change, and says exactly what a
6447
/// snapshot's diff says.
6448
#[test]
6449
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6450
    hermetic();
6451
    let dir = tempfile::tempdir().unwrap();
6452
    let root = dir.path();
6453
    let repo = Repo::init(root).unwrap();
6454
    write(root, "a.txt", b"one\ntwo\nthree\n");
6455
    write(root, "gone.txt", b"bye\n");
6456
    repo.commit("base", &[]).unwrap();
6457
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6458
    write(root, "new.txt", b"hello\n");
6459
    fs::remove_file(root.join("gone.txt")).unwrap();
6460
    let snap = repo.snapshot_status("oxy status").unwrap();
6461
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6462
    assert!(
6463
        repo.status_by_manifest().unwrap().is_some(),
6464
        "the cache holds"
6465
    );
6466
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6467
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6468
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6469
6470
    // Committed, nothing changes: the diff is empty without loading the
6471
    // base (oxygen#94), and the same as rendering it.
6472
    repo.commit("all", &[]).unwrap();
6473
    repo.snapshot_status("oxy status").unwrap();
6474
    assert!(repo.status_by_manifest().unwrap().is_some());
6475
    assert!(repo
6476
        .working_copy_with_base_unless_unchanged()
6477
        .unwrap()
6478
        .is_none());
6479
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6480
    assert_eq!(render_change(&wc, &base, &snapshot), "");
6481
    assert!(repo.diff_files(None).unwrap().is_empty());
6482
}
6483
6484
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6485
/// while none has moved, the check stats the tracked files without listing
6486
/// the tree, and a file added or removed anywhere moves its directory's
6487
/// time, so the tree is listed again.
6488
#[test]
6489
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6490
    hermetic();
6491
    let dir = tempfile::tempdir().unwrap();
6492
    let root = dir.path();
6493
    let repo = Repo::init(root).unwrap();
6494
    write(root, "a.txt", b"a\n");
6495
    write(root, "sub/deep/b.txt", b"b\n");
6496
    repo.commit("base", &[]).unwrap();
6497
    // Out of the racy window: every file and directory a minute old.
6498
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6499
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6500
        fs::File::open(root.join(p))
6501
            .unwrap()
6502
            .set_modified(old)
6503
            .unwrap();
6504
    }
6505
    repo.snapshot_status("oxy status").unwrap();
6506
    repo.write_manifest(false, false).unwrap();
6507
    let m = repo.read_manifest().unwrap().unwrap().2;
6508
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6509
    assert_eq!(
6510
        repo.disk_differs_by_dirs(&m),
6511
        Some(false),
6512
        "no listing needed"
6513
    );
6514
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6515
6516
    // A same-size edit with a new time: found by its stat.
6517
    write(root, "sub/deep/b.txt", b"c\n");
6518
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6519
    write(root, "sub/deep/b.txt", b"b\n");
6520
    fs::File::open(root.join("sub/deep/b.txt"))
6521
        .unwrap()
6522
        .set_modified(old)
6523
        .unwrap();
6524
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6525
6526
    // A new file moves its directory's time: the tree must be listed.
6527
    write(root, "sub/deep/new.txt", b"n\n");
6528
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6529
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6530
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6531
    // A removed one too.
6532
    fs::remove_file(root.join("a.txt")).unwrap();
6533
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6534
}
6535
6536
/// oxygen#41: a commit right after a status takes the snapshot the status
6537
/// left (the status cache holds) rather than walking again, and commits
6538
/// exactly what a snapshot would have.
6539
#[test]
6540
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6541
    hermetic();
6542
    let dir = tempfile::tempdir().unwrap();
6543
    let root = dir.path();
6544
    let repo = Repo::init(root).unwrap();
6545
    write(root, "a.txt", b"a\nb\n");
6546
    write(root, ".oxyattributes", b"*.bin binary\n");
6547
    repo.commit("base", &[]).unwrap();
6548
    write(root, "a.txt", b"a\nB\n");
6549
    write(root, "new.txt", b"new\n");
6550
    let snap = repo.snapshot_status("oxy status").unwrap();
6551
    let cached = repo
6552
        .snapshot_from_cache()
6553
        .unwrap()
6554
        .expect("the cache holds");
6555
    assert_eq!(cached.wc_hash, snap.wc_hash);
6556
    assert_eq!(cached.statuses, snap.statuses);
6557
    assert!(
6558
        !cached.attributes.is_empty(),
6559
        "the .oxyattributes file was read"
6560
    );
6561
    let h = repo.commit("edit", &[]).unwrap();
6562
    let c = repo.store().get_change(&h).unwrap();
6563
    assert_eq!(
6564
        c.tree_ops.len() + c.edits.len(),
6565
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6566
    );
6567
    assert_eq!(
6568
        repo.status_by_manifest().unwrap(),
6569
        Some(vec![]),
6570
        "clean after the commit"
6571
    );
6572
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6573
}
6574
6575
/// oxygen#41: a clean check that verified racy entries restamps the
6576
/// manifest, so later checks can trust them, and a same-size rewrite
6577
/// straight afterwards is still found: entries within two seconds of the
6578
/// new time stay racy.
6579
#[test]
6580
fn a_verified_clean_check_restamps_the_manifest_safely() {
6581
    hermetic();
6582
    let dir = tempfile::tempdir().unwrap();
6583
    let root = dir.path();
6584
    let repo = Repo::init(root).unwrap();
6585
    write(root, "a.txt", b"one\n");
6586
    repo.commit("one", &[]).unwrap();
6587
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6588
    assert!(repo.clean_by_manifest().unwrap());
6589
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6590
    assert!(after > before, "restamped");
6591
    write(root, "a.txt", b"two\n");
6592
    assert!(
6593
        !repo.clean_by_manifest().unwrap(),
6594
        "a same-size rewrite is still seen"
6595
    );
6596
}
6597
6598
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6599
/// stored insert's text blob only when it builds that file's graph, and
6600
/// builds the same graph a full load does.
6601
#[test]
6602
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6603
    hermetic();
6604
    let dir = tempfile::tempdir().unwrap();
6605
    let root = dir.path();
6606
    let repo = Repo::init(root).unwrap();
6607
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6608
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6609
    write(root, "big.txt", big.as_bytes());
6610
    write(root, "other.txt", other.as_bytes());
6611
    let h = repo.commit("two large files", &[]).unwrap();
6612
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6613
    let h2 = repo.commit("append", &[]).unwrap();
6614
6615
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6616
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6617
        FileContent::Text { bytes, .. } => bytes.clone(),
6618
        other => panic!("{other:?}"),
6619
    };
6620
    // Built on demand, every graph renders as the full load's.
6621
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6622
    let big_node = full.files["big.txt"].node;
6623
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6624
    repo.load_all_graphs(&mut hist).unwrap();
6625
    let rendered = hist.materialize();
6626
    for p in ["big.txt", "other.txt"] {
6627
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6628
    }
6629
6630
    // Without other.txt's text blob, history still loads and big.txt still
6631
    // builds: nothing read the other text.
6632
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6633
    assert_eq!(texts.len(), 2);
6634
    let content = |r: &ObjectRef| -> Vec<u8> {
6635
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6636
        blob.chunks
6637
            .iter()
6638
            .flat_map(|c| repo.store().get(c).unwrap().1)
6639
            .collect()
6640
    };
6641
    let other_text = texts
6642
        .iter()
6643
        .filter_map(|t| match t {
6644
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6645
            _ => None,
6646
        })
6647
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6648
        .unwrap();
6649
    repo.store().remove_loose_for_test(&other_text).unwrap();
6650
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6651
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6652
    assert!(repo
6653
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6654
        .is_err());
6655
}
6656
6657
/// oxygen#35: the first status after a commit read and rendered every
6658
/// file (79 s and more than 14 GB on the Linux tree), because the
6659
/// manifest had no graph keys for files the commit added.
6660
#[test]
6661
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6662
    use std::os::unix::fs::PermissionsExt;
6663
    hermetic();
6664
    let dir = tempfile::tempdir().unwrap();
6665
    let root = dir.path();
6666
    let repo = Repo::init(root).unwrap();
6667
    let files = ["a.txt", "b.txt", "d/c.txt"];
6668
    for p in files {
6669
        write(root, p, format!("{p}\n").as_bytes());
6670
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6671
        fs::File::options()
6672
            .write(true)
6673
            .open(root.join(p))
6674
            .unwrap()
6675
            .set_modified(old)
6676
            .unwrap();
6677
    }
6678
    repo.commit("added", &[]).unwrap();
6679
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6680
    assert!(
6681
        m.entries.values().all(|e| e.graph.is_some()),
6682
        "keys recorded at commit"
6683
    );
6684
    // Unreadable files prove the next status reads none of them.
6685
    for p in files {
6686
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6687
    }
6688
    let snap = repo.snapshot_status("status").unwrap();
6689
    for p in files {
6690
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6691
    }
6692
    assert!(!snap.changed && snap.statuses.is_empty());
6693
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6694
}
6695
6696
/// oxygen#35: a checkout reads, renders and writes only the files whose
6697
/// graphs differ, and renders the rest a batch at a time.
6698
#[test]
6699
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6700
    use std::os::unix::fs::PermissionsExt;
6701
    hermetic();
6702
    let dir = tempfile::tempdir().unwrap();
6703
    let root = dir.path();
6704
    let origin = root.join("origin");
6705
    let mut repo = Repo::init(&origin).unwrap();
6706
    // More files than one batch holds.
6707
    let n = 2100;
6708
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6709
    for i in 0..n {
6710
        let p = format!("f/{i:04}.txt");
6711
        write(&origin, &p, format!("file {i}\n").as_bytes());
6712
        fs::File::options()
6713
            .write(true)
6714
            .open(origin.join(&p))
6715
            .unwrap()
6716
            .set_modified(old)
6717
            .unwrap();
6718
    }
6719
    repo.commit("many", &[]).unwrap();
6720
    repo.bookmark_create("feature", None).unwrap();
6721
    repo.bookmark_switch("feature", false).unwrap();
6722
    write(&origin, "f/0007.txt", b"changed\n");
6723
    repo.commit("one change", &[]).unwrap();
6724
6725
    // Switching back to main must not read the unchanged files.
6726
    for i in 0..n {
6727
        if i != 7 {
6728
            let p = origin.join(format!("f/{i:04}.txt"));
6729
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6730
        }
6731
    }
6732
    let r = repo.bookmark_switch("main", false).unwrap();
6733
    for i in 0..n {
6734
        let p = origin.join(format!("f/{i:04}.txt"));
6735
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6736
    }
6737
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6738
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6739
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6740
6741
    // A clone renders every file, across batches.
6742
    let c = root.join("clone");
6743
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6744
    for i in [0, 2047, 2048, n - 1] {
6745
        assert_eq!(
6746
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6747
            format!("file {i}\n").as_bytes()
6748
        );
6749
    }
6750
    let cloned = Repo::open(&c).unwrap();
6751
    assert!(cloned
6752
        .snapshot_status("status")
6753
        .unwrap()
6754
        .statuses
6755
        .is_empty());
6756
}
6757
6758
/// A file written just before the manifest (inside the racy window) is
6759
/// checked by its hash: trusted when equal, caught when edited in place
6760
/// with the same size and time.
6761
#[test]
6762
fn a_racy_manifest_entry_is_checked_by_hash() {
6763
    hermetic();
6764
    let dir = tempfile::tempdir().unwrap();
6765
    let root = dir.path();
6766
    let repo = Repo::init(root).unwrap();
6767
    write(root, "a.txt", b"one\n");
6768
    repo.commit("fresh", &[]).unwrap();
6769
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6770
    let t = fs::metadata(root.join("a.txt"))
6771
        .unwrap()
6772
        .modified()
6773
        .unwrap();
6774
    write(root, "a.txt", b"two\n");
6775
    fs::File::options()
6776
        .write(true)
6777
        .open(root.join("a.txt"))
6778
        .unwrap()
6779
        .set_modified(t)
6780
        .unwrap();
6781
    assert!(
6782
        !repo.clean_by_manifest().unwrap(),
6783
        "same size and time, other bytes"
6784
    );
6785
    assert_eq!(
6786
        statuses(&repo.snapshot_status("status").unwrap()),
6787
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6788
    );
6789
}
6790
6791
/// A fetch on one machine moves changes as stored, text blobs among the
6792
/// objects; a change whose text blob did not come is refused, not stored.
6793
#[test]
6794
fn a_raw_bundle_without_a_changes_text_is_refused() {
6795
    hermetic();
6796
    let dir = tempfile::tempdir().unwrap();
6797
    let root = dir.path();
6798
    let a = Repo::init(&root.join("a")).unwrap();
6799
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6800
    write(&root.join("a"), "big.txt", big.as_bytes());
6801
    let h = a.commit("big", &[]).unwrap();
6802
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6803
    assert_eq!(bundle.raw_changes.len(), 1);
6804
    assert!(bundle.changes.is_empty());
6805
    let b = Repo::init(&root.join("b")).unwrap();
6806
    let mut without = bundle.clone();
6807
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6808
    let e = b.import_bundle(&without, false).unwrap_err();
6809
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6810
    assert!(!b.store().has(&h));
6811
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6812
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6813
}
6814
6815
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6816
/// again was a second node for one Git path, so a file moved into it on
6817
/// another line, where the first node still stood, ended up in two places.
6818
/// An import now brings the directory back rather than make a new one.
6819
#[test]
6820
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6821
    hermetic();
6822
    if std::process::Command::new("git")
6823
        .arg("--version")
6824
        .output()
6825
        .is_err()
6826
    {
6827
        eprintln!("git not installed; skipping");
6828
        return;
6829
    }
6830
    let dir = tempfile::tempdir().unwrap();
6831
    let root = dir.path();
6832
    let g = root.join("src.git");
6833
    fs::create_dir_all(&g).unwrap();
6834
    let git = |args: &[&str]| -> String {
6835
        let out = std::process::Command::new("git")
6836
            .arg("-C")
6837
            .arg(&g)
6838
            .args([
6839
                "-c",
6840
                "user.name=Grace",
6841
                "-c",
6842
                "[email protected]",
6843
                "-c",
6844
                "commit.gpgsign=false",
6845
            ])
6846
            .args(args)
6847
            .output()
6848
            .unwrap();
6849
        assert!(
6850
            out.status.success(),
6851
            "git {args:?}: {}",
6852
            String::from_utf8_lossy(&out.stderr)
6853
        );
6854
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6855
    };
6856
    git(&["init", "-q", "-b", "main"]);
6857
    write(&g, "d/a.txt", b"a\n");
6858
    write(&g, "c/x.txt", b"x\n");
6859
    git(&["add", "."]);
6860
    git(&["commit", "-qm", "base"]);
6861
    // One line: move x into d while d still stands.
6862
    git(&["checkout", "-qb", "side"]);
6863
    git(&["mv", "c/x.txt", "d/x.txt"]);
6864
    git(&["commit", "-qm", "x into d"]);
6865
    // The other: d goes, comes back, and x moves into it too.
6866
    git(&["checkout", "-q", "main"]);
6867
    git(&["rm", "-q", "d/a.txt"]);
6868
    git(&["commit", "-qm", "d goes"]);
6869
    write(&g, "d/b.txt", b"b\n");
6870
    git(&["add", "."]);
6871
    git(&["commit", "-qm", "d comes back"]);
6872
    git(&["mv", "c/x.txt", "d/x.txt"]);
6873
    git(&["commit", "-qm", "x into d again"]);
6874
    git(&["merge", "-q", "--no-edit", "side"]);
6875
6876
    let repo = Repo::init(&root.join("o")).unwrap();
6877
    repo.import_git(&g, "main").unwrap();
6878
    let v = repo.verify_git_import(&g, "main").unwrap();
6879
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6880
    let st = repo
6881
        .load_state_history(&repo.bookmark_heads().unwrap())
6882
        .unwrap();
6883
    let view = st.tree().view();
6884
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6885
    // The directory is the one the first commit made.
6886
    // Commits made in one second tie on time: find the first by its message.
6887
    let first = repo
6888
        .log()
6889
        .unwrap()
6890
        .into_iter()
6891
        .find(|e| e.change.message.starts_with("base"))
6892
        .unwrap();
6893
    let base = repo
6894
        .load_state_history(&[first.hash])
6895
        .unwrap()
6896
        .tree()
6897
        .view();
6898
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6899
}
6900
6901
/// oxygen#30, the rest: a placement left under a directory another line
6902
/// removed is out of sight, so no diff reaches it; the merge that settles
6903
/// where the file is retires it.
6904
#[test]
6905
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6906
    hermetic();
6907
    if std::process::Command::new("git")
6908
        .arg("--version")
6909
        .output()
6910
        .is_err()
6911
    {
6912
        eprintln!("git not installed; skipping");
6913
        return;
6914
    }
6915
    let dir = tempfile::tempdir().unwrap();
6916
    let root = dir.path();
6917
    let g = root.join("src.git");
6918
    fs::create_dir_all(&g).unwrap();
6919
    let run = |args: &[&str]| {
6920
        std::process::Command::new("git")
6921
            .arg("-C")
6922
            .arg(&g)
6923
            .args([
6924
                "-c",
6925
                "user.name=Grace",
6926
                "-c",
6927
                "[email protected]",
6928
                "-c",
6929
                "commit.gpgsign=false",
6930
            ])
6931
            .args(args)
6932
            .output()
6933
            .unwrap()
6934
    };
6935
    let git = |args: &[&str]| {
6936
        let out = run(args);
6937
        assert!(
6938
            out.status.success(),
6939
            "git {args:?}: {}",
6940
            String::from_utf8_lossy(&out.stderr)
6941
        );
6942
    };
6943
    git(&["init", "-q", "-b", "main"]);
6944
    write(&g, "c/x.txt", b"x\n");
6945
    write(&g, "keep.txt", b"k\n");
6946
    git(&["add", "."]);
6947
    git(&["commit", "-qm", "base"]);
6948
    // One line renames the file within c; the other moves it out of c,
6949
    // which goes.
6950
    git(&["checkout", "-qb", "side"]);
6951
    git(&["mv", "c/x.txt", "c/y.txt"]);
6952
    git(&["commit", "-qm", "rename within c"]);
6953
    git(&["checkout", "-q", "main"]);
6954
    fs::create_dir_all(g.join("n")).unwrap();
6955
    git(&["mv", "c/x.txt", "n/x.txt"]);
6956
    git(&["commit", "-qm", "move out of c"]);
6957
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6958
    let _ = run(&["merge", "-q", "side"]);
6959
    let _ = run(&[
6960
        "rm",
6961
        "-q",
6962
        "--cached",
6963
        "--ignore-unmatch",
6964
        "c/y.txt",
6965
        "c/x.txt",
6966
    ]);
6967
    let _ = std::fs::remove_dir_all(g.join("c"));
6968
    write(&g, "n/x.txt", b"x\n");
6969
    git(&["add", "-A"]);
6970
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6971
6972
    let repo = Repo::init(&root.join("o")).unwrap();
6973
    repo.import_git(&g, "main").unwrap();
6974
    let v = repo.verify_git_import(&g, "main").unwrap();
6975
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6976
    let st = repo
6977
        .load_state_history(&repo.bookmark_heads().unwrap())
6978
        .unwrap();
6979
    let view = st.tree().view();
6980
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6981
    assert!(view.entries.contains_key("n/x.txt"));
6982
}
6983
6984
/// oxygen#30, orphans: a file added on one line into a directory the other
6985
/// line removed is placed where the tree cannot show it; Git's merge keeps
6986
/// the file, and the import's merge leaves exactly one of it.
6987
#[test]
6988
fn git_import_merge_leaves_no_orphan_behind() {
6989
    hermetic();
6990
    if std::process::Command::new("git")
6991
        .arg("--version")
6992
        .output()
6993
        .is_err()
6994
    {
6995
        eprintln!("git not installed; skipping");
6996
        return;
6997
    }
6998
    let dir = tempfile::tempdir().unwrap();
6999
    let root = dir.path();
7000
    let g = root.join("src.git");
7001
    fs::create_dir_all(&g).unwrap();
7002
    let git = |args: &[&str]| {
7003
        let out = std::process::Command::new("git")
7004
            .arg("-C")
7005
            .arg(&g)
7006
            .args([
7007
                "-c",
7008
                "user.name=Grace",
7009
                "-c",
7010
                "[email protected]",
7011
                "-c",
7012
                "commit.gpgsign=false",
7013
            ])
7014
            .args(args)
7015
            .output()
7016
            .unwrap();
7017
        assert!(
7018
            out.status.success(),
7019
            "git {args:?}: {}",
7020
            String::from_utf8_lossy(&out.stderr)
7021
        );
7022
    };
7023
    git(&["init", "-q", "-b", "main"]);
7024
    write(&g, "d/f.txt", b"f\n");
7025
    write(&g, "keep.txt", b"k\n");
7026
    git(&["add", "."]);
7027
    git(&["commit", "-qm", "base"]);
7028
    git(&["checkout", "-qb", "side"]);
7029
    write(&g, "d/new.txt", b"new\n");
7030
    git(&["add", "."]);
7031
    git(&["commit", "-qm", "add into d"]);
7032
    git(&["checkout", "-q", "main"]);
7033
    git(&["rm", "-q", "d/f.txt"]);
7034
    git(&["commit", "-qm", "d goes"]);
7035
    git(&["merge", "-q", "--no-edit", "side"]);
7036
7037
    let repo = Repo::init(&root.join("o")).unwrap();
7038
    repo.import_git(&g, "main").unwrap();
7039
    let v = repo.verify_git_import(&g, "main").unwrap();
7040
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7041
    let st = repo
7042
        .load_state_history(&repo.bookmark_heads().unwrap())
7043
        .unwrap();
7044
    let view = st.tree().view();
7045
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7046
    assert!(view.entries.contains_key("d/new.txt"));
7047
}
7048
7049
/// fsck checks a change's text as the blobs it is stored in, without
7050
/// decoding it: a missing text blob is an error named for the change.
7051
#[test]
7052
fn fsck_names_a_missing_text_blob() {
7053
    hermetic();
7054
    let dir = tempfile::tempdir().unwrap();
7055
    let root = dir.path();
7056
    let repo = Repo::init(root).unwrap();
7057
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7058
    write(root, "big.txt", big.as_bytes());
7059
    let h = repo.commit("big", &[]).unwrap();
7060
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7061
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7062
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7063
        panic!("a stored text")
7064
    };
7065
    repo.store().remove_loose_for_test(&b).unwrap();
7066
    let rep = repo.fsck().unwrap();
7067
    assert!(rep.errors() > 0);
7068
    assert!(
7069
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7070
        "{:?}",
7071
        rep.problems
7072
    );
7073
}
7074
7075
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7076
/// reached with that remote's token and CA (a private subrepo then clones
7077
/// for anyone who can read the parent); another hub gets none of them.
7078
#[test]
7079
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7080
    hermetic();
7081
    let dir = tempfile::tempdir().unwrap();
7082
    let mut repo = Repo::init(dir.path()).unwrap();
7083
    repo.config
7084
        .set(
7085
            "remote.origin.url",
7086
            "https://Hub.example:7343/doomsdayone/metalgear",
7087
        )
7088
        .unwrap();
7089
    repo.config.set("remote.origin.token", "secret").unwrap();
7090
    repo.config
7091
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7092
        .unwrap();
7093
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7094
    assert_eq!(same.token.as_deref(), Some("secret"));
7095
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7096
    for other in [
7097
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7098
        "https://hub.example/doomsdayone/rstar-api",
7099
        "http://hub.example:7343/doomsdayone/rstar-api",
7100
    ] {
7101
        let o = repo.credentials_for(other);
7102
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7103
    }
7104
}
7105
7106
/// oxygen#47: a remote with no token of its own uses the user's credential
7107
/// store for its hub, and a nested checkout finds its parent's remote
7108
/// token there instead of keeping a copy.
7109
#[test]
7110
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7111
    hermetic();
7112
    let home = tempfile::tempdir().unwrap();
7113
    let dir = tempfile::tempdir().unwrap();
7114
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7115
    parent
7116
        .config
7117
        .set("remote.origin.url", "https://hub.example/o/parent")
7118
        .unwrap();
7119
    parent.save_config().unwrap();
7120
    assert_eq!(parent.remote_options("origin").token, None);
7121
    crate::credentials::Credentials::at(home.path())
7122
        .save("https://hub.example", "stored", Some("andy"), None)
7123
        .unwrap();
7124
    assert_eq!(
7125
        parent.remote_options("origin").token.as_deref(),
7126
        Some("stored")
7127
    );
7128
7129
    let empty_home = tempfile::tempdir().unwrap();
7130
    let nested = dir.path().join("deps").join("child");
7131
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7132
    child
7133
        .config
7134
        .set("remote.origin.url", "https://hub.example/o/child")
7135
        .unwrap();
7136
    child.save_config().unwrap();
7137
    assert_eq!(child.remote_options("origin").token, None);
7138
    parent
7139
        .config
7140
        .set("remote.origin.token", "checkout")
7141
        .unwrap();
7142
    parent.save_config().unwrap();
7143
    assert_eq!(
7144
        child.remote_options("origin").token.as_deref(),
7145
        Some("checkout")
7146
    );
7147
    // Another hub's checkout token is not borrowed.
7148
    child
7149
        .config
7150
        .set("remote.origin.url", "https://other.example/o/child")
7151
        .unwrap();
7152
    assert_eq!(child.remote_options("origin").token, None);
7153
}
7154
7155
#[test]
7156
fn the_metadata_cache_survives_a_torn_tail() {
7157
    hermetic();
7158
    let dir = tempfile::tempdir().unwrap();
7159
    let root = dir.path();
7160
    let repo = Repo::init(root).unwrap();
7161
    write(root, "a.txt", b"1\n");
7162
    let h = repo.commit("first", &[]).unwrap();
7163
    let meta = repo.store().get_change_meta(&h).unwrap();
7164
    let cache = repo.store().dir().join("metas");
7165
    let len = fs::metadata(&cache).unwrap().len();
7166
    assert!(len > 0, "a change read is cached");
7167
    // A torn record at the end: the cache reads up to it and cuts it off.
7168
    fs::OpenOptions::new()
7169
        .append(true)
7170
        .open(&cache)
7171
        .unwrap()
7172
        .write_all(&[7; 20])
7173
        .unwrap();
7174
    let again = Repo::open(root).unwrap();
7175
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7176
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7177
}
7178
7179
#[test]
7180
fn a_manifest_that_does_not_check_reads_as_none() {
7181
    hermetic();
7182
    let dir = tempfile::tempdir().unwrap();
7183
    let root = dir.path();
7184
    let repo = Repo::init(root).unwrap();
7185
    write(root, "a.txt", b"1\n");
7186
    repo.commit("first", &[]).unwrap();
7187
    let path = repo.manifest_path();
7188
    let mut bytes = fs::read(&path).unwrap();
7189
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7190
    let last = bytes.len() - 1;
7191
    bytes[last] ^= 1;
7192
    fs::write(&path, &bytes).unwrap();
7193
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7194
    // The next status reads the files and writes it again.
7195
    let again = Repo::open(root).unwrap();
7196
    assert!(!again.snapshot("status").unwrap().changed);
7197
    assert!(again.read_manifest().unwrap().is_some());
7198
}
7199
7200
#[test]
7201
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7202
    hermetic();
7203
    let dir = tempfile::tempdir().unwrap();
7204
    let root = dir.path();
7205
    let repo = Repo::init(root).unwrap();
7206
    write(root, "a.txt", b"1\n");
7207
    write(root, "b.txt", b"2\n");
7208
    // b.txt outside the racy window, so snapshots take it as unchanged.
7209
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7210
    fs::File::options()
7211
        .write(true)
7212
        .open(root.join("b.txt"))
7213
        .unwrap()
7214
        .set_modified(old)
7215
        .unwrap();
7216
    repo.commit("first", &[]).unwrap();
7217
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7218
    repo.snapshot_status("status").unwrap();
7219
    write(root, "a.txt", b"1\n2\n");
7220
    repo.commit("second", &[]).unwrap();
7221
    assert!(
7222
        repo.clean_by_manifest().unwrap(),
7223
        "after a commit of one file"
7224
    );
7225
    // Edited, seen by a status, edited again, then committed: the status
7226
    // left the first edit's stat, which the commit must not keep.
7227
    write(root, "a.txt", b"1\n2\n3\n");
7228
    repo.snapshot_status("status").unwrap();
7229
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7230
    repo.commit("third", &[]).unwrap();
7231
    assert!(
7232
        repo.clean_by_manifest().unwrap(),
7233
        "after an edit a status saw"
7234
    );
7235
}
7236
7237
#[test]
7238
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7239
    hermetic();
7240
    let dir = tempfile::tempdir().unwrap();
7241
    let root = dir.path();
7242
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7243
    write(root, "a.txt", b"1\n2\n");
7244
    let a = repo.commit("A", &[]).unwrap();
7245
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7246
    write(root, "a.txt", b"1\nX\n");
7247
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7248
    repo.bookmark_switch("develop", false).unwrap();
7249
    write(root, "a.txt", b"1\nY\n");
7250
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7251
    repo.bookmark_switch("main", false).unwrap();
7252
7253
    let err = repo.rebase(&c, &[d]).unwrap_err();
7254
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7255
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7256
    assert!(r.changed && r.checked_out);
7257
    let snap = repo.snapshot_status("status").unwrap();
7258
    assert!(
7259
        snap.base_snapshot.is_conflicted(),
7260
        "the conflict is in the working copy"
7261
    );
7262
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7263
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7264
7265
    write(root, "a.txt", b"1\nXY\n");
7266
    repo.commit("Resolve", &[]).unwrap();
7267
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7268
    assert!(st.contains(&c) && st.contains(&d));
7269
    let files = st.materialize().files;
7270
    assert!(!files["a.txt"].is_conflicted());
7271
    assert!(
7272
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7273
    );
7274
7275
    // A change the current bookmark does not hold is refused.
7276
    repo.bookmark_switch("develop", false).unwrap();
7277
    write(root, "b.txt", b"b\n");
7278
    let e = repo.commit("E", &[]).unwrap();
7279
    repo.bookmark_switch("main", false).unwrap();
7280
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7281
    assert!(
7282
        err.to_string().contains("not on the current bookmark"),
7283
        "{err}"
7284
    );
7285
}
7286
7287
#[test]
7288
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7289
    hermetic();
7290
    let dir = tempfile::tempdir().unwrap();
7291
    let root = dir.path();
7292
    let repo = Repo::init(root).unwrap();
7293
    write(root, "a.txt", b"a\n");
7294
    write(root, "kept.log", b"tracked\n");
7295
    repo.commit("first", &[]).unwrap();
7296
    write(root, "build.log", b"made\n");
7297
    let snap = repo.snapshot_status("status").unwrap();
7298
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7299
    // A rule written afterwards leaves the added file out again, while the
7300
    // committed one stays tracked.
7301
    write(root, ".gitignore", b"*.log\n");
7302
    let snap = repo.snapshot_status("status").unwrap();
7303
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7304
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7305
    write(root, "kept.log", b"tracked, edited\n");
7306
    let snap = repo.snapshot_status("status").unwrap();
7307
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7308
}
7309
7310
#[test]
7311
fn shed_graphs_come_back_the_same() {
7312
    hermetic();
7313
    let dir = tempfile::tempdir().unwrap();
7314
    let root = dir.path();
7315
    let repo = Repo::init(root).unwrap();
7316
    write(root, "a.txt", b"1\n2\n3\n");
7317
    write(root, "b.txt", b"x\n");
7318
    repo.commit("first", &[]).unwrap();
7319
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7320
    repo.commit("second", &[]).unwrap();
7321
    let heads = repo.bookmark_heads().unwrap();
7322
    let mut st = repo.load_state_history(&heads).unwrap();
7323
    let view = st.tree().view();
7324
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7325
        .iter()
7326
        .map(|p| view.entries[*p].node)
7327
        .collect();
7328
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7329
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7330
    assert_eq!(st.built_count(), 2);
7331
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7332
    assert_eq!((shed, st.built_count()), (2, 0));
7333
    // A later change applies on top of the shed history.
7334
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7335
    let h3 = repo.commit("third", &[]).unwrap();
7336
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7337
    st.add_known(h3, skeleton, texts);
7338
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7339
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7340
    assert_eq!(after[1], before[1]);
7341
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7342
}
7343
7344
#[test]
7345
fn many_edited_files_diff_in_parallel() {
7346
    // Enough edited files that the builder diffs them in parallel; the
7347
    // commit must hold exactly what is on disk, and a second snapshot
7348
    // must find nothing left to commit.
7349
    hermetic();
7350
    let dir = tempfile::tempdir().unwrap();
7351
    let root = dir.path();
7352
    let repo = Repo::init(root).unwrap();
7353
    let text = |i: usize, round: usize| {
7354
        let mut s = String::new();
7355
        for line in 0..50 {
7356
            if round > 0 && line % 7 == i % 7 {
7357
                s.push_str(&format!("edited {round} {i} {line}\n"));
7358
            } else {
7359
                s.push_str(&format!("file {i} line {line}\n"));
7360
            }
7361
        }
7362
        if round > 0 && i.is_multiple_of(3) {
7363
            s.push_str("appended\n");
7364
        }
7365
        s
7366
    };
7367
    for i in 0..40 {
7368
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7369
    }
7370
    repo.commit("first", &[]).unwrap();
7371
    for i in 0..40 {
7372
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7373
    }
7374
    let h = repo.commit("edit every file", &[]).unwrap();
7375
    let snap = repo.load_state(&[h]).unwrap().materialize();
7376
    for i in 0..40 {
7377
        let want = text(i, 1);
7378
        assert!(
7379
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
7380
            "d/f{i}.txt as committed"
7381
        );
7382
    }
7383
    assert!(
7384
        repo.commit("nothing", &[]).is_err(),
7385
        "nothing left to commit"
7386
    );
7387
}
7388
7389
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7390
/// is known (fetch printed "up to date" while main was behind), a change
7391
/// only fetched resolves and says where it is, and a checkout whose only
7392
/// remote is not `origin` uses that one.
7393
#[test]
7394
fn a_fetched_change_shows_as_behind_and_resolves() {
7395
    hermetic();
7396
    let dir = tempfile::tempdir().unwrap();
7397
    let root = dir.path();
7398
    let origin = Repo::init(&root.join("origin")).unwrap();
7399
    drop(origin);
7400
    let url = root.join("origin").to_string_lossy().to_string();
7401
    let a = Repo::clone(&url, &root.join("a"))
7402
        .unwrap()
7403
        .with_home(root.join("home-a"));
7404
    write(&root.join("a"), "f.txt", b"one\n");
7405
    a.commit("one", &[]).unwrap();
7406
    a.push("origin", false).unwrap();
7407
    let b = Repo::clone(&url, &root.join("b"))
7408
        .unwrap()
7409
        .with_home(root.join("home-b"));
7410
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7411
7412
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7413
    let h2 = a.commit("two", &[]).unwrap();
7414
    a.push("origin", false).unwrap();
7415
    b.fetch("origin").unwrap();
7416
    // Fetched, not pulled: one behind, the change found and placed.
7417
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7418
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7419
    assert_eq!(
7420
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7421
            .unwrap(),
7422
        h2
7423
    );
7424
    assert_eq!(
7425
        b.remote_only_location(&h2).unwrap().as_deref(),
7426
        Some("origin/main")
7427
    );
7428
    // Fetching again changes nothing: still behind, which is what the
7429
    // CLI now says rather than "up to date".
7430
    b.fetch("origin").unwrap();
7431
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7432
    b.pull("origin").unwrap();
7433
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7434
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7435
7436
    // One remote, not called origin: it is the default.
7437
    let mut c = Repo::init(&root.join("c")).unwrap();
7438
    assert_eq!(c.default_remote(), "origin");
7439
    c.config.set("remote.earth.url", &url).unwrap();
7440
    assert_eq!(c.default_remote(), "earth");
7441
    c.config.set("remote.origin.url", &url).unwrap();
7442
    assert_eq!(c.default_remote(), "origin");
7443
}
7444
7445
/// oxygen#57: a clone from a relative local path records the remote as an
7446
/// absolute path, so fetch still finds it from inside the clone.
7447
#[test]
7448
fn a_clone_from_a_relative_path_records_it_absolute() {
7449
    hermetic();
7450
    let dir = tempfile::tempdir().unwrap();
7451
    let root = dir.path();
7452
    Repo::init(&root.join("origin")).unwrap();
7453
    let rel = crate::protocol::stored_url("relative/repo");
7454
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7455
    assert_eq!(
7456
        crate::protocol::stored_url("https://hub.example/o/n"),
7457
        "https://hub.example/o/n"
7458
    );
7459
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7460
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7461
    // A bucket is kept as written: it is not a path.
7462
    assert_eq!(
7463
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7464
        "s3://bucket/prefix?profile=p"
7465
    );
7466
    let url = root.join("origin").to_string_lossy().to_string();
7467
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7468
    assert_eq!(b.config.remotes["origin"], url);
7469
    b.fetch("origin").unwrap();
7470
}
7471
7472
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7473
/// and gets its subrepos at their pins from this workspace's copies, with
7474
/// their remotes pointing where the subrepos come from.
7475
#[test]
7476
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7477
    hermetic();
7478
    let dir = tempfile::tempdir().unwrap();
7479
    let root = dir.path();
7480
    Repo::init(&root.join("lib-origin")).unwrap();
7481
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7482
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7483
        .unwrap()
7484
        .with_home(root.join("home"));
7485
    write(&root.join("lib"), "lib.txt", b"v1\n");
7486
    let l1 = lib.commit("lib v1", &[]).unwrap();
7487
    assert!(lib.push("origin", false).unwrap()[0].ok);
7488
7489
    let app_dir = root.join("app");
7490
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7491
    write(&app_dir, "main.txt", b"app\n");
7492
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7493
    app.commit("app with lib", &[]).unwrap();
7494
    // A second bookmark, and the main workspace on another.
7495
    app.bookmark_create("develop", None).unwrap();
7496
    app.bookmark_create("feature", None).unwrap();
7497
    let mut app = app;
7498
    app.bookmark_switch("feature", false).unwrap();
7499
    assert_eq!(app.config.bookmark, "feature");
7500
7501
    // The library's origin goes away: the subrepo must come from here.
7502
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7503
    let heads = app.resolve_heads("develop").unwrap();
7504
    let ws = app
7505
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7506
        .unwrap();
7507
    assert_eq!(
7508
        ws.config.bookmark, "develop",
7509
        "the new workspace is on develop"
7510
    );
7511
    assert_eq!(
7512
        app.config.bookmark, "feature",
7513
        "and this one stays on its own"
7514
    );
7515
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7516
    assert_eq!(
7517
        sub.config.remotes["origin"], lib_url,
7518
        "its origin is the subrepo's URL"
7519
    );
7520
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7521
    assert_eq!(
7522
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7523
        b"v1\n"
7524
    );
7525
}
7526
7527
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7528
/// operators and the predicates, over a small graph with two heads and
7529
/// a rename.
7530
#[test]
7531
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7532
    hermetic();
7533
    let dir = tempfile::tempdir().unwrap();
7534
    let root = dir.path();
7535
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7536
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7537
        .unwrap();
7538
    write(root, "src/a.rs", b"one\n");
7539
    let a = repo.commit("first: add a", &[]).unwrap();
7540
    write(root, "src/a.rs", b"one\ntwo\n");
7541
    let b = repo.commit("second: grow a", &[]).unwrap();
7542
    // A second head, independent of b: a new file on top of a.
7543
    repo.checkout(&[a], false, "checkout a").unwrap();
7544
    write(root, "docs/notes.md", b"notes\n");
7545
    let c = repo.commit("third: notes", &[]).unwrap();
7546
    // Back to both heads, then rename a.rs: the node keeps its identity.
7547
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7548
        .unwrap();
7549
    fs::remove_file(root.join("src/a.rs")).unwrap();
7550
    write(root, "src/z.rs", b"one\ntwo\n");
7551
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7552
    let wc = repo.working_copy().unwrap().0;
7553
    // A saved revset is checked when set.
7554
    repo.set_user_config("revset.mine", "author(me) & ::main")
7555
        .unwrap();
7556
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7557
    let set = |src: &str| -> Vec<ChangeHash> {
7558
        let mut v = repo.revset(src).unwrap().hashes;
7559
        v.sort();
7560
        v
7561
    };
7562
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7563
        let mut v = hs.to_vec();
7564
        v.sort();
7565
        v
7566
    };
7567
7568
    // Changes commute: a new file depends on nothing and the rename on the
7569
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7570
    // copy on the three heads b, c, d.
7571
    let heads = sorted(&repo.bookmark_heads().unwrap());
7572
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7573
    assert!(heads.contains(&d) && heads.contains(&c));
7574
    // Symbols and closures.
7575
    assert_eq!(set("main"), heads);
7576
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7577
    assert_eq!(set("@"), vec![wc]);
7578
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7579
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7580
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7581
    assert_eq!(
7582
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7583
        sorted(&[a, b])
7584
    );
7585
    // Ranges: what main has beyond b, and `..` forms.
7586
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7587
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7588
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7589
    // Operators and precedence: ~ binds tighter than &, & than |.
7590
    assert_eq!(
7591
        set(&format!("::main ~ #{}", d.short(12))),
7592
        sorted(&[a, b, c])
7593
    );
7594
    assert_eq!(
7595
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7596
        sorted(&[b, c])
7597
    );
7598
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7599
    // Relations.
7600
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7601
    head_deps.sort();
7602
    head_deps.dedup();
7603
    assert_eq!(set("deps(main)"), head_deps);
7604
    let on_a: Vec<ChangeHash> = [b, c, d]
7605
        .into_iter()
7606
        .filter(|h| meta(h).deps.contains(&a))
7607
        .collect();
7608
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7609
    assert_eq!(set("heads(::main)"), heads);
7610
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7611
    assert_eq!(
7612
        set(&format!(
7613
            "heads(#{} | #{} | #{})",
7614
            a.short(12),
7615
            b.short(12),
7616
            c.short(12)
7617
        )),
7618
        sorted(&[b, c])
7619
    );
7620
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7621
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7622
    assert_eq!(set("none()"), vec![]);
7623
    // Predicates: author by name, email, key prefix and `me`.
7624
    let key = repo.config.author_key.unwrap();
7625
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7626
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7627
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7628
    assert_eq!(set("author(me) & ::main").len(), 4);
7629
    assert_eq!(set("author(nobody)"), vec![]);
7630
    assert_eq!(set("description(notes)"), vec![c]);
7631
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7632
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7633
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7634
    // touches follows the node through the rename, in the current state.
7635
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7636
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7637
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7638
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7639
    // Newest first in the result order.
7640
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7641
    // The saved revset, and errors that say what is wrong.
7642
    assert_eq!(set("mine()").len(), 4);
7643
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7644
    assert!(e.contains("unknown function nosuch()"), "{e}");
7645
    let e = repo.revset("main &").unwrap_err().to_string();
7646
    assert!(e.contains("at character"), "{e}");
7647
    let e = repo.revset("zzzz").unwrap_err().to_string();
7648
    assert!(e.contains("no change matches"), "{e}");
7649
    let e = repo
7650
        .revset_with_budget("::main", std::time::Duration::ZERO)
7651
        .unwrap_err()
7652
        .to_string();
7653
    assert!(e.contains("budget"), "{e}");
7654
    // The log entries carry the bookmark's heads and the working copy.
7655
    let entries = repo.log_revset("::@").unwrap();
7656
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7657
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7658
    // push); then a signed change, a tag, and a revocation.
7659
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7660
    assert_eq!(set("signed_by(me)"), vec![]);
7661
    repo.sign_change(&d).unwrap();
7662
    assert_eq!(set("signed_by(me)"), vec![d]);
7663
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7664
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7665
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7666
    assert_eq!(set("delegated()"), vec![]);
7667
    assert_eq!(set("revoked()"), vec![]);
7668
    assert_eq!(set("attested(tag)"), vec![]);
7669
    repo.tag_create("v1", &[b], "first").unwrap();
7670
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7671
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7672
    assert_eq!(set("attested(receipt)"), vec![]);
7673
    assert_eq!(set("built(test)"), vec![]);
7674
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7675
    assert!(e.contains("tag, receipt or ref"), "{e}");
7676
    repo.revoke_identity(&key, "test").unwrap();
7677
    assert_eq!(set("revoked()"), vec![d]);
7678
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7679
    // independent(X, IN): what could ship without X. c and d neither
7680
    // depend on b nor are depended on by it; a is below, the working copy
7681
    // above.
7682
    assert_eq!(
7683
        set(&format!("independent(#{}, ::@)", b.short(12))),
7684
        sorted(&[c, d])
7685
    );
7686
    assert_eq!(
7687
        set(&format!("independent(#{}, ::main)", a.short(12))),
7688
        vec![c]
7689
    );
7690
    // conflicts(S): nothing conflicts yet; then two edits of one line.
7691
    assert_eq!(set("conflicts()"), vec![]);
7692
    assert_eq!(set("conflicts(main)"), vec![]);
7693
    // (The saved revset above edited the user config under the root:
7694
    // discard it.)
7695
    repo.checkout(&[a], true, "checkout a").unwrap();
7696
    write(root, "src/a.rs", b"one\nTWO\n");
7697
    let e = repo
7698
        .commit("fifth: the other edit of line two", &[])
7699
        .unwrap();
7700
    repo.checkout(&repo.bookmark_heads().unwrap(), true, "checkout main")
7701
        .unwrap();
7702
    let conflicted = repo.revset("conflicts()").unwrap().hashes;
7703
    assert!(
7704
        conflicted.contains(&e) && conflicted.contains(&b),
7705
        "{conflicted:?} should hold b and e"
7706
    );
7707
    assert!(!conflicted.contains(&c));
7708
    assert_eq!(set("conflicts() & author(nobody)"), vec![]);
7709
}
7710
7711
#[test]
7712
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7713
    let dir = tempfile::tempdir().unwrap();
7714
    let root = dir.path();
7715
    let home = root.join("home");
7716
    // Ada's identity lives in the user file; repository `a` pins the same
7717
    // key in its own file, repository `b` names none.
7718
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7719
    let (key, _) = a
7720
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7721
        .unwrap();
7722
    a.config.set("author.key", &key.to_hex()).unwrap();
7723
    a.save_config().unwrap();
7724
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7725
    let r = a
7726
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7727
        .unwrap();
7728
    assert_eq!(
7729
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7730
        r.new.to_hex(),
7731
        "the user file follows"
7732
    );
7733
    assert_eq!(
7734
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7735
        r.new.to_hex(),
7736
        "the pinning repository follows"
7737
    );
7738
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7739
    assert_eq!(
7740
        b.config.author_key,
7741
        Some(r.new),
7742
        "a checkout without a pin follows the user file"
7743
    );
7744
    // A repository-scoped identity leaves the user file alone.
7745
    let other_home = root.join("home2");
7746
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7747
    let (ck, _) = c
7748
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7749
        .unwrap();
7750
    assert!(!other_home.join("config.toml").exists());
7751
    let r2 = c.rotate_identity().unwrap();
7752
    assert_ne!(r2.new, ck);
7753
    assert_eq!(
7754
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7755
        r2.new.to_hex()
7756
    );
7757
    assert!(
7758
        !other_home.join("config.toml").exists(),
7759
        "a repository-scoped identity stays repository-scoped"
7760
    );
7761
    // Several delegates in one rotation; a repeat is refused.
7762
    let (d1, d2) = (
7763
        SecretKey::generate().identity("D1", "d1@x", 1),
7764
        SecretKey::generate().identity("D2", "d2@x", 1),
7765
    );
7766
    let r3 = c
7767
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7768
        .unwrap();
7769
    assert_eq!(r3.identity.delegates.len(), 2);
7770
    assert!(c
7771
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7772
        .is_err());
7773
}
7774
7775
/// Two unrelated histories that both add the same file, joined by two
7776
/// independent merges on two branches, then those branches merged: Git
7777
/// merges identical additions cleanly, and the import must too (#71,
7778
/// found in VS Code's history).
7779
#[test]
7780
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7781
    // Batches of one: every merge renders apart from the state, where a
7782
    // file whose graph the state had built came out empty (#71).
7783
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7784
    hermetic();
7785
    if std::process::Command::new("git")
7786
        .arg("--version")
7787
        .output()
7788
        .is_err()
7789
    {
7790
        eprintln!("git not installed; skipping");
7791
        return;
7792
    }
7793
    let dir = tempfile::tempdir().unwrap();
7794
    let root = dir.path();
7795
    let g = root.join("src.git");
7796
    fs::create_dir_all(&g).unwrap();
7797
    let git = |args: &[&str]| -> String {
7798
        let out = std::process::Command::new("git")
7799
            .arg("-C")
7800
            .arg(&g)
7801
            .args([
7802
                "-c",
7803
                "user.name=Grace",
7804
                "-c",
7805
                "[email protected]",
7806
                "-c",
7807
                "commit.gpgsign=false",
7808
            ])
7809
            .args(args)
7810
            .output()
7811
            .unwrap();
7812
        assert!(
7813
            out.status.success(),
7814
            "git {args:?}: {}",
7815
            String::from_utf8_lossy(&out.stderr)
7816
        );
7817
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7818
    };
7819
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7820
    // History A: main.
7821
    git(&["init", "-q", "-b", "main"]);
7822
    write(&g, "gulpfile.js", text);
7823
    write(&g, "a.txt", b"a\n");
7824
    git(&["add", "."]);
7825
    git(&["commit", "-q", "-m", "A root"]);
7826
    // History B: an unrelated root adding the same file, identical.
7827
    git(&["checkout", "-q", "--orphan", "fork"]);
7828
    git(&["rm", "-q", "-r", "--cached", "."]);
7829
    for f in ["gulpfile.js", "a.txt"] {
7830
        let _ = fs::remove_file(g.join(f));
7831
    }
7832
    write(&g, "gulpfile.js", text);
7833
    write(&g, "b.txt", b"b\n");
7834
    git(&["add", "."]);
7835
    git(&["commit", "-q", "-m", "B root"]);
7836
    // Two branches from main, each joining B on its own.
7837
    git(&["checkout", "-q", "-b", "one", "main"]);
7838
    git(&[
7839
        "merge",
7840
        "-q",
7841
        "--no-ff",
7842
        "--allow-unrelated-histories",
7843
        "-m",
7844
        "join on one",
7845
        "fork",
7846
    ]);
7847
    git(&["checkout", "-q", "-b", "two", "main"]);
7848
    write(&g, "a.txt", b"a\ntwo\n");
7849
    git(&["commit", "-q", "-am", "work on two"]);
7850
    git(&[
7851
        "merge",
7852
        "-q",
7853
        "--no-ff",
7854
        "--allow-unrelated-histories",
7855
        "-m",
7856
        "join on two",
7857
        "fork",
7858
    ]);
7859
    // Then the two joins meet, and the file is reformatted after.
7860
    git(&["checkout", "-q", "main"]);
7861
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7862
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7863
    write(
7864
        &g,
7865
        "gulpfile.js",
7866
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7867
    );
7868
    git(&["commit", "-q", "-am", "after"]);
7869
7870
    let dest = root.join("dest");
7871
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7872
    repo.import_git(&g, "main").unwrap();
7873
    let v = repo.verify_git_import(&g, "main").unwrap();
7874
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7875
    assert_eq!(
7876
        fs::read(dest.join("gulpfile.js")).unwrap(),
7877
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7878
    );
7879
}
7880
7881
/// As above, but the two joins keep different copies (each branch had a
7882
/// different version when it joined), and later work edits each copy:
7883
/// the shape of VS Code's c67ef57cda90 (#71).
7884
#[test]
7885
fn git_import_joins_where_each_join_kept_a_different_copy() {
7886
    // Batches of one: every merge renders apart from the state, where a
7887
    // file whose graph the state had built came out empty (#71).
7888
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7889
    hermetic();
7890
    if std::process::Command::new("git")
7891
        .arg("--version")
7892
        .output()
7893
        .is_err()
7894
    {
7895
        eprintln!("git not installed; skipping");
7896
        return;
7897
    }
7898
    let dir = tempfile::tempdir().unwrap();
7899
    let root = dir.path();
7900
    let g = root.join("src.git");
7901
    fs::create_dir_all(&g).unwrap();
7902
    let run = |args: &[&str]| {
7903
        std::process::Command::new("git")
7904
            .arg("-C")
7905
            .arg(&g)
7906
            .args([
7907
                "-c",
7908
                "user.name=Grace",
7909
                "-c",
7910
                "[email protected]",
7911
                "-c",
7912
                "commit.gpgsign=false",
7913
            ])
7914
            .args(args)
7915
            .output()
7916
            .unwrap()
7917
    };
7918
    let git = |args: &[&str]| -> String {
7919
        let out = run(args);
7920
        assert!(
7921
            out.status.success(),
7922
            "git {args:?}: {}",
7923
            String::from_utf8_lossy(&out.stderr)
7924
        );
7925
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7926
    };
7927
    git(&["init", "-q", "-b", "main"]);
7928
    write(
7929
        &g,
7930
        "gulpfile.js",
7931
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7932
    );
7933
    git(&["add", "."]);
7934
    git(&["commit", "-q", "-m", "A root"]);
7935
    write(
7936
        &g,
7937
        "gulpfile.js",
7938
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7939
    );
7940
    git(&["commit", "-q", "-am", "whitespace"]);
7941
    git(&["checkout", "-q", "--orphan", "fork"]);
7942
    git(&["rm", "-q", "-r", "--cached", "."]);
7943
    let _ = fs::remove_file(g.join("gulpfile.js"));
7944
    write(
7945
        &g,
7946
        "gulpfile.js",
7947
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7948
    );
7949
    git(&["add", "."]);
7950
    git(&["commit", "-q", "-m", "B root"]);
7951
    // Branch one joins B keeping main's copy; branch two keeps B's.
7952
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7953
        git(&["checkout", "-q", "-b", branch, "main"]);
7954
        let _ = run(&[
7955
            "merge",
7956
            "-q",
7957
            "--no-ff",
7958
            "--allow-unrelated-histories",
7959
            "-m",
7960
            "join",
7961
            "fork",
7962
        ]);
7963
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7964
        git(&["add", "gulpfile.js"]);
7965
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7966
    }
7967
    // Each branch then edits its copy.
7968
    git(&["checkout", "-q", "one"]);
7969
    write(
7970
        &g,
7971
        "gulpfile.js",
7972
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7973
    );
7974
    git(&["commit", "-q", "-am", "tslint on one"]);
7975
    git(&["checkout", "-q", "two"]);
7976
    write(
7977
        &g,
7978
        "gulpfile.js",
7979
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7980
    );
7981
    write(&g, "extra.txt", b"x\n");
7982
    write(&g, "more.txt", b"m\n");
7983
    git(&["add", "."]);
7984
    git(&["commit", "-q", "-am", "fmt on two"]);
7985
    // They meet: resolved by hand.
7986
    git(&["checkout", "-q", "one"]);
7987
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7988
    write(
7989
        &g,
7990
        "gulpfile.js",
7991
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7992
    );
7993
    git(&["add", "gulpfile.js"]);
7994
    git(&["commit", "-q", "-m", "merge two into one"]);
7995
7996
    let dest = root.join("dest");
7997
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7998
    repo.import_git(&g, "one").unwrap();
7999
    let v = repo.verify_git_import(&g, "one").unwrap();
8000
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8001
}
8002
8003
/// oxygen#68: on a store that is not this disk's directory, the operation
8004
/// head is the store's reference record, moved by compare-and-swap. Two
8005
/// handles recording from the same head both get through, merged; a swap
8006
/// from a stale version is refused; a second repository cannot start on a
8007
/// store that already holds one.
8008
#[test]
8009
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8010
    use crate::strata::{MemoryStore, Store as _};
8011
    let backend = std::sync::Arc::new(MemoryStore::new());
8012
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8013
    let dir = tempfile::tempdir().unwrap();
8014
    let a = Repo::init(dir.path()).unwrap();
8015
    assert!(
8016
        !dir.path().join(".oxy/ops/head").exists(),
8017
        "the head is not a file"
8018
    );
8019
    let (h0, op0) = a.head_op().unwrap();
8020
    let record = backend
8021
        .read_ref(HEAD_RECORD)
8022
        .unwrap()
8023
        .expect("the head is the store's record");
8024
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8025
8026
    let b = Repo::open(dir.path()).unwrap();
8027
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8028
    let mut va = op0.view.clone();
8029
    va.bookmarks.insert("from-a".into(), state);
8030
    let mut vb = op0.view.clone();
8031
    vb.bookmarks.insert("from-b".into(), state);
8032
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8033
    assert_eq!(b.head_ref().unwrap(), rb);
8034
    // a recorded from h0 too: the head moved, so the two are merged.
8035
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8036
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8037
    assert_eq!(head, ra);
8038
    assert!(
8039
        op.command.ends_with("(merged with a concurrent operation)"),
8040
        "{}",
8041
        op.command
8042
    );
8043
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8044
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8045
8046
    // A swap from a version that is no longer current moves nothing.
8047
    let (h, v) = a.read_head().unwrap();
8048
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8049
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8050
    assert_eq!(a.head_ref().unwrap(), rb);
8051
8052
    let other = tempfile::tempdir().unwrap();
8053
    let err = Repo::init(other.path())
8054
        .err()
8055
        .expect("the store already holds a log")
8056
        .to_string();
8057
    assert!(
8058
        err.contains("already holds a repository's operation log"),
8059
        "{err}"
8060
    );
8061
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8062
}
8063
8064
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8065
/// objects and operation head there, with `.oxy/cache` in front: it works
8066
/// as one on disk does, reopens, and survives losing its cache.
8067
#[test]
8068
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8069
    hermetic();
8070
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8071
        return;
8072
    }
8073
    let dir = tempfile::tempdir().unwrap();
8074
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8075
    let url = format!("dir://{}", bucket.display());
8076
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8077
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8078
    write(&root, "a.txt", b"one\n");
8079
    let h1 = repo.commit("First", &[]).unwrap();
8080
    write(&root, "a.txt", b"one\ntwo\n");
8081
    let h2 = repo.commit("Second", &[]).unwrap();
8082
    assert!(
8083
        !root.join(".oxy/ops/head").exists(),
8084
        "the head is in the store"
8085
    );
8086
    assert!(bucket.join("ops/head").is_file());
8087
    assert!(root.join(".oxy/cache").is_dir());
8088
    drop(repo);
8089
8090
    // Reopened, and again with no cache at all: everything comes from the store.
8091
    for drop_cache in [false, true] {
8092
        if drop_cache {
8093
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8094
        }
8095
        let repo = Repo::open(&root).unwrap();
8096
        let log: Vec<String> = repo
8097
            .op_log()
8098
            .unwrap()
8099
            .into_iter()
8100
            .map(|(_, op)| op.command)
8101
            .collect();
8102
        assert!(log.len() >= 3, "{log:?}");
8103
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8104
        let heads = repo
8105
            .store()
8106
            .get_state(&repo.view().unwrap().bookmarks["main"])
8107
            .unwrap()
8108
            .heads;
8109
        assert_eq!(heads, vec![h2]);
8110
        assert_eq!(
8111
            repo.load_state(&heads).unwrap().materialize().files.len(),
8112
            1
8113
        );
8114
    }
8115
8116
    // A second repository cannot start on the same store.
8117
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8118
        .err()
8119
        .unwrap()
8120
        .to_string();
8121
    assert!(
8122
        err.contains("already holds a repository's operation log"),
8123
        "{err}"
8124
    );
8125
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8126
        .err()
8127
        .unwrap()
8128
        .to_string();
8129
    assert!(err.contains("cannot open that kind of store"), "{err}");
8130
}
8131
8132
/// oxygen#75: the prompt's quick check agrees with status in a repository
8133
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8134
/// another state, clean again once that pin is committed. (It compared the
8135
/// subrepo's directory as if it were a file, so it was always dirty.)
8136
#[test]
8137
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8138
    hermetic();
8139
    let dir = tempfile::tempdir().unwrap();
8140
    let root = dir.path();
8141
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8142
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8143
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8144
        .unwrap()
8145
        .with_home(root.join("home"));
8146
    write(&root.join("lib"), "lib.txt", b"v1\n");
8147
    lib.commit("lib v1", &[]).unwrap();
8148
    assert!(lib.push("origin", false).unwrap()[0].ok);
8149
    let app_dir = root.join("app");
8150
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8151
    write(&app_dir, "main.txt", b"app\n");
8152
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8153
    app.commit("app with lib", &[]).unwrap();
8154
    // Out of the racy window, so the stat-only path decides.
8155
    std::thread::sleep(std::time::Duration::from_millis(2100));
8156
    let reopen = || Repo::open(&app_dir).unwrap();
8157
    assert_eq!(
8158
        reopen().quick_dirty().unwrap(),
8159
        Some(false),
8160
        "clean, as status says"
8161
    );
8162
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8163
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8164
    nested.commit("lib v2", &[]).unwrap();
8165
    assert_eq!(
8166
        reopen().quick_dirty().unwrap(),
8167
        Some(true),
8168
        "the subrepo moved"
8169
    );
8170
    reopen().commit("pin lib v2", &[]).unwrap();
8171
    std::thread::sleep(std::time::Duration::from_millis(2100));
8172
    assert_eq!(
8173
        reopen().quick_dirty().unwrap(),
8174
        Some(false),
8175
        "the new pin is committed"
8176
    );
8177
}
8178
8179
#[test]
8180
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8181
    // oxygen#72: a .oxymodules section with no subrepo behind it.
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(
8196
        &app_dir,
8197
        ".oxymodules",
8198
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8199
    );
8200
    let unpinned = app.unpinned_modules().unwrap();
8201
    assert_eq!(unpinned.len(), 1);
8202
    assert_eq!(unpinned[0].0, "libs/lib");
8203
    assert_eq!(unpinned[0].1.url, lib_url);
8204
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8205
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8206
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8207
}
8208
8209
#[test]
8210
fn the_bookmark_revset_function_names_only_bookmarks() {
8211
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8212
    hermetic();
8213
    let dir = tempfile::tempdir().unwrap();
8214
    let repo = Repo::init(dir.path()).unwrap();
8215
    write(dir.path(), "a.txt", b"a\n");
8216
    let a = repo.commit("A", &[]).unwrap();
8217
    write(dir.path(), "b.txt", b"b\n");
8218
    let b = repo.commit("B", &[]).unwrap();
8219
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8220
    heads.sort();
8221
    let mut want = repo.bookmark_heads().unwrap();
8222
    want.sort();
8223
    assert_eq!(heads, want);
8224
    assert!(heads.contains(&b));
8225
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8226
    // A change prefix is a symbol, not a bookmark.
8227
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8228
    assert!(repo.revset(&prefix).is_ok());
8229
    let e = repo
8230
        .revset(&format!("bookmark({prefix})"))
8231
        .unwrap_err()
8232
        .to_string();
8233
    assert!(e.contains("no such bookmark"), "{e}");
8234
}
8235
8236
#[test]
8237
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8238
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8239
    // pinning the subrepo, and the nested repository on disk at that pin.
8240
    hermetic();
8241
    let dir = tempfile::tempdir().unwrap();
8242
    let root = dir.path();
8243
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8244
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8245
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8246
        .unwrap()
8247
        .with_home(root.join("home"));
8248
    write(&root.join("lib"), "lib.txt", b"v1\n");
8249
    lib.commit("lib v1", &[]).unwrap();
8250
    assert!(lib.push("origin", false).unwrap()[0].ok);
8251
    let app_dir = root.join("app");
8252
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8253
    write(&app_dir, "main.txt", b"app\n");
8254
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8255
    // The stale state: registered in .oxymodules, never pinned.
8256
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8257
    app.commit("initial", &[]).unwrap();
8258
    let stale = app.bookmark_heads().unwrap();
8259
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8260
    app.commit("pin lib", &[]).unwrap();
8261
    let newer = app.bookmark_heads().unwrap();
8262
    app.checkout(&stale, false, "test").unwrap();
8263
    write(&app_dir, "notes.txt", b"mine\n");
8264
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8265
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8266
    assert!(app_dir.join("notes.txt").exists());
8267
}
8268
8269
#[test]
8270
fn a_bookmark_only_behind_its_remote_catches_up() {
8271
    // oxygen#74: switch takes the remote's state rather than a stale one.
8272
    hermetic();
8273
    let dir = tempfile::tempdir().unwrap();
8274
    let root = dir.path();
8275
    let _origin = Repo::init(&root.join("origin")).unwrap();
8276
    let url = root.join("origin").to_string_lossy().to_string();
8277
    let one = Repo::clone(&url, &root.join("one"))
8278
        .unwrap()
8279
        .with_home(root.join("home"));
8280
    write(&root.join("one"), "a.txt", b"a\n");
8281
    one.commit("A", &[]).unwrap();
8282
    assert!(one.push("origin", false).unwrap()[0].ok);
8283
    let two = Repo::clone(&url, &root.join("two"))
8284
        .unwrap()
8285
        .with_home(root.join("home"));
8286
    write(&root.join("two"), "b.txt", b"b\n");
8287
    two.commit("B", &[]).unwrap();
8288
    assert!(two.push("origin", false).unwrap()[0].ok);
8289
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8290
    one.fetch("origin").unwrap();
8291
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8292
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8293
    // Local work the remote lacks: left alone.
8294
    write(&root.join("one"), "c.txt", b"c\n");
8295
    one.commit("C", &[]).unwrap();
8296
    write(&root.join("two"), "d.txt", b"d\n");
8297
    two.commit("D", &[]).unwrap();
8298
    assert!(two.push("origin", false).unwrap()[0].ok);
8299
    one.fetch("origin").unwrap();
8300
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8301
}
8302
8303
#[test]
8304
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8305
    // oxygen#83: remotes earth and gcs, origin removed.
8306
    hermetic();
8307
    let dir = tempfile::tempdir().unwrap();
8308
    let root = dir.path();
8309
    let _up = Repo::init(&root.join("up")).unwrap();
8310
    let url = root.join("up").to_string_lossy().to_string();
8311
    let other = Repo::clone(&url, &root.join("other"))
8312
        .unwrap()
8313
        .with_home(root.join("home"));
8314
    write(&root.join("other"), "a.txt", b"a\n");
8315
    other.commit("a", &[]).unwrap();
8316
    assert!(other.push("origin", false).unwrap()[0].ok);
8317
    let mut one = Repo::clone(&url, &root.join("one"))
8318
        .unwrap()
8319
        .with_home(root.join("home"));
8320
    one.config.set("remote.earth.url", &url).unwrap();
8321
    one.config.set("remote.gcs.url", &url).unwrap();
8322
    one.config.set("remote.origin.url", "").unwrap();
8323
    one.save_config().unwrap();
8324
    write(&root.join("other"), "b.txt", b"b\n");
8325
    other.commit("b", &[]).unwrap();
8326
    assert!(other.push("origin", false).unwrap()[0].ok);
8327
    one.fetch("earth").unwrap();
8328
    let b = one
8329
        .bookmarks()
8330
        .unwrap()
8331
        .into_iter()
8332
        .find(|b| b.name == "main")
8333
        .unwrap();
8334
    assert_eq!(
8335
        (b.remote.as_deref(), b.behind),
8336
        (Some("earth"), Some(1)),
8337
        "a stale origin copy is not used"
8338
    );
8339
    assert_eq!(
8340
        one.default_remote(),
8341
        "origin",
8342
        "no default chosen among several"
8343
    );
8344
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8345
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8346
    one.config.set("core.remote", "earth").unwrap();
8347
    assert_eq!(one.default_remote(), "earth");
8348
}
8349
8350
#[test]
8351
fn a_missing_author_identity_says_how_to_fix_it() {
8352
    // oxygen#82: an agent home's author.key naming an identity the
8353
    // repository does not hold.
8354
    hermetic();
8355
    let dir = tempfile::tempdir().unwrap();
8356
    let mut repo = Repo::init(dir.path()).unwrap();
8357
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8358
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8359
    let e = repo.identity(&missing).unwrap_err().to_string();
8360
    assert!(
8361
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8362
        "{e}"
8363
    );
8364
    assert!(e.contains("this repository's config"), "{e}");
8365
}
8366
8367
#[test]
8368
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8369
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8370
    // the working copy, a pull with nothing new left it there, and status
8371
    // said "clean".
8372
    hermetic();
8373
    let dir = tempfile::tempdir().unwrap();
8374
    let root = dir.path();
8375
    let _up = Repo::init(&root.join("up")).unwrap();
8376
    let url = root.join("up").to_string_lossy().to_string();
8377
    let other = Repo::clone(&url, &root.join("other"))
8378
        .unwrap()
8379
        .with_home(root.join("home"));
8380
    write(&root.join("other"), "a.txt", b"a\n");
8381
    other.commit("a", &[]).unwrap();
8382
    assert!(other.push("origin", false).unwrap()[0].ok);
8383
    let one = Repo::clone(&url, &root.join("one"))
8384
        .unwrap()
8385
        .with_home(root.join("home"));
8386
    write(&root.join("other"), "b.txt", b"b\n");
8387
    other.commit("b", &[]).unwrap();
8388
    assert!(other.push("origin", false).unwrap()[0].ok);
8389
    one.fetch("origin").unwrap();
8390
    // The bookmark moves; the working copy does not.
8391
    let theirs = one.resolve_heads("origin/main").unwrap();
8392
    one.bookmark_set("main", &theirs).unwrap();
8393
    assert!(!root.join("one/b.txt").exists());
8394
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8395
    let r = one.pull("origin").unwrap();
8396
    assert!(
8397
        !r.changed && r.checked_out,
8398
        "nothing new, but the working copy caught up"
8399
    );
8400
    assert!(root.join("one/b.txt").exists());
8401
    assert_eq!(one.working_copy_behind().unwrap(), None);
8402
}
8403
8404
#[test]
8405
fn touched_nodes_cache_answers_as_the_changes_do() {
8406
    hermetic();
8407
    let dir = tempfile::tempdir().unwrap();
8408
    let repo = Repo::init(dir.path()).unwrap();
8409
    write(dir.path(), "a.txt", b"one\n");
8410
    write(dir.path(), "b.txt", b"x\n");
8411
    repo.snapshot("t").unwrap();
8412
    let c1 = repo.commit("first", &[]).unwrap();
8413
    write(dir.path(), "b.txt", b"y\n");
8414
    repo.snapshot("t").unwrap();
8415
    repo.commit("b only", &[]).unwrap();
8416
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8417
    write(dir.path(), "c.txt", b"one\ntwo\n");
8418
    repo.snapshot("t").unwrap();
8419
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8420
    // Uncommitted work, so the working copy touches a file too.
8421
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8422
    repo.snapshot("t").unwrap();
8423
8424
    let path = dir.path().join(".oxy/index/touched");
8425
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8426
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8427
    assert!(path.exists(), "the first query writes the cache");
8428
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8429
    assert_eq!(cold, warm, "the cache answers as the changes do");
8430
    let (wc, _) = repo.working_copy().unwrap();
8431
    assert_eq!(
8432
        cold,
8433
        vec![wc, c3, c1],
8434
        "renames followed, the working copy included"
8435
    );
8436
8437
    // Working-copy changes are not kept: they are replaced by every snapshot.
8438
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8439
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8440
    assert!(cached.contains(&c1) && cached.contains(&c3));
8441
8442
    // A damaged cache is ignored, not trusted.
8443
    let mut bytes = fs::read(&path).unwrap();
8444
    let last = bytes.len() - 40;
8445
    bytes[last] ^= 1;
8446
    fs::write(&path, &bytes).unwrap();
8447
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8448
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8449
    assert_eq!(hashes(touches), vec![c3, c1]);
8450
}
8451
8452
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8453
/// file back where it was leave two placements at one place, which the
8454
/// tree shows as one file. Removing it, and then its directory, retires
8455
/// both, so no copy is left under a directory that is gone.
8456
#[test]
8457
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8458
    hermetic();
8459
    if std::process::Command::new("git")
8460
        .arg("--version")
8461
        .output()
8462
        .is_err()
8463
    {
8464
        eprintln!("git not installed; skipping");
8465
        return;
8466
    }
8467
    let dir = tempfile::tempdir().unwrap();
8468
    let root = dir.path();
8469
    let g = root.join("src.git");
8470
    fs::create_dir_all(&g).unwrap();
8471
    let git = |args: &[&str]| {
8472
        let out = std::process::Command::new("git")
8473
            .arg("-C")
8474
            .arg(&g)
8475
            .args([
8476
                "-c",
8477
                "user.name=Grace",
8478
                "-c",
8479
                "[email protected]",
8480
                "-c",
8481
                "commit.gpgsign=false",
8482
            ])
8483
            .args(args)
8484
            .output()
8485
            .unwrap();
8486
        assert!(
8487
            out.status.success(),
8488
            "git {args:?}: {}",
8489
            String::from_utf8_lossy(&out.stderr)
8490
        );
8491
    };
8492
    git(&["init", "-q", "-b", "main"]);
8493
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8494
    write(&g, "keep.txt", b"k\n");
8495
    git(&["add", "."]);
8496
    git(&["commit", "-qm", "base"]);
8497
    fs::create_dir_all(g.join("d/sub")).unwrap();
8498
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8499
    git(&["commit", "-qm", "into sub"]);
8500
    git(&["checkout", "-qb", "side"]);
8501
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8502
    git(&["commit", "-qm", "back, on side"]);
8503
    git(&["checkout", "-q", "main"]);
8504
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8505
    git(&["commit", "-qm", "back, on main"]);
8506
    git(&["merge", "-q", "--no-edit", "side"]);
8507
    git(&["rm", "-rq", "d"]);
8508
    git(&["commit", "-qm", "d goes"]);
8509
8510
    let repo = Repo::init(&root.join("o")).unwrap();
8511
    repo.import_git(&g, "main").unwrap();
8512
    let v = repo.verify_git_import(&g, "main").unwrap();
8513
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8514
    let st = repo
8515
        .load_state_history(&repo.bookmark_heads().unwrap())
8516
        .unwrap();
8517
    let view = st.tree().view();
8518
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8519
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8520
}
8521
8522
/// oxygen#94: a state index's file histories are read, and checked by
8523
/// their own hashes, only when a file is built. One found damaged is an
8524
/// error that says so, the index is removed, and the next read rebuilds it.
8525
#[test]
8526
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8527
    hermetic();
8528
    let dir = tempfile::tempdir().unwrap();
8529
    let repo = Repo::init(dir.path()).unwrap();
8530
    for i in 0..6 {
8531
        write(
8532
            dir.path(),
8533
            &format!("f{i}.txt"),
8534
            format!("one {i}\n").as_bytes(),
8535
        );
8536
    }
8537
    repo.snapshot("t").unwrap();
8538
    repo.commit("first", &[]).unwrap();
8539
    for i in 0..6 {
8540
        write(
8541
            dir.path(),
8542
            &format!("f{i}.txt"),
8543
            format!("one {i}\ntwo\n").as_bytes(),
8544
        );
8545
    }
8546
    repo.snapshot("t").unwrap();
8547
    repo.commit("second", &[]).unwrap();
8548
    let want: Vec<Vec<u8>> = (0..6)
8549
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8550
        .collect();
8551
    // The index of the working copy's base, holding every file's history
8552
    // (a few changes behind, an index is replayed onto, not rewritten).
8553
    let (_, wc) = repo.working_copy().unwrap();
8554
    let base = repo.load_state_history(&wc.deps).unwrap();
8555
    repo.write_state_index(&wc.deps, &base);
8556
    for (i, w) in want.iter().enumerate() {
8557
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8558
    }
8559
    let index = repo.state_indexes();
8560
    assert!(!index.is_empty(), "a state index was written");
8561
    // The histories are last in the file: damage the last of them.
8562
    let mut bytes = fs::read(&index[0]).unwrap();
8563
    let last = bytes.len() - 1;
8564
    bytes[last] ^= 0x40;
8565
    fs::write(&index[0], &bytes).unwrap();
8566
8567
    let reads: Vec<_> = (0..6)
8568
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8569
        .collect();
8570
    let damaged: Vec<String> = reads
8571
        .iter()
8572
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8573
        .collect();
8574
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8575
    assert!(
8576
        damaged[0].contains("state index was damaged")
8577
            && damaged[0].contains("run the command again"),
8578
        "{}",
8579
        damaged[0]
8580
    );
8581
    // Every file reads right again, from an index rebuilt from history.
8582
    for (i, w) in want.iter().enumerate() {
8583
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8584
    }
8585
}
8586
8587
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8588
/// objects alone and in dependency order, and the last moves the bookmark.
8589
/// The remote ends with every change and the same state, and says how each
8590
/// part went.
8591
#[test]
8592
fn a_long_push_goes_in_parts() {
8593
    hermetic();
8594
    let dir = tempfile::tempdir().unwrap();
8595
    let root = dir.path();
8596
    let origin = root.join("origin");
8597
    Repo::init_bare_unbound(&origin).unwrap();
8598
    let main = root.join("main");
8599
    let mut repo = Repo::init(&main).unwrap();
8600
    repo.config
8601
        .set("remote.origin.url", &origin.to_string_lossy())
8602
        .unwrap();
8603
    // One byte: every change is a part of its own.
8604
    repo.config.set("push.batch-bytes", "1").unwrap();
8605
    repo.save_config().unwrap();
8606
    for i in 0..6 {
8607
        write(
8608
            &main,
8609
            &format!("f{i}.txt"),
8610
            format!("file {i}\n").as_bytes(),
8611
        );
8612
        repo.commit(&format!("c{i}"), &[]).unwrap();
8613
    }
8614
    let mut parts = Vec::new();
8615
    let results = repo
8616
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8617
        .unwrap();
8618
    assert!(
8619
        results.iter().any(|r| r.ok && r.name == "main"),
8620
        "{results:?}"
8621
    );
8622
    assert_eq!(parts.len(), 6, "{parts:?}");
8623
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8624
8625
    let remote = Repo::open(&origin).unwrap();
8626
    let heads = repo.bookmark_heads().unwrap();
8627
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8628
    assert_eq!(
8629
        remote.log_state(&heads).unwrap().len(),
8630
        repo.log_state(&heads).unwrap().len()
8631
    );
8632
    // A push of objects alone reports how it went, as `objects`.
8633
    let got = remote
8634
        .receive_push(Bundle::default(), vec![], None, vec![])
8635
        .unwrap();
8636
    assert_eq!(got.len(), 1);
8637
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8638
}
8639
8640
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8641
/// own commits (Git author email = its email, any case) with its key, and
8642
/// leaves anyone else's with the zero key; the history verifies as before.
8643
#[test]
8644
fn git_import_claims_your_own_commits() {
8645
    hermetic();
8646
    if std::process::Command::new("git")
8647
        .arg("--version")
8648
        .output()
8649
        .is_err()
8650
    {
8651
        eprintln!("git not installed; skipping");
8652
        return;
8653
    }
8654
    let dir = tempfile::tempdir().unwrap();
8655
    let root = dir.path();
8656
    let g = root.join("src.git");
8657
    fs::create_dir_all(&g).unwrap();
8658
    let git = |who: &str, args: &[&str]| {
8659
        let (name, email) = who.split_once(' ').unwrap();
8660
        let out = std::process::Command::new("git")
8661
            .arg("-C")
8662
            .arg(&g)
8663
            .args([
8664
                "-c",
8665
                &format!("user.name={name}"),
8666
                "-c",
8667
                &format!("user.email={email}"),
8668
                "-c",
8669
                "commit.gpgsign=false",
8670
            ])
8671
            .args(args)
8672
            .output()
8673
            .unwrap();
8674
        assert!(
8675
            out.status.success(),
8676
            "git {args:?}: {}",
8677
            String::from_utf8_lossy(&out.stderr)
8678
        );
8679
    };
8680
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8681
    write(&g, "a.txt", b"a\n");
8682
    git("Grace [email protected]", &["add", "."]);
8683
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8684
    write(&g, "b.txt", b"b\n");
8685
    git("Ada [email protected]", &["add", "."]);
8686
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8687
8688
    let mut repo = Repo::init(&root.join("o")).unwrap();
8689
    let (key, _) = repo
8690
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8691
        .unwrap();
8692
    repo.config.set("git.claim", "true").unwrap();
8693
    repo.save_config().unwrap();
8694
    let repo = Repo::open(&root.join("o")).unwrap();
8695
    repo.import_git(&g, "main").unwrap();
8696
    let v = repo.verify_git_import(&g, "main").unwrap();
8697
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8698
    let heads = repo.bookmark_heads().unwrap();
8699
    let by_message: std::collections::HashMap<String, KeyId> = repo
8700
        .log_state(&heads)
8701
        .unwrap()
8702
        .into_iter()
8703
        .map(|e| {
8704
            (
8705
                e.change.message.lines().next().unwrap_or("").to_string(),
8706
                e.change.author,
8707
            )
8708
        })
8709
        .collect();
8710
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8711
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8712
}
8713
8714
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8715
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8716
#[test]
8717
fn removing_a_remote_leaves_nothing_of_it() {
8718
    hermetic();
8719
    let dir = tempfile::tempdir().unwrap();
8720
    let origin = dir.path().join("origin");
8721
    Repo::init_bare_unbound(&origin).unwrap();
8722
    let main = dir.path().join("main");
8723
    let mut repo = Repo::init(&main).unwrap();
8724
    repo.config
8725
        .set("remote.origin.url", &origin.to_string_lossy())
8726
        .unwrap();
8727
    repo.config
8728
        .set("remote.origin.token", "secret-ish")
8729
        .unwrap();
8730
    repo.config
8731
        .set("remote.keep.url", &origin.to_string_lossy())
8732
        .unwrap();
8733
    repo.save_config().unwrap();
8734
    write(&main, "a.txt", b"a\n");
8735
    repo.commit("a", &[]).unwrap();
8736
    assert!(repo.push("origin", false).unwrap()[0].ok);
8737
    assert!(
8738
        repo.view().unwrap().remotes.contains_key("origin"),
8739
        "a tracking bookmark"
8740
    );
8741
8742
    repo.remove_remote("origin").unwrap();
8743
    let again = Repo::open(&main).unwrap();
8744
    assert!(
8745
        !again
8746
            .config
8747
            .repo_layer()
8748
            .keys()
8749
            .any(|k| k.starts_with("remote.origin.")),
8750
        "{:?}",
8751
        again.config.repo_layer()
8752
    );
8753
    assert!(!again.config.remotes.contains_key("origin"));
8754
    assert!(
8755
        !again.view().unwrap().remotes.contains_key("origin"),
8756
        "its tracking bookmarks go"
8757
    );
8758
    assert!(
8759
        again.config.remotes.contains_key("keep"),
8760
        "another remote stays"
8761
    );
8762
    let mut again = again;
8763
    assert!(
8764
        again.remove_remote("origin").is_err(),
8765
        "a second removal is refused"
8766
    );
8767
}
8768
8769
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
8770
/// unreachable from history, so gc prunes it, unless the host names it:
8771
/// then it and its chunks stay, and it reads back whole.
8772
#[test]
8773
fn gc_keeps_the_blobs_a_host_names() {
8774
    hermetic();
8775
    let dir = tempfile::tempdir().unwrap();
8776
    let repo = Repo::init(dir.path()).unwrap();
8777
    write(dir.path(), "a.txt", b"a\n");
8778
    repo.commit("a", &[]).unwrap();
8779
    // Large enough to be several chunks.
8780
    let body: Vec<u8> = (0..400_000u32)
8781
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
8782
        .collect();
8783
    let kept = repo.store_blob(&body).unwrap();
8784
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
8785
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
8786
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
8787
    assert!(!repo.store().has(&lost), "not named: pruned");
8788
    repo.gc(true).unwrap();
8789
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
8790
}
8791
8792
/// oxygen#99: undo in one workspace undoes that workspace's last command,
8793
/// never another workspace's, says what it undid, and goes further back
8794
/// when run again.
8795
#[test]
8796
fn undo_is_scoped_to_its_workspace() {
8797
    hermetic();
8798
    let dir = tempfile::tempdir().unwrap();
8799
    let root = dir.path().join("main");
8800
    let a = Repo::init(&root).unwrap();
8801
    write(&root, "base.txt", b"base\n");
8802
    let base = a.commit("base", &[]).unwrap();
8803
    a.bookmark_create("feature", None).unwrap();
8804
    let ws_dir = dir.path().join("ws");
8805
    let heads = a.resolve_heads("feature").unwrap();
8806
    let b = a
8807
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
8808
        .unwrap();
8809
8810
    // A commits on main, then B commits on feature: B's is the newest.
8811
    write(&root, "a.txt", b"a\n");
8812
    let ca = a.commit("from a", &[]).unwrap();
8813
    write(&ws_dir, "b.txt", b"b\n");
8814
    let cb = b.commit("from b", &[]).unwrap();
8815
8816
    // A's undo undoes A's commit and leaves B's.
8817
    let u = a.undo().unwrap();
8818
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8819
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
8820
    assert!(!u.changes.is_empty());
8821
    let view = a.view().unwrap();
8822
    // (Independent changes commute, so a bookmark's heads may hold base too.)
8823
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
8824
    assert!(
8825
        a.heads_of(&view, "feature").unwrap().contains(&cb),
8826
        "B's commit stands"
8827
    );
8828
    assert!(
8829
        a.store().get_change(&ca).is_ok(),
8830
        "the change itself is still in the store"
8831
    );
8832
    // A's working copy was clean, so its files followed; B's are untouched.
8833
    assert!(!root.join("a.txt").exists());
8834
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
8835
    assert!(ws_dir.join("b.txt").exists());
8836
8837
    // B's undo still finds B's own commit, under A's undo.
8838
    let u = b.undo().unwrap();
8839
    assert_eq!(u.command, "oxy commit -m \"from b\"");
8840
    assert!(!b
8841
        .heads_of(&b.view().unwrap(), "feature")
8842
        .unwrap()
8843
        .contains(&cb));
8844
    assert_eq!(
8845
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
8846
        vec![base],
8847
        "A's undo stands"
8848
    );
8849
8850
    // A's next undo goes past the commit it already undid, to adding B's
8851
    // workspace: refused, since B has worked there since.
8852
    let e = a.undo().unwrap_err().to_string();
8853
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
8854
}
8855
8856
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
8857
/// own commit's head, and the other workspace's head stays.
8858
#[test]
8859
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
8860
    hermetic();
8861
    let dir = tempfile::tempdir().unwrap();
8862
    let root = dir.path().join("main");
8863
    let a = Repo::init(&root).unwrap();
8864
    write(&root, "base.txt", b"base\n");
8865
    a.commit("base", &[]).unwrap();
8866
    let ws_dir = dir.path().join("ws");
8867
    let b = a.workspace_add(&ws_dir, None).unwrap();
8868
    write(&root, "a.txt", b"a\n");
8869
    let ca = a.commit("from a", &[]).unwrap();
8870
    write(&ws_dir, "b.txt", b"b\n");
8871
    let cb = b.commit("from b", &[]).unwrap();
8872
    let u = a.undo().unwrap();
8873
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8874
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
8875
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
8876
}
8877
8878
/// oxygen#99: an undo that would also take back what another workspace
8879
/// did since to the same bookmark is refused, naming it.
8880
#[test]
8881
fn undo_refuses_to_take_back_another_workspaces_work() {
8882
    hermetic();
8883
    let dir = tempfile::tempdir().unwrap();
8884
    let root = dir.path().join("main");
8885
    let a = Repo::init(&root).unwrap();
8886
    write(&root, "base.txt", b"base\n");
8887
    a.commit("base", &[]).unwrap();
8888
    let ws_dir = dir.path().join("ws");
8889
    let b = a.workspace_add(&ws_dir, None).unwrap();
8890
    // Both on main: A commits, then B builds on it, editing A's file.
8891
    write(&root, "a.txt", b"a\n");
8892
    a.commit("from a", &[]).unwrap();
8893
    let heads = b.resolve_heads("main").unwrap();
8894
    b.checkout(&heads, false, "oxy checkout").unwrap();
8895
    write(&ws_dir, "a.txt", b"a, then b\n");
8896
    b.commit("from b", &[]).unwrap();
8897
    let e = a.undo().unwrap_err().to_string();
8898
    assert!(
8899
        e.contains("bookmark main") && e.contains("builds on"),
8900
        "{e}"
8901
    );
8902
    assert!(e.contains("oxy op restore"), "{e}");
8903
}
8904
8905
/// oxygen#99: undoing a commit that was already pushed says so: the remote
8906
/// still has it.
8907
#[test]
8908
fn undo_says_when_the_commit_was_pushed() {
8909
    hermetic();
8910
    let dir = tempfile::tempdir().unwrap();
8911
    let root = dir.path();
8912
    Repo::init(&root.join("origin")).unwrap();
8913
    let url = root.join("origin").to_string_lossy().to_string();
8914
    let repo = Repo::clone(&url, &root.join("work"))
8915
        .unwrap()
8916
        .with_home(root.join("home"));
8917
    write(&root.join("work"), "a.txt", b"a\n");
8918
    repo.commit("a", &[]).unwrap();
8919
    assert!(repo.push("origin", false).unwrap()[0].ok);
8920
    // The push itself is passed over: the remote keeps what it was sent.
8921
    let u = repo.undo().unwrap();
8922
    assert_eq!(u.command, "oxy commit -m \"a\"");
8923
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
8924
}
8925
8926
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
8927
/// out of the snapshot and named; tracked files and files already in the
8928
/// working copy are not.
8929
#[test]
8930
fn large_new_files_are_left_out_of_snapshots() {
8931
    hermetic();
8932
    let dir = tempfile::tempdir().unwrap();
8933
    let root = dir.path();
8934
    let mut repo = Repo::init(root).unwrap();
8935
    repo.config.max_new_file = 1024;
8936
    write(root, "small.txt", b"small\n");
8937
    write(root, "big.bin", &vec![0u8; 4096]);
8938
    let s = repo.snapshot("oxy status").unwrap();
8939
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8940
    assert_eq!(paths, ["small.txt"]);
8941
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
8942
    repo.commit("small", &[]).unwrap();
8943
8944
    // A tracked file may grow past the limit.
8945
    write(root, "small.txt", &vec![b'x'; 4096]);
8946
    let s = repo.snapshot("oxy status").unwrap();
8947
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
8948
    // With no limit the big file is taken in, and stays once it is.
8949
    repo.config.max_new_file = 0;
8950
    let s = repo.snapshot("oxy status").unwrap();
8951
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
8952
    repo.config.max_new_file = 1024;
8953
    let s = repo.snapshot("oxy status").unwrap();
8954
    assert!(
8955
        s.statuses.iter().any(|p| p.path == "big.bin"),
8956
        "already in the working copy"
8957
    );
8958
    assert!(repo.skipped_large().is_empty());
8959
}
8960
8961
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
8962
/// snapshots expire, and kept while they have not.
8963
#[test]
8964
fn gc_prunes_what_only_expired_snapshots_held() {
8965
    hermetic();
8966
    let dir = tempfile::tempdir().unwrap();
8967
    let root = dir.path();
8968
    let mut repo = Repo::init(root).unwrap();
8969
    repo.config.gc_grace_days = 0;
8970
    write(root, "a.txt", b"a\n");
8971
    repo.commit("a", &[]).unwrap();
8972
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
8973
    write(root, "image.tar", &image);
8974
    repo.snapshot("oxy status").unwrap();
8975
    std::fs::remove_file(root.join("image.tar")).unwrap();
8976
    repo.snapshot("oxy status").unwrap();
8977
    let blob = Repo::blob_ref(&image);
8978
    assert!(repo.store().has(&blob));
8979
    repo.gc(true).unwrap();
8980
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
8981
    repo.config.snapshot_retention_days = 0;
8982
    repo.gc(true).unwrap();
8983
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
8984
    assert_eq!(
8985
        repo.file_at("a.txt", None).unwrap(),
8986
        b"a\n",
8987
        "committed files stay"
8988
    );
8989
}
8990
8991
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
8992
/// already has is no conflict: the switch goes through, nothing is lost,
8993
/// and other carried work still comes along.
8994
#[test]
8995
fn carrying_work_the_target_already_has_is_no_conflict() {
8996
    hermetic();
8997
    let dir = tempfile::tempdir().unwrap();
8998
    let root = dir.path();
8999
    let mut repo = Repo::init(root).unwrap();
9000
    write(root, "a.txt", b"one\n");
9001
    write(root, "b.txt", b"b\n");
9002
    repo.commit("one", &[]).unwrap();
9003
    repo.bookmark_create("landed", None).unwrap();
9004
    // On landed, a.txt becomes "two" (as a proposal landing would).
9005
    repo.bookmark_switch("landed", false).unwrap();
9006
    write(root, "a.txt", b"two\n");
9007
    repo.commit("two", &[]).unwrap();
9008
    repo.bookmark_switch("main", false).unwrap();
9009
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
9010
    // The same edit, uncommitted, on main; and another edit besides.
9011
    write(root, "a.txt", b"two\n");
9012
    write(root, "b.txt", b"b, edited\n");
9013
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
9014
    assert_eq!(
9015
        carried,
9016
        vec!["b.txt".to_string()],
9017
        "only the work landed lacks is carried"
9018
    );
9019
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
9020
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
9021
    let s = repo.snapshot("oxy status").unwrap();
9022
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9023
    assert_eq!(paths, ["b.txt"]);
9024
9025
    // A real difference is still refused.
9026
    repo.bookmark_switch("main", true).unwrap();
9027
    write(root, "a.txt", b"three\n");
9028
    let e = repo
9029
        .bookmark_switch_carry("landed")
9030
        .unwrap_err()
9031
        .to_string();
9032
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
9033
}
9034
9035
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
9036
/// resolves, so JSON output feeds back into commands.
9037
#[test]
9038
fn a_full_hash_resolves_without_its_hash_sign() {
9039
    hermetic();
9040
    let dir = tempfile::tempdir().unwrap();
9041
    let root = dir.path();
9042
    let repo = Repo::init(root).unwrap();
9043
    write(root, "a.txt", b"a\n");
9044
    let h = repo.commit("a", &[]).unwrap();
9045
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
9046
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
9047
    assert!(repo
9048
        .resolve_change(&"0".repeat(64))
9049
        .unwrap_err()
9050
        .to_string()
9051
        .contains("no change matches"));
9052
}
9053
9054
#[test]
9055
fn a_pin_change_moves_only_the_pin() {
9056
    hermetic();
9057
    let dir = tempfile::tempdir().unwrap();
9058
    let root = dir.path();
9059
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9060
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9061
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9062
        .unwrap()
9063
        .with_home(root.join("home"));
9064
    write(&root.join("lib"), "lib.txt", b"v1\n");
9065
    lib.commit("lib v1", &[]).unwrap();
9066
    assert!(lib.push("origin", false).unwrap()[0].ok);
9067
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
9068
    let app_dir = root.join("app");
9069
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
9070
        .unwrap()
9071
        .with_home(root.join("home"));
9072
    write(&app_dir, "main.txt", b"app\n");
9073
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9074
    let a1 = app.commit("app with lib", &[]).unwrap();
9075
    // The library moves on.
9076
    write(&root.join("lib"), "more.txt", b"v2\n");
9077
    let l2 = lib.commit("lib v2", &[]).unwrap();
9078
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
9079
        panic!("an Oxygen pin")
9080
    };
9081
    let pin2 = crate::subrepo::Pin::Oxy {
9082
        repo,
9083
        heads: vec![l2],
9084
        bookmark,
9085
    };
9086
    let author = app.store().get_change(&a1).unwrap().author;
9087
    let change = app
9088
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
9089
        .unwrap();
9090
    let mut state = app.load_state(&[a1]).unwrap();
9091
    state.add(change).unwrap();
9092
    let files = state.materialize().files;
9093
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
9094
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
9095
        panic!("a pin is opaque")
9096
    };
9097
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
9098
    assert_eq!(read, pin2, "the new pin");
9099
    assert!(
9100
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
9101
        "nothing else changes"
9102
    );
9103
    // Only a subrepo's pin can be moved this way.
9104
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
9105
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
9106
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
9107
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
9108
}