OXYGENHUB
# b333a19976e4 oxygen / crates / oxy-core / src / repo / tests.rs
325.1 KiB · Rust · last changed Grants let certified keys act for an author (keyless step 5a) 19 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!(d.contains("+    println!(\"hi\");"), "{d}");
138
    assert!(d.contains("-fn main() {}"), "{d}");
139
140
    // Resolution by prefix.
141
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
142
    assert_eq!(
143
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
144
        h1
145
    );
146
    assert!(repo.resolve_change("zzzz").is_err());
147
148
    // Undo the commit: bookmark and working copy go back.
149
    repo.undo().unwrap();
150
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
151
    let s = repo.snapshot("oxy status").unwrap();
152
    assert!(
153
        !s.changed,
154
        "files on disk still match the pre-commit working copy"
155
    );
156
    assert_eq!(s.statuses.len(), 3);
157
}
158
159
/// Make `main` conflicted: two commits on the same base that edit the same line.
160
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
161
    let dir = tempfile::tempdir().unwrap();
162
    let root = dir.path();
163
    let repo = Repo::init(root).unwrap();
164
    write(root, "f.txt", b"a\nb\nc\n");
165
    let h1 = repo.commit("base", &[]).unwrap();
166
    write(root, "f.txt", b"a\nB\nc\n");
167
    let h2 = repo.commit("upper", &[]).unwrap();
168
    repo.checkout(&[h1], false, "checkout").unwrap();
169
    write(root, "f.txt", b"a\nX\nc\n");
170
    let h3 = repo.commit("ex", &[]).unwrap();
171
    (dir, repo, h1, h2, h3)
172
}
173
174
#[test]
175
fn concurrent_edits_conflict_and_can_be_resolved() {
176
    hermetic();
177
    let (dir, repo, h1, h2, h3) = conflicted_repo();
178
    let root = dir.path();
179
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
180
    assert_eq!(heads, [h2, h3].into_iter().collect());
181
    let st = repo.load_state(&[h2, h3]).unwrap();
182
    assert!(st.materialize().is_conflicted());
183
184
    // Checking out main writes markers.
185
    let r = repo
186
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
187
        .unwrap();
188
    assert!(r.conflicted);
189
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
190
    assert!(
191
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
192
        "{marked}"
193
    );
194
    assert!(
195
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
196
        "{marked}"
197
    );
198
    assert!(has_conflict_markers(marked.as_bytes()));
199
    // Untouched markers: clean working copy; commit has nothing to do.
200
    let s = repo.snapshot("status").unwrap();
201
    assert!(s.statuses.is_empty());
202
    assert!(!s.resolves);
203
204
    // Partially edited file that still has markers cannot be committed.
205
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
206
    let s = repo.snapshot("status").unwrap();
207
    assert_eq!(
208
        statuses(&s),
209
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
210
    );
211
    assert!(repo.commit("no", &[]).is_err());
212
213
    // Resolve by keeping one side and adding a line elsewhere.
214
    write(root, "f.txt", b"a\nX\nc\nd\n");
215
    let s = repo.snapshot("status").unwrap();
216
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
217
    assert!(s.resolves);
218
    let h4 = repo.commit("resolve", &[]).unwrap();
219
    let c4 = repo.store().get_change(&h4).unwrap();
220
    assert_eq!(c4.kind, ChangeKind::Resolution);
221
    let mut want = vec![h1, h2, h3];
222
    want.sort();
223
    assert_eq!(
224
        c4.deps, want,
225
        "a resolution depends on exactly the contributors and what it references"
226
    );
227
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
228
    let snap = repo.load_state(&[h4]).unwrap().materialize();
229
    assert!(!snap.is_conflicted());
230
    assert!(
231
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
232
    );
233
    assert!(!repo.snapshot("status").unwrap().changed);
234
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
235
    // whatever order the changes arrive in.
236
    let mut st = State::new();
237
    for h in [h4, h3, h1, h2] {
238
        st.add_unchecked(repo.store().get_change(&h).unwrap());
239
    }
240
    st.validate().unwrap();
241
    assert!(
242
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
243
    );
244
}
245
246
#[test]
247
fn resolution_may_keep_both_sides_or_neither() {
248
    hermetic();
249
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
250
    let root = dir.path();
251
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
252
        .unwrap();
253
    // Keep both sides in a chosen order.
254
    write(root, "f.txt", b"a\nX\nB\nc\n");
255
    let h = repo.commit("both", &[]).unwrap();
256
    let snap = repo.load_state(&[h]).unwrap().materialize();
257
    assert!(!snap.is_conflicted());
258
    assert!(
259
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
260
    );
261
    // Undo and instead drop the whole region.
262
    repo.undo().unwrap();
263
    write(root, "f.txt", b"a\nc\n");
264
    let h = repo.commit("neither", &[]).unwrap();
265
    let snap = repo.load_state(&[h]).unwrap().materialize();
266
    assert!(!snap.is_conflicted());
267
    assert!(
268
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
269
    );
270
}
271
272
#[test]
273
fn name_conflict_resolved_by_removing_a_candidate() {
274
    hermetic();
275
    let dir = tempfile::tempdir().unwrap();
276
    let root = dir.path();
277
    let repo = Repo::init(root).unwrap();
278
    write(root, "keep.txt", b"k\n");
279
    let h1 = repo.commit("base", &[]).unwrap();
280
    write(root, "new.txt", b"one\n");
281
    repo.commit("one", &[]).unwrap();
282
    repo.checkout(&[h1], false, "checkout").unwrap();
283
    write(root, "new.txt", b"two\n");
284
    repo.commit("two", &[]).unwrap();
285
    let r = repo
286
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
287
        .unwrap();
288
    assert!(r.conflicted);
289
    assert!(
290
        root.join("new.txt.oxy-conflict-1").exists()
291
            && root.join("new.txt.oxy-conflict-2").exists()
292
    );
293
    assert!(!root.join("new.txt").exists());
294
    // Candidate numbering follows change-hash order, so pick by content:
295
    // keep the "two" candidate under the real name and drop the other.
296
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
297
        (1, 2)
298
    } else {
299
        (2, 1)
300
    };
301
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
302
    fs::rename(
303
        root.join(format!("new.txt.oxy-conflict-{keep}")),
304
        root.join("new.txt"),
305
    )
306
    .unwrap();
307
    let h = repo.commit("pick two", &[]).unwrap();
308
    assert_eq!(
309
        repo.store().get_change(&h).unwrap().kind,
310
        ChangeKind::Resolution
311
    );
312
    // The resolution does not touch keep.txt, so it does not depend on h1;
313
    // the bookmark keeps both as heads and their union is the state.
314
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
315
    assert_eq!(heads, [h1, h].into_iter().collect());
316
    let snap = repo
317
        .load_state(&repo.bookmark_heads().unwrap())
318
        .unwrap()
319
        .materialize();
320
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
321
    assert_eq!(
322
        snap.files.keys().cloned().collect::<Vec<_>>(),
323
        ["keep.txt", "new.txt"]
324
    );
325
    assert!(
326
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
327
    );
328
}
329
330
#[test]
331
fn identities_and_signed_commits() {
332
    hermetic();
333
    let dir = tempfile::tempdir().unwrap();
334
    let root = dir.path();
335
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
336
    write(root, "a.txt", b"a\n");
337
    let h0 = repo.commit("unsigned", &[]).unwrap();
338
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
339
    assert_eq!(
340
        repo.store().get_change(&h0).unwrap().author,
341
        ObjectRef::ZERO
342
    );
343
344
    let (key, id) = repo
345
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
346
        .unwrap();
347
    assert_eq!(id.hash(), key);
348
    assert_eq!(repo.config.author_key, Some(key));
349
    // Config survives reopen; the secret key is found again.
350
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
351
    assert_eq!(reopened.config.author_key, Some(key));
352
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
353
354
    // Default core.sign = seal: commits carry the author but no signature.
355
    write(root, "a.txt", b"a\nb\n");
356
    let h1 = repo.commit("authored", &[]).unwrap();
357
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
358
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
359
    // Signing later works too.
360
    repo.sign_change(&h1).unwrap();
361
    assert!(
362
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
363
    );
364
365
    repo.config.set("core.sign", "change").unwrap();
366
    repo.save_config().unwrap();
367
    write(root, "a.txt", b"a\nb\nc\n");
368
    let h2 = repo.commit("signed", &[]).unwrap();
369
    assert_eq!(
370
        repo.verify_change(&h2).unwrap(),
371
        SignatureStatus::Valid {
372
            key,
373
            name: "Ada".into(),
374
            email: "[email protected]".into(),
375
            sealed: false,
376
            revoked: false
377
        }
378
    );
379
380
    // A signature by a key that is not the author or a delegate is rejected
381
    // when the change names an author; an anonymous change (made before any
382
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
383
    let other = SecretKey::generate();
384
    let other_id = other.identity("Mallory", "[email protected]", 0);
385
    let other_key = repo.store().put_identity(&other_id).unwrap();
386
    write(root, "a.txt", b"a\nb\nc\nd\n");
387
    repo.config.set("core.sign", "seal").unwrap();
388
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
389
    let forged = other.sign(Domain::Change, &other_key, &h3);
390
    repo.store().put_signature(&h3, &forged).unwrap();
391
    assert!(
392
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
393
    );
394
    let adopted = other.sign(Domain::Change, &other_key, &h0);
395
    repo.store().put_signature(&h0, &adopted).unwrap();
396
    assert!(
397
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
398
    );
399
400
    // Tampering with the stored signature invalidates it.
401
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
402
    sig.ed[0] ^= 1;
403
    repo.store().put_signature(&h2, &sig).unwrap();
404
    assert!(matches!(
405
        repo.verify_change(&h2).unwrap(),
406
        SignatureStatus::Invalid(_)
407
    ));
408
409
    // Without the secret key, signing at commit fails cleanly.
410
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
411
    write(root, "a.txt", b"z\n");
412
    assert!(no_keys.commit("cannot sign", &[]).is_err());
413
}
414
415
#[test]
416
fn checkout_moves_the_working_copy() {
417
    hermetic();
418
    let dir = tempfile::tempdir().unwrap();
419
    let root = dir.path();
420
    let repo = Repo::init(root).unwrap();
421
    write(root, "a.txt", b"one\n");
422
    write(root, "sub/deep/b.txt", b"b\n");
423
    let h1 = repo.commit("first", &[]).unwrap();
424
    write(root, "a.txt", b"two\n");
425
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
426
    write(root, "bin.dat", &[0, 1, 2, 3]);
427
    let h2 = repo.commit("second", &[]).unwrap();
428
429
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
430
    assert_eq!(
431
        r,
432
        CheckoutReport {
433
            written: 2,
434
            removed: 1,
435
            conflicted: false,
436
            notes: vec![],
437
            lacks: 1,
438
        }
439
    );
440
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
441
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
442
    assert!(!root.join("bin.dat").exists());
443
    let (_, wc) = repo.working_copy().unwrap();
444
    assert_eq!(wc.deps, vec![h1]);
445
    assert!(
446
        !repo.snapshot("status").unwrap().changed,
447
        "checkout leaves a clean working copy"
448
    );
449
    // The bookmark still points at h2.
450
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
451
452
    // Dirty working copy refuses without --discard.
453
    write(root, "a.txt", b"dirty\n");
454
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
455
    let r = repo
456
        .checkout(&[h2], true, "oxy checkout --discard")
457
        .unwrap();
458
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
459
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
460
    assert!(!root.join("sub").exists(), "empty directories are pruned");
461
    assert_eq!(r.removed, 1);
462
    assert!(!repo.snapshot("status").unwrap().changed);
463
464
    // Refuses to write through a symlinked directory.
465
    #[cfg(unix)]
466
    {
467
        fs::remove_dir_all(root.join("sub")).ok();
468
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
469
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
470
    }
471
}
472
473
#[test]
474
fn large_files_are_chunked_and_read_back() {
475
    hermetic();
476
    let dir = tempfile::tempdir().unwrap();
477
    let repo = Repo::init(dir.path()).unwrap();
478
    let mut big = vec![0u8; 700 * 1024];
479
    for (i, b) in big.iter_mut().enumerate() {
480
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
481
    }
482
    let r = repo.store_blob(&big).unwrap();
483
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
484
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
485
    assert_eq!(repo.read_blob(&r).unwrap(), big);
486
    assert_eq!(Repo::blob_ref(&big), r);
487
}
488
489
#[test]
490
fn clone_push_pull_with_seals_and_attestations() {
491
    hermetic();
492
    let dir = tempfile::tempdir().unwrap();
493
    let root = dir.path();
494
    let origin_path = root.join("origin");
495
    let origin = Repo::init(&origin_path).unwrap();
496
    let origin_url = origin_path.to_string_lossy().to_string();
497
498
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
499
    let mut a = Repo::clone(&origin_url, &root.join("a"))
500
        .unwrap()
501
        .with_home(root.join("home-a"));
502
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
503
    let (key_a, _) = a
504
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
505
        .unwrap();
506
    write(&root.join("a"), "f.txt", b"a\n");
507
    let h1 = a.commit("first", &[]).unwrap();
508
    let results = a.push("origin", false).unwrap();
509
    assert!(results[0].ok, "{}", results[0].reason);
510
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
511
    // The change was sealed at push and the reference attested.
512
    assert!(
513
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
514
    );
515
    assert_eq!(
516
        origin.verify_change(&h1).unwrap(),
517
        SignatureStatus::Unsigned
518
    );
519
    let serial_of = |att: &SignedAttest| match att.attest.body {
520
        AttestBody::Ref { serial, .. } => serial,
521
        _ => unreachable!(),
522
    };
523
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
524
    // A bookmark new to the remote starts at the clock (past any deleted
525
    // namesake's serial); later updates count up from there.
526
    let first = serial_of(&att);
527
    assert!(first > 1_000_000_000_000, "{first}");
528
    let again = a.push("origin", false).unwrap();
529
    assert!(again[0].ok && again[0].reason.contains("up to date"));
530
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
531
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
532
533
    // B clones and sees the file and the seal.
534
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
535
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
536
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
537
    assert!(matches!(
538
        b.authenticate_change(&h1).unwrap(),
539
        SignatureStatus::Valid { sealed: true, .. }
540
    ));
541
542
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
543
    write(&root.join("b"), "f.txt", b"a\nb\n");
544
    let h2 = b.commit("second", &[]).unwrap();
545
    assert!(b.push("origin", false).unwrap()[0].ok);
546
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
547
548
    // A commits an independent change; push is refused until A pulls.
549
    write(&root.join("a"), "g.txt", b"g\n");
550
    let h3 = a.commit("third", &[]).unwrap();
551
    assert!(a.push("origin", false).is_err());
552
    let pr = a.pull("origin").unwrap();
553
    assert!(pr.changed && pr.checked_out);
554
    let mut want = vec![h2, h3];
555
    want.sort();
556
    assert_eq!(pr.heads, want);
557
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
558
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
559
    let results = a.push("origin", false).unwrap();
560
    assert!(results[0].ok, "{}", results[0].reason);
561
    let mut origin_heads = origin.bookmark_heads().unwrap();
562
    origin_heads.sort();
563
    assert_eq!(origin_heads, want);
564
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
565
    assert_eq!(serial_of(&att), first + 1);
566
567
    // B pulls and ends up identical.
568
    let pr = b.pull("origin").unwrap();
569
    assert_eq!(pr.heads, want);
570
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
571
    assert!(!b.snapshot("status").unwrap().changed);
572
573
    // Concurrent edits of the same line: the union is a reified conflict.
574
    write(&root.join("a"), "f.txt", b"a\nA\n");
575
    a.commit("a-edit", &[]).unwrap();
576
    a.push("origin", false).unwrap();
577
    write(&root.join("b"), "f.txt", b"a\nB\n");
578
    b.commit("b-edit", &[]).unwrap();
579
    let pr = b.pull("origin").unwrap();
580
    assert!(pr.changed && pr.checked_out);
581
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
582
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
583
    write(&root.join("b"), "f.txt", b"a\nAB\n");
584
    let hr = b.commit("resolve", &[]).unwrap();
585
    assert_eq!(
586
        b.store().get_change(&hr).unwrap().kind,
587
        ChangeKind::Resolution
588
    );
589
    assert!(b.push("origin", false).unwrap()[0].ok);
590
    a.pull("origin").unwrap();
591
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
592
    // The resolution depends on the conflicting edits, but nothing depends
593
    // on "third" (it only added g.txt), so it stays a head beside it.
594
    let mut want = vec![hr, h3];
595
    want.sort();
596
    assert_eq!(a.bookmark_heads().unwrap(), want);
597
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
598
}
599
600
#[test]
601
fn receive_push_rejects_bad_updates() {
602
    hermetic();
603
    let dir = tempfile::tempdir().unwrap();
604
    let root = dir.path();
605
    let origin = Repo::init(&root.join("origin")).unwrap();
606
    let url = root.join("origin").to_string_lossy().to_string();
607
    let mut a = Repo::clone(&url, &root.join("a"))
608
        .unwrap()
609
        .with_home(root.join("home"));
610
    let (key, _) = a
611
        .create_identity("Ada", "a@b", IdentityScope::Repo)
612
        .unwrap();
613
    write(&root.join("a"), "f.txt", b"x\n");
614
    let h1 = a.commit("one", &[]).unwrap();
615
    assert!(a.push("origin", false).unwrap()[0].ok);
616
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
617
    let s1 = origin
618
        .store()
619
        .put_state(&StateObject::new(vec![h1]))
620
        .unwrap();
621
622
    // Missing head.
623
    let ghost = origin
624
        .store()
625
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
626
        .unwrap();
627
    let r = origin
628
        .receive_push(
629
            Bundle::default(),
630
            vec![RefUpdate {
631
                name: "main".into(),
632
                old_state: s1,
633
                new_state: ghost,
634
                force: false,
635
                attestation: None,
636
            }],
637
            None,
638
            vec![],
639
        )
640
        .unwrap();
641
    assert!(
642
        !r[0].ok && r[0].reason.contains("missing"),
643
        "{}",
644
        r[0].reason
645
    );
646
647
    // Stale old_state.
648
    let r = origin
649
        .receive_push(
650
            Bundle::default(),
651
            vec![RefUpdate {
652
                name: "main".into(),
653
                old_state: empty,
654
                new_state: s1,
655
                force: false,
656
                attestation: None,
657
            }],
658
            None,
659
            vec![],
660
        )
661
        .unwrap();
662
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
663
664
    // Non-fast-forward without force is refused; with force it passes.
665
    let r = origin
666
        .receive_push(
667
            Bundle::default(),
668
            vec![RefUpdate {
669
                name: "main".into(),
670
                old_state: s1,
671
                new_state: empty,
672
                force: false,
673
                attestation: None,
674
            }],
675
            None,
676
            vec![],
677
        )
678
        .unwrap();
679
    assert!(
680
        !r[0].ok && r[0].reason.contains("fast-forward"),
681
        "{}",
682
        r[0].reason
683
    );
684
    let r = origin
685
        .receive_push(
686
            Bundle::default(),
687
            vec![RefUpdate {
688
                name: "main".into(),
689
                old_state: s1,
690
                new_state: empty,
691
                force: true,
692
                attestation: None,
693
            }],
694
            None,
695
            vec![],
696
        )
697
        .unwrap();
698
    assert!(r[0].ok);
699
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
700
701
    // Attestation with a stale serial is a rollback and is refused.
702
    let sa = a
703
        .sign_attest(&Attest {
704
            repo: a.id().unwrap(),
705
            hlc: Hlc::now(),
706
            body: AttestBody::Ref {
707
                name: "main".into(),
708
                old_state: empty,
709
                new_state: s1,
710
                serial: 1,
711
            },
712
        })
713
        .unwrap();
714
    let r = origin
715
        .receive_push(
716
            Bundle::default(),
717
            vec![RefUpdate {
718
                name: "main".into(),
719
                old_state: empty,
720
                new_state: s1,
721
                force: false,
722
                attestation: Some(sa.clone()),
723
            }],
724
            None,
725
            vec![],
726
        )
727
        .unwrap();
728
    assert!(
729
        !r[0].ok && r[0].reason.contains("serial"),
730
        "{}",
731
        r[0].reason
732
    );
733
    // An attestation for a different update is refused too.
734
    let sa2 = a
735
        .sign_attest(&Attest {
736
            repo: a.id().unwrap(),
737
            hlc: Hlc::now(),
738
            body: AttestBody::Ref {
739
                name: "main".into(),
740
                old_state: s1,
741
                new_state: empty,
742
                serial: 5,
743
            },
744
        })
745
        .unwrap();
746
    let r = origin
747
        .receive_push(
748
            Bundle::default(),
749
            vec![RefUpdate {
750
                name: "main".into(),
751
                old_state: empty,
752
                new_state: s1,
753
                force: false,
754
                attestation: Some(sa2),
755
            }],
756
            None,
757
            vec![],
758
        )
759
        .unwrap();
760
    assert!(
761
        !r[0].ok && r[0].reason.contains("describe"),
762
        "{}",
763
        r[0].reason
764
    );
765
    let _ = key;
766
}
767
768
#[test]
769
fn user_config_supplies_defaults_and_clones_sign() {
770
    hermetic();
771
    let dir = tempfile::tempdir().unwrap();
772
    let root = dir.path();
773
    let home = root.join("home");
774
    let origin = Repo::init(&root.join("origin")).unwrap();
775
    let url = root.join("origin").to_string_lossy().to_string();
776
777
    // Identity at user scope: the repository file stays free of author keys.
778
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
779
    let (key, _) = a
780
        .create_identity("Ada", "[email protected]", IdentityScope::User)
781
        .unwrap();
782
    assert!(!a.config.repo_layer().contains_key("author.key"));
783
    assert_eq!(a.config.author_key, Some(key));
784
    assert!(home.join("config.toml").exists());
785
    a.set_user_config("core.sign", "change").unwrap();
786
    assert!(a.config.sign_changes);
787
788
    // Repository settings override user settings and are the only ones saved.
789
    a.config.set("core.sign", "seal").unwrap();
790
    a.save_config().unwrap();
791
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
792
    assert!(!again.config.sign_changes);
793
    assert_eq!(again.config.author_key, Some(key));
794
    assert_eq!(
795
        read_config_file(&root.join("a/.oxy/config"))
796
            .unwrap()
797
            .get("core.sign")
798
            .map(String::as_str),
799
        Some("seal")
800
    );
801
802
    // A fresh clone made by this user signs with the user-level identity,
803
    // even though the clone's store has never seen the identity object.
804
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
805
    assert!(b.config.sign_changes);
806
    write(&root.join("b"), "f.txt", b"f\n");
807
    let h = b.commit("signed from a clone", &[]).unwrap();
808
    assert!(
809
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
810
    );
811
    assert!(b.push("origin", false).unwrap()[0].ok);
812
    assert!(matches!(
813
        origin.verify_change(&h).unwrap(),
814
        SignatureStatus::Valid { .. }
815
    ));
816
}
817
818
#[test]
819
fn format1_repositories_are_migrated_on_open() {
820
    hermetic();
821
    use crate::oplog::{Format1Op, Format1View};
822
    let dir = tempfile::tempdir().unwrap();
823
    let root = dir.path();
824
    let repo = Repo::init(root).unwrap();
825
    write(root, "a.txt", b"a\n");
826
    let h1 = repo.commit("one", &[]).unwrap();
827
    let (wc_hash, _) = repo.working_copy().unwrap();
828
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
829
    let mut v1 = Format1View::default();
830
    v1.bookmarks.insert("main".into(), vec![]);
831
    v1.workspaces.insert(repo.workspace(), wc_hash);
832
    let init = Format1Op {
833
        parents: vec![],
834
        hlc: Hlc::default(),
835
        command: "oxy init".into(),
836
        view: v1.clone(),
837
    };
838
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
839
    v1.bookmarks.insert("main".into(), vec![h1]);
840
    let commit = Format1Op {
841
        parents: vec![init_ref],
842
        hlc: Hlc::default(),
843
        command: "oxy commit".into(),
844
        view: v1,
845
    };
846
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
847
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
848
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
849
    drop(repo);
850
851
    let repo = Repo::open(root).unwrap();
852
    assert_eq!(
853
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
854
        FORMAT_LINE
855
    );
856
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
857
    let ops = repo.op_log().unwrap();
858
    assert_eq!(
859
        ops.iter()
860
            .map(|(_, o)| o.command.as_str())
861
            .collect::<Vec<_>>(),
862
        ["oxy commit", "oxy init"]
863
    );
864
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
865
    assert!(!repo.snapshot("status").unwrap().changed);
866
    // Reopening again is a no-op.
867
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
868
}
869
870
#[test]
871
fn undo_skips_snapshot_operations() {
872
    hermetic();
873
    let dir = tempfile::tempdir().unwrap();
874
    let root = dir.path();
875
    let repo = Repo::init(root).unwrap();
876
    write(root, "a.txt", b"a\n");
877
    let h1 = repo.commit("a", &[]).unwrap();
878
    // A later command snapshots new edits on top of the commit.
879
    write(root, "b.txt", b"b\n");
880
    let s = repo.snapshot("oxy status").unwrap();
881
    assert!(s.changed);
882
    assert!(repo.head_op().unwrap().1.is_snapshot());
883
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
884
    // Undo must undo the commit, not the snapshot.
885
    repo.undo().unwrap();
886
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
887
    let s = repo.snapshot("oxy status").unwrap();
888
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
889
    assert_eq!(
890
        paths,
891
        ["a.txt", "b.txt"],
892
        "both files are back in the working copy"
893
    );
894
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
895
    // Only snapshots remain above `init`, so there is nothing left to undo.
896
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
897
    assert!(repo.undo().is_err());
898
}
899
900
#[test]
901
fn independent_changes_commute_and_make_multiple_heads() {
902
    hermetic();
903
    let dir = tempfile::tempdir().unwrap();
904
    let root = dir.path();
905
    let repo = Repo::init(root).unwrap();
906
    write(root, "a.txt", b"a\n");
907
    let h1 = repo.commit("a", &[]).unwrap();
908
    write(root, "b.txt", b"b\n");
909
    let h2 = repo.commit("b", &[]).unwrap();
910
    let c2 = repo.store().get_change(&h2).unwrap();
911
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
912
    let mut heads = repo.bookmark_heads().unwrap();
913
    heads.sort();
914
    let mut want = vec![h1, h2];
915
    want.sort();
916
    assert_eq!(heads, want);
917
    // Editing a.txt depends on h1 only.
918
    write(root, "a.txt", b"a\na2\n");
919
    let h3 = repo.commit("a2", &[]).unwrap();
920
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
921
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
922
    assert_eq!(heads, [h2, h3].into_iter().collect());
923
    // Explicit dependency.
924
    write(root, "c.txt", b"c\n");
925
    let h4 = repo.commit("c", &[h2]).unwrap();
926
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
927
}
928
929
#[test]
930
fn mode_change_and_text_binary_switch() {
931
    hermetic();
932
    let dir = tempfile::tempdir().unwrap();
933
    let root = dir.path();
934
    let repo = Repo::init(root).unwrap();
935
    write(root, "run.sh", b"#!/bin/sh\n");
936
    repo.commit("add script", &[]).unwrap();
937
    #[cfg(unix)]
938
    {
939
        use std::os::unix::fs::PermissionsExt;
940
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
941
        let s = repo.snapshot("status").unwrap();
942
        assert_eq!(
943
            statuses(&s),
944
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
945
        );
946
        let h = repo.commit("exec", &[]).unwrap();
947
        let snap = repo.load_state(&[h]).unwrap().materialize();
948
        assert!(snap.files["run.sh"].mode.exec);
949
    }
950
    // Text → binary → text.
951
    write(root, "run.sh", b"\0binary");
952
    let h = repo.commit("binary", &[]).unwrap();
953
    let snap = repo.load_state(&[h]).unwrap().materialize();
954
    assert!(snap.files["run.sh"].mode.opaque);
955
    write(root, "run.sh", b"text again\n");
956
    let h = repo.commit("text", &[]).unwrap();
957
    let snap = repo.load_state(&[h]).unwrap().materialize();
958
    assert!(!snap.files["run.sh"].mode.opaque);
959
    assert!(
960
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
961
    );
962
    assert!(!snap.is_conflicted());
963
}
964
965
/// oxygen#87: a binary file given new contents and the executable bit in
966
/// one commit kept the contents and lost the bit.
967
#[cfg(unix)]
968
#[test]
969
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
970
    use std::os::unix::fs::PermissionsExt;
971
    hermetic();
972
    let dir = tempfile::tempdir().unwrap();
973
    let root = dir.path();
974
    let repo = Repo::init(root).unwrap();
975
    write(root, "tool.exe", b"MZ\0one");
976
    repo.commit("add", &[]).unwrap();
977
    write(root, "tool.exe", b"MZ\0two");
978
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
979
    let h = repo.commit("update and +x", &[]).unwrap();
980
    let snap = repo.load_state(&[h]).unwrap().materialize();
981
    let f = &snap.files["tool.exe"];
982
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
983
    assert!(
984
        repo.snapshot("status").unwrap().statuses.is_empty(),
985
        "nothing left to commit"
986
    );
987
}
988
989
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
990
/// key whose certificate an issuer gave pushes when the policy grants its
991
/// subject, and a fetch accepts what it attested; an expired certificate,
992
/// or a subject the policy does not grant, may not move the bookmark.
993
#[test]
994
fn a_certified_key_pushes_under_a_subject_grant() {
995
    use crate::cert::{Certificate, SignedCertificate};
996
    use crate::identity::Scope;
997
    hermetic();
998
    let dir = tempfile::tempdir().unwrap();
999
    let root = dir.path();
1000
    let _origin = Repo::init(&root.join("origin")).unwrap();
1001
    let url = root.join("origin").to_string_lossy().to_string();
1002
    let mut a = Repo::clone(&url, &root.join("a"))
1003
        .unwrap()
1004
        .with_home(root.join("home-a"));
1005
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1006
        .unwrap();
1007
    write(&root.join("a"), "a.txt", b"a\n");
1008
    a.commit("a", &[]).unwrap();
1009
    a.policy_init().unwrap();
1010
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1011
    let hub_sk = SecretKey::generate();
1012
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1013
    a.policy_grant_subject(
1014
        "agent:claude@ada",
1015
        hub.clone(),
1016
        Scope::CHANGES | Scope::REFS,
1017
        None,
1018
    )
1019
    .unwrap();
1020
    assert!(a
1021
        .push("origin", false)
1022
        .unwrap()
1023
        .iter()
1024
        .any(|r| r.name == "policy" && r.ok));
1025
1026
    let now = Hlc::now().wall_ms;
1027
    // An agent repository whose key the hub certified for `subject`, from
1028
    // `from` to `to`.
1029
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1030
        let mut r = Repo::clone(&url, &root.join(name))
1031
            .unwrap()
1032
            .with_home(root.join(format!("home-{name}")));
1033
        let (_, id) = r
1034
            .create_identity(name, "[email protected]", IdentityScope::User)
1035
            .unwrap();
1036
        let cert = SignedCertificate::sign(
1037
            Certificate {
1038
                key: id,
1039
                issuer: hub.hash(),
1040
                subject: subject.into(),
1041
                claims: vec![],
1042
                scope: Scope::CHANGES | Scope::REFS,
1043
                not_before: from,
1044
                expires: to,
1045
                grant: None,
1046
            },
1047
            &hub,
1048
            &hub_sk,
1049
        );
1050
        r.store().put_identity(&hub).unwrap();
1051
        r.store().put_certificate(&cert).unwrap();
1052
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1053
        r.commit("work", &[]).unwrap();
1054
        r
1055
    };
1056
1057
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1058
    let r = claude.push("origin", false).unwrap();
1059
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1060
    // Ada's fetch accepts the bookmark the certified key attested.
1061
    a.pull("origin").unwrap();
1062
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1063
        .store()
1064
        .get_change(h)
1065
        .map(|c| c.message == "work")
1066
        .unwrap_or(false)));
1067
1068
    // Step 4c: a host with an acceptor key records when it accepted the
1069
    // certified update and serves it; a fetch checks the certificate at
1070
    // that time only when the certificate's issuer signed it for exactly
1071
    // this attestation, else at the attestation's own time.
1072
    let host = Repo::open(&root.join("origin"))
1073
        .unwrap()
1074
        .with_acceptor(hub.clone(), hub_sk.clone());
1075
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1076
    host.record_acceptance(&attest_ref).unwrap();
1077
    let served = host.remote_refs().unwrap();
1078
    let acc = served
1079
        .refs
1080
        .iter()
1081
        .find(|r| r.name == "main")
1082
        .unwrap()
1083
        .accepted
1084
        .clone()
1085
        .expect("served with the refs");
1086
    let signer = sa.sigs[0].key;
1087
    assert_eq!(
1088
        a.certified_time(&signer, &sa, Some(&acc)),
1089
        acc.attest.hlc.wall_ms
1090
    );
1091
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1092
    let stranger_sk = SecretKey::generate();
1093
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1094
    let mut forged = acc.clone();
1095
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1096
    assert_eq!(
1097
        a.certified_time(&signer, &sa, Some(&forged)),
1098
        sa.attest.hlc.wall_ms,
1099
        "not the issuer's"
1100
    );
1101
    let mut elsewhere = acc.clone();
1102
    elsewhere.attest.body = AttestBody::Accepted {
1103
        attest: ObjectRef([7; 32]),
1104
    };
1105
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1106
    assert_eq!(
1107
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1108
        sa.attest.hlc.wall_ms,
1109
        "another attestation's"
1110
    );
1111
    a.pull("origin").unwrap();
1112
    // gc keeps the acceptance with the attestation.
1113
    host.gc(true).unwrap();
1114
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1115
1116
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1117
    let r = late.push("origin", false).unwrap();
1118
    assert!(
1119
        !r[0].ok && r[0].reason.contains("may not update"),
1120
        "an expired certificate: {r:?}"
1121
    );
1122
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1123
    let r = other.push("origin", false).unwrap();
1124
    assert!(
1125
        !r[0].ok && r[0].reason.contains("may not update"),
1126
        "a subject not granted: {r:?}"
1127
    );
1128
}
1129
1130
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1131
/// subject the author granted, seals changes in the author's name; with
1132
/// no grant, a stranger's, or one that had ended, it is neither the
1133
/// author nor a delegate.
1134
#[test]
1135
fn a_certified_key_acts_for_its_author_under_a_grant() {
1136
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1137
    use crate::identity::{Identity, Scope};
1138
    hermetic();
1139
    let dir = tempfile::tempdir().unwrap();
1140
    let root = dir.path();
1141
    let _origin = Repo::init(&root.join("origin")).unwrap();
1142
    let url = root.join("origin").to_string_lossy().to_string();
1143
    let mut a = Repo::clone(&url, &root.join("a"))
1144
        .unwrap()
1145
        .with_home(root.join("home-a"));
1146
    let (ada, _) = a
1147
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1148
        .unwrap();
1149
    write(&root.join("a"), "a.txt", b"a\n");
1150
    a.commit("a", &[]).unwrap();
1151
    a.policy_init().unwrap();
1152
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1153
    let hub_sk = SecretKey::generate();
1154
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1155
    a.policy_grant_subject(
1156
        "agent:claude@ada",
1157
        hub.clone(),
1158
        Scope::CHANGES | Scope::REFS,
1159
        None,
1160
    )
1161
    .unwrap();
1162
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1163
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1164
    let ada_id = a.identity(&ada).unwrap();
1165
1166
    let now = Hlc::now().wall_ms;
1167
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1168
        SignedGrant::sign(
1169
            Grant {
1170
                grantor: by.hash(),
1171
                subject: "agent:claude@ada".into(),
1172
                issuer: hub.hash(),
1173
                scope: Scope::CHANGES | Scope::SEAL,
1174
                not_before: from,
1175
                expires: to,
1176
            },
1177
            by,
1178
            sk,
1179
        )
1180
    };
1181
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1182
    // certified (with `g` inside) the signer.
1183
    let agent = |name: &str, g: Option<SignedGrant>| {
1184
        let mut r = Repo::clone(&url, &root.join(name))
1185
            .unwrap()
1186
            .with_home(root.join(format!("home-{name}")));
1187
        let (key, id) = r
1188
            .create_identity(name, "[email protected]", IdentityScope::User)
1189
            .unwrap();
1190
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1191
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1192
        let cert = SignedCertificate::sign(
1193
            Certificate {
1194
                key: id,
1195
                issuer: hub.hash(),
1196
                subject: "agent:claude@ada".into(),
1197
                claims: vec![],
1198
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1199
                not_before: now - 60_000,
1200
                expires: now + 600_000,
1201
                grant: g,
1202
            },
1203
            &hub,
1204
            &hub_sk,
1205
        );
1206
        r.store().put_identity(&hub).unwrap();
1207
        r.store().put_certificate(&cert).unwrap();
1208
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1209
        let h = r.commit("work", &[]).unwrap();
1210
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1211
        (r, key, h)
1212
    };
1213
1214
    let (claude, key, h) = agent(
1215
        "claude",
1216
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1217
    );
1218
    let r = claude.push("origin", false).unwrap();
1219
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1220
    let host = Repo::open(&root.join("origin")).unwrap();
1221
    assert!(matches!(
1222
        host.authenticate_change(&h).unwrap(),
1223
        SignatureStatus::Valid { key: k, sealed: true, .. } if k == key
1224
    ));
1225
    a.pull("origin").unwrap();
1226
    assert!(matches!(
1227
        a.authenticate_change(&h).unwrap(),
1228
        SignatureStatus::Valid { key: k, .. } if k == key
1229
    ));
1230
1231
    let (none, _, _) = agent("none", None);
1232
    let r = none.push("origin", false).unwrap();
1233
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1234
    let mallory_sk = SecretKey::generate();
1235
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1236
    let (stranger, _, _) = agent(
1237
        "stranger",
1238
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1239
    );
1240
    let r = stranger.push("origin", false).unwrap();
1241
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1242
    let (ended, _, eh) = agent(
1243
        "ended",
1244
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1245
    );
1246
    let r = ended.push("origin", false).unwrap();
1247
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1248
    assert!(matches!(
1249
        ended.authenticate_change(&eh).unwrap(),
1250
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1251
    ));
1252
}
1253
1254
#[test]
1255
fn trust_policy_governs_pushes_and_fetches() {
1256
    hermetic();
1257
    let dir = tempfile::tempdir().unwrap();
1258
    let root = dir.path();
1259
    let origin = Repo::init(&root.join("origin")).unwrap();
1260
    let url = root.join("origin").to_string_lossy().to_string();
1261
1262
    // A is the root. Before the policy, an unsigned push from B is fine.
1263
    let mut a = Repo::clone(&url, &root.join("a"))
1264
        .unwrap()
1265
        .with_home(root.join("home-a"));
1266
    let (key_a, _) = a
1267
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1268
        .unwrap();
1269
    let mut b = Repo::clone(&url, &root.join("b"))
1270
        .unwrap()
1271
        .with_home(root.join("home-b"));
1272
    write(&root.join("b"), "b.txt", b"b\n");
1273
    b.commit("unsigned before policy", &[]).unwrap();
1274
    assert!(b.push("origin", false).unwrap()[0].ok);
1275
1276
    // A creates the policy and pushes it; origin now enforces it.
1277
    write(&root.join("a"), "a.txt", b"a\n");
1278
    a.commit("a", &[]).unwrap();
1279
    let sp = a.policy_init().unwrap();
1280
    assert_eq!(sp.policy.serial, 1);
1281
    a.pull("origin").unwrap();
1282
    let results = a.push("origin", false).unwrap();
1283
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1284
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1285
1286
    // B pulls the policy. Without an identity B cannot push at all.
1287
    b.pull("origin").unwrap();
1288
    assert!(
1289
        b.current_policy().unwrap().is_some(),
1290
        "the policy arrived with the fetch"
1291
    );
1292
    assert!(b.push("origin", false).is_err());
1293
    // With an identity the policy does not list, the push is rejected by origin.
1294
    let (key_b, id_b) = b
1295
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1296
        .unwrap();
1297
    write(&root.join("b"), "b.txt", b"b2\n");
1298
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1299
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1300
    let r = b.push("origin", false).unwrap();
1301
    assert!(
1302
        !r[0].ok && r[0].reason.contains("may not update"),
1303
        "{:?}",
1304
        r
1305
    );
1306
1307
    // A grants B (identity handed over as a file) and publishes the policy.
1308
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1309
    assert_eq!(sp.policy.serial, 2);
1310
    let r = a.push("origin", false).unwrap();
1311
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1312
    // B must fetch the new policy before pushing.
1313
    assert!(b
1314
        .push("origin", false)
1315
        .unwrap_or_else(|e| vec![RefResult {
1316
            name: "main".into(),
1317
            ok: false,
1318
            reason: e.to_string()
1319
        }])
1320
        .iter()
1321
        .all(|x| !x.ok));
1322
    b.pull("origin").unwrap();
1323
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1324
    let r = b.push("origin", false).unwrap();
1325
    assert!(r[0].ok, "{:?}", r);
1326
    // Origin verified B's change under the policy.
1327
    let heads = origin.bookmark_heads().unwrap();
1328
    for h in &heads {
1329
        let c = origin.store().get_change(h).unwrap();
1330
        if c.author == key_b {
1331
            origin
1332
                .change_allowed(
1333
                    h,
1334
                    &origin.current_policy().unwrap().unwrap().1.policy,
1335
                    "main",
1336
                )
1337
                .unwrap();
1338
        }
1339
    }
1340
1341
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1342
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1343
    forged.serial = 3;
1344
    forged.roots = vec![key_b];
1345
    let fh = forged.hash();
1346
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1347
    let forged = SignedPolicy {
1348
        policy: forged,
1349
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1350
    };
1351
    let r = origin
1352
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1353
        .unwrap();
1354
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1355
    let stale = a.current_policy().unwrap().unwrap().1;
1356
    let mut old = stale.clone();
1357
    old.policy.serial = 1;
1358
    let r = origin
1359
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1360
        .unwrap();
1361
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1362
1363
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1364
    a.pull("origin").unwrap();
1365
    a.policy_revoke(&key_b).unwrap();
1366
    let r = a.push("origin", false).unwrap();
1367
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1368
    b.pull("origin").unwrap();
1369
    write(&root.join("b"), "b.txt", b"b3\n");
1370
    b.commit("b3", &[]).unwrap();
1371
    let r = b.push("origin", false).unwrap();
1372
    assert!(!r[0].ok, "{:?}", r);
1373
1374
    // A clone by a third party receives and verifies everything.
1375
    let c = Repo::clone(&url, &root.join("c"))
1376
        .unwrap()
1377
        .with_home(root.join("home-c"));
1378
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1379
    assert!(c
1380
        .current_policy()
1381
        .unwrap()
1382
        .unwrap()
1383
        .1
1384
        .policy
1385
        .roots
1386
        .contains(&key_a));
1387
    assert!(!c.snapshot("status").unwrap().changed);
1388
}
1389
1390
/// oxygen#66: a gc says what it is doing, phase by phase.
1391
#[test]
1392
fn gc_reports_its_phases() {
1393
    hermetic();
1394
    let dir = tempfile::tempdir().unwrap();
1395
    let repo = Repo::init(dir.path()).unwrap();
1396
    for i in 0..3 {
1397
        write(
1398
            dir.path(),
1399
            &format!("f{i}.txt"),
1400
            format!("{i}\n").as_bytes(),
1401
        );
1402
        repo.commit(&format!("c{i}"), &[]).unwrap();
1403
    }
1404
    let mut phases = Vec::new();
1405
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1406
        .unwrap();
1407
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1408
    assert!(
1409
        phases.iter().any(|p| p.starts_with("pruning")),
1410
        "{phases:?}"
1411
    );
1412
    assert!(
1413
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1414
        "{phases:?}"
1415
    );
1416
    assert!(
1417
        phases
1418
            .iter()
1419
            .any(|p| p.starts_with("writing the index of ")),
1420
        "{phases:?}"
1421
    );
1422
}
1423
1424
#[test]
1425
fn gc_packs_objects_and_history_still_works() {
1426
    hermetic();
1427
    let dir = tempfile::tempdir().unwrap();
1428
    let root = dir.path();
1429
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1430
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1431
        .unwrap();
1432
    repo.set_user_config("core.sign", "change").unwrap();
1433
    write(root, "a.txt", b"one\n");
1434
    let h1 = repo.commit("one", &[]).unwrap();
1435
    write(root, "a.txt", b"two\n");
1436
    write(root, "big.bin", &vec![0u8; 100_000]);
1437
    let h2 = repo.commit("two", &[]).unwrap();
1438
    // Several snapshots leave superseded working-copy versions behind.
1439
    for i in 0..5 {
1440
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1441
        repo.snapshot("status").unwrap();
1442
    }
1443
    write(root, "a.txt", b"two\n");
1444
    repo.snapshot("status").unwrap();
1445
    let before = repo.store().list().unwrap();
1446
    assert!(repo.store().loose_count().unwrap() > 0);
1447
1448
    // With the default retention every operation's view is a root: nothing prunes.
1449
    let r = repo.gc(true).unwrap();
1450
    assert_eq!(r.packed.objects, before.len());
1451
    assert_eq!(r.pruned.objects, 0);
1452
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1453
    assert_eq!(repo.store().list().unwrap(), before);
1454
1455
    // With zero retention only the current view is a root: superseded
1456
    // working copies go, everything reachable stays.
1457
    repo.config.set("core.op-retention", "0").unwrap();
1458
    repo.save_config().unwrap();
1459
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1460
    let r = repo.gc(true).unwrap();
1461
    assert!(r.pruned.objects >= 5, "{r:?}");
1462
    let after = repo.store().list().unwrap();
1463
    assert!(after.len() < before.len());
1464
    assert!(after.contains(&h1) && after.contains(&h2));
1465
    for (_, op) in repo.op_log().unwrap() {
1466
        assert!(!op.command.is_empty(), "operation objects are all kept");
1467
    }
1468
    // Everything still works from the pruned, packed store.
1469
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1470
    assert!(matches!(
1471
        repo.verify_change(&h2).unwrap(),
1472
        SignatureStatus::Valid { .. }
1473
    ));
1474
    assert_eq!(repo.log().unwrap().len(), 3);
1475
    repo.checkout(&[h1], false, "checkout").unwrap();
1476
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1477
    repo.checkout(&[h2], false, "checkout").unwrap();
1478
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1479
    assert!(!repo.snapshot("status").unwrap().changed);
1480
    // Grace period defers pruning of young garbage.
1481
    write(root, "a.txt", b"three\n");
1482
    repo.commit("three", &[]).unwrap();
1483
    let r = repo.gc(false).unwrap();
1484
    assert_eq!(r.pruned.objects, 0);
1485
    assert!(r.pruned.deferred > 0);
1486
    let r = repo.gc(true).unwrap();
1487
    assert!(r.pruned.objects > 0);
1488
    assert_eq!(repo.log().unwrap().len(), 4);
1489
    // Restoring the default retention makes the old views roots again; the
1490
    // working copies they name were pruned, which gc tolerates.
1491
    repo.config.set("core.op-retention", "90").unwrap();
1492
    repo.save_config().unwrap();
1493
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1494
    let r = repo.gc(false).unwrap();
1495
    assert_eq!(r.pruned.objects, 0);
1496
    assert_eq!(repo.log().unwrap().len(), 4);
1497
}
1498
1499
#[test]
1500
fn describe_amend_abandon_heads() {
1501
    hermetic();
1502
    let dir = tempfile::tempdir().unwrap();
1503
    let root = dir.path();
1504
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1505
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1506
        .unwrap();
1507
    repo.set_user_config("core.sign", "change").unwrap();
1508
    write(root, "a.txt", b"one\n");
1509
    let h1 = repo.commit("first", &[]).unwrap();
1510
    write(root, "a.txt", b"one\ntwo\n");
1511
    let h2 = repo.commit("secnod", &[]).unwrap();
1512
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1513
1514
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1515
    let h2b = repo.describe(&h2, "second").unwrap();
1516
    assert_ne!(h2b, h2);
1517
    let c = repo.store().get_change(&h2b).unwrap();
1518
    assert_eq!(
1519
        (c.change_id, c.message.as_str(), c.deps.clone()),
1520
        (id2, "second", vec![h1])
1521
    );
1522
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1523
    assert!(matches!(
1524
        repo.verify_change(&h2b).unwrap(),
1525
        SignatureStatus::Valid { .. }
1526
    ));
1527
    let s = repo.snapshot("status").unwrap();
1528
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1529
    assert_eq!(
1530
        repo.resolve_change(&id2.short(8)).unwrap(),
1531
        h2b,
1532
        "the old object is no longer reachable from the log"
1533
    );
1534
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1535
    let h1b = repo.describe(&h1, "first, described").unwrap();
1536
    assert_ne!(h1b, h1);
1537
    let heads = repo.bookmark_heads().unwrap();
1538
    assert_eq!(heads.len(), 1);
1539
    let top = repo.store().get_change(&heads[0]).unwrap();
1540
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1541
    assert!(
1542
        matches!(
1543
            repo.verify_change(&heads[0]).unwrap(),
1544
            SignatureStatus::Valid { .. }
1545
        ),
1546
        "rewritten own change is re-signed"
1547
    );
1548
    let (_, wc) = repo.working_copy().unwrap();
1549
    assert_eq!(
1550
        wc.deps,
1551
        vec![heads[0]],
1552
        "the working copy follows the rewrite"
1553
    );
1554
    assert!(!repo.snapshot("status").unwrap().changed);
1555
    let snap = repo.load_state(&heads).unwrap().materialize();
1556
    assert!(
1557
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1558
    );
1559
1560
    // amend: fold an edit into the head; the result is one change from h1.
1561
    write(root, "a.txt", b"one\ntwo\nthree\n");
1562
    write(root, "b.txt", b"b\n");
1563
    let h2c = repo.amend(None).unwrap();
1564
    let c = repo.store().get_change(&h2c).unwrap();
1565
    assert_eq!(c.change_id, id2);
1566
    assert_eq!(c.message, "second");
1567
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1568
    assert_eq!(
1569
        repo.log().unwrap().len(),
1570
        3,
1571
        "working copy, amended head, first"
1572
    );
1573
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1574
    assert!(
1575
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1576
    );
1577
    assert!(snap.files.contains_key("b.txt"));
1578
    assert!(!repo.snapshot("status").unwrap().changed);
1579
    assert!(
1580
        repo.amend(None).is_err(),
1581
        "clean working copy and no message"
1582
    );
1583
    let h2d = repo.amend(Some("second, amended")).unwrap();
1584
    assert_eq!(
1585
        repo.store().get_change(&h2d).unwrap().message,
1586
        "second, amended"
1587
    );
1588
1589
    // abandon: the head goes, its content stays as uncommitted work.
1590
    repo.abandon(&h2d).unwrap();
1591
    assert_eq!(
1592
        repo.bookmark_heads().unwrap(),
1593
        vec![h1b],
1594
        "the described first change is the head again"
1595
    );
1596
    let s = repo.snapshot("status").unwrap();
1597
    let paths: Vec<_> = s
1598
        .statuses
1599
        .iter()
1600
        .map(|p| (p.path.as_str(), p.status))
1601
        .collect();
1602
    assert_eq!(
1603
        paths,
1604
        vec![
1605
            ("a.txt", ChangeStatus::Modified),
1606
            ("b.txt", ChangeStatus::Added)
1607
        ]
1608
    );
1609
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1610
    let h3 = repo.commit("recommitted", &[]).unwrap();
1611
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1612
    // undo brings the abandoned head back.
1613
    repo.undo().unwrap();
1614
    repo.undo().unwrap();
1615
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1616
1617
    // Abandoning a non-head whose dependent references its atoms reifies
1618
    // the references (here: a.txt vanishes with it, so the dependent's edit
1619
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1620
    let base = repo.bookmark_heads().unwrap()[0];
1621
    let base_change = repo.store().get_change(&base).unwrap();
1622
    let h1_now = base_change.deps[0];
1623
    let notes = repo.abandon(&h1_now).unwrap();
1624
    assert!(
1625
        !notes.is_empty(),
1626
        "the dependent's edit of a.txt was reified"
1627
    );
1628
    let heads = repo.bookmark_heads().unwrap();
1629
    let after = repo.load_state(&heads).unwrap().materialize();
1630
    assert!(
1631
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1632
        "{:?}",
1633
        after.files.keys()
1634
    );
1635
    repo.undo().unwrap();
1636
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1637
    write(root, "c.txt", b"c\n");
1638
    let hc = repo.commit("c", &[]).unwrap();
1639
    write(root, "d.txt", b"d\n");
1640
    let hd = repo.commit("d", &[hc]).unwrap();
1641
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1642
    repo.abandon(&hc).unwrap();
1643
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1644
    assert!(!heads.contains(&hc));
1645
    let d_now = heads
1646
        .iter()
1647
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1648
        .copied()
1649
        .unwrap();
1650
    assert!(
1651
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1652
        "d inherited c's (empty) dependencies"
1653
    );
1654
    let s = repo.snapshot("status").unwrap();
1655
    assert_eq!(
1656
        s.statuses
1657
            .iter()
1658
            .map(|p| p.path.as_str())
1659
            .collect::<Vec<_>>(),
1660
        vec!["c.txt"],
1661
        "c's content is now uncommitted work"
1662
    );
1663
}
1664
1665
#[test]
1666
fn git_export_mirrors_history() {
1667
    hermetic();
1668
    if std::process::Command::new("git")
1669
        .arg("--version")
1670
        .output()
1671
        .is_err()
1672
    {
1673
        eprintln!("git not installed; skipping");
1674
        return;
1675
    }
1676
    let dir = tempfile::tempdir().unwrap();
1677
    let root = dir.path();
1678
    let mut repo = Repo::init(&root.join("r"))
1679
        .unwrap()
1680
        .with_home(root.join("home"));
1681
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1682
        .unwrap();
1683
    let r = root.join("r");
1684
    write(&r, "README.md", b"hello\n");
1685
    write(&r, "src/main.rs", b"fn main() {}\n");
1686
    let h1 = repo.commit("first", &[]).unwrap();
1687
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1688
    write(&r, "logo.png", b"\x89PNG\0\0");
1689
    let h2 = repo.commit("second", &[]).unwrap();
1690
1691
    let git_dir = root.join("mirror.git");
1692
    let rep = repo.git_export(&git_dir).unwrap();
1693
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1694
    let git = |args: &[&str]| -> String {
1695
        let out = std::process::Command::new("git")
1696
            .arg("-C")
1697
            .arg(&git_dir)
1698
            .args(args)
1699
            .output()
1700
            .unwrap();
1701
        assert!(
1702
            out.status.success(),
1703
            "{}",
1704
            String::from_utf8_lossy(&out.stderr)
1705
        );
1706
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1707
    };
1708
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1709
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1710
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1711
    let body = git(&["log", "-1", "--format=%B", "main"]);
1712
    assert!(
1713
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1714
        "{body}"
1715
    );
1716
    assert!(body.contains("Change-Id: "), "{body}");
1717
    assert_eq!(
1718
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1719
        "Ada Lovelace <[email protected]>"
1720
    );
1721
    assert_eq!(
1722
        git(&["ls-tree", "--name-only", "main"]),
1723
        "README.md\nlogo.png\nsrc"
1724
    );
1725
1726
    // Re-export is incremental.
1727
    let rep = repo.git_export(&git_dir).unwrap();
1728
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1729
1730
    // An independent change makes two heads; the next state is one more
1731
    // commit on the linear branch whose tree is the union.
1732
    repo.checkout(&[h1], false, "checkout").unwrap();
1733
    write(&r, "other.txt", b"o\n");
1734
    let h3 = repo.commit("third", &[]).unwrap();
1735
    let rep = repo.git_export(&git_dir).unwrap();
1736
    assert_eq!((rep.exported, rep.heads), (1, 2));
1737
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1738
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1739
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1740
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1741
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1742
    assert_eq!(
1743
        git(&["ls-tree", "--name-only", "main"]),
1744
        "README.md\nlogo.png\nother.txt\nsrc"
1745
    );
1746
    let body = git(&["log", "-1", "--format=%B", "main"]);
1747
    assert!(
1748
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1749
        "{body}"
1750
    );
1751
    // A rewrite is a new state whose one new change is the rewritten one.
1752
    repo.describe(&h3, "third, described").unwrap();
1753
    let rep = repo.git_export(&git_dir).unwrap();
1754
    assert_eq!(rep.exported, 1);
1755
    assert_eq!(
1756
        git(&["log", "-1", "--format=%s", "main"]),
1757
        "third, described"
1758
    );
1759
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1760
    let _ = h2;
1761
}
1762
1763
#[test]
1764
fn git_import_reproduces_trees() {
1765
    git_import_reproduces_trees_with(None);
1766
}
1767
1768
/// The same import with every merge rendered in batches of one file
1769
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1770
#[test]
1771
fn git_import_reproduces_trees_in_batches() {
1772
    git_import_reproduces_trees_with(Some(1));
1773
}
1774
1775
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1776
    crate::repo::git::set_merge_batch_for_tests(batch);
1777
    hermetic();
1778
    if std::process::Command::new("git")
1779
        .arg("--version")
1780
        .output()
1781
        .is_err()
1782
    {
1783
        eprintln!("git not installed; skipping");
1784
        return;
1785
    }
1786
    let dir = tempfile::tempdir().unwrap();
1787
    let root = dir.path();
1788
    let g = root.join("src.git");
1789
    fs::create_dir_all(&g).unwrap();
1790
    let git = |args: &[&str]| -> String {
1791
        let out = std::process::Command::new("git")
1792
            .arg("-C")
1793
            .arg(&g)
1794
            .args([
1795
                "-c",
1796
                "user.name=Grace",
1797
                "-c",
1798
                "[email protected]",
1799
                "-c",
1800
                "commit.gpgsign=false",
1801
            ])
1802
            .args(args)
1803
            .output()
1804
            .unwrap();
1805
        assert!(
1806
            out.status.success(),
1807
            "git {args:?}: {}",
1808
            String::from_utf8_lossy(&out.stderr)
1809
        );
1810
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1811
    };
1812
    git(&["init", "-q", "-b", "main"]);
1813
    write(&g, "README.md", b"# Hi\n");
1814
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1815
    git(&["add", "."]);
1816
    git(&["commit", "-q", "-m", "initial"]);
1817
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1818
    write(&g, "run.sh", b"#!/bin/sh\n");
1819
    #[cfg(unix)]
1820
    {
1821
        use std::os::unix::fs::PermissionsExt;
1822
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1823
    }
1824
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1825
    git(&["add", "."]);
1826
    git(&[
1827
        "commit",
1828
        "-q",
1829
        "-m",
1830
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1831
    ]);
1832
    // A branch that edits README, merged back with a conflict-free merge.
1833
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1834
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1835
    git(&["commit", "-q", "-am", "readme"]);
1836
    git(&["checkout", "-q", "main"]);
1837
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1838
    // A branch from the initial commit inserting at the same place as
1839
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1840
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1841
    git(&["checkout", "-q", "-b", "clash", &initial]);
1842
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1843
    git(&["commit", "-q", "-am", "clash"]);
1844
    git(&["checkout", "-q", "main"]);
1845
    let _ = std::process::Command::new("git")
1846
        .arg("-C")
1847
        .arg(&g)
1848
        .args(["merge", "-q", "clash"])
1849
        .output();
1850
    write(
1851
        &g,
1852
        "src/lib.rs",
1853
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1854
    );
1855
    git(&["add", "."]);
1856
    git(&["commit", "-q", "-m", "resolve clash"]);
1857
    git(&["rm", "-q", "logo.png"]);
1858
    git(&["commit", "-q", "-m", "drop logo"]);
1859
    // A rename with a small edit is imported as a move of the same node.
1860
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1861
    write(
1862
        &g,
1863
        "src/lib2.rs",
1864
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1865
    );
1866
    git(&["add", "."]);
1867
    git(&["commit", "-q", "-m", "rename lib"]);
1868
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1869
    // run.sh is the same as in the first parent's tree, but the merged
1870
    // change touched it, so the importer must compare it, not skip it.
1871
    git(&["checkout", "-q", "-b", "discarded"]);
1872
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1873
    git(&["commit", "-q", "-am", "discarded edit"]);
1874
    git(&["checkout", "-q", "main"]);
1875
    git(&[
1876
        "merge",
1877
        "-q",
1878
        "-s",
1879
        "ours",
1880
        "-m",
1881
        "merge discarded, keeping ours",
1882
        "discarded",
1883
    ]);
1884
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1885
1886
    let dest = root.join("oxy");
1887
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1888
    let rep = repo.import_git(&g, "main").unwrap();
1889
    assert_eq!(rep.commits, expected_count);
1890
    assert_eq!(rep.merges, 3);
1891
    assert_eq!(
1892
        fs::read(dest.join("run.sh")).unwrap(),
1893
        b"#!/bin/sh\n",
1894
        "the ours merge kept main's run.sh"
1895
    );
1896
    let v = repo.verify_git_import(&g, "main").unwrap();
1897
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1898
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1899
    // The working copy equals the Git tree at main.
1900
    assert_eq!(
1901
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1902
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1903
    );
1904
    assert!(!dest.join("src/lib.rs").exists());
1905
    assert_eq!(
1906
        fs::read(dest.join("README.md")).unwrap(),
1907
        b"# Hi\n\nMore.\n"
1908
    );
1909
    assert!(!dest.join("logo.png").exists());
1910
    #[cfg(unix)]
1911
    {
1912
        use std::os::unix::fs::PermissionsExt;
1913
        assert!(
1914
            fs::metadata(dest.join("run.sh"))
1915
                .unwrap()
1916
                .permissions()
1917
                .mode()
1918
                & 0o111
1919
                != 0
1920
        );
1921
    }
1922
    assert!(
1923
        !repo.snapshot("status").unwrap().changed,
1924
        "clean after import"
1925
    );
1926
    let heads = repo.bookmark_heads().unwrap();
1927
    let st = repo.load_state(&heads).unwrap();
1928
    assert!(!st.materialize().is_conflicted());
1929
    assert_eq!(st.len(), expected_count);
1930
    let tip = repo
1931
        .log()
1932
        .unwrap()
1933
        .into_iter()
1934
        .find(|e| e.change.message.starts_with("rename lib"))
1935
        .unwrap();
1936
    let c = repo.store().get_change(&tip.hash).unwrap();
1937
    assert!(
1938
        c.tree_ops
1939
            .iter()
1940
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1941
        "{:?}",
1942
        c.tree_ops
1943
    );
1944
    assert!(!c
1945
        .tree_ops
1946
        .iter()
1947
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1948
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1949
    let log = repo.log().unwrap();
1950
    let second = log
1951
        .iter()
1952
        .find(|e| e.change.message.starts_with("second"))
1953
        .unwrap();
1954
    assert_eq!(
1955
        second.change.change_id,
1956
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1957
    );
1958
    assert!(second
1959
        .change
1960
        .message
1961
        .contains("Git-Author: Grace <[email protected]>"));
1962
    let resolve = log
1963
        .iter()
1964
        .find(|e| e.change.message.starts_with("resolve clash"))
1965
        .unwrap();
1966
    assert_eq!(
1967
        resolve.change.kind,
1968
        ChangeKind::Resolution,
1969
        "a conflicting Git merge becomes a resolution"
1970
    );
1971
    // Re-importing into another fresh repository gives the same ChangeIds.
1972
    let repo2 = Repo::init(&root.join("oxy2"))
1973
        .unwrap()
1974
        .with_home(root.join("home"));
1975
    repo2.import_git(&g, "main").unwrap();
1976
    // New nodes' identifiers derive from the commit (spec §23), so the
1977
    // re-import is not just the same ChangeIds but the same changes.
1978
    assert_eq!(
1979
        repo2.bookmark_heads().unwrap(),
1980
        repo.bookmark_heads().unwrap()
1981
    );
1982
    let ids: BTreeSet<ChangeId> = repo
1983
        .log()
1984
        .unwrap()
1985
        .iter()
1986
        .filter(|e| !e.is_working_copy)
1987
        .map(|e| e.change.change_id)
1988
        .collect();
1989
    let ids2: BTreeSet<ChangeId> = repo2
1990
        .log()
1991
        .unwrap()
1992
        .iter()
1993
        .filter(|e| !e.is_working_copy)
1994
        .map(|e| e.change.change_id)
1995
        .collect();
1996
    assert_eq!(ids, ids2);
1997
    // Round trip back out to Git reproduces the tip tree.
1998
    let mirror = root.join("mirror.git");
1999
    repo.git_export(&mirror).unwrap();
2000
    let out = std::process::Command::new("git")
2001
        .arg("-C")
2002
        .arg(&mirror)
2003
        .args(["show", "main:src/lib2.rs"])
2004
        .output()
2005
        .unwrap();
2006
    assert_eq!(
2007
        String::from_utf8_lossy(&out.stdout),
2008
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2009
    );
2010
    let out = std::process::Command::new("git")
2011
        .arg("-C")
2012
        .arg(&mirror)
2013
        .args(["show", "main:src/lib.rs"])
2014
        .output()
2015
        .unwrap();
2016
    assert!(
2017
        !out.status.success(),
2018
        "the old path is gone from the export"
2019
    );
2020
}
2021
2022
#[test]
2023
fn checkpoints_accelerate_loading_and_stay_correct() {
2024
    hermetic();
2025
    let dir = tempfile::tempdir().unwrap();
2026
    let root = dir.path();
2027
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2028
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2029
    repo.save_config().unwrap();
2030
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2031
    let mut hashes = Vec::new();
2032
    for i in 0..12 {
2033
        write(
2034
            root,
2035
            "a.txt",
2036
            format!(
2037
                "{}\n",
2038
                (0..=i)
2039
                    .map(|k| k.to_string())
2040
                    .collect::<Vec<_>>()
2041
                    .join("\n")
2042
            )
2043
            .as_bytes(),
2044
        );
2045
        write(root, &format!("f{i}.txt"), b"x\n");
2046
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2047
    }
2048
    let (_, cp) = repo
2049
        .latest_checkpoint("main")
2050
        .unwrap()
2051
        .expect("automatic checkpoint");
2052
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2053
    // Loading through the checkpoint equals loading everything.
2054
    let heads = repo.bookmark_heads().unwrap();
2055
    let fast = repo.load_state(&heads).unwrap();
2056
    let full = repo.load_state_full(&heads).unwrap();
2057
    assert_eq!(fast.len(), full.len());
2058
    assert_eq!(fast.heads(), full.heads());
2059
    let (a, b) = (fast.materialize(), full.materialize());
2060
    assert_eq!(
2061
        a.files.keys().collect::<Vec<_>>(),
2062
        b.files.keys().collect::<Vec<_>>()
2063
    );
2064
    for (p, f) in &a.files {
2065
        assert_eq!(f.content, b.files[p].content, "{p}");
2066
    }
2067
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2068
    // A head set that does not contain the checkpoint's heads falls back.
2069
    assert!(repo
2070
        .load_state_checkpointed(&[hashes[0]])
2071
        .unwrap()
2072
        .is_none());
2073
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2074
    // Everything else keeps working on top of the checkpoint.
2075
    assert!(!repo.snapshot("status").unwrap().changed);
2076
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2077
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2078
    let (r, n, bytes) = repo.checkpoint().unwrap();
2079
    assert!(n >= 12 && bytes > 0);
2080
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2081
    write(root, "a.txt", b"after\n");
2082
    let h_after = repo.commit("after", &[]).unwrap();
2083
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2084
    assert!(st.contains(&h_after));
2085
    assert!(
2086
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2087
    );
2088
    assert_eq!(repo.log().unwrap().len(), 14);
2089
    // Checkpoints survive gc.
2090
    repo.gc(true).unwrap();
2091
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
2092
    assert!(repo
2093
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2094
        .unwrap()
2095
        .is_some());
2096
}
2097
2098
#[test]
2099
fn quick_status_for_prompts() {
2100
    hermetic();
2101
    let dir = tempfile::tempdir().unwrap();
2102
    let root = dir.path();
2103
    let origin = Repo::init(&root.join("origin")).unwrap();
2104
    let url = root.join("origin").to_string_lossy().to_string();
2105
    let a = Repo::clone(&url, &root.join("a"))
2106
        .unwrap()
2107
        .with_home(root.join("home"));
2108
    let ops_before = a.op_log().unwrap().len();
2109
    let info = a.quick_status().unwrap();
2110
    assert_eq!(
2111
        (
2112
            info.bookmark.as_str(),
2113
            info.heads,
2114
            info.dirty,
2115
            info.conflicted,
2116
            info.ahead,
2117
            info.behind
2118
        ),
2119
        ("main", 0, false, false, Some(0), Some(0))
2120
    );
2121
    write(&root.join("a"), "f.txt", b"f\n");
2122
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
2123
    assert_eq!(
2124
        a.op_log().unwrap().len(),
2125
        ops_before,
2126
        "quick_status records nothing"
2127
    );
2128
    // A snapshotted but uncommitted change is still dirty.
2129
    a.snapshot("status").unwrap();
2130
    assert!(a.quick_status().unwrap().dirty);
2131
    a.commit("f", &[]).unwrap();
2132
    let info = a.quick_status().unwrap();
2133
    assert!(!info.dirty, "clean right after a commit");
2134
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
2135
    assert_eq!(
2136
        info.format("%b %c%d%x%A%D"),
2137
        format!("main {}+1", info.change_id)
2138
    );
2139
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2140
    // Touching a file without changing it is not dirty; changing content of
2141
    // the same size is.
2142
    let p = root.join("a/f.txt");
2143
    let content = fs::read(&p).unwrap();
2144
    fs::write(&p, &content).unwrap();
2145
    assert!(!a.quick_status().unwrap().dirty);
2146
    fs::write(&p, b"g\n").unwrap();
2147
    assert!(a.quick_status().unwrap().dirty);
2148
    fs::write(&p, b"f\n").unwrap();
2149
    // Push, then a second clone commits and pushes: we are behind.
2150
    assert!(a.push("origin", false).unwrap()[0].ok);
2151
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
2152
    let b = Repo::clone(&url, &root.join("b"))
2153
        .unwrap()
2154
        .with_home(root.join("home-b"));
2155
    write(&root.join("b"), "g.txt", b"g\n");
2156
    b.commit("g", &[]).unwrap();
2157
    b.push("origin", false).unwrap();
2158
    a.fetch("origin").unwrap();
2159
    let info = a.quick_status().unwrap();
2160
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2161
    assert_eq!(info.format("%A%D"), "-1");
2162
    let _ = origin;
2163
}
2164
2165
#[test]
2166
fn lazy_blobs_are_fetched_on_first_read() {
2167
    hermetic();
2168
    let dir = tempfile::tempdir().unwrap();
2169
    let root = dir.path();
2170
    let origin_dir = root.join("origin");
2171
    let origin = Repo::init(&origin_dir)
2172
        .unwrap()
2173
        .with_home(root.join("home"));
2174
    let url = origin_dir.to_string_lossy().to_string();
2175
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2176
    write(&origin_dir, "big.bin", &big);
2177
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2178
    write(&origin_dir, "t.txt", b"t\n");
2179
    let h = origin.commit("blobs", &[]).unwrap();
2180
    let big_ref = Repo::blob_ref(&big);
2181
2182
    // Fetch only (no checkout) with a filter: the big blob stays absent.
2183
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2184
        .unwrap()
2185
        .with_home(root.join("home"));
2186
    let a = {
2187
        let mut a = a;
2188
        a.config.set("remote.origin.url", &url).unwrap();
2189
        a.config.set("filter.max-blob", "100K").unwrap();
2190
        a.save_config().unwrap();
2191
        a
2192
    };
2193
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2194
    a.fetch("origin").unwrap();
2195
    assert!(a.store().has(&h));
2196
    assert!(!a.store().has(&big_ref), "withheld");
2197
    assert!(
2198
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2199
        "small blob came along"
2200
    );
2201
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2202
2203
    // status and commit do not need it: adopt the state, edit a text file, commit.
2204
    let (op_ref, op) = a.head_op().unwrap();
2205
    let mut view = op.view.clone();
2206
    view.bookmarks.insert(
2207
        "main".into(),
2208
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2209
    );
2210
    a.record_op(&[op_ref], "adopt", view).unwrap();
2211
    // Checkout reads the blob lazily, which fetches it.
2212
    a.checkout(&[h], true, "checkout").unwrap();
2213
    assert!(a.store().has(&big_ref), "fetched on first read");
2214
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2215
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2216
    write(&root.join("a"), "t.txt", b"t2\n");
2217
    a.commit("text edit", &[]).unwrap();
2218
2219
    // clone --max-blob records the filter; the checkout fetches lazily.
2220
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
2221
    assert_eq!(b.config.max_blob, Some(1024));
2222
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2223
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2224
    assert!(parse_size("lots").is_err());
2225
}
2226
2227
#[test]
2228
fn sparse_checkout_materializes_only_chosen_paths() {
2229
    hermetic();
2230
    let dir = tempfile::tempdir().unwrap();
2231
    let root = dir.path();
2232
    let origin_dir = root.join("origin");
2233
    let origin = Repo::init(&origin_dir)
2234
        .unwrap()
2235
        .with_home(root.join("home"));
2236
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2237
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2238
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2239
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2240
    write(&origin_dir, "docs/logo.png", &logo);
2241
    write(&origin_dir, "README.md", b"# top\n");
2242
    let h1 = origin.commit("tree", &[]).unwrap();
2243
    let url = origin_dir.to_string_lossy().to_string();
2244
2245
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2246
        .unwrap()
2247
        .with_home(root.join("home"));
2248
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2249
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2250
    assert!(root.join("a/src/main.rs").exists());
2251
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
2252
    assert!(
2253
        !a.store().has(&Repo::blob_ref(&logo)),
2254
        "out-of-scope blob never fetched"
2255
    );
2256
    assert!(
2257
        !a.snapshot("status").unwrap().changed,
2258
        "out-of-scope files are not removals"
2259
    );
2260
    assert!(!a.quick_status().unwrap().dirty);
2261
2262
    // Edits in scope commit normally and keep the rest of the tree intact.
2263
    write(
2264
        &root.join("a"),
2265
        "src/lib.rs",
2266
        b"pub fn a() {}\npub fn b() {}\n",
2267
    );
2268
    let h2 = a.commit("edit lib", &[]).unwrap();
2269
    let st = a.load_state(&[h2]).unwrap().materialize();
2270
    assert!(
2271
        st.files.contains_key("docs/guide.md"),
2272
        "the state still has everything"
2273
    );
2274
    assert!(a.push("origin", false).unwrap()[0].ok);
2275
    // Files created outside the scope are ignored by status.
2276
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2277
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2278
2279
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2280
    let mut a = a;
2281
    a.config.set("filter.paths", "src,docs").unwrap();
2282
    a.save_config().unwrap();
2283
    let r = a
2284
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2285
        .unwrap();
2286
    assert!(r.written >= 2);
2287
    assert_eq!(
2288
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2289
        logo,
2290
        "now fetched lazily"
2291
    );
2292
    assert!(!root.join("a/README.md").exists());
2293
    // Origin sees the change made under a sparse checkout with the full tree intact.
2294
    origin.pull("origin").err();
2295
    let full = origin
2296
        .load_state(&origin.bookmark_heads().unwrap())
2297
        .unwrap()
2298
        .materialize();
2299
    assert!(
2300
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2301
    );
2302
    assert!(full.files.contains_key("README.md"));
2303
    let _ = h1;
2304
}
2305
2306
#[test]
2307
fn shallow_clone_and_deepen() {
2308
    hermetic();
2309
    let dir = tempfile::tempdir().unwrap();
2310
    let root = dir.path();
2311
    let origin_dir = root.join("origin");
2312
    let origin = Repo::init(&origin_dir)
2313
        .unwrap()
2314
        .with_home(root.join("home"));
2315
    let mut hashes = Vec::new();
2316
    for i in 0..8 {
2317
        write(
2318
            &origin_dir,
2319
            "a.txt",
2320
            format!(
2321
                "{}\n",
2322
                (0..=i)
2323
                    .map(|k| k.to_string())
2324
                    .collect::<Vec<_>>()
2325
                    .join("\n")
2326
            )
2327
            .as_bytes(),
2328
        );
2329
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2330
    }
2331
    let url = origin_dir.to_string_lossy().to_string();
2332
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2333
        .unwrap()
2334
        .with_home(root.join("home"));
2335
    assert!(a.is_shallow());
2336
    assert_eq!(
2337
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2338
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2339
    );
2340
    assert!(
2341
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2342
        "three levels present"
2343
    );
2344
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2345
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2346
    assert_eq!(
2347
        a.log().unwrap().len(),
2348
        9,
2349
        "the log shows every change from the checkpoint's metadata"
2350
    );
2351
    assert!(!a.snapshot("status").unwrap().changed);
2352
    assert_eq!(a.quick_status().unwrap().heads, 1);
2353
2354
    // Work continues on top of the shallow history and pushes back.
2355
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2356
    let h_new = a.commit("c8", &[]).unwrap();
2357
    assert!(a.push("origin", false).unwrap()[0].ok);
2358
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2359
    // Fetching new work from origin into the shallow clone works too.
2360
    write(&origin_dir, "b.txt", b"b\n");
2361
    origin.pull("origin").err();
2362
    let (_, wc) = origin.working_copy().unwrap();
2363
    let _ = wc;
2364
    origin
2365
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2366
        .unwrap();
2367
    write(&origin_dir, "b.txt", b"b\n");
2368
    let h_b = origin.commit("b", &[]).unwrap();
2369
    let pr = a.pull("origin").unwrap();
2370
    assert!(pr.changed);
2371
    assert!(a.store().has(&h_b));
2372
    assert!(root.join("a/b.txt").exists());
2373
2374
    // Deepening fetches older history until the boundary is gone.
2375
    // Every commit also depends on the change that created the file, so two
2376
    // levels below the boundary hold h4, h3, and the root.
2377
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2378
    assert!(a.store().has(&hashes[3]));
2379
    assert!(a.is_shallow());
2380
    a.deepen("origin", 100).unwrap();
2381
    assert!(!a.is_shallow(), "boundary reached the root");
2382
    assert!(a.store().has(&hashes[0]));
2383
    assert_eq!(
2384
        a.load_state_full(&a.bookmark_heads().unwrap())
2385
            .unwrap()
2386
            .len(),
2387
        10
2388
    );
2389
}
2390
2391
#[test]
2392
fn tags_are_immutable_named_states_and_travel() {
2393
    hermetic();
2394
    let dir = tempfile::tempdir().unwrap();
2395
    let root = dir.path();
2396
    let origin = Repo::init(&root.join("origin")).unwrap();
2397
    let url = root.join("origin").to_string_lossy().to_string();
2398
    let mut a = Repo::clone(&url, &root.join("a"))
2399
        .unwrap()
2400
        .with_home(root.join("home-a"));
2401
    let (key_a, _) = a
2402
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2403
        .unwrap();
2404
    write(&root.join("a"), "f.txt", b"1\n");
2405
    let h1 = a.commit("one", &[]).unwrap();
2406
    write(&root.join("a"), "f.txt", b"1\n2\n");
2407
    let h2 = a.commit("two", &[]).unwrap();
2408
2409
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2410
    assert_eq!(
2411
        (t.heads.clone(), t.signer.as_deref()),
2412
        (vec![h1], Some("Ada"))
2413
    );
2414
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2415
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2416
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2417
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2418
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2419
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2420
    assert_eq!(sa.sigs[0].key, key_a);
2421
    // Checkout by tag.
2422
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2423
        .unwrap();
2424
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2425
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2426
        .unwrap();
2427
2428
    // Push carries the tag; a second attestation for the name is refused.
2429
    let r = a.push("origin", false).unwrap();
2430
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2431
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2432
    let mut forged = a
2433
        .tag_refs()
2434
        .unwrap()
2435
        .into_iter()
2436
        .find(|t| t.name == "v1")
2437
        .unwrap();
2438
    forged.state = origin
2439
        .store()
2440
        .put_state(&StateObject::new(vec![h2]))
2441
        .unwrap();
2442
    forged.heads = vec![h2];
2443
    forged.attestation = None;
2444
    let r = origin
2445
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2446
        .unwrap();
2447
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2448
2449
    // A clone gets the tag; a later tag arrives on fetch.
2450
    let b = Repo::clone(&url, &root.join("b"))
2451
        .unwrap()
2452
        .with_home(root.join("home-b"));
2453
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2454
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2455
    a.tag_create("v2", &[h2], "second").unwrap();
2456
    a.push("origin", false).unwrap();
2457
    let rep = b.fetch("origin").unwrap();
2458
    assert_eq!(rep.new_tags, 1);
2459
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2460
2461
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2462
    a.policy_init().unwrap();
2463
    a.push("origin", false).unwrap();
2464
    let unattested = crate::protocol::TagRef {
2465
        name: "v3".into(),
2466
        state: origin
2467
            .store()
2468
            .put_state(&StateObject::new(vec![h2]))
2469
            .unwrap(),
2470
        heads: vec![h2],
2471
        attestation: None,
2472
    };
2473
    let r = origin
2474
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2475
        .unwrap();
2476
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2477
    a.tag_create("v3", &[h2], "").unwrap();
2478
    let r = a.push("origin", false).unwrap();
2479
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2480
    assert!(a.gc(true).is_ok());
2481
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2482
}
2483
2484
#[test]
2485
fn multiple_workspaces_share_a_repository() {
2486
    hermetic();
2487
    let dir = tempfile::tempdir().unwrap();
2488
    let root = dir.path();
2489
    let main_dir = root.join("main");
2490
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2491
    write(&main_dir, "a.txt", b"a\n");
2492
    let h1 = repo.commit("a", &[]).unwrap();
2493
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2494
2495
    // A second workspace elsewhere, checked out on the bookmark.
2496
    let ws_dir = root.join("ws2");
2497
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2498
    assert!(ws_dir.join(".oxy").is_file());
2499
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2500
    assert_ne!(ws.workspace(), repo.workspace());
2501
    let list = repo.workspaces().unwrap();
2502
    assert_eq!(list.len(), 2);
2503
    assert!(list
2504
        .iter()
2505
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2506
    assert!(!ws.snapshot("status").unwrap().changed);
2507
2508
    // Work in the second workspace: its own working copy, shared bookmark.
2509
    write(&ws_dir, "b.txt", b"b\n");
2510
    let s = ws.snapshot("status").unwrap();
2511
    assert_eq!(s.statuses.len(), 1);
2512
    assert!(
2513
        !repo.snapshot("status").unwrap().changed,
2514
        "the first workspace is untouched"
2515
    );
2516
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2517
    let mut heads = repo.bookmark_heads().unwrap();
2518
    heads.sort();
2519
    let mut want = vec![h1, h2];
2520
    want.sort();
2521
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2522
    assert!(!main_dir.join("b.txt").exists());
2523
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2524
        .unwrap();
2525
    assert!(main_dir.join("b.txt").exists());
2526
2527
    // Reopening from inside the second workspace finds the shared repository.
2528
    let reopened = Repo::open(&ws_dir).unwrap();
2529
    assert_eq!(reopened.workspace(), ws.workspace());
2530
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2531
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2532
2533
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2534
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2535
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2536
    repo.workspace_forget(&ws.workspace()).unwrap();
2537
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2538
    assert!(ws_dir.join("b.txt").exists());
2539
    assert!(
2540
        ws.snapshot("status").is_err(),
2541
        "a forgotten workspace is no longer in the view"
2542
    );
2543
2544
    // The working-copy lock: re-entrant in a thread; a lock whose process
2545
    // is gone is taken over, and a live process's is not, however old.
2546
    let lock = repo.lock_snapshot().unwrap();
2547
    let again = repo.lock_working_copy().unwrap();
2548
    drop(again);
2549
    drop(lock);
2550
    let lock_path = main_dir
2551
        .join(".oxy/workspaces")
2552
        .join(repo.workspace().to_hex())
2553
        .join("lock");
2554
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2555
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2556
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2557
    age(&lock_path);
2558
    assert!(
2559
        !super::workspace::lock_is_stale(&lock_path),
2560
        "a live process keeps its lock"
2561
    );
2562
    fs::write(&lock_path, "4294967295").unwrap();
2563
    age(&lock_path);
2564
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2565
}
2566
2567
#[test]
2568
fn attributes_binary_eol_nocompress_lockable() {
2569
    hermetic();
2570
    let dir = tempfile::tempdir().unwrap();
2571
    let root = dir.path();
2572
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2573
    write(
2574
        root,
2575
        ".oxyattributes",
2576
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2577
    );
2578
    write(root, "plain.dat", b"no nul bytes here\n");
2579
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2580
    write(root, "assets/model.bin", b"\0model");
2581
    let h = repo.commit("attrs", &[]).unwrap();
2582
    let snap = repo.load_state(&[h]).unwrap().materialize();
2583
    assert!(
2584
        snap.files["plain.dat"].mode.opaque,
2585
        "binary attribute forces opaque without NUL bytes"
2586
    );
2587
    assert!(
2588
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2589
        "stored with LF"
2590
    );
2591
    assert!(
2592
        !repo.snapshot("status").unwrap().changed,
2593
        "CRLF on disk equals LF in the state"
2594
    );
2595
    // nocompress chunks pack raw.
2596
    let r = repo.gc(true).unwrap();
2597
    assert!(r.packed.objects > 0);
2598
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2599
    fs::remove_file(root.join("notes.txt")).unwrap();
2600
    repo.checkout(&[h], true, "co").unwrap();
2601
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2602
    assert!(fs::metadata(root.join("assets/model.bin"))
2603
        .unwrap()
2604
        .permissions()
2605
        .readonly());
2606
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2607
    repo.lock_path("assets/model.bin").unwrap();
2608
    assert!(!fs::metadata(root.join("assets/model.bin"))
2609
        .unwrap()
2610
        .permissions()
2611
        .readonly());
2612
    assert!(repo.is_locked("assets/model.bin"));
2613
    write(root, "assets/model.bin", b"\0model2");
2614
    repo.commit("edit model", &[]).unwrap();
2615
    repo.unlock_path("assets/model.bin").unwrap();
2616
    assert!(fs::metadata(root.join("assets/model.bin"))
2617
        .unwrap()
2618
        .permissions()
2619
        .readonly());
2620
    // A later checkout can still overwrite a read-only lockable file.
2621
    repo.checkout(&[h], true, "co").unwrap();
2622
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2623
}
2624
2625
#[cfg(unix)]
2626
#[test]
2627
fn hooks_can_veto_observe_and_add_dependencies() {
2628
    use std::os::unix::fs::PermissionsExt;
2629
    hermetic();
2630
    let dir = tempfile::tempdir().unwrap();
2631
    let root = dir.path();
2632
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2633
    let hooks = root.join(".oxy/hooks");
2634
    fs::create_dir_all(&hooks).unwrap();
2635
    let hook = |name: &str, body: &str| {
2636
        let p = hooks.join(name);
2637
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2638
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2639
    };
2640
    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");
2641
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2642
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2643
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2644
    write(root, ".oxyignore", b".last-*\n");
2645
    write(root, "a.txt", b"a\n");
2646
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2647
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2648
    let h1 = repo.commit("first", &[]).unwrap();
2649
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2650
    assert!(
2651
        pre.contains("\"event\":\"pre-commit\"")
2652
            && pre.contains("\"path\":\"a.txt\"")
2653
            && pre.contains("\"message\":\"first\""),
2654
        "{pre}"
2655
    );
2656
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2657
    assert!(post.contains(&h1.to_hex()), "{post}");
2658
    repo.checkout(&[h1], false, "co").unwrap();
2659
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2660
        .unwrap()
2661
        .contains("post-checkout"));
2662
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2663
    repo.save_config().unwrap();
2664
    let err = repo.push("origin", false).unwrap_err().to_string();
2665
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2666
2667
    // semantic-deps: only when enabled; adds an explicit dependency.
2668
    write(root, "b.txt", b"b\n");
2669
    hook(
2670
        "semantic-deps",
2671
        &format!(
2672
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2673
            h1.to_hex()
2674
        ),
2675
    );
2676
    let h2 = repo.commit("b without hook", &[]).unwrap();
2677
    assert!(
2678
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2679
        "hook disabled by default"
2680
    );
2681
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2682
    repo.save_config().unwrap();
2683
    write(root, "c.txt", b"c\n");
2684
    let h3 = repo.commit("c with hook", &[]).unwrap();
2685
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2686
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2687
    assert!(
2688
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2689
        "{sem}"
2690
    );
2691
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2692
}
2693
2694
#[test]
2695
fn amend_into_older_change_and_split() {
2696
    hermetic();
2697
    let dir = tempfile::tempdir().unwrap();
2698
    let root = dir.path();
2699
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2700
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2701
        .unwrap();
2702
    repo.set_user_config("core.sign", "change").unwrap();
2703
    write(root, "a.txt", b"one\ntwo\n");
2704
    let h0 = repo.commit("base", &[]).unwrap();
2705
    write(root, "a.txt", b"one\nTWO\n");
2706
    let h1 = repo.commit("edit two", &[]).unwrap();
2707
    write(root, "a.txt", b"one\nTWO\nthree\n");
2708
    let h2 = repo.commit("add three", &[]).unwrap();
2709
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2710
2711
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2712
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2713
    let h1b = repo.amend_into(&h1, None).unwrap();
2714
    assert_ne!(h1b, h1);
2715
    let c1b = repo.store().get_change(&h1b).unwrap();
2716
    assert_eq!(c1b.change_id, id1);
2717
    assert_eq!(c1b.deps, vec![h0]);
2718
    assert!(matches!(
2719
        repo.verify_change(&h1b).unwrap(),
2720
        SignatureStatus::Valid { .. }
2721
    ));
2722
    let heads = repo.bookmark_heads().unwrap();
2723
    assert_eq!(heads.len(), 1);
2724
    let top = repo.store().get_change(&heads[0]).unwrap();
2725
    assert_eq!(top.message, "add three");
2726
    assert_eq!(
2727
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2728
        [h0, h1b].into_iter().collect(),
2729
        "depends on the file's creator and the rewritten line"
2730
    );
2731
    let snap = repo.load_state(&heads).unwrap().materialize();
2732
    assert!(
2733
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2734
    );
2735
    assert!(
2736
        !repo.snapshot("status").unwrap().changed,
2737
        "the working copy is clean after folding"
2738
    );
2739
    // Only h1b's own state shows the fix without "three".
2740
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2741
    assert!(
2742
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2743
    );
2744
    assert_eq!(repo.log().unwrap().len(), 4);
2745
2746
    // An edit to a line introduced by h2 cannot fold into h1.
2747
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2748
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2749
    assert!(err.contains("introduced after"), "{err}");
2750
    assert!(
2751
        repo.snapshot("status").unwrap().statuses.len() == 1,
2752
        "nothing was changed by the refusal"
2753
    );
2754
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2755
2756
    // Split the head that touches two files.
2757
    write(root, "b.txt", b"b\n");
2758
    write(root, "c.txt", b"c\n");
2759
    let h3 = repo.commit("b and c", &[]).unwrap();
2760
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2761
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2762
    let c_1 = repo.store().get_change(&p1).unwrap();
2763
    let c_2 = repo.store().get_change(&p2).unwrap();
2764
    assert!(c_1.message.contains("part 1: b.txt"));
2765
    assert_eq!(c_2.change_id, id3);
2766
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2767
    assert!(
2768
        heads.contains(&p1) && heads.contains(&p2),
2769
        "independent parts are both heads"
2770
    );
2771
    let snap = repo
2772
        .load_state(&repo.bookmark_heads().unwrap())
2773
        .unwrap()
2774
        .materialize();
2775
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2776
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2777
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2778
    assert!(!repo.snapshot("status").unwrap().changed);
2779
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2780
    let _ = h2;
2781
}
2782
2783
#[test]
2784
fn identity_lifecycle() {
2785
    hermetic();
2786
    let dir = tempfile::tempdir().unwrap();
2787
    let root = dir.path();
2788
    let origin = Repo::init(&root.join("origin")).unwrap();
2789
    let url = root.join("origin").to_string_lossy().to_string();
2790
    let mut a = Repo::clone(&url, &root.join("a"))
2791
        .unwrap()
2792
        .with_home(root.join("home-a"));
2793
    a.set_user_config("core.sign", "change").unwrap();
2794
    let (key_a, _) = a
2795
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2796
        .unwrap();
2797
    write(&root.join("a"), "a.txt", b"a\n");
2798
    let h1 = a.commit("one", &[]).unwrap();
2799
    assert!(a.policy_init().unwrap().applied);
2800
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2801
2802
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2803
    let mut e = Repo::init(&root.join("e"))
2804
        .unwrap()
2805
        .with_home(root.join("home-e"));
2806
    e.set_user_config("core.sign", "change").unwrap();
2807
    e.create_identity_with(
2808
        "Eve",
2809
        "[email protected]",
2810
        IdentityScope::User,
2811
        Some(Hlc::now().wall_ms - 1),
2812
    )
2813
    .unwrap();
2814
    write(&root.join("e"), "e.txt", b"e\n");
2815
    let he = e.commit("late", &[]).unwrap();
2816
    assert!(
2817
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2818
    );
2819
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2820
    let r = e
2821
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2822
        .unwrap();
2823
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2824
    write(&root.join("e"), "e.txt", b"e2\n");
2825
    let he2 = e.commit("in time", &[]).unwrap();
2826
    assert!(
2827
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2828
    );
2829
2830
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2831
    let r = a.rotate_identity().unwrap();
2832
    assert_eq!(r.old, key_a);
2833
    assert_eq!(a.config.author_key, Some(r.new));
2834
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2835
    assert!(r.policy.as_ref().unwrap().applied);
2836
    let (_, sp) = a.current_policy().unwrap().unwrap();
2837
    assert_eq!(
2838
        (sp.policy.serial, sp.policy.roots.clone()),
2839
        (2, vec![r.new])
2840
    );
2841
    assert!(
2842
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2843
        "superseded, not revoked"
2844
    );
2845
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2846
    assert!(
2847
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2848
    );
2849
    write(&root.join("a"), "a.txt", b"a2\n");
2850
    let h2 = a.commit("two", &[]).unwrap();
2851
    assert!(
2852
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2853
    );
2854
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2855
    let res = a.push("origin", false).unwrap();
2856
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2857
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2858
    let key_a = r.new;
2859
2860
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2861
    // identity object, so Ada's KeyId changes while her keys stay the same.
2862
    let mut b = Repo::clone(&url, &root.join("b"))
2863
        .unwrap()
2864
        .with_home(root.join("home-b"));
2865
    let (key_b, id_b) = b
2866
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2867
        .unwrap();
2868
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
2869
    assert_eq!(r.old, key_a);
2870
    let key_a2 = r.new;
2871
    assert_eq!(
2872
        a.identity(&key_a2).unwrap().delegates,
2873
        vec![Delegate::full(key_b)]
2874
    );
2875
    assert_eq!(
2876
        a.identity(&key_a2).unwrap().ed25519_pk,
2877
        a.identity(&key_a).unwrap().ed25519_pk
2878
    );
2879
    assert!(
2880
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2881
        "already a delegate"
2882
    );
2883
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2884
    write(&root.join("a"), "a.txt", b"a3\n");
2885
    let h3 = a.commit("three", &[]).unwrap();
2886
    assert!(
2887
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2888
        "the same secret signs under the new KeyId"
2889
    );
2890
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2891
    a.set_user_config("core.sign", "seal").unwrap();
2892
    write(&root.join("a"), "a.txt", b"a4\n");
2893
    let h4 = a.commit("four", &[]).unwrap();
2894
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2895
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2896
    a.store()
2897
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2898
        .unwrap();
2899
    assert!(
2900
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2901
    );
2902
    a.set_user_config("core.sign", "change").unwrap();
2903
    // Withdrawing the delegation re-issues the identity again.
2904
    let r = a.delegate_remove(&key_b).unwrap();
2905
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2906
    assert!(a.delegate_remove(&key_b).is_err());
2907
    let key_a3 = r.new;
2908
    let res = a.push("origin", false).unwrap();
2909
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2910
2911
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2912
    // both applied under the old threshold of 1. A grant then needs Bob too.
2913
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2914
    assert!(a.policy_root_add(id_b.clone()).is_err());
2915
    assert!(a.policy_set_threshold(3).is_err());
2916
    assert!(a.policy_set_threshold(2).unwrap().applied);
2917
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2918
    b.pull("origin").unwrap();
2919
    assert_eq!(
2920
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2921
        2
2922
    );
2923
    let mut c = Repo::init(&root.join("c"))
2924
        .unwrap()
2925
        .with_home(root.join("home-c"));
2926
    let (key_c, id_c) = c
2927
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2928
        .unwrap();
2929
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2930
    let proposal = a.policy_grant(id_c, None).unwrap();
2931
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2932
    assert_eq!(proposal.policy.serial, serial_before + 1);
2933
    assert_eq!(
2934
        a.current_policy().unwrap().unwrap().1.policy.serial,
2935
        serial_before,
2936
        "a proposal changes nothing yet"
2937
    );
2938
    // Bob signs the proposal, handed over as a file, and it applies for him.
2939
    let bytes = proposal.signed().encode();
2940
    let signed = b
2941
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2942
        .unwrap();
2943
    assert!(signed.applied && signed.sigs.len() == 2);
2944
    assert!(b
2945
        .current_policy()
2946
        .unwrap()
2947
        .unwrap()
2948
        .1
2949
        .policy
2950
        .authorizes(&key_c, "main"));
2951
    assert!(
2952
        b.policy_sign(signed.signed()).is_err(),
2953
        "a stale proposal is refused"
2954
    );
2955
    // Bob publishes it and Ada picks it up.
2956
    assert!(b
2957
        .push("origin", false)
2958
        .unwrap()
2959
        .iter()
2960
        .any(|x| x.name == "policy" && x.ok));
2961
    a.pull("origin").unwrap();
2962
    assert_eq!(
2963
        a.current_policy().unwrap().unwrap().1.policy.serial,
2964
        serial_before + 1
2965
    );
2966
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2967
    assert!(a.policy_revoke(&key_a3).is_err());
2968
    let u = a
2969
        .revoke_identity(&key_c, "left the project")
2970
        .unwrap()
2971
        .unwrap();
2972
    assert!(!u.applied);
2973
    assert!(a.is_revoked(&key_c).unwrap());
2974
    assert!(!b.is_revoked(&key_c).unwrap());
2975
    let u = b.policy_sign(u.signed()).unwrap();
2976
    assert!(u.applied && u.policy.is_revoked(&key_c));
2977
    assert!(b.is_revoked(&key_c).unwrap());
2978
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2979
    assert!(
2980
        b.policy_revoke(&key_a3).is_err(),
2981
        "would leave one root for a threshold of 2"
2982
    );
2983
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2984
    let key_c_own = c.config.author_key.unwrap();
2985
    assert!(c
2986
        .revoke_identity(&key_c_own, "lost laptop")
2987
        .unwrap()
2988
        .is_none());
2989
    assert!(c.is_revoked(&key_c_own).unwrap());
2990
    assert_eq!(key_c_own, key_c);
2991
}
2992
2993
#[test]
2994
fn renames_are_detected_and_tracked_as_moves() {
2995
    hermetic();
2996
    let dir = tempfile::tempdir().unwrap();
2997
    let root = dir.path();
2998
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2999
    write(
3000
        root,
3001
        "src/old.rs",
3002
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3003
    );
3004
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3005
    write(root, "tiny.txt", b"x\n");
3006
    let h1 = repo.commit("base", &[]).unwrap();
3007
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3008
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3009
3010
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3011
    // that shares nothing with the removed file.
3012
    fs::remove_file(root.join("src/old.rs")).unwrap();
3013
    write(
3014
        root,
3015
        "lib/new.rs",
3016
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3017
    );
3018
    fs::remove_file(root.join("img.bin")).unwrap();
3019
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3020
    fs::remove_file(root.join("tiny.txt")).unwrap();
3021
    write(root, "other.txt", b"completely different\n");
3022
    let snap = repo.snapshot("status").unwrap();
3023
    let statuses: Vec<(&str, ChangeStatus)> = snap
3024
        .statuses
3025
        .iter()
3026
        .map(|s| (s.path.as_str(), s.status))
3027
        .collect();
3028
    assert_eq!(
3029
        statuses,
3030
        vec![
3031
            ("assets/img.bin", ChangeStatus::Renamed),
3032
            ("lib/new.rs", ChangeStatus::Renamed),
3033
            ("other.txt", ChangeStatus::Added),
3034
            ("src", ChangeStatus::Removed),
3035
            ("tiny.txt", ChangeStatus::Removed)
3036
        ]
3037
    );
3038
    let h2 = repo.commit("move things", &[]).unwrap();
3039
    let c = repo.store().get_change(&h2).unwrap();
3040
    let moves: Vec<_> = c
3041
        .tree_ops
3042
        .iter()
3043
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3044
        .collect();
3045
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3046
    assert!(c.tree_ops.iter().any(
3047
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3048
    ));
3049
    assert!(c.tree_ops.iter().any(
3050
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3051
    ));
3052
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3053
    assert_eq!(
3054
        snap.files["lib/new.rs"].node, node_old,
3055
        "the node survives the rename"
3056
    );
3057
    assert!(
3058
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3059
    );
3060
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3061
    assert!(render_change(
3062
        &c,
3063
        &repo.load_state(&[h1]).unwrap(),
3064
        &repo.load_state(&[h1]).unwrap().materialize()
3065
    )
3066
    .contains("R "));
3067
    // A fresh checkout reproduces the tree.
3068
    let other = tempfile::tempdir().unwrap();
3069
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3070
    assert_eq!(
3071
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3072
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3073
    );
3074
    assert!(!other.path().join("src").exists());
3075
    assert!(!clone.snapshot("status").unwrap().changed);
3076
    // Similarity is line based, byte weighted.
3077
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3078
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3079
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3080
    assert_eq!(similarity(b"", b"x\n"), 0);
3081
}
3082
3083
#[test]
3084
fn git_fetch_and_push_round_trip() {
3085
    hermetic();
3086
    if std::process::Command::new("git")
3087
        .arg("--version")
3088
        .output()
3089
        .is_err()
3090
    {
3091
        eprintln!("git not installed; skipping");
3092
        return;
3093
    }
3094
    let dir = tempfile::tempdir().unwrap();
3095
    let root = dir.path();
3096
    let git_in = |d: &Path, args: &[&str]| -> String {
3097
        let out = std::process::Command::new("git")
3098
            .arg("-C")
3099
            .arg(d)
3100
            .args([
3101
                "-c",
3102
                "user.name=Grace",
3103
                "-c",
3104
                "[email protected]",
3105
                "-c",
3106
                "commit.gpgsign=false",
3107
            ])
3108
            .args(args)
3109
            .output()
3110
            .unwrap();
3111
        assert!(
3112
            out.status.success(),
3113
            "git {args:?}: {}",
3114
            String::from_utf8_lossy(&out.stderr)
3115
        );
3116
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3117
    };
3118
    // A bare "remote" and a work tree that pushes to it.
3119
    let remote = root.join("remote.git");
3120
    fs::create_dir_all(&remote).unwrap();
3121
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3122
    let work = root.join("work");
3123
    git_in(
3124
        root,
3125
        &[
3126
            "clone",
3127
            "-q",
3128
            remote.to_str().unwrap(),
3129
            work.to_str().unwrap(),
3130
        ],
3131
    );
3132
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3133
    write(&work, "README.md", b"# Project\n");
3134
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3135
    git_in(&work, &["add", "."]);
3136
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3137
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3138
    git_in(&work, &["commit", "-q", "-am", "second"]);
3139
    git_in(&work, &["push", "-q", "origin", "main"]);
3140
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3141
3142
    // Fetch into a fresh oxy repository.
3143
    let o = root.join("oxy");
3144
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3145
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3146
        .unwrap();
3147
    let url = remote.to_string_lossy().to_string();
3148
    let r = repo.git_fetch(&url, "main").unwrap();
3149
    assert_eq!((r.commits, r.heads), (2, 1));
3150
    assert_eq!(
3151
        fs::read(o.join("src/lib.rs")).unwrap(),
3152
        b"pub fn a() {}\npub fn b() {}\n"
3153
    );
3154
    assert!(!repo.snapshot("status").unwrap().changed);
3155
    assert_eq!(
3156
        repo.git_fetch(&url, "main").unwrap().commits,
3157
        0,
3158
        "nothing new"
3159
    );
3160
3161
    // An oxy change, pushed back: one commit on top of the Git tip.
3162
    write(
3163
        &o,
3164
        "src/lib.rs",
3165
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3166
    );
3167
    write(&o, "NOTES.md", b"from oxy\n");
3168
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3169
    let r = repo.git_push(&url, "main").unwrap();
3170
    assert_eq!(r.exported, 1, "{r:?}");
3171
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3172
    assert_eq!(
3173
        git_in(&work, &["log", "--format=%s", "main"]),
3174
        "add c and notes\nsecond\ninitial"
3175
    );
3176
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3177
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3178
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3179
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3180
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3181
    assert_eq!(
3182
        repo.git_push(&url, "main").unwrap().exported,
3183
        0,
3184
        "already pushed"
3185
    );
3186
3187
    // Git moves on; pushing without fetching is refused, fetching brings
3188
    // the commit in and the working copy follows.
3189
    write(&work, "README.md", b"# Project\n\nMore.\n");
3190
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3191
    git_in(&work, &["push", "-q", "origin", "main"]);
3192
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3193
    assert!(repo
3194
        .git_push(&url, "main")
3195
        .unwrap_err()
3196
        .to_string()
3197
        .contains("fetch"));
3198
    let r = repo.git_fetch(&url, "main").unwrap();
3199
    assert_eq!(
3200
        (r.commits, r.heads),
3201
        (1, 2),
3202
        "the Git change and the oxy change commute"
3203
    );
3204
    assert_eq!(
3205
        fs::read(o.join("README.md")).unwrap(),
3206
        b"# Project\n\nMore.\n"
3207
    );
3208
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3209
    assert!(!repo.snapshot("status").unwrap().changed);
3210
    // Another oxy change pushes on top of Git's newest commit.
3211
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3212
    repo.commit("notes again", &[]).unwrap();
3213
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3214
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3215
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
3216
    assert_eq!(
3217
        fs::read(work.join("NOTES.md")).unwrap(),
3218
        b"from oxy\nagain\n"
3219
    );
3220
    assert_eq!(
3221
        git_in(&work, &["log", "--format=%s", "main"])
3222
            .lines()
3223
            .count(),
3224
        5
3225
    );
3226
}
3227
3228
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3229
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3230
#[test]
3231
#[ignore]
3232
fn bench_one_gibibyte_file() {
3233
    hermetic();
3234
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3235
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3236
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3237
        None => tempfile::tempdir().unwrap(),
3238
    };
3239
    let root = dir.path();
3240
    let repo = Repo::init(&root.join("r"))
3241
        .unwrap()
3242
        .with_home(root.join("home"));
3243
    let size = 1usize << 30;
3244
    let mut data = vec![0u8; size];
3245
    let mut x = 0x9e3779b97f4a7c15u64;
3246
    for chunk in data.chunks_mut(8) {
3247
        x ^= x << 13;
3248
        x ^= x >> 7;
3249
        x ^= x << 17;
3250
        let b = x.to_le_bytes();
3251
        chunk.copy_from_slice(&b[..chunk.len()]);
3252
    }
3253
    let t = std::time::Instant::now();
3254
    write(&root.join("r"), "big.bin", &data);
3255
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3256
    let t = std::time::Instant::now();
3257
    let h = repo.commit("big", &[]).unwrap();
3258
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3259
    let t = std::time::Instant::now();
3260
    assert!(!repo.snapshot("status").unwrap().changed);
3261
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3262
    let t = std::time::Instant::now();
3263
    let objects = repo.store().list().unwrap().len();
3264
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3265
    let t = std::time::Instant::now();
3266
    let g = repo.gc(true).unwrap();
3267
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3268
    let t = std::time::Instant::now();
3269
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3270
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3271
    let t = std::time::Instant::now();
3272
    let back = fs::read(root.join("c/big.bin")).unwrap();
3273
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3274
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3275
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3276
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
3277
    eprintln!(
3278
        "store size: {:.1} MiB for 1 GiB of data",
3279
        store_bytes as f64 / (1024.0 * 1024.0)
3280
    );
3281
}
3282
3283
fn walkdir_size(p: &Path) -> u64 {
3284
    let mut total = 0;
3285
    if let Ok(rd) = fs::read_dir(p) {
3286
        for e in rd.flatten() {
3287
            let path = e.path();
3288
            if path.is_dir() {
3289
                total += walkdir_size(&path);
3290
            } else if let Ok(m) = fs::metadata(&path) {
3291
                total += m.len();
3292
            }
3293
        }
3294
    }
3295
    total
3296
}
3297
3298
/// An opaque file whose size and mtime match the manifest is not read on
3299
/// the next snapshot: its blob comes from the manifest's stat cache.
3300
#[cfg(unix)]
3301
#[test]
3302
fn stat_cache_skips_reading_unchanged_opaque_files() {
3303
    use std::os::unix::fs::PermissionsExt;
3304
    hermetic();
3305
    let dir = tempfile::tempdir().unwrap();
3306
    let root = dir.path();
3307
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3308
    let mut big = vec![0u8; 300 * 1024];
3309
    for (i, b) in big.iter_mut().enumerate() {
3310
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3311
    }
3312
    big[0] = 0;
3313
    write(root, "big.bin", &big);
3314
    write(root, "a.txt", b"text\n");
3315
    let h1 = repo.commit("base", &[]).unwrap();
3316
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3317
    assert!(
3318
        m.entries["big.bin"].blob.is_some(),
3319
        "opaque files record their blob"
3320
    );
3321
    assert!(m.entries["a.txt"].blob.is_none());
3322
    let blob = m.entries["big.bin"].blob.unwrap();
3323
    assert!(repo.store().has(&blob));
3324
3325
    // Files modified within two seconds of the manifest are racy and still
3326
    // read; age the file so the cache applies, then snapshot to record it.
3327
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3328
    fs::File::options()
3329
        .write(true)
3330
        .open(root.join("big.bin"))
3331
        .unwrap()
3332
        .set_modified(old)
3333
        .unwrap();
3334
    assert!(!repo.snapshot("status").unwrap().changed);
3335
    // Now the file cannot be read at all; the snapshot succeeds without it.
3336
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3337
    let snap = repo.snapshot("status").unwrap();
3338
    assert!(
3339
        !snap.changed && snap.statuses.is_empty(),
3340
        "{:?}",
3341
        snap.statuses
3342
    );
3343
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3344
    // A real change (new mtime, new content) is seen and committed correctly.
3345
    let mut big2 = big.clone();
3346
    big2[10] ^= 0xff;
3347
    write(root, "big.bin", &big2);
3348
    let snap = repo.snapshot("status").unwrap();
3349
    assert_eq!(
3350
        snap.statuses
3351
            .iter()
3352
            .map(|s| (s.path.as_str(), s.status))
3353
            .collect::<Vec<_>>(),
3354
        vec![("big.bin", ChangeStatus::Modified)]
3355
    );
3356
    let h2 = repo.commit("edit", &[]).unwrap();
3357
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3358
    assert_eq!(
3359
        files["big.bin"].content,
3360
        FileContent::Opaque {
3361
            blobs: vec![Repo::blob_ref(&big2)]
3362
        }
3363
    );
3364
    // Checkout writes a manifest with blobs too, so the next status is cached.
3365
    repo.checkout(&[h1], false, "checkout").unwrap();
3366
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3367
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3368
    assert!(!repo.snapshot("status").unwrap().changed);
3369
}
3370
3371
#[test]
3372
fn status_json_lists_conflicts_with_contributors() {
3373
    hermetic();
3374
    let dir = tempfile::tempdir().unwrap();
3375
    let root = dir.path();
3376
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3377
    write(root, "a.txt", b"one\n");
3378
    let h1 = repo.commit("base", &[]).unwrap();
3379
    write(root, "a.txt", b"one\nleft\n");
3380
    let ha = repo.commit("left", &[]).unwrap();
3381
    repo.checkout(&[h1], true, "checkout").unwrap();
3382
    write(root, "a.txt", b"one\nright\n");
3383
    let hb = repo.commit("right", &[]).unwrap();
3384
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3385
    let snap = repo.snapshot("status").unwrap();
3386
    assert!(snap.base_snapshot.is_conflicted());
3387
    let json = repo.status_json(&snap).unwrap();
3388
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3389
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3390
    assert!(json.contains("\"conflicted\":true"), "{json}");
3391
    assert!(
3392
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3393
        "{json}"
3394
    );
3395
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3396
    assert!(json.contains("\"resolved\":false"), "{json}");
3397
    assert!(json.starts_with('{') && json.ends_with('}'));
3398
    // Resolve and the report says so; a clean copy has no conflicts.
3399
    write(root, "a.txt", b"one\nleft\nright\n");
3400
    let snap = repo.snapshot("status").unwrap();
3401
    let json = repo.status_json(&snap).unwrap();
3402
    assert!(json.contains("\"resolved\":true"), "{json}");
3403
    repo.commit("resolve", &[]).unwrap();
3404
    let snap = repo.snapshot("status").unwrap();
3405
    let json = repo.status_json(&snap).unwrap();
3406
    assert!(
3407
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3408
        "{json}"
3409
    );
3410
}
3411
3412
#[test]
3413
fn ignore_rules_do_not_untrack_files() {
3414
    hermetic();
3415
    let dir = tempfile::tempdir().unwrap();
3416
    let root = dir.path();
3417
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3418
    write(root, "src.c", b"int x;\n");
3419
    write(root, "build/out.o", b"\0obj");
3420
    write(root, "sub/keep.log", b"keep\n");
3421
    write(root, "sub/junk.log", b"junk\n");
3422
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3423
    let snap = repo.snapshot("status").unwrap();
3424
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3425
    assert_eq!(
3426
        added,
3427
        vec![".oxyignore", "src.c", "sub/keep.log"],
3428
        "anchored, glob, and negated rules"
3429
    );
3430
    let h1 = repo.commit("base", &[]).unwrap();
3431
    // Ignoring a tracked file changes nothing about it.
3432
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3433
    let snap = repo.snapshot("status").unwrap();
3434
    assert_eq!(
3435
        snap.statuses
3436
            .iter()
3437
            .map(|s| s.path.as_str())
3438
            .collect::<Vec<_>>(),
3439
        vec![".oxyignore"]
3440
    );
3441
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3442
    assert!(repo
3443
        .load_state(&[h2])
3444
        .unwrap()
3445
        .materialize()
3446
        .files
3447
        .contains_key("src.c"));
3448
    // Its edits are still seen, by status and by the prompt.
3449
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3450
    write(root, "src.c", b"int x, y;\n");
3451
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3452
    let snap = repo.snapshot("status").unwrap();
3453
    assert_eq!(
3454
        snap.statuses
3455
            .iter()
3456
            .map(|s| (s.path.as_str(), s.status))
3457
            .collect::<Vec<_>>(),
3458
        vec![("src.c", ChangeStatus::Modified)]
3459
    );
3460
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3461
    assert!(
3462
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3463
    );
3464
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3465
    fs::remove_file(root.join("src.c")).unwrap();
3466
    let snap = repo.snapshot("status").unwrap();
3467
    assert_eq!(
3468
        snap.statuses
3469
            .iter()
3470
            .map(|s| (s.path.as_str(), s.status))
3471
            .collect::<Vec<_>>(),
3472
        vec![("src.c", ChangeStatus::Removed)]
3473
    );
3474
    repo.checkout(&[h3], true, "checkout").unwrap();
3475
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3476
    assert!(!repo.snapshot("status").unwrap().changed);
3477
    let _ = h1;
3478
}
3479
3480
#[test]
3481
fn split_works_on_non_heads_by_node() {
3482
    hermetic();
3483
    let dir = tempfile::tempdir().unwrap();
3484
    let root = dir.path();
3485
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3486
    write(root, "a.txt", b"one\n");
3487
    write(root, "junk/x.lock", b"lock\n");
3488
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3489
    write(root, "a.txt", b"one\ntwo\n");
3490
    let h2 = repo.commit("more work", &[]).unwrap();
3491
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3492
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3493
    // h1 is not a head: split it by node.
3494
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3495
    assert_ne!(h1b, h1);
3496
    assert_eq!(
3497
        repo.store().get_change(&h1b).unwrap().change_id,
3498
        id1,
3499
        "the rest keeps the ChangeId"
3500
    );
3501
    let junk = repo.store().get_change(&hj).unwrap();
3502
    assert!(junk.tree_ops.iter().all(
3503
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3504
    ));
3505
    let heads = repo.bookmark_heads().unwrap();
3506
    assert!(
3507
        heads.contains(&hj),
3508
        "the split-off part is a head of its own"
3509
    );
3510
    let snap = repo.load_state(&heads).unwrap().materialize();
3511
    assert!(
3512
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3513
        "the dependent was rewritten onto the new hash"
3514
    );
3515
    assert!(snap.files.contains_key("junk/x.lock"));
3516
    let h2b = heads
3517
        .iter()
3518
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3519
        .copied()
3520
        .unwrap();
3521
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3522
    assert!(!repo.snapshot("status").unwrap().changed);
3523
    // Abandoning the split-off head removes the junk from history.
3524
    repo.abandon(&hj).unwrap();
3525
    let heads = repo.bookmark_heads().unwrap();
3526
    let snap = repo.load_state(&heads).unwrap().materialize();
3527
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3528
    assert!(snap.files.contains_key("a.txt"));
3529
    // A dependent that touches the split-off paths blocks the split.
3530
    write(root, "junk/y.lock", b"y\n");
3531
    let hb = repo.commit("junk base", &[]).unwrap();
3532
    write(root, "junk/y.lock", b"yy\n");
3533
    write(root, "b.txt", b"b\n");
3534
    repo.commit("touches junk", &[]).unwrap();
3535
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3536
    assert!(err.contains("depends on the split-off paths"), "{err}");
3537
}
3538
3539
#[test]
3540
fn bookmarks_switch_merge_and_push() {
3541
    hermetic();
3542
    let dir = tempfile::tempdir().unwrap();
3543
    let root = dir.path();
3544
    let origin = Repo::init(&root.join("origin")).unwrap();
3545
    let url = root.join("origin").to_string_lossy().to_string();
3546
    let mut repo = Repo::clone(&url, &root.join("r"))
3547
        .unwrap()
3548
        .with_home(root.join("home"));
3549
    let r = root.join("r");
3550
    write(&r, "a.txt", b"a\n");
3551
    let h_a = repo.commit("a", &[]).unwrap();
3552
    assert!(repo.push("origin", false).unwrap()[0].ok);
3553
3554
    // A bookmark at the working copy's base, then work on it.
3555
    assert!(repo.bookmark_create("bad name..", None).is_err());
3556
    assert!(repo.bookmark_create("-x", None).is_err());
3557
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3558
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3559
    repo.bookmark_switch("feature", false).unwrap();
3560
    assert_eq!(repo.config.bookmark, "feature");
3561
    write(&r, "a.txt", b"a\nb\n");
3562
    write(&r, "b.txt", b"b\n");
3563
    let h_b = repo.commit("b on feature", &[]).unwrap();
3564
    assert_eq!(
3565
        repo.bookmark_heads().unwrap(),
3566
        vec![h_b],
3567
        "b edits a.txt, so it depends on a"
3568
    );
3569
    assert_eq!(
3570
        repo.resolve_heads("main").unwrap(),
3571
        vec![h_a],
3572
        "main is untouched"
3573
    );
3574
    assert_eq!(
3575
        repo.resolve_change("feature").unwrap(),
3576
        h_b,
3577
        "a one-head bookmark names its change"
3578
    );
3579
    // Reopening keeps the workspace's bookmark.
3580
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3581
    assert_eq!(reopened.config.bookmark, "feature");
3582
    // Back to main: b.txt goes away; work there.
3583
    repo.bookmark_switch("main", false).unwrap();
3584
    assert!(!r.join("b.txt").exists());
3585
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3586
    write(&r, "c.txt", b"c\n");
3587
    let h_c = repo.commit("c on main", &[]).unwrap();
3588
    let list = repo.bookmarks().unwrap();
3589
    assert_eq!(
3590
        list.iter()
3591
            .map(|b| (b.name.as_str(), b.current))
3592
            .collect::<Vec<_>>(),
3593
        vec![("feature", false), ("main", true)]
3594
    );
3595
    assert_eq!(
3596
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3597
        Some(1),
3598
        "c is not on origin yet"
3599
    );
3600
    // Merge feature into main: the union, both heads, no merge change.
3601
    let m = repo.merge("feature").unwrap();
3602
    assert!(m.changed && m.checked_out);
3603
    let mut want = vec![h_b, h_c];
3604
    want.sort();
3605
    assert_eq!(m.heads, want);
3606
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3607
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3608
    assert!(repo.merge("main").is_err());
3609
    // The other bookmark can be pushed by name and appears at origin.
3610
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3611
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3612
    assert!(repo.push("origin", false).unwrap()[0].ok);
3613
    assert_eq!(
3614
        repo.bookmarks()
3615
            .unwrap()
3616
            .iter()
3617
            .find(|b| b.name == "main")
3618
            .unwrap()
3619
            .ahead,
3620
        Some(0)
3621
    );
3622
    // A second workspace inherits the current bookmark and can switch independently.
3623
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3624
    assert_eq!(ws.config.bookmark, "main");
3625
    let mut ws = ws;
3626
    ws.bookmark_switch("feature", false).unwrap();
3627
    assert_eq!(
3628
        Repo::open(&r).unwrap().config.bookmark,
3629
        "main",
3630
        "the first workspace is unaffected"
3631
    );
3632
    assert!(
3633
        repo.bookmark_delete("feature").is_err(),
3634
        "current bookmark of another workspace"
3635
    );
3636
    ws.bookmark_switch("main", false).unwrap();
3637
    // Set and delete.
3638
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3639
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3640
    repo.bookmark_delete("feature").unwrap();
3641
    assert!(repo.resolve_heads("feature").is_err());
3642
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3643
    assert!(
3644
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3645
        "changes of a deleted bookmark remain"
3646
    );
3647
}
3648
3649
#[test]
3650
fn oxygen_subrepos_pin_follow_and_update() {
3651
    hermetic();
3652
    let dir = tempfile::tempdir().unwrap();
3653
    let root = dir.path();
3654
    // A library repository with two commits, and a bare-ish origin for it.
3655
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3656
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3657
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3658
        .unwrap()
3659
        .with_home(root.join("home"));
3660
    write(&root.join("lib"), "lib.txt", b"v1\n");
3661
    let l1 = lib.commit("lib v1", &[]).unwrap();
3662
    assert!(lib.push("origin", false).unwrap()[0].ok);
3663
    let _ = lib_origin;
3664
3665
    // The application (a clone of its own origin) adds it as a subrepo.
3666
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3667
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3668
    let _ = app_origin;
3669
    let app_dir = root.join("app");
3670
    let app = Repo::clone(&app_url, &app_dir)
3671
        .unwrap()
3672
        .with_home(root.join("home"));
3673
    write(&app_dir, "main.txt", b"app\n");
3674
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3675
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3676
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3677
    let snap = app.snapshot("status").unwrap();
3678
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3679
    assert_eq!(
3680
        paths,
3681
        vec![".oxymodules", "libs/lib", "main.txt"],
3682
        "the nested files are not walked"
3683
    );
3684
    let a1 = app.commit("app with lib", &[]).unwrap();
3685
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3686
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3687
    assert!(!files.contains_key("libs/lib/lib.txt"));
3688
    assert!(!app.snapshot("status").unwrap().changed);
3689
    let subs = app.subrepos().unwrap();
3690
    assert_eq!(subs.len(), 1);
3691
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3692
3693
    // Advance the nested repository: the parent sees a modified pin.
3694
    let nested = Repo::open(&app_dir.join("libs/lib"))
3695
        .unwrap()
3696
        .with_home(root.join("home"));
3697
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3698
    let l2 = nested.commit("lib v2", &[]).unwrap();
3699
    assert!(nested.push("origin", false).unwrap()[0].ok);
3700
    let snap = app.snapshot("status").unwrap();
3701
    assert_eq!(
3702
        snap.statuses
3703
            .iter()
3704
            .map(|s| (s.path.as_str(), s.status))
3705
            .collect::<Vec<_>>(),
3706
        vec![("libs/lib", ChangeStatus::Modified)]
3707
    );
3708
    let a2 = app.commit("bump lib", &[]).unwrap();
3709
    // Checking out the older app state brings the nested working copy back
3710
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3711
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3712
    assert!(
3713
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3714
        "{:?}",
3715
        r.notes
3716
    );
3717
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3718
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3719
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3720
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3721
    assert!(!app.snapshot("status").unwrap().changed);
3722
    // A dirty nested repository is left alone and reported.
3723
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3724
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3725
    assert!(
3726
        r.notes.iter().any(|n| n.contains("uncommitted")),
3727
        "{:?}",
3728
        r.notes
3729
    );
3730
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3731
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3732
    let r = app.submodule_update(false, &[]).unwrap();
3733
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3734
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3735
    let _ = l2;
3736
3737
    // A fresh clone of the app has the pin but no nested repository until update --init.
3738
    assert!(app.push("origin", false).unwrap()[0].ok);
3739
    let clone_dir = root.join("app-clone");
3740
    let clone = Repo::clone(&app_url, &clone_dir)
3741
        .unwrap()
3742
        .with_home(root.join("home"));
3743
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3744
    assert_eq!(
3745
        clone.submodule_update(false, &[]).unwrap(),
3746
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3747
    );
3748
    assert_eq!(
3749
        clone.submodule_update(true, &[]).unwrap(),
3750
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3751
    );
3752
    assert_eq!(
3753
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3754
        b"v2\n"
3755
    );
3756
    assert!(!clone.snapshot("status").unwrap().changed);
3757
    // Removing the subrepo leaves the directory and drops the node.
3758
    clone.submodule_remove("libs/lib").unwrap();
3759
    let snap = clone.snapshot("status").unwrap();
3760
    assert!(
3761
        snap.statuses
3762
            .iter()
3763
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3764
        "{:?}",
3765
        snap.statuses
3766
    );
3767
    let c = clone.commit("drop lib", &[]).unwrap();
3768
    assert!(!clone
3769
        .load_state(&[c])
3770
        .unwrap()
3771
        .materialize()
3772
        .files
3773
        .contains_key("libs/lib"));
3774
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3775
    assert!(
3776
        !clone.snapshot("status").unwrap().changed,
3777
        "an unregistered nested repository is ignored"
3778
    );
3779
}
3780
3781
#[test]
3782
fn git_submodules_import_and_export_as_gitlinks() {
3783
    hermetic();
3784
    if std::process::Command::new("git")
3785
        .arg("--version")
3786
        .output()
3787
        .is_err()
3788
    {
3789
        eprintln!("git not installed; skipping");
3790
        return;
3791
    }
3792
    let dir = tempfile::tempdir().unwrap();
3793
    let root = dir.path();
3794
    let git_in = |d: &Path, args: &[&str]| -> String {
3795
        let out = std::process::Command::new("git")
3796
            .arg("-C")
3797
            .arg(d)
3798
            .args([
3799
                "-c",
3800
                "user.name=Grace",
3801
                "-c",
3802
                "[email protected]",
3803
                "-c",
3804
                "commit.gpgsign=false",
3805
                "-c",
3806
                "protocol.file.allow=always",
3807
            ])
3808
            .args(args)
3809
            .output()
3810
            .unwrap();
3811
        assert!(
3812
            out.status.success(),
3813
            "git {args:?}: {}",
3814
            String::from_utf8_lossy(&out.stderr)
3815
        );
3816
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3817
    };
3818
    let sub = root.join("sub");
3819
    fs::create_dir_all(&sub).unwrap();
3820
    git_in(&sub, &["init", "-q", "-b", "main"]);
3821
    write(&sub, "s.txt", b"sub\n");
3822
    git_in(&sub, &["add", "."]);
3823
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3824
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3825
    let g = root.join("main.git");
3826
    fs::create_dir_all(&g).unwrap();
3827
    git_in(&g, &["init", "-q", "-b", "main"]);
3828
    write(&g, "README.md", b"# app\n");
3829
    git_in(&g, &["add", "."]);
3830
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3831
    git_in(
3832
        &g,
3833
        &[
3834
            "submodule",
3835
            "add",
3836
            "-q",
3837
            sub.to_str().unwrap(),
3838
            "vendor/sub",
3839
        ],
3840
    );
3841
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3842
3843
    let dest = root.join("oxy");
3844
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3845
    let rep = repo.import_git(&g, "main").unwrap();
3846
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3847
    let files = repo
3848
        .load_state(&repo.bookmark_heads().unwrap())
3849
        .unwrap()
3850
        .materialize()
3851
        .files;
3852
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3853
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3854
        panic!()
3855
    };
3856
    assert_eq!(
3857
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3858
        crate::subrepo::Pin::Git {
3859
            sha: sub_sha.clone(),
3860
            branch: "HEAD".into()
3861
        }
3862
    );
3863
    let modules =
3864
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3865
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3866
    assert!(modules.entries["vendor/sub"].git);
3867
    assert!(
3868
        files.contains_key(".gitmodules"),
3869
        "the Git file is kept for round trips"
3870
    );
3871
    assert!(
3872
        !dest.join("vendor/sub/.git").exists(),
3873
        "not cloned until update --init"
3874
    );
3875
    assert!(!repo.snapshot("status").unwrap().changed);
3876
    // update --init clones it at the pinned commit; status is unchanged.
3877
    assert_eq!(
3878
        repo.submodule_update(true, &[]).unwrap(),
3879
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3880
    );
3881
    assert_eq!(
3882
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3883
        sub_sha
3884
    );
3885
    assert!(!repo.snapshot("status").unwrap().changed);
3886
    // Export writes the gitlink and .gitmodules back.
3887
    let mirror = root.join("mirror.git");
3888
    let rep = repo.git_export(&mirror).unwrap();
3889
    assert_eq!(rep.skipped_subrepos, 0);
3890
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3891
    assert!(
3892
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3893
        "{ls}"
3894
    );
3895
    assert_eq!(
3896
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3897
        ".gitmodules\nREADME.md\nvendor"
3898
    );
3899
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3900
    assert_eq!(
3901
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3902
        orig_tree,
3903
        "tree round trip"
3904
    );
3905
}
3906
3907
#[test]
3908
fn partial_commits_by_path_and_by_hunk() {
3909
    hermetic();
3910
    let dir = tempfile::tempdir().unwrap();
3911
    let root = dir.path();
3912
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3913
    write(root, "a.txt", b"1\n2\n3\n");
3914
    write(root, "b.txt", b"b\n");
3915
    let h0 = repo.commit("base", &[]).unwrap();
3916
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3917
    write(root, "b.txt", b"b\nbb\n");
3918
    write(root, "c.txt", b"c\n");
3919
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3920
    let h1 = repo
3921
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3922
        .unwrap();
3923
    let c1 = repo.store().get_change(&h1).unwrap();
3924
    assert!(
3925
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3926
        "{:?}",
3927
        c1.tree_ops
3928
    );
3929
    assert_eq!(c1.deps, vec![h0]);
3930
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3931
    assert!(
3932
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3933
    );
3934
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3935
    assert!(!files.contains_key("c.txt"));
3936
    let snap = repo.snapshot("status").unwrap();
3937
    assert_eq!(
3938
        snap.statuses
3939
            .iter()
3940
            .map(|s| (s.path.as_str(), s.status))
3941
            .collect::<Vec<_>>(),
3942
        vec![
3943
            ("b.txt", ChangeStatus::Modified),
3944
            ("c.txt", ChangeStatus::Added)
3945
        ]
3946
    );
3947
    assert_eq!(
3948
        fs::read(root.join("b.txt")).unwrap(),
3949
        b"b\nbb\n",
3950
        "disk untouched"
3951
    );
3952
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3953
    let (_, hunks) = repo.hunks().unwrap();
3954
    let b_hunk = hunks
3955
        .iter()
3956
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3957
        .unwrap()
3958
        .index;
3959
    let h2 = repo
3960
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3961
        .unwrap();
3962
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3963
    assert!(
3964
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3965
    );
3966
    assert!(!files.contains_key("c.txt"));
3967
    let snap = repo.snapshot("status").unwrap();
3968
    assert_eq!(
3969
        snap.statuses
3970
            .iter()
3971
            .map(|s| s.path.as_str())
3972
            .collect::<Vec<_>>(),
3973
        vec!["c.txt"]
3974
    );
3975
    // Choosing only the content hunk of a file in a new directory pulls in
3976
    // the directory and file additions it needs.
3977
    write(root, "d/e.txt", b"e\n");
3978
    let (_, hunks) = repo.hunks().unwrap();
3979
    let e_insert = hunks
3980
        .iter()
3981
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3982
        .unwrap()
3983
        .index;
3984
    let h3 = repo
3985
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3986
        .unwrap();
3987
    let c3 = repo.store().get_change(&h3).unwrap();
3988
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3989
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3990
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3991
    // Choosing a new file's addition hunk brings its content along.
3992
    write(root, "f/g.txt", b"g\n");
3993
    let (_, hunks) = repo.hunks().unwrap();
3994
    let g_add = hunks
3995
        .iter()
3996
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3997
        .unwrap()
3998
        .index;
3999
    let h4 = repo
4000
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4001
        .unwrap();
4002
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4003
    assert!(
4004
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4005
    );
4006
    assert!(!repo
4007
        .snapshot("status")
4008
        .unwrap()
4009
        .statuses
4010
        .iter()
4011
        .any(|s| s.path == "f/g.txt"));
4012
    // Everything left commits normally; the working copy is then clean.
4013
    repo.commit("the rest", &[]).unwrap();
4014
    assert!(!repo.snapshot("status").unwrap().changed);
4015
    let files = repo
4016
        .load_state(&repo.bookmark_heads().unwrap())
4017
        .unwrap()
4018
        .materialize()
4019
        .files;
4020
    assert!(files.contains_key("c.txt"));
4021
}
4022
4023
#[test]
4024
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4025
    hermetic();
4026
    let dir = tempfile::tempdir().unwrap();
4027
    let root = dir.path();
4028
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4029
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4030
        .unwrap();
4031
    write(root, "a.txt", b"one\n");
4032
    let h1 = repo.commit("first", &[]).unwrap();
4033
    write(root, "a.txt", b"one\ntwo\n");
4034
    let h2 = repo.commit("second", &[]).unwrap();
4035
    let b = repo.blame("a.txt").unwrap();
4036
    assert_eq!(
4037
        b.iter()
4038
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4039
            .collect::<Vec<_>>(),
4040
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4041
    );
4042
    assert!(b.iter().all(|l| l.author == "Ada"));
4043
    assert_eq!(
4044
        b[0].change_id,
4045
        repo.store().get_change(&h1).unwrap().change_id
4046
    );
4047
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4048
    repo.commit("rename", &[]).unwrap();
4049
    let b = repo.blame("b.txt").unwrap();
4050
    assert_eq!(
4051
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4052
        vec![h1, h2],
4053
        "the node survives the rename"
4054
    );
4055
    assert!(repo.blame("a.txt").is_err());
4056
}
4057
4058
#[test]
4059
fn bisect_finds_the_first_bad_change() {
4060
    hermetic();
4061
    let dir = tempfile::tempdir().unwrap();
4062
    let root = dir.path();
4063
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4064
    let mut content = String::new();
4065
    let mut hashes = Vec::new();
4066
    for i in 1..=8 {
4067
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4068
        write(root, "f.txt", content.as_bytes());
4069
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4070
    }
4071
    // Each step appends after the previous line, so the chain is linear.
4072
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4073
    repo.bisect_start().unwrap();
4074
    assert!(matches!(
4075
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4076
        BisectStep::NeedMarks { good: 1, bad: 0 }
4077
    ));
4078
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4079
    assert!(
4080
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4081
        "{step:?}"
4082
    );
4083
    // Automated: bad when the bug line is present.
4084
    let step = repo
4085
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4086
        .unwrap();
4087
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4088
    assert_eq!(
4089
        repo.bisect_status().unwrap(),
4090
        Some(BisectStep::Found { culprit: hashes[4] })
4091
    );
4092
    repo.bisect_reset().unwrap();
4093
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4094
    assert!(repo.bisect_status().unwrap().is_none());
4095
    assert!(!repo.snapshot("status").unwrap().changed);
4096
    // Manual marks and a skip.
4097
    repo.bisect_start().unwrap();
4098
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4099
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4100
    let mut skipped_once = false;
4101
    let mut guard = 0;
4102
    while let BisectStep::Testing { .. } = step {
4103
        guard += 1;
4104
        assert!(guard < 20);
4105
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4106
        if !skipped_once && text.contains("line 6") {
4107
            // An untestable state away from the boundary: the search routes around it.
4108
            skipped_once = true;
4109
            step = repo.bisect_mark(None, &[]).unwrap();
4110
            continue;
4111
        }
4112
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4113
    }
4114
    assert!(skipped_once);
4115
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4116
    repo.bisect_reset().unwrap();
4117
    // Skipping the culprit itself leaves it among the candidates reported.
4118
    repo.bisect_start().unwrap();
4119
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4120
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4121
    let mut guard = 0;
4122
    while let BisectStep::Testing { heads, .. } = &step {
4123
        guard += 1;
4124
        assert!(guard < 20);
4125
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4126
        let is_culprit_state =
4127
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4128
        step = if is_culprit_state {
4129
            repo.bisect_mark(None, &[]).unwrap()
4130
        } else {
4131
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4132
        };
4133
    }
4134
    match step {
4135
        BisectStep::Inconclusive { candidates } => assert!(
4136
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4137
            "{candidates:?}"
4138
        ),
4139
        other => panic!("{other:?}"),
4140
    }
4141
    repo.bisect_reset().unwrap();
4142
}
4143
4144
#[test]
4145
fn squash_folds_a_change_into_its_dependency() {
4146
    hermetic();
4147
    let dir = tempfile::tempdir().unwrap();
4148
    let root = dir.path();
4149
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4150
    write(root, "a.txt", b"1\n");
4151
    let a = repo.commit("A", &[]).unwrap();
4152
    write(root, "a.txt", b"1\n2\n");
4153
    let c = repo.commit("C", &[]).unwrap();
4154
    write(root, "a.txt", b"1\n2\n3\n");
4155
    let e = repo.commit("E", &[]).unwrap();
4156
    write(root, "b.txt", b"b\n");
4157
    let b = repo.commit("B", &[]).unwrap();
4158
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4159
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4160
    // E depends on C which A lacks: refused, naming it.
4161
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4162
    assert!(err.contains(&c.short(12)), "{err}");
4163
    // C into A: A' has both, C is gone, E follows and still reads the same.
4164
    let a2 = repo.squash(&c, &a).unwrap();
4165
    let a2c = repo.store().get_change(&a2).unwrap();
4166
    assert_eq!(a2c.change_id, id_a);
4167
    assert!(a2c.deps.is_empty());
4168
    let heads = repo.bookmark_heads().unwrap();
4169
    let st = repo.load_state(&heads).unwrap();
4170
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4171
    let e2 = st
4172
        .changes()
4173
        .find(|(_, m)| m.change_id == id_e)
4174
        .map(|(h, _)| *h)
4175
        .unwrap();
4176
    assert_eq!(
4177
        repo.store().get_change(&e2).unwrap().deps,
4178
        vec![a2],
4179
        "E now depends on A' alone"
4180
    );
4181
    let files = st.materialize().files;
4182
    assert!(
4183
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4184
    );
4185
    assert!(files.contains_key("b.txt"));
4186
    assert!(st.contains(&b));
4187
    assert!(!repo.snapshot("status").unwrap().changed);
4188
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4189
    // Undo restores the three original changes.
4190
    repo.undo().unwrap();
4191
    repo.undo().unwrap();
4192
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4193
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4194
}
4195
4196
#[test]
4197
fn rebase_re_expresses_a_change_against_another_base() {
4198
    hermetic();
4199
    let dir = tempfile::tempdir().unwrap();
4200
    let root = dir.path();
4201
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4202
    write(root, "a.txt", b"1\n2\n");
4203
    let a = repo.commit("A", &[]).unwrap();
4204
    write(root, "a.txt", b"1\n2\n3\n");
4205
    let c = repo.commit("C: append 3", &[]).unwrap();
4206
    write(root, "a.txt", b"1\n2\n3\n4\n");
4207
    let e = repo.commit("E: append 4", &[]).unwrap();
4208
    // A different base: A plus a change that prepends a line.
4209
    repo.checkout(&[a], true, "checkout").unwrap();
4210
    write(root, "a.txt", b"0\n1\n2\n");
4211
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4212
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4213
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4214
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4215
    let c2 = repo.rebase(&c, &[d]).unwrap();
4216
    let c2c = repo.store().get_change(&c2).unwrap();
4217
    assert_eq!(c2c.change_id, id_c);
4218
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4219
    let heads = repo.bookmark_heads().unwrap();
4220
    let st = repo.load_state(&heads).unwrap();
4221
    assert!(!st.contains(&c) && st.contains(&d));
4222
    let e2 = st
4223
        .changes()
4224
        .find(|(_, m)| m.change_id == id_e)
4225
        .map(|(h, _)| *h)
4226
        .unwrap();
4227
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
4228
    assert!(
4229
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4230
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4231
    );
4232
    let files = st.materialize().files;
4233
    assert!(
4234
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4235
        "{:?}",
4236
        files["a.txt"].content
4237
    );
4238
    assert!(!files["a.txt"].is_conflicted());
4239
    // Rebasing onto a state that already contains the change is refused.
4240
    assert!(repo.rebase(&c2, &[c2]).is_err());
4241
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
4242
    assert!(
4243
        err.contains("lacks dependencies"),
4244
        "E needs C, which D's state does not have: {err}"
4245
    );
4246
}
4247
4248
#[test]
4249
fn unsigned_tags_keep_their_message() {
4250
    hermetic();
4251
    let dir = tempfile::tempdir().unwrap();
4252
    let root = dir.path();
4253
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4254
    write(root, "a.txt", b"a\n");
4255
    repo.commit("a", &[]).unwrap();
4256
    assert!(repo.secret_key().unwrap().is_none());
4257
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4258
        .unwrap();
4259
    let tags = repo.tags().unwrap();
4260
    assert_eq!(
4261
        (
4262
            tags[0].name.as_str(),
4263
            tags[0].message.as_str(),
4264
            tags[0].signer.as_deref()
4265
        ),
4266
        ("v1", "first release", None)
4267
    );
4268
    assert!(
4269
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4270
        "an unsigned attestation is not advertised"
4271
    );
4272
}
4273
4274
#[test]
4275
fn fsck_passes_a_sound_repository_and_names_each_fault() {
4276
    // Files on disk are what this tests: tampering with them, and the
4277
    // directory store's crash points.
4278
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4279
        return;
4280
    }
4281
    hermetic();
4282
    let dir = tempfile::tempdir().unwrap();
4283
    let root = dir.path();
4284
    let origin_path = root.join("origin");
4285
    let origin = Repo::init(&origin_path).unwrap();
4286
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4287
        .unwrap()
4288
        .with_home(root.join("home-a"));
4289
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4290
        .unwrap();
4291
    write(&root.join("a"), "f.txt", b"one\n");
4292
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4293
    let h1 = a.commit("first", &[]).unwrap();
4294
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4295
    let h2 = a.commit("second", &[]).unwrap();
4296
    a.tag_create("v1", &[h2], "first release").unwrap();
4297
    a.checkpoint().unwrap();
4298
    assert!(a.push("origin", false).unwrap()[0].ok);
4299
4300
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4301
    for repo in [&a, &origin] {
4302
        let rep = repo.fsck().unwrap();
4303
        assert_eq!(rep.problems, vec![], "{rep:?}");
4304
        // The two commits, plus the working copy's change in `a`.
4305
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4306
        assert!(rep.ops > 1 && rep.objects > 5);
4307
    }
4308
    assert!(origin.fsck().unwrap().attestations >= 1);
4309
4310
    // A flipped byte in a stored object is corruption, named by hash.
4311
    let c1 = a.store().path_for(&h1);
4312
    let pristine = fs::read(&c1).unwrap();
4313
    let mut bytes = pristine.clone();
4314
    *bytes.last_mut().unwrap() ^= 1;
4315
    fs::write(&c1, &bytes).unwrap();
4316
    let rep = a.fsck().unwrap();
4317
    assert!(rep.errors() >= 1);
4318
    assert!(
4319
        rep.problems
4320
            .iter()
4321
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4322
        "{rep:?}"
4323
    );
4324
    fs::write(&c1, &pristine).unwrap();
4325
    assert_eq!(a.fsck().unwrap().errors(), 0);
4326
4327
    // A missing change is named with what needed it.
4328
    fs::remove_file(&c1).unwrap();
4329
    let rep = a.fsck().unwrap();
4330
    assert!(
4331
        rep.problems.iter().any(|p| p.severity == Severity::Error
4332
            && p.object == Some(h1)
4333
            && p.what.contains("change missing, needed by change")),
4334
        "{rep:?}"
4335
    );
4336
    fs::write(&c1, &pristine).unwrap();
4337
4338
    // A missing blob is an error in a full clone.
4339
    let c2 = a.store().get_change(&h1).unwrap();
4340
    let blob = c2
4341
        .edits
4342
        .iter()
4343
        .find_map(|e| match e {
4344
            Edit::Replace { new: Some(b), .. } => Some(*b),
4345
            _ => None,
4346
        })
4347
        .expect("the binary file is a blob");
4348
    let bp = a.store().path_for(&blob);
4349
    let blob_bytes = fs::read(&bp).unwrap();
4350
    fs::remove_file(&bp).unwrap();
4351
    let rep = a.fsck().unwrap();
4352
    assert!(
4353
        rep.problems
4354
            .iter()
4355
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4356
        "{rep:?}"
4357
    );
4358
    fs::write(&bp, &blob_bytes).unwrap();
4359
4360
    // A broken op log head is reported, not a crash.
4361
    let head = root.join("a/.oxy/ops/head");
4362
    let saved = fs::read(&head).unwrap();
4363
    fs::write(&head, b"not a hash").unwrap();
4364
    let rep = a.fsck().unwrap();
4365
    assert!(
4366
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4367
        "{rep:?}"
4368
    );
4369
    fs::write(&head, saved).unwrap();
4370
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4371
}
4372
4373
/// Copy a directory tree (for restoring a pristine repository).
4374
fn copy_tree(from: &Path, to: &Path) {
4375
    fs::create_dir_all(to).unwrap();
4376
    for e in fs::read_dir(from).unwrap() {
4377
        let e = e.unwrap();
4378
        let target = to.join(e.file_name());
4379
        if e.file_type().unwrap().is_dir() {
4380
            copy_tree(&e.path(), &target);
4381
        } else {
4382
            fs::copy(e.path(), &target).unwrap();
4383
        }
4384
    }
4385
}
4386
4387
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4388
/// would, and check that both repositories still open, pass `fsck`, and
4389
/// accept the same operation again.
4390
#[test]
4391
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4392
    // Files on disk are what this tests: tampering with them, and the
4393
    // directory store's crash points.
4394
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4395
        return;
4396
    }
4397
    use crate::durable::failpoint;
4398
    hermetic();
4399
    let dir = tempfile::tempdir().unwrap();
4400
    let pristine = dir.path().join("pristine");
4401
    let origin_path = pristine.join("origin");
4402
    Repo::init(&origin_path).unwrap();
4403
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4404
        .unwrap()
4405
        .with_home(dir.path().join("home"));
4406
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4407
        .unwrap();
4408
    write(&pristine.join("a"), "f.txt", b"one\n");
4409
    a.commit("first", &[]).unwrap();
4410
    assert!(a.push("origin", false).unwrap()[0].ok);
4411
    drop(a);
4412
4413
    type Op = fn(&Repo) -> Result<()>;
4414
    let edit_and_commit: Op = |r| {
4415
        write(r.root(), "f.txt", b"one\ntwo\n");
4416
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4417
        r.commit("second", &[]).map(|_| ())
4418
    };
4419
    let push: Op = |r| {
4420
        let res = r.push("origin", false)?;
4421
        if res.iter().all(|x| x.ok) {
4422
            Ok(())
4423
        } else {
4424
            Err(RepoError::Msg(format!("{res:?}")))
4425
        }
4426
    };
4427
4428
    for (name, prepare, op) in [
4429
        ("commit", None, edit_and_commit),
4430
        ("push", Some(edit_and_commit), push),
4431
    ] {
4432
        let mut steps = 0;
4433
        for n in 1.. {
4434
            let run = dir.path().join(format!("{name}-{n}"));
4435
            copy_tree(&pristine, &run);
4436
            // Clones record their remote by path; point it at this copy.
4437
            let open = |p: &Path| {
4438
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4439
                r.config
4440
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4441
                    .unwrap();
4442
                r.save_config().unwrap();
4443
                r
4444
            };
4445
            let a = open(&run.join("a"));
4446
            if let Some(prep) = prepare {
4447
                prep(&a).unwrap();
4448
            }
4449
            failpoint::crash_after(n);
4450
            let outcome = op(&a);
4451
            let crashed = failpoint::disarm();
4452
            drop(a);
4453
            if !crashed {
4454
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4455
                steps = n - 1;
4456
                break;
4457
            }
4458
            assert!(
4459
                outcome.is_err(),
4460
                "{name}: a crash at step {n} was swallowed"
4461
            );
4462
            for repo in ["a", "origin"] {
4463
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4464
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4465
                });
4466
                let rep = r.fsck().unwrap();
4467
                assert_eq!(
4468
                    rep.errors(),
4469
                    0,
4470
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4471
                    rep.problems
4472
                );
4473
            }
4474
            // The interrupted operation can simply be run again.
4475
            let a = open(&run.join("a"));
4476
            // A crash after the commit point leaves the commit done.
4477
            let landed = a
4478
                .bookmark_heads()
4479
                .unwrap()
4480
                .iter()
4481
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4482
            let again = match (name, landed) {
4483
                ("commit", true) => Ok(()),
4484
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4485
                _ => op(&a),
4486
            };
4487
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4488
            assert_eq!(a.fsck().unwrap().errors(), 0);
4489
            fs::remove_dir_all(&run).unwrap();
4490
        }
4491
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4492
    }
4493
}
4494
4495
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4496
/// running at the same time lose nothing: every commit ends up on the
4497
/// bookmark, locally and on the remote, and the repository passes fsck.
4498
#[test]
4499
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4500
    hermetic();
4501
    let dir = tempfile::tempdir().unwrap();
4502
    let root = dir.path();
4503
    let origin = root.join("origin");
4504
    Repo::init_bare_unbound(&origin).unwrap();
4505
    let main = root.join("main");
4506
    let mut repo = Repo::init(&main).unwrap();
4507
    repo.config
4508
        .set("remote.origin.url", &origin.to_string_lossy())
4509
        .unwrap();
4510
    repo.save_config().unwrap();
4511
    write(&main, "seed.txt", b"seed\n");
4512
    repo.commit("seed", &[]).unwrap();
4513
    let second = root.join("second");
4514
    repo.workspace_add(&second, None).unwrap();
4515
    drop(repo);
4516
4517
    const EACH: usize = 15;
4518
    std::thread::scope(|s| {
4519
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4520
            s.spawn(move || {
4521
                let r = Repo::open(&dir).unwrap();
4522
                for i in 0..EACH {
4523
                    write(
4524
                        &dir,
4525
                        &format!("{tag}-{i}.txt"),
4526
                        format!("{tag} {i}\n").as_bytes(),
4527
                    );
4528
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4529
                    if push && i % 5 == 4 {
4530
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4531
                        let _ = r.push("origin", false);
4532
                    }
4533
                }
4534
            });
4535
        }
4536
    });
4537
4538
    let repo = Repo::open(&main).unwrap();
4539
    let heads = repo.bookmark_heads().unwrap();
4540
    let state = repo.load_state(&heads).unwrap();
4541
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4542
    for tag in ["a", "b"] {
4543
        for i in 0..EACH {
4544
            assert!(
4545
                messages.contains(&format!("{tag} {i}")),
4546
                "lost commit {tag} {i}; have {messages:?}"
4547
            );
4548
        }
4549
    }
4550
    let rep = repo.fsck().unwrap();
4551
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4552
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4553
    let hosted = Repo::open(&origin).unwrap();
4554
    let hosted_heads = hosted.bookmark_heads().unwrap();
4555
    assert_eq!(
4556
        hosted.load_state(&hosted_heads).unwrap().len(),
4557
        state.len(),
4558
        "the remote has every commit"
4559
    );
4560
}
4561
4562
/// Two operations recorded from the same parent (what two processes do
4563
/// when they race) are merged: both bookmarks' heads survive, and a
4564
/// change made on one side only is kept.
4565
#[test]
4566
fn operations_from_the_same_parent_are_merged() {
4567
    hermetic();
4568
    let dir = tempfile::tempdir().unwrap();
4569
    let root = dir.path();
4570
    let repo = Repo::init(root).unwrap();
4571
    write(root, "a.txt", b"a\n");
4572
    let a = repo.commit("a", &[]).unwrap();
4573
    write(root, "b.txt", b"b\n");
4574
    let b = repo.commit("b", &[]).unwrap();
4575
    let (x, op) = repo.head_op().unwrap();
4576
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4577
4578
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4579
    let mut one = op.view.clone();
4580
    one.bookmarks.insert("main".into(), state(vec![a]));
4581
    one.bookmarks.insert("topic".into(), state(vec![a]));
4582
    let mut two = op.view.clone();
4583
    two.bookmarks.insert("main".into(), state(vec![b]));
4584
    repo.record_op(&[x], "one", one).unwrap();
4585
    let merged = repo.record_op(&[x], "two", two).unwrap();
4586
4587
    let (head, op) = repo.head_op().unwrap();
4588
    assert_eq!(head, merged);
4589
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4590
    assert!(op.command.contains("merged with a concurrent operation"));
4591
    let mut main = repo
4592
        .store()
4593
        .get_state(&op.view.bookmarks["main"])
4594
        .unwrap()
4595
        .heads;
4596
    main.sort();
4597
    let mut want = vec![a, b];
4598
    want.sort();
4599
    assert_eq!(main, want, "both sides' heads are kept");
4600
    assert!(
4601
        op.view.bookmarks.contains_key("topic"),
4602
        "a one-sided change survives"
4603
    );
4604
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4605
}
4606
4607
#[test]
4608
fn failed_requests_come_with_a_next_step() {
4609
    use crate::protocol::hint_for;
4610
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4611
        .unwrap()
4612
        .contains("token"));
4613
    assert!(hint_for("…: HTTP 403: forbidden")
4614
        .unwrap()
4615
        .contains("repo:write"));
4616
    assert!(hint_for("…: HTTP 404: no such repository")
4617
        .unwrap()
4618
        .contains("owner and repository name"));
4619
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4620
        .unwrap()
4621
        .contains("oxyhub-ca.pem"));
4622
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4623
        .unwrap()
4624
        .contains("running"));
4625
    assert!(hint_for("Dns Failed: failed to lookup address information")
4626
        .unwrap()
4627
        .contains("resolve"));
4628
    assert_eq!(hint_for("something else entirely"), None);
4629
}
4630
4631
#[test]
4632
fn doctor_names_problems_and_what_to_do() {
4633
    hermetic();
4634
    let dir = tempfile::tempdir().unwrap();
4635
    let root = dir.path();
4636
    let origin = root.join("origin");
4637
    Repo::init_bare_unbound(&origin).unwrap();
4638
    let mut repo = Repo::init(&root.join("r"))
4639
        .unwrap()
4640
        .with_home(root.join("home"));
4641
    let find = |r: &DoctorReport, area: &str, h: Health| {
4642
        r.checks
4643
            .iter()
4644
            .find(|c| c.area == area && c.health == h)
4645
            .cloned()
4646
    };
4647
4648
    let r = repo.doctor(true);
4649
    assert!(find(&r, "identity", Health::Warn)
4650
        .unwrap()
4651
        .hint
4652
        .unwrap()
4653
        .contains("oxy identity create"));
4654
    assert!(find(&r, "repository", Health::Ok).is_some());
4655
4656
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4657
        .unwrap();
4658
    repo.config.set("author.name", "Ada").unwrap();
4659
    repo.config.set("author.email", "[email protected]").unwrap();
4660
    repo.config
4661
        .set("remote.origin.url", &origin.to_string_lossy())
4662
        .unwrap();
4663
    repo.config
4664
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4665
        .unwrap();
4666
    repo.config.set("remote.down.token", "t").unwrap();
4667
    repo.config
4668
        .set("remote.badca.url", "https://example.invalid/a/b")
4669
        .unwrap();
4670
    repo.config
4671
        .set(
4672
            "remote.badca.ca",
4673
            &root.join("missing.pem").to_string_lossy(),
4674
        )
4675
        .unwrap();
4676
    repo.save_config().unwrap();
4677
4678
    let r = repo.doctor(true);
4679
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4680
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4681
    assert!(find(&r, "remote origin", Health::Ok)
4682
        .unwrap()
4683
        .message
4684
        .contains("first push binds it"));
4685
    let down = find(&r, "remote down", Health::Fail).unwrap();
4686
    assert!(
4687
        down.hint.as_deref().unwrap_or("").contains("running"),
4688
        "{down:?}"
4689
    );
4690
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4691
    assert!(
4692
        badca.hint.unwrap().contains("remote.badca.ca"),
4693
        "the remote's own name is in the hint"
4694
    );
4695
    assert_eq!(r.worst(), Health::Fail);
4696
4697
    // Offline, nothing is contacted.
4698
    let r = repo.doctor(false);
4699
    assert!(find(&r, "remote down", Health::Fail).is_none());
4700
    assert!(find(&r, "remote down", Health::Ok)
4701
        .unwrap()
4702
        .message
4703
        .contains("not contacted"));
4704
}
4705
4706
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4707
/// after it. Inserting after `b` and then deleting `b`, one commit after
4708
/// the other, must not leave a delete/insert conflict.
4709
#[test]
4710
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4711
    hermetic();
4712
    let dir = tempfile::tempdir().unwrap();
4713
    let root = dir.path();
4714
    let repo = Repo::init(root).unwrap();
4715
    write(root, "f", b"a\nb\nc\n");
4716
    repo.commit("base", &[]).unwrap();
4717
    write(root, "f", b"a\nb\nx\nc\n");
4718
    let insert = repo.commit("insert x after b", &[]).unwrap();
4719
    write(root, "f", b"a\nx\nc\n");
4720
    let delete = repo.commit("delete b", &[]).unwrap();
4721
    assert!(
4722
        repo.store()
4723
            .get_change(&delete)
4724
            .unwrap()
4725
            .deps
4726
            .contains(&insert),
4727
        "the deletion depends on the insertion below the deleted line"
4728
    );
4729
    let heads = repo.bookmark_heads().unwrap();
4730
    assert_eq!(heads, vec![delete]);
4731
    let snap = repo.load_state(&heads).unwrap().materialize();
4732
    assert!(!snap.is_conflicted());
4733
    assert!(
4734
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4735
    );
4736
}
4737
4738
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4739
/// replacement depends on the change that set the blob it replaces.
4740
#[test]
4741
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4742
    hermetic();
4743
    let dir = tempfile::tempdir().unwrap();
4744
    let root = dir.path();
4745
    let repo = Repo::init(root).unwrap();
4746
    write(root, "bin", b"\0A");
4747
    let v1 = repo.commit("v1", &[]).unwrap();
4748
    write(root, "bin", b"\0B");
4749
    let v2 = repo.commit("v2", &[]).unwrap();
4750
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4751
    write(root, "bin", b"\0A");
4752
    let v3 = repo.commit("back to A", &[]).unwrap();
4753
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4754
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4755
    let state = repo.load_state(&[v3]).unwrap();
4756
    let snap = state.materialize();
4757
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4758
        panic!("opaque")
4759
    };
4760
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4761
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4762
}
4763
4764
/// Spec §23: a binary file changed on two branches and merged in Git to
4765
/// one side's version comes back as that version at the merge, and the
4766
/// import verifies commit by commit.
4767
#[test]
4768
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4769
    hermetic();
4770
    if std::process::Command::new("git")
4771
        .arg("--version")
4772
        .output()
4773
        .is_err()
4774
    {
4775
        eprintln!("git not installed; skipping");
4776
        return;
4777
    }
4778
    let dir = tempfile::tempdir().unwrap();
4779
    let root = dir.path();
4780
    let g = root.join("src.git");
4781
    fs::create_dir_all(&g).unwrap();
4782
    let git = |args: &[&str]| -> String {
4783
        let out = std::process::Command::new("git")
4784
            .arg("-C")
4785
            .arg(&g)
4786
            .args([
4787
                "-c",
4788
                "user.name=Grace",
4789
                "-c",
4790
                "[email protected]",
4791
                "-c",
4792
                "commit.gpgsign=false",
4793
            ])
4794
            .args(args)
4795
            .output()
4796
            .unwrap();
4797
        assert!(
4798
            out.status.success(),
4799
            "git {args:?}: {}",
4800
            String::from_utf8_lossy(&out.stderr)
4801
        );
4802
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4803
    };
4804
    git(&["init", "-q", "-b", "main"]);
4805
    write(&g, "logo.bin", b"\0base");
4806
    write(&g, "notes.txt", b"a\nb\nc\n");
4807
    git(&["add", "."]);
4808
    git(&["commit", "-qm", "base"]);
4809
    git(&["checkout", "-qb", "side"]);
4810
    write(&g, "logo.bin", b"\0side");
4811
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4812
    git(&["commit", "-qam", "side"]);
4813
    git(&["checkout", "-q", "main"]);
4814
    write(&g, "logo.bin", b"\0main");
4815
    git(&["commit", "-qam", "main"]);
4816
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4817
    let _ = std::process::Command::new("git")
4818
        .arg("-C")
4819
        .arg(&g)
4820
        .args([
4821
            "-c",
4822
            "user.name=G",
4823
            "-c",
4824
            "user.email=g@e",
4825
            "merge",
4826
            "-q",
4827
            "side",
4828
        ])
4829
        .output();
4830
    write(&g, "logo.bin", b"\0main");
4831
    git(&["add", "."]);
4832
    git(&["commit", "-qm", "merge side"]);
4833
    // Then a revert of the binary to its first version.
4834
    write(&g, "logo.bin", b"\0base");
4835
    git(&["commit", "-qam", "back to base"]);
4836
4837
    let repo = Repo::init(&root.join("o")).unwrap();
4838
    let rep = repo.import_git(&g, "main").unwrap();
4839
    assert_eq!(rep.merges, 1);
4840
    let v = repo.verify_git_import(&g, "main").unwrap();
4841
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4842
    assert_eq!(v.commits, 5);
4843
    let snap = repo
4844
        .load_state(&repo.bookmark_heads().unwrap())
4845
        .unwrap()
4846
        .materialize();
4847
    assert!(!snap.is_conflicted());
4848
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4849
        panic!("opaque")
4850
    };
4851
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4852
}
4853
4854
/// Spec §7.7 on a file system without executable bits or symlinks: the
4855
/// recorded bit is kept, and a symlink checked out as a plain file holding
4856
/// its target is still that symlink.
4857
#[cfg(unix)]
4858
#[test]
4859
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4860
    use crate::portable::Platform;
4861
    use std::os::unix::fs::PermissionsExt;
4862
    hermetic();
4863
    let dir = tempfile::tempdir().unwrap();
4864
    let root = dir.path();
4865
    let repo = Repo::init(root).unwrap();
4866
    write(root, "run.sh", b"#!/bin/sh\n");
4867
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4868
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4869
    repo.commit("script and link", &[]).unwrap();
4870
    drop(repo);
4871
4872
    // What checking out on Windows leaves: no exec bit, the link as a file.
4873
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4874
    fs::remove_file(root.join("link")).unwrap();
4875
    write(root, "link", b"run.sh");
4876
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4877
    let s = win.snapshot("oxy status").unwrap();
4878
    assert!(
4879
        s.statuses.is_empty(),
4880
        "nothing changed on Windows: {:?}",
4881
        statuses(&s)
4882
    );
4883
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4884
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4885
    write(root, "link", b"other");
4886
    let h = win.commit("edit on Windows", &[]).unwrap();
4887
    let snap = win.load_state(&[h]).unwrap().materialize();
4888
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4889
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4890
    // The same working copy read as Linux sees the lost bit and the plain file.
4891
    let linux = Repo::open(root).unwrap();
4892
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4893
}
4894
4895
/// Paths that collide on case-insensitive or Windows file systems are
4896
/// named at checkout there, and by doctor everywhere.
4897
#[test]
4898
fn paths_other_platforms_cannot_hold_are_reported() {
4899
    use crate::portable::Platform;
4900
    hermetic();
4901
    let dir = tempfile::tempdir().unwrap();
4902
    let root = dir.path();
4903
    let repo = Repo::init(root).unwrap();
4904
    write(root, "README.md", b"a\n");
4905
    write(root, "readme.md", b"b\n");
4906
    write(root, "src/aux.c", b"int x;\n");
4907
    let h = repo.commit("unportable", &[]).unwrap();
4908
    let r = repo.doctor(false);
4909
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4910
    assert_eq!(port.health, Health::Warn);
4911
    assert!(
4912
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4913
        "{}",
4914
        port.message
4915
    );
4916
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4917
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4918
    assert!(
4919
        rep.notes
4920
            .iter()
4921
            .any(|n| n.contains("README.md and readme.md")),
4922
        "{:?}",
4923
        rep.notes
4924
    );
4925
    assert!(
4926
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4927
        "macOS allows aux.c"
4928
    );
4929
}
4930
4931
#[test]
4932
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4933
    hermetic();
4934
    let dir = tempfile::tempdir().unwrap();
4935
    let repo = Repo::init(dir.path()).unwrap();
4936
    write(dir.path(), "a.txt", b"one\n");
4937
    write(dir.path(), "other.txt", b"x\n");
4938
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4939
    repo.snapshot("t").unwrap();
4940
    let c1 = repo.commit("first", &[]).unwrap();
4941
    write(dir.path(), "other.txt", b"y\n");
4942
    repo.snapshot("t").unwrap();
4943
    repo.commit("other only", &[]).unwrap();
4944
    write(dir.path(), "a.txt", b"one\ntwo\n");
4945
    repo.snapshot("t").unwrap();
4946
    let c3 = repo.commit("second line", &[]).unwrap();
4947
    write(dir.path(), "other.txt", b"z\n");
4948
    repo.snapshot("t").unwrap();
4949
    repo.commit("other again", &[]).unwrap();
4950
4951
    let heads = repo.bookmark_heads().unwrap();
4952
    let state = repo.load_state(&heads).unwrap();
4953
    let full: Vec<ChangeHash> = repo
4954
        .log_for_path_in("a.txt", &heads)
4955
        .unwrap()
4956
        .iter()
4957
        .map(|e| e.hash)
4958
        .collect();
4959
    assert_eq!(
4960
        full,
4961
        vec![c3, c1],
4962
        "newest first, only changes touching the path"
4963
    );
4964
    let newest: Vec<ChangeHash> = repo
4965
        .log_for_path_of(&state, "a.txt", Some(1))
4966
        .unwrap()
4967
        .iter()
4968
        .map(|e| e.hash)
4969
        .collect();
4970
    assert_eq!(newest, vec![c3], "stops at the first");
4971
    assert_eq!(
4972
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4973
        2
4974
    );
4975
    assert!(repo
4976
        .log_for_path_of(&state, "missing.txt", Some(1))
4977
        .is_err());
4978
    assert_eq!(
4979
        repo.log_state(&heads).unwrap().len(),
4980
        repo.log_of(&state).len()
4981
    );
4982
4983
    let tree = state.tree().view();
4984
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4985
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4986
    assert_eq!(
4987
        via_state
4988
            .iter()
4989
            .map(|l| (l.hash, l.text.clone()))
4990
            .collect::<Vec<_>>(),
4991
        via_heads
4992
            .iter()
4993
            .map(|l| (l.hash, l.text.clone()))
4994
            .collect::<Vec<_>>()
4995
    );
4996
    assert_eq!(
4997
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4998
        vec![c1, c3]
4999
    );
5000
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5001
}
5002
5003
/// A text file whose stat matches the manifest and whose recorded hash is
5004
/// the base's content is taken from the base without reading it; anything
5005
/// else is read, so no edit is missed (spec §12.3).
5006
#[cfg(unix)]
5007
#[test]
5008
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5009
    use std::os::unix::fs::PermissionsExt;
5010
    hermetic();
5011
    let dir = tempfile::tempdir().unwrap();
5012
    let root = dir.path();
5013
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5014
    write(root, "a.txt", b"one\ntwo\n");
5015
    write(root, "b.txt", b"bee\n");
5016
    repo.commit("base", &[]).unwrap();
5017
    let age = |p: &str| {
5018
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5019
        fs::File::options()
5020
            .write(true)
5021
            .open(root.join(p))
5022
            .unwrap()
5023
            .set_modified(old)
5024
            .unwrap();
5025
    };
5026
    age("a.txt");
5027
    age("b.txt");
5028
    assert!(
5029
        !repo.snapshot("status").unwrap().changed,
5030
        "records the aged stat"
5031
    );
5032
5033
    // Clean and equal to the base: not read at all.
5034
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5035
    let snap = repo.snapshot("status").unwrap();
5036
    assert!(
5037
        !snap.changed && snap.statuses.is_empty(),
5038
        "{:?}",
5039
        snap.statuses
5040
    );
5041
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5042
5043
    // An uncommitted edit that is older than the manifest: stat-clean, but
5044
    // its hash is not the base's, so it is read and stays visible.
5045
    write(root, "b.txt", b"bee edited\n");
5046
    age("b.txt");
5047
    let first = repo.snapshot("status").unwrap();
5048
    assert_eq!(
5049
        statuses(&first),
5050
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5051
    );
5052
    let again = repo.snapshot("status").unwrap();
5053
    assert_eq!(
5054
        statuses(&again),
5055
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5056
        "still seen once stat-clean"
5057
    );
5058
    assert!(!again.changed, "and the working copy hashes the same");
5059
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5060
    assert!(
5061
        repo.snapshot("status").is_err(),
5062
        "an edited file must be read, never taken from the base"
5063
    );
5064
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5065
5066
    // A same-size edit made just now is racy and read.
5067
    write(root, "a.txt", b"one\nTWO\n");
5068
    assert_eq!(
5069
        statuses(&repo.snapshot("status").unwrap()),
5070
        vec![
5071
            ("a.txt".to_string(), ChangeStatus::Modified),
5072
            ("b.txt".to_string(), ChangeStatus::Modified)
5073
        ]
5074
    );
5075
    // Committing makes the edits the base: both are clean and served from it again.
5076
    repo.commit("edits", &[]).unwrap();
5077
    age("a.txt");
5078
    age("b.txt");
5079
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5080
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5081
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5082
    let snap = repo.snapshot("status").unwrap();
5083
    assert!(!snap.changed && snap.statuses.is_empty());
5084
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5085
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5086
}
5087
5088
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5089
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5090
/// file is unchanged, and loading through the checkpoint equals a full load.
5091
#[test]
5092
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5093
    hermetic();
5094
    let dir = tempfile::tempdir().unwrap();
5095
    let root = dir.path();
5096
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5097
    let long: String = (0..300)
5098
        .map(|i| format!("line {i} of a long file\n"))
5099
        .collect();
5100
    write(root, "long.txt", long.as_bytes());
5101
    write(root, "short.txt", b"short\n");
5102
    repo.commit("base", &[]).unwrap();
5103
    let (r1, _, _) = repo.checkpoint().unwrap();
5104
    let cp1 = crate::objects::Checkpoint::decode(
5105
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5106
    )
5107
    .unwrap();
5108
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5109
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5110
5111
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5112
    repo.gc(true).unwrap();
5113
    assert!(repo.store().has(&graphs1[0]));
5114
    let report = repo.fsck().unwrap();
5115
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5116
5117
    // Loading through the checkpoint equals a full load.
5118
    write(root, "short.txt", b"short, edited\n");
5119
    repo.commit("edit the short file", &[]).unwrap();
5120
    let heads = repo.bookmark_heads().unwrap();
5121
    let fast = repo.load_state(&heads).unwrap();
5122
    let full = repo.load_state_full(&heads).unwrap();
5123
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5124
5125
    // The next checkpoint shares the unchanged long file's graph.
5126
    let (r2, _, _) = repo.checkpoint().unwrap();
5127
    let cp2 = crate::objects::Checkpoint::decode(
5128
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5129
    )
5130
    .unwrap();
5131
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5132
5133
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5134
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5135
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5136
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5137
5138
    // A version 1 checkpoint written by an older oxy still loads.
5139
    let state = repo.load_state_full(&heads).unwrap();
5140
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5141
    let cp_old = crate::objects::Checkpoint {
5142
        heads: cp2.heads.clone(),
5143
        count: cp2.count,
5144
        payload: old,
5145
    };
5146
    let r_old = repo
5147
        .store()
5148
        .put(ObjectType::Checkpoint, &cp_old.encode())
5149
        .unwrap();
5150
    repo.install_checkpoint("main", &r_old).unwrap();
5151
    assert_eq!(
5152
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5153
        full.checkpoint_payload()
5154
    );
5155
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5156
5157
    // A lost graph blob fails the load loudly rather than dropping the
5158
    // file, and fsck reports it (a fresh repository, objects still loose).
5159
    let dir2 = tempfile::tempdir().unwrap();
5160
    let root2 = dir2.path();
5161
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5162
    write(root2, "long.txt", long.as_bytes());
5163
    repo2.commit("base", &[]).unwrap();
5164
    let (r, _, _) = repo2.checkpoint().unwrap();
5165
    let cp = crate::objects::Checkpoint::decode(
5166
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5167
    )
5168
    .unwrap();
5169
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5170
    repo2.store().remove_loose_for_test(&graph).unwrap();
5171
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5172
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5173
}
5174
5175
/// A new repository has not stored the user's identity yet (that happens
5176
/// at the first signed change); looking it up falls back to the key
5177
/// directory, and a file there that does not hash to the key is refused.
5178
#[test]
5179
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5180
    hermetic();
5181
    let dir = tempfile::tempdir().unwrap();
5182
    let home = dir.path().join("home");
5183
    let mut first = Repo::init(&dir.path().join("a"))
5184
        .unwrap()
5185
        .with_home(home.clone());
5186
    let (key, _) = first
5187
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5188
        .unwrap();
5189
    let fresh = Repo::init(&dir.path().join("b"))
5190
        .unwrap()
5191
        .with_home(home.clone());
5192
    assert!(!fresh.store().has(&key), "nothing stored yet");
5193
    let id = fresh.identity(&key).unwrap();
5194
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5195
    // A key file that is not this identity is an error, not a wrong answer.
5196
    let keys = fresh.keys_dir.clone();
5197
    let (other, _) = first
5198
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5199
        .unwrap();
5200
    fs::copy(
5201
        keys.join(format!("{}.identity", other.to_hex())),
5202
        keys.join(format!("{}.identity", key.to_hex())),
5203
    )
5204
    .unwrap();
5205
    assert!(fresh
5206
        .identity(&key)
5207
        .unwrap_err()
5208
        .to_string()
5209
        .contains("does not hold identity"));
5210
}
5211
5212
/// Status snapshots (spec §12.3): a text file whose stat matches the
5213
/// manifest, and whose base graph key is the one the manifest recorded it
5214
/// equal to, is neither read nor rendered; any edit, and any change to the
5215
/// file's graph in the base, brings it back.
5216
#[cfg(unix)]
5217
#[test]
5218
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5219
    use std::os::unix::fs::PermissionsExt;
5220
    hermetic();
5221
    let dir = tempfile::tempdir().unwrap();
5222
    let root = dir.path();
5223
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5224
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5225
        write(root, p, c.as_bytes());
5226
    }
5227
    repo.commit("base", &[]).unwrap();
5228
    let age = |p: &str| {
5229
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5230
        fs::File::options()
5231
            .write(true)
5232
            .open(root.join(p))
5233
            .unwrap()
5234
            .set_modified(old)
5235
            .unwrap();
5236
    };
5237
    let lock = |p: &str, mode: u32| {
5238
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5239
    };
5240
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5241
        age(p);
5242
    }
5243
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5244
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5245
    assert!(
5246
        m.entries.values().all(|e| e.graph.is_some()),
5247
        "keys recorded"
5248
    );
5249
5250
    // Unreadable files prove they are not read; the status snapshot does
5251
    // not render them either, and its base lacks their graphs.
5252
    lock("a.txt", 0o000);
5253
    lock("b.txt", 0o000);
5254
    let snap = repo.snapshot_status("status").unwrap();
5255
    assert!(!snap.changed && snap.statuses.is_empty());
5256
    assert_eq!(
5257
        snap.base_snapshot
5258
            .unrendered
5259
            .iter()
5260
            .cloned()
5261
            .collect::<Vec<_>>(),
5262
        vec!["a.txt", "b.txt", "d/c.txt"]
5263
    );
5264
    assert!(!snap.base.is_full());
5265
    assert!(!snap.base_snapshot.is_conflicted());
5266
    // A full snapshot does not read them either, but renders everything.
5267
    let full = repo.snapshot("status").unwrap();
5268
    assert!(full.statuses.is_empty() && full.base.is_full());
5269
    assert!(full.base_snapshot.unrendered.is_empty());
5270
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5271
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5272
5273
    // An edit is seen; the file is rendered, the others still are not.
5274
    write(root, "d/c.txt", b"sea edited\n");
5275
    let snap = repo.snapshot_status("status").unwrap();
5276
    assert_eq!(
5277
        statuses(&snap),
5278
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5279
    );
5280
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5281
    // So is a mode change of an unread file.
5282
    lock("b.txt", 0o100);
5283
    assert_eq!(
5284
        statuses(&repo.snapshot_status("status").unwrap()),
5285
        vec![
5286
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5287
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5288
        ]
5289
    );
5290
    lock("b.txt", 0o000);
5291
5292
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5293
    // stays unread, c.txt is read once and then skipped too.
5294
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5295
        .unwrap();
5296
    age("d/c.txt");
5297
    let snap = repo.snapshot_status("status").unwrap();
5298
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5299
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5300
    lock("d/c.txt", 0o000);
5301
    let snap = repo.snapshot_status("status").unwrap();
5302
    assert!(snap.statuses.is_empty());
5303
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5304
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5305
        lock(p, 0o644);
5306
    }
5307
}
5308
5309
/// Attributes decide how a file compares with the base, so a changed
5310
/// `.oxyattributes` makes every text file be compared again.
5311
#[cfg(unix)]
5312
#[test]
5313
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5314
    hermetic();
5315
    let dir = tempfile::tempdir().unwrap();
5316
    let root = dir.path();
5317
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5318
    write(root, "a.txt", b"crlf\r\n");
5319
    repo.commit("base", &[]).unwrap();
5320
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5321
    fs::File::options()
5322
        .write(true)
5323
        .open(root.join("a.txt"))
5324
        .unwrap()
5325
        .set_modified(old)
5326
        .unwrap();
5327
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5328
    assert!(repo
5329
        .snapshot_status("status")
5330
        .unwrap()
5331
        .base_snapshot
5332
        .unrendered
5333
        .contains("a.txt"));
5334
    // With eol=lf, a.txt as stored no longer equals the base.
5335
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5336
    let snap = repo.snapshot_status("status").unwrap();
5337
    assert_eq!(
5338
        statuses(&snap),
5339
        vec![
5340
            (".oxyattributes".to_string(), ChangeStatus::Added),
5341
            ("a.txt".to_string(), ChangeStatus::Modified)
5342
        ]
5343
    );
5344
}
5345
5346
/// Bookmarks with `/` in their names: pushing records their
5347
/// attestations, and checkpoints are kept for them, beside `feature`
5348
/// itself.
5349
#[test]
5350
fn bookmarks_with_slashes_push_and_checkpoint() {
5351
    hermetic();
5352
    let dir = tempfile::tempdir().unwrap();
5353
    let root = dir.path();
5354
    let origin = Repo::init(&root.join("origin")).unwrap();
5355
    let url = root.join("origin").to_string_lossy().to_string();
5356
    let mut repo = Repo::clone(&url, &root.join("r"))
5357
        .unwrap()
5358
        .with_home(root.join("home"));
5359
    // With an identity, pushes carry reference attestations: the case
5360
    // that failed, since the attestation is a file named after the bookmark.
5361
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5362
        .unwrap();
5363
    let r = root.join("r");
5364
    write(&r, "a.txt", b"a\n");
5365
    let h_a = repo.commit("a", &[]).unwrap();
5366
    assert!(repo.push("origin", false).unwrap()[0].ok);
5367
    repo.bookmark_create("feature", None).unwrap();
5368
    repo.bookmark_create("feature/x", None).unwrap();
5369
    repo.bookmark_switch("feature/x", false).unwrap();
5370
    write(&r, "b.txt", b"b\n");
5371
    let h_b = repo.commit("b", &[]).unwrap();
5372
    for name in ["feature", "feature/x"] {
5373
        let res = repo.push_bookmark("origin", name, false).unwrap();
5374
        assert!(res[0].ok, "{name}: {res:?}");
5375
    }
5376
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5377
    assert_eq!(
5378
        origin.resolve_heads("feature/x").unwrap(),
5379
        repo.resolve_heads("feature/x").unwrap()
5380
    );
5381
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5382
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5383
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5384
5385
    // A checkpoint of feature/x is found again when loading its state.
5386
    let (cp, _, _) = repo.checkpoint().unwrap();
5387
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5388
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5389
    let heads = repo.resolve_heads("feature/x").unwrap();
5390
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5391
}
5392
5393
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5394
/// never the remote's own bookmark, and a bookmark created again later is
5395
/// accepted although the deletion's attestation stays the latest.
5396
#[test]
5397
fn bookmarks_are_deleted_on_a_remote() {
5398
    hermetic();
5399
    let dir = tempfile::tempdir().unwrap();
5400
    let root = dir.path();
5401
    let origin = Repo::init(&root.join("origin")).unwrap();
5402
    let url = root.join("origin").to_string_lossy().to_string();
5403
    let mut repo = Repo::clone(&url, &root.join("r"))
5404
        .unwrap()
5405
        .with_home(root.join("home"));
5406
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5407
        .unwrap();
5408
    let r = root.join("r");
5409
    write(&r, "a.txt", b"a\n");
5410
    repo.commit("a", &[]).unwrap();
5411
    assert!(repo.push("origin", false).unwrap()[0].ok);
5412
    repo.bookmark_create("feature/x", None).unwrap();
5413
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5414
    assert!(origin.resolve_heads("feature/x").is_ok());
5415
5416
    let res = repo.push_delete("origin", "feature/x").unwrap();
5417
    assert!(res[0].ok, "{res:?}");
5418
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5419
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5420
    assert!(
5421
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5422
        "the deletion is attested"
5423
    );
5424
    assert!(
5425
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5426
        "the local bookmark stays"
5427
    );
5428
    assert!(!repo
5429
        .view()
5430
        .unwrap()
5431
        .remotes
5432
        .get("origin")
5433
        .is_some_and(|m| m.contains_key("feature/x")));
5434
5435
    // Pushing it again creates it again, past the deletion's serial.
5436
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5437
    assert!(res[0].ok, "{res:?}");
5438
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5439
5440
    // Nothing to delete, and never the remote's own bookmark.
5441
    assert!(repo.push_delete("origin", "nope").is_err());
5442
    let res = repo.push_delete("origin", "main").unwrap();
5443
    assert!(
5444
        !res[0].ok && res[0].reason.contains("default bookmark"),
5445
        "{res:?}"
5446
    );
5447
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5448
}
5449
5450
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5451
/// when the target has the same versions of the files it touches, and is
5452
/// refused, untouched, when it has others.
5453
#[test]
5454
fn switching_bookmarks_carries_uncommitted_work() {
5455
    hermetic();
5456
    let dir = tempfile::tempdir().unwrap();
5457
    let root = dir.path();
5458
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5459
    write(root, "a.txt", b"a\n");
5460
    write(root, "b.txt", b"b\n");
5461
    write(root, "gone.txt", b"gone\n");
5462
    repo.commit("base", &[]).unwrap();
5463
    repo.bookmark_create("feature", None).unwrap();
5464
    // Started on main, belongs on feature: edit, add, remove.
5465
    write(root, "a.txt", b"a\nmore\n");
5466
    write(root, "new.txt", b"new\n");
5467
    fs::remove_file(root.join("gone.txt")).unwrap();
5468
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5469
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5470
    assert_eq!(repo.config.bookmark, "feature");
5471
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5472
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5473
    assert!(!root.join("gone.txt").exists());
5474
    let snap = repo.snapshot("status").unwrap();
5475
    assert_eq!(
5476
        statuses(&snap),
5477
        vec![
5478
            ("a.txt".to_string(), ChangeStatus::Modified),
5479
            ("gone.txt".to_string(), ChangeStatus::Removed),
5480
            ("new.txt".to_string(), ChangeStatus::Added)
5481
        ]
5482
    );
5483
    repo.commit("the work", &[]).unwrap();
5484
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5485
5486
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5487
    repo.bookmark_switch("main", false).unwrap();
5488
    write(root, "b.txt", b"b on main\n");
5489
    repo.commit("b on main", &[]).unwrap();
5490
    repo.bookmark_switch("feature", false).unwrap();
5491
    write(root, "b.txt", b"b edited\n");
5492
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5493
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5494
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5495
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5496
}
5497
5498
/// Merging and checking out (feedback 3): a working copy without changes
5499
/// follows a merge whichever state it sat on; a refused checkout names
5500
/// what is in the way; `checkout --carry` takes the work along.
5501
#[test]
5502
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5503
    hermetic();
5504
    let dir = tempfile::tempdir().unwrap();
5505
    let root = dir.path();
5506
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5507
    write(root, "a.txt", b"a\n");
5508
    let h1 = repo.commit("a", &[]).unwrap();
5509
    write(root, "b.txt", b"b\n");
5510
    repo.commit("b", &[]).unwrap();
5511
    repo.bookmark_create("feature", None).unwrap();
5512
    repo.bookmark_switch("feature", false).unwrap();
5513
    write(root, "c.txt", b"c\n");
5514
    repo.commit("c on feature", &[]).unwrap();
5515
    repo.bookmark_switch("main", false).unwrap();
5516
    // The working copy sits on an older state than main's heads.
5517
    repo.checkout(&[h1], false, "checkout").unwrap();
5518
    assert!(!root.join("b.txt").exists());
5519
    let m = repo.merge("feature").unwrap();
5520
    assert!(m.checked_out, "a clean working copy follows the merge");
5521
    for f in ["a.txt", "b.txt", "c.txt"] {
5522
        assert!(root.join(f).exists(), "{f}");
5523
    }
5524
5525
    // A refusal says which paths are in the way and what to do.
5526
    fs::remove_file(root.join("b.txt")).unwrap();
5527
    write(root, "a.txt", b"a edited\n");
5528
    let err = repo
5529
        .checkout(&[h1], false, "checkout")
5530
        .unwrap_err()
5531
        .to_string();
5532
    assert!(
5533
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5534
        "{err}"
5535
    );
5536
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5537
    // is carried as absent (h1 has none either, so that is refused).
5538
    let err = repo
5539
        .checkout_carry(&[h1], "the first change", "checkout")
5540
        .unwrap_err()
5541
        .to_string();
5542
    assert!(
5543
        err.contains("b.txt") && err.contains("the first change"),
5544
        "{err}"
5545
    );
5546
    write(root, "b.txt", b"b\n");
5547
    let (_, carried) = repo
5548
        .checkout_carry(&[h1], "the first change", "checkout")
5549
        .unwrap();
5550
    assert_eq!(carried, vec!["a.txt"]);
5551
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5552
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5553
}
5554
5555
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5556
/// user identity not stored in a new repository yet is fine while its
5557
/// secret key is there; an added subrepo is listed as not committed yet.
5558
#[test]
5559
fn a_new_repository_is_healthy_before_its_first_commit() {
5560
    hermetic();
5561
    let dir = tempfile::tempdir().unwrap();
5562
    let root = dir.path();
5563
    let home = root.join("home");
5564
    let mut first = Repo::init(&root.join("first"))
5565
        .unwrap()
5566
        .with_home(home.clone());
5567
    let (key, _) = first
5568
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5569
        .unwrap();
5570
    let repo = Repo::init(&root.join("second"))
5571
        .unwrap()
5572
        .with_home(home.clone());
5573
    // Only the secret key: no identity object anywhere this repository sees.
5574
    let keys = repo.keys_dir.clone();
5575
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5576
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5577
    let r = repo.doctor(true);
5578
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5579
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5580
    assert!(id.message.contains("first signed change"), "{}", id.message);
5581
5582
    // A subrepo added and not committed yet is listed, pinned where it is.
5583
    let lib = root.join("lib");
5584
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5585
    write(&lib, "x.txt", b"x\n");
5586
    l.commit("x", &[]).unwrap();
5587
    let second = root.join("second");
5588
    write(&second, "a.txt", b"a\n");
5589
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5590
        .unwrap();
5591
    let subs = repo.subrepos().unwrap();
5592
    assert_eq!(subs.len(), 1);
5593
    assert_eq!(
5594
        (subs[0].path.as_str(), subs[0].committed),
5595
        ("deps/lib", false)
5596
    );
5597
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5598
    repo.commit("add lib", &[]).unwrap();
5599
    let subs = repo.subrepos().unwrap();
5600
    assert!(subs[0].committed, "committed now");
5601
}
5602
5603
/// Commit, diff, hunks and discard use the partial snapshot: a file
5604
/// unchanged since the manifest is neither read nor rendered, and showing
5605
/// a change renders only what it edits, the same as from a full base.
5606
#[cfg(unix)]
5607
#[test]
5608
fn commits_and_diffs_leave_unchanged_files_alone() {
5609
    use std::os::unix::fs::PermissionsExt;
5610
    hermetic();
5611
    let dir = tempfile::tempdir().unwrap();
5612
    let root = dir.path();
5613
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5614
    write(root, "big.txt", b"lots\nof\nlines\n");
5615
    write(root, "a.txt", b"one\ntwo\n");
5616
    repo.commit("base", &[]).unwrap();
5617
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5618
    for f in ["big.txt", "a.txt"] {
5619
        fs::File::options()
5620
            .write(true)
5621
            .open(root.join(f))
5622
            .unwrap()
5623
            .set_modified(old)
5624
            .unwrap();
5625
    }
5626
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5627
    // big.txt cannot be read at all from here on.
5628
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5629
5630
    write(root, "a.txt", b"one\nTWO\nthree\n");
5631
    let diff = repo.diff_files(None).unwrap();
5632
    assert_eq!(
5633
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5634
        ["a.txt"]
5635
    );
5636
    let (_, hunks) = repo.hunks().unwrap();
5637
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5638
    let h = repo.commit("edit a", &[]).unwrap();
5639
5640
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5641
    let c = repo.store().get_change(&h).unwrap();
5642
    let full = repo.load_state(&c.deps).unwrap();
5643
    let want = render_change(&c, &full, &full.materialize());
5644
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5645
    let (base, snap) = repo.change_base(&c).unwrap();
5646
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5647
5648
    // Discarding works the same way.
5649
    write(root, "a.txt", b"scratch\n");
5650
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5651
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5652
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5653
}
5654
5655
/// A replace conflict (spec §9.3) is settled by a change that writes one
5656
/// candidate, or new bytes, at the path when the caller names it; a plain
5657
/// snapshot of a checkout never settles it on its own.
5658
#[test]
5659
fn replace_conflicts_are_settled_when_asked() {
5660
    hermetic();
5661
    let dir = tempfile::tempdir().unwrap();
5662
    let root = dir.path();
5663
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5664
    let blob = |n: u8| {
5665
        let mut v = vec![0u8; 64];
5666
        v[1] = n;
5667
        v
5668
    };
5669
    write(root, "img.bin", &blob(1));
5670
    repo.commit("add img", &[]).unwrap();
5671
    repo.bookmark_create("other", None).unwrap();
5672
    write(root, "img.bin", &blob(2));
5673
    repo.commit("img two", &[]).unwrap();
5674
    repo.bookmark_switch("other", false).unwrap();
5675
    write(root, "img.bin", &blob(3));
5676
    repo.commit("img three", &[]).unwrap();
5677
    repo.bookmark_switch("main", false).unwrap();
5678
    repo.merge("other").unwrap();
5679
    let heads = repo.bookmark_heads().unwrap();
5680
    let merged = repo.load_state(&heads).unwrap().materialize();
5681
    assert!(
5682
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5683
        "a replace conflict"
5684
    );
5685
    // A snapshot of the checkout records nothing.
5686
    assert!(repo
5687
        .snapshot("status")
5688
        .unwrap()
5689
        .statuses
5690
        .iter()
5691
        .all(|s| s.path != "img.bin"));
5692
5693
    // Keeping candidate 3 settles it.
5694
    let author = repo.author();
5695
    let edits = [FileEdit {
5696
        path: "img.bin".into(),
5697
        content: Some(blob(3)),
5698
    }];
5699
    let c = repo
5700
        .build_change(&heads, &edits, "keep three", author)
5701
        .unwrap();
5702
    assert_eq!(c.kind, ChangeKind::Resolution);
5703
    let mut st = repo.load_state(&heads).unwrap();
5704
    for d in &c.deps {
5705
        assert!(st.contains(d));
5706
    }
5707
    assert!(
5708
        heads.iter().all(|h| c.deps.contains(h)),
5709
        "depends on both contributors"
5710
    );
5711
    st.add(c).unwrap();
5712
    let after = st.materialize();
5713
    assert!(!after.is_conflicted());
5714
    assert_eq!(
5715
        after.files["img.bin"].content,
5716
        FileContent::Opaque {
5717
            blobs: vec![Repo::blob_ref(&blob(3))]
5718
        }
5719
    );
5720
5721
    // New bytes settle it too.
5722
    let edits = [FileEdit {
5723
        path: "img.bin".into(),
5724
        content: Some(blob(9)),
5725
    }];
5726
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5727
    let mut st = repo.load_state(&heads).unwrap();
5728
    st.add(c).unwrap();
5729
    assert_eq!(
5730
        st.materialize().files["img.bin"].content,
5731
        FileContent::Opaque {
5732
            blobs: vec![Repo::blob_ref(&blob(9))]
5733
        }
5734
    );
5735
}
5736
5737
/// The history of a range of lines (spec §27): the changes that wrote
5738
/// or deleted its atoms, or deleted atoms from between them; edits outside
5739
/// the range and changes the range's lines survived are not in it.
5740
#[test]
5741
fn line_ranges_have_exact_histories() {
5742
    hermetic();
5743
    let dir = tempfile::tempdir().unwrap();
5744
    let root = dir.path();
5745
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5746
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5747
    let base = repo.commit("add f", &[]).unwrap();
5748
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5749
    let outside = repo.commit("change the import", &[]).unwrap();
5750
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5751
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5752
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5753
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5754
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5755
    let after = repo.commit("add b after a", &[]).unwrap();
5756
    let heads = repo.bookmark_heads().unwrap();
5757
5758
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5759
    let hist: Vec<ChangeHash> = repo
5760
        .line_history(&heads, "f.rs", 2, 4)
5761
        .unwrap()
5762
        .iter()
5763
        .map(|e| e.hash)
5764
        .collect();
5765
    for (h, what) in [
5766
        (base, "wrote it"),
5767
        (inside, "edited a line"),
5768
        (deleted, "deleted a line from inside"),
5769
    ] {
5770
        assert!(hist.contains(&h), "{what}");
5771
    }
5772
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5773
        assert!(!hist.contains(&h), "{what}");
5774
    }
5775
    assert_eq!(hist[0], deleted, "newest first");
5776
    // One line: only what touched it.
5777
    let one: Vec<ChangeHash> = repo
5778
        .line_history(&heads, "f.rs", 1, 1)
5779
        .unwrap()
5780
        .iter()
5781
        .map(|e| e.hash)
5782
        .collect();
5783
    assert!(one.contains(&outside) && !one.contains(&inside));
5784
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5785
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5786
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5787
}
5788
5789
#[test]
5790
fn receipts_are_kept_with_their_state_and_verified() {
5791
    use crate::receipt::{Receipt, SignedReceipt};
5792
    hermetic();
5793
    let dir = tempfile::tempdir().unwrap();
5794
    let root = dir.path();
5795
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5796
    write(root, "a.txt", b"1\n");
5797
    repo.commit("A", &[]).unwrap();
5798
    let heads = repo.bookmark_heads().unwrap();
5799
    let state = repo
5800
        .store()
5801
        .put_state(&StateObject::new(heads.clone()))
5802
        .unwrap();
5803
    let out = repo.store_blob(b"built\n").unwrap();
5804
    let receipt = Receipt {
5805
        job_name: "build".into(),
5806
        pipeline_hash: ObjectRef([1; 32]),
5807
        scope_tree_hash: ObjectRef([2; 32]),
5808
        inputs: vec![],
5809
        environment: ObjectRef([3; 32]),
5810
        outputs: vec![out],
5811
        exit_code: 0,
5812
        duration_ms: 42,
5813
    };
5814
    let sk = SecretKey::generate();
5815
    let runner = sk.identity("earth-1", "runner@earth", 1);
5816
    let sr = SignedReceipt::sign(
5817
        receipt.clone(),
5818
        repo.id().unwrap(),
5819
        state,
5820
        "demo#1",
5821
        &runner,
5822
        &sk,
5823
    );
5824
5825
    let r = repo.add_receipt(&sr).unwrap();
5826
    let found = repo.receipts(&heads).unwrap();
5827
    assert_eq!(found.len(), 1);
5828
    assert_eq!(found[0].attest, r);
5829
    assert_eq!(found[0].signed, sr);
5830
    assert!(found[0].problem.is_none() && !found[0].revoked);
5831
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5832
5833
    // Another repository's receipt, or a forged one, is refused.
5834
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5835
    assert!(repo
5836
        .add_receipt(&elsewhere)
5837
        .unwrap_err()
5838
        .to_string()
5839
        .contains("another repository"));
5840
    let mut forged = sr.clone();
5841
    forged.receipt.exit_code = 1;
5842
    assert!(repo
5843
        .add_receipt(&forged)
5844
        .unwrap_err()
5845
        .to_string()
5846
        .contains("does not verify"));
5847
5848
    // A receipt signed by a short-lived key keeps its certificate and the
5849
    // issuer's identity, and reads back with them (oxygenhub#241).
5850
    let hub_sk = SecretKey::generate();
5851
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
5852
    let job_sk = SecretKey::generate();
5853
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
5854
    let mut test_receipt = receipt.clone();
5855
    test_receipt.job_name = "test".into();
5856
    let plain = SignedReceipt::sign(
5857
        test_receipt,
5858
        repo.id().unwrap(),
5859
        state,
5860
        "demo#2",
5861
        &job,
5862
        &job_sk,
5863
    );
5864
    let now = plain.attest.hlc.wall_ms;
5865
    let cert = crate::cert::SignedCertificate::sign(
5866
        crate::cert::Certificate {
5867
            key: job.clone(),
5868
            issuer: hub.hash(),
5869
            subject: "repo:andy/demo:bookmark:main".into(),
5870
            claims: vec![],
5871
            scope: crate::identity::Scope::SEAL,
5872
            not_before: now - 1_000,
5873
            expires: now + 600_000,
5874
            grant: None,
5875
        },
5876
        &hub,
5877
        &hub_sk,
5878
    );
5879
    let certified = plain.with_certificate(cert, hub.clone());
5880
    repo.add_receipt(&certified).unwrap();
5881
    let found = repo.receipts(&heads).unwrap();
5882
    let got = found
5883
        .iter()
5884
        .find(|i| i.signed.receipt.job_name == "test")
5885
        .unwrap();
5886
    assert_eq!(got.signed, certified);
5887
    assert!(got.problem.is_none(), "{:?}", got.problem);
5888
5889
    // gc keeps the receipts, their runners, the certificate and its issuer,
5890
    // and the output while the state lives.
5891
    repo.gc(true).unwrap();
5892
    let found = repo.receipts(&heads).unwrap();
5893
    assert_eq!(found.len(), 2);
5894
    let got = found
5895
        .iter()
5896
        .find(|i| i.signed.receipt.job_name == "test")
5897
        .unwrap();
5898
    assert_eq!(got.signed, certified, "the certificate survives gc");
5899
    assert!(got.problem.is_none());
5900
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5901
    assert!(repo.fsck().unwrap().problems.is_empty());
5902
}
5903
5904
#[test]
5905
fn status_leaves_an_unchanged_manifest_alone() {
5906
    hermetic();
5907
    let dir = tempfile::tempdir().unwrap();
5908
    let root = dir.path();
5909
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5910
    write(root, "a.txt", b"1\n");
5911
    write(root, "b.txt", b"2\n");
5912
    repo.commit("A", &[]).unwrap();
5913
    // Files last touched well outside the racy window.
5914
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5915
    for f in ["a.txt", "b.txt"] {
5916
        fs::File::options()
5917
            .write(true)
5918
            .open(root.join(f))
5919
            .unwrap()
5920
            .set_modified(old)
5921
            .unwrap();
5922
    }
5923
    repo.snapshot_status("status").unwrap();
5924
    let path = repo.manifest_path();
5925
    let first = fs::read(&path).unwrap();
5926
    repo.snapshot_status("status").unwrap();
5927
    assert_eq!(
5928
        fs::read(&path).unwrap(),
5929
        first,
5930
        "an unchanged tree does not rewrite the manifest"
5931
    );
5932
    // A change rewrites it.
5933
    write(root, "a.txt", b"1\n2\n");
5934
    repo.snapshot_status("status").unwrap();
5935
    assert_ne!(fs::read(&path).unwrap(), first);
5936
}
5937
5938
#[test]
5939
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5940
    hermetic();
5941
    let dir = tempfile::tempdir().unwrap();
5942
    let root = dir.path();
5943
    let origin_path = root.join("origin");
5944
    Repo::init(&origin_path).unwrap();
5945
    let origin_url = origin_path.to_string_lossy().to_string();
5946
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5947
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5948
    write(&root.join("a"), "big.txt", big.as_bytes());
5949
    write(&root.join("a"), "small.txt", b"small\n");
5950
    let h1 = a.commit("large", &[]).unwrap();
5951
    let (_, body) = a.store().get(&h1).unwrap();
5952
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5953
    assert!(a.push("origin", false).unwrap()[0].ok);
5954
5955
    // A clone reads the text from the blobs that came with the change.
5956
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5957
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5958
    // An edit in the middle of the stored insert is an ordinary change.
5959
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5960
    write(&root.join("b"), "big.txt", edited.as_bytes());
5961
    let h2 = b.commit("edit", &[]).unwrap();
5962
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5963
    assert!(b.push("origin", false).unwrap()[0].ok);
5964
    assert!(a.pull("origin").unwrap().checked_out);
5965
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5966
    assert_eq!(
5967
        a.fsck().unwrap().errors(),
5968
        0,
5969
        "{:?}",
5970
        a.fsck().unwrap().problems
5971
    );
5972
5973
    // With zero retention gc keeps the text blobs of every kept change.
5974
    let mut a = Repo::open(&root.join("a")).unwrap();
5975
    a.config.set("core.op-retention", "0").unwrap();
5976
    a.save_config().unwrap();
5977
    let a = Repo::open(&root.join("a")).unwrap();
5978
    a.gc(true).unwrap();
5979
    let a = Repo::open(&root.join("a")).unwrap();
5980
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5981
    assert_eq!(
5982
        a.fsck().unwrap().errors(),
5983
        0,
5984
        "{:?}",
5985
        a.fsck().unwrap().problems
5986
    );
5987
    // And a clone of the packed repository reads them from its packs.
5988
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5989
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5990
    drop(c);
5991
}
5992
5993
#[test]
5994
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5995
    hermetic();
5996
    let dir = tempfile::tempdir().unwrap();
5997
    let root = dir.path();
5998
    let repo = Repo::init(root).unwrap();
5999
    write(root, "a.txt", b"a\n");
6000
    let a = repo.commit("a", &[]).unwrap();
6001
    write(root, "b.txt", b"b\n");
6002
    repo.commit("b", &[]).unwrap();
6003
    let (x, op) = repo.head_op().unwrap();
6004
    let ws = *op.view.workspaces.keys().next().unwrap();
6005
    let mut one = op.view.clone();
6006
    one.workspaces.insert(ws, a);
6007
    let mut two = op.view.clone();
6008
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6009
    let first = repo.record_op(&[x], "one", one).unwrap();
6010
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6011
    assert!(
6012
        e.to_string()
6013
            .contains("changed this working copy at the same time"),
6014
        "{e}"
6015
    );
6016
    assert_eq!(
6017
        repo.head_op().unwrap().0,
6018
        first,
6019
        "the second is not recorded"
6020
    );
6021
}
6022
6023
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6024
/// rewrote the working copy recorded the half-written files as edits, and
6025
/// its view replaced the switch's.
6026
#[test]
6027
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6028
    hermetic();
6029
    let dir = tempfile::tempdir().unwrap();
6030
    let root = dir.path().to_path_buf();
6031
    let mut repo = Repo::init(&root).unwrap();
6032
    write(&root, "keep.txt", b"keep\n");
6033
    repo.commit("base", &[]).unwrap();
6034
    repo.bookmark_create("small", None).unwrap();
6035
    for i in 0..300 {
6036
        write(
6037
            &root,
6038
            &format!("many/f{i}.txt"),
6039
            format!("file {i}\n").as_bytes(),
6040
        );
6041
    }
6042
    repo.commit("many", &[]).unwrap();
6043
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6044
    let watcher = {
6045
        let (root, stop) = (root.clone(), stop.clone());
6046
        std::thread::spawn(move || {
6047
            let r = Repo::open(&root).unwrap();
6048
            let mut ran = 0;
6049
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6050
                if r.snapshot_status("oxy status").is_ok() {
6051
                    ran += 1;
6052
                }
6053
            }
6054
            ran
6055
        })
6056
    };
6057
    for i in 0..20 {
6058
        let to = if i % 2 == 0 { "small" } else { "main" };
6059
        repo.bookmark_switch(to, false).unwrap();
6060
    }
6061
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6062
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6063
    // Back on main, clean, with every file where main has it.
6064
    let repo = Repo::open(&root).unwrap();
6065
    let s = repo.snapshot_status("oxy status").unwrap();
6066
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6067
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6068
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6069
    assert!(root.join("many/f299.txt").exists());
6070
}
6071
6072
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6073
/// put a subrepo that was ahead of its pin back at the pin and moved the
6074
/// subrepo's own bookmark backwards.
6075
#[test]
6076
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6077
    hermetic();
6078
    let dir = tempfile::tempdir().unwrap();
6079
    let root = dir.path();
6080
    Repo::init(&root.join("lib-origin")).unwrap();
6081
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6082
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6083
    write(&root.join("lib"), "lib.txt", b"v1\n");
6084
    lib.commit("lib v1", &[]).unwrap();
6085
    assert!(lib.push("origin", false).unwrap()[0].ok);
6086
6087
    let app_dir = root.join("app");
6088
    let mut app = Repo::init(&app_dir).unwrap();
6089
    write(&app_dir, "main.txt", b"app\n");
6090
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6091
    app.commit("app with lib", &[]).unwrap();
6092
    app.bookmark_create("feature", None).unwrap();
6093
6094
    // New work in the subrepo, not yet pinned by the parent.
6095
    let nested_dir = app_dir.join("libs/lib");
6096
    let nested = Repo::open(&nested_dir).unwrap();
6097
    write(&nested_dir, "new.txt", b"new\n");
6098
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6099
    drop(nested);
6100
6101
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6102
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6103
    let nested = Repo::open(&nested_dir).unwrap();
6104
    assert!(
6105
        nested.bookmark_heads().unwrap().contains(&l2),
6106
        "its bookmark kept its work"
6107
    );
6108
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6109
    let s = app.snapshot("status").unwrap();
6110
    assert_eq!(
6111
        statuses(&s),
6112
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6113
    );
6114
}
6115
6116
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6117
/// moving `main` to a change this clone had pushed on another bookmark,
6118
/// the first `pull` said "Already up to date" while `main` was behind.
6119
#[test]
6120
fn pull_takes_a_remote_move_to_changes_already_here() {
6121
    hermetic();
6122
    let dir = tempfile::tempdir().unwrap();
6123
    let root = dir.path();
6124
    let origin_path = root.join("origin");
6125
    let origin = Repo::init(&origin_path).unwrap();
6126
    let url = origin_path.to_string_lossy().to_string();
6127
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6128
    write(&root.join("b"), "base.txt", b"base\n");
6129
    b.commit("base", &[]).unwrap();
6130
    assert!(b.push("origin", false).unwrap()[0].ok);
6131
6132
    // A feature bookmark with one change, pushed.
6133
    b.bookmark_create("feat", None).unwrap();
6134
    b.bookmark_switch("feat", false).unwrap();
6135
    write(&root.join("b"), "x.txt", b"x\n");
6136
    let x = b.commit("x", &[]).unwrap();
6137
    assert!(b.push("origin", false).unwrap()[0].ok);
6138
    b.bookmark_switch("main", false).unwrap();
6139
6140
    // The remote lands it: its main moves to the feature's state.
6141
    let feat = origin
6142
        .store()
6143
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6144
        .unwrap()
6145
        .heads;
6146
    origin.bookmark_set("main", &feat).unwrap();
6147
6148
    let r = b.pull("origin").unwrap();
6149
    assert!(r.changed, "{r:?}");
6150
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6151
    let main = b
6152
        .bookmarks()
6153
        .unwrap()
6154
        .into_iter()
6155
        .find(|m| m.name == "main")
6156
        .unwrap();
6157
    assert_eq!(main.behind, Some(0), "{main:?}");
6158
}
6159
6160
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6161
/// to one only the remote has makes a local bookmark from it; a pull moves
6162
/// every local bookmark the remote has too; a clone checks out the remote's
6163
/// default bookmark.
6164
#[test]
6165
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6166
    hermetic();
6167
    let dir = tempfile::tempdir().unwrap();
6168
    let root = dir.path();
6169
    let origin_path = root.join("origin");
6170
    let mut origin = Repo::init(&origin_path).unwrap();
6171
    let url = origin_path.to_string_lossy().to_string();
6172
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6173
    write(&root.join("a"), "base.txt", b"base\n");
6174
    a.commit("base", &[]).unwrap();
6175
    assert!(a.push("origin", false).unwrap()[0].ok);
6176
    a.bookmark_create("develop", None).unwrap();
6177
    a.bookmark_switch("develop", false).unwrap();
6178
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6179
    let d1 = a.commit("d1", &[]).unwrap();
6180
    assert!(a.push("origin", false).unwrap()[0].ok);
6181
6182
    // A clone has main only; origin/develop is a name all the same.
6183
    let c_root = root.join("c");
6184
    let mut c = Repo::clone(&url, &c_root).unwrap();
6185
    assert_eq!(c.config.bookmark, "main");
6186
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6187
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6188
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6189
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6190
6191
    // Switching makes the local bookmark from origin's.
6192
    c.bookmark_switch("develop", false).unwrap();
6193
    assert_eq!(c.config.bookmark, "develop");
6194
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6195
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6196
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6197
    assert!(c.bookmark_switch("nowhere", false).is_err());
6198
6199
    // Both bookmarks move on the remote; one pull takes both.
6200
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6201
    let d2 = a.commit("d2", &[]).unwrap();
6202
    assert!(a.push("origin", false).unwrap()[0].ok);
6203
    a.bookmark_switch("main", false).unwrap();
6204
    write(&root.join("a"), "m.txt", b"m\n");
6205
    let m = a.commit("m", &[]).unwrap();
6206
    assert!(a.push("origin", false).unwrap()[0].ok);
6207
    let r = c.pull("origin").unwrap();
6208
    assert!(r.changed && r.checked_out, "{r:?}");
6209
    assert_eq!(r.heads, vec![d2]);
6210
    assert_eq!(r.others, vec!["main".to_string()]);
6211
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6212
    assert_eq!(
6213
        fs::read(c_root.join("base.txt")).unwrap(),
6214
        b"base\nd1\nd2\n"
6215
    );
6216
    let again = c.pull("origin").unwrap();
6217
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6218
6219
    // A clone checks out the remote's default bookmark.
6220
    origin.config.set("workspace.bookmark", "develop").unwrap();
6221
    origin.save_config().unwrap();
6222
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6223
    assert_eq!(e.config.bookmark, "develop");
6224
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6225
    let reopened = Repo::open(&root.join("e")).unwrap();
6226
    assert_eq!(reopened.config.bookmark, "develop");
6227
    // REMOTE/NAME names the remote's bookmark to switch to.
6228
    let mut e = reopened;
6229
    e.bookmark_switch("origin/main", false).unwrap();
6230
    assert_eq!(e.config.bookmark, "main");
6231
    assert!(e.bookmark_heads().unwrap().contains(&m));
6232
}
6233
6234
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6235
/// op restore goes back to an operation, files included, and undo takes
6236
/// the restore back whole; op revert undoes one operation alone; each
6237
/// operation's changes are described from the views.
6238
#[test]
6239
fn operations_can_be_read_restored_and_reverted() {
6240
    hermetic();
6241
    let dir = tempfile::tempdir().unwrap();
6242
    let root = dir.path();
6243
    let repo = Repo::init(root).unwrap();
6244
    write(root, "a.txt", b"a\n");
6245
    let first = repo.commit("first", &[]).unwrap();
6246
    write(root, "a.txt", b"a\nb\n");
6247
    let second = repo.commit("second", &[]).unwrap();
6248
    let at_second = repo.head_op().unwrap().0.to_hex();
6249
    repo.bookmark_create("keep", None).unwrap();
6250
    let created = repo.head_op().unwrap().0.to_hex();
6251
    write(root, "n.txt", b"n\n");
6252
    let third = repo.commit("third", &[]).unwrap();
6253
6254
    // What each operation changed.
6255
    let ops = repo.op_log().unwrap();
6256
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6257
    assert!(
6258
        changes
6259
            .iter()
6260
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6261
        "{changes:?}"
6262
    );
6263
    assert!(changes
6264
        .iter()
6265
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6266
6267
    // Reading at an earlier operation.
6268
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6269
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6270
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6271
    write(root, "z.txt", b"z\n");
6272
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6273
    fs::remove_file(root.join("z.txt")).unwrap();
6274
    assert!(repo.resolve_op("zz").is_err());
6275
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
6276
6277
    // Restore goes back, files and all; undo takes it back whole.
6278
    repo.op_restore(&at_second, false).unwrap();
6279
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
6280
    assert!(!root.join("n.txt").exists());
6281
    repo.undo().unwrap();
6282
    let mut heads = repo.bookmark_heads().unwrap();
6283
    heads.sort();
6284
    let mut want = vec![second, third];
6285
    want.sort();
6286
    assert_eq!(heads, want);
6287
    assert!(
6288
        root.join("n.txt").exists(),
6289
        "the files came back with the undo"
6290
    );
6291
6292
    // Revert the bookmark's creation alone: the commit after it stays.
6293
    let r = repo.op_revert(&created).unwrap();
6294
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6295
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6296
    assert!(repo
6297
        .load_state(&repo.bookmark_heads().unwrap())
6298
        .unwrap()
6299
        .contains(&third));
6300
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6301
    let _ = first;
6302
}
6303
6304
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6305
/// from the status cache while every file is as the snapshot left it, and
6306
/// from a snapshot again as soon as one is not.
6307
#[test]
6308
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6309
    hermetic();
6310
    let dir = tempfile::tempdir().unwrap();
6311
    let root = dir.path();
6312
    let repo = Repo::init(root).unwrap();
6313
    write(root, "a.txt", b"a\n");
6314
    write(root, "b.txt", b"b\n");
6315
    repo.commit("base", &[]).unwrap();
6316
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6317
6318
    write(root, "a.txt", b"a\nmore\n");
6319
    assert_eq!(
6320
        repo.status_by_manifest().unwrap(),
6321
        None,
6322
        "no snapshot of the edit yet"
6323
    );
6324
    let snap = repo.snapshot_status("oxy status").unwrap();
6325
    assert_eq!(snap.statuses.len(), 1);
6326
    let cached = repo
6327
        .status_by_manifest()
6328
        .unwrap()
6329
        .expect("answered from the cache");
6330
    assert_eq!(cached.len(), 1);
6331
    assert_eq!(
6332
        (cached[0].path.as_str(), cached[0].status),
6333
        ("a.txt", ChangeStatus::Modified)
6334
    );
6335
6336
    // Any further change sends status back to a snapshot.
6337
    write(root, "a.txt", b"a\nmore\nand more\n");
6338
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6339
    repo.snapshot_status("oxy status").unwrap();
6340
    assert!(repo.status_by_manifest().unwrap().is_some());
6341
    write(root, "new.txt", b"n\n");
6342
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6343
    fs::remove_file(root.join("new.txt")).unwrap();
6344
    assert!(
6345
        repo.status_by_manifest().unwrap().is_some(),
6346
        "back as it was"
6347
    );
6348
    fs::remove_file(root.join("b.txt")).unwrap();
6349
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6350
    write(root, "b.txt", b"b\n");
6351
6352
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6353
    repo.snapshot_status("oxy status").unwrap();
6354
    repo.commit("more", &[]).unwrap();
6355
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6356
}
6357
6358
/// oxygen#41: while the status cache holds, the working copy's diff is
6359
/// rendered from the stored working-copy change, and says exactly what a
6360
/// snapshot's diff says.
6361
#[test]
6362
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6363
    hermetic();
6364
    let dir = tempfile::tempdir().unwrap();
6365
    let root = dir.path();
6366
    let repo = Repo::init(root).unwrap();
6367
    write(root, "a.txt", b"one\ntwo\nthree\n");
6368
    write(root, "gone.txt", b"bye\n");
6369
    repo.commit("base", &[]).unwrap();
6370
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6371
    write(root, "new.txt", b"hello\n");
6372
    fs::remove_file(root.join("gone.txt")).unwrap();
6373
    let snap = repo.snapshot_status("oxy status").unwrap();
6374
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6375
    assert!(
6376
        repo.status_by_manifest().unwrap().is_some(),
6377
        "the cache holds"
6378
    );
6379
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6380
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6381
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6382
}
6383
6384
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6385
/// while none has moved, the check stats the tracked files without listing
6386
/// the tree, and a file added or removed anywhere moves its directory's
6387
/// time, so the tree is listed again.
6388
#[test]
6389
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6390
    hermetic();
6391
    let dir = tempfile::tempdir().unwrap();
6392
    let root = dir.path();
6393
    let repo = Repo::init(root).unwrap();
6394
    write(root, "a.txt", b"a\n");
6395
    write(root, "sub/deep/b.txt", b"b\n");
6396
    repo.commit("base", &[]).unwrap();
6397
    // Out of the racy window: every file and directory a minute old.
6398
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6399
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6400
        fs::File::open(root.join(p))
6401
            .unwrap()
6402
            .set_modified(old)
6403
            .unwrap();
6404
    }
6405
    repo.snapshot_status("oxy status").unwrap();
6406
    repo.write_manifest(false, false).unwrap();
6407
    let m = repo.read_manifest().unwrap().unwrap().2;
6408
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6409
    assert_eq!(
6410
        repo.disk_differs_by_dirs(&m),
6411
        Some(false),
6412
        "no listing needed"
6413
    );
6414
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6415
6416
    // A same-size edit with a new time: found by its stat.
6417
    write(root, "sub/deep/b.txt", b"c\n");
6418
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6419
    write(root, "sub/deep/b.txt", b"b\n");
6420
    fs::File::open(root.join("sub/deep/b.txt"))
6421
        .unwrap()
6422
        .set_modified(old)
6423
        .unwrap();
6424
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6425
6426
    // A new file moves its directory's time: the tree must be listed.
6427
    write(root, "sub/deep/new.txt", b"n\n");
6428
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6429
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6430
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6431
    // A removed one too.
6432
    fs::remove_file(root.join("a.txt")).unwrap();
6433
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6434
}
6435
6436
/// oxygen#41: a commit right after a status takes the snapshot the status
6437
/// left (the status cache holds) rather than walking again, and commits
6438
/// exactly what a snapshot would have.
6439
#[test]
6440
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6441
    hermetic();
6442
    let dir = tempfile::tempdir().unwrap();
6443
    let root = dir.path();
6444
    let repo = Repo::init(root).unwrap();
6445
    write(root, "a.txt", b"a\nb\n");
6446
    write(root, ".oxyattributes", b"*.bin binary\n");
6447
    repo.commit("base", &[]).unwrap();
6448
    write(root, "a.txt", b"a\nB\n");
6449
    write(root, "new.txt", b"new\n");
6450
    let snap = repo.snapshot_status("oxy status").unwrap();
6451
    let cached = repo
6452
        .snapshot_from_cache()
6453
        .unwrap()
6454
        .expect("the cache holds");
6455
    assert_eq!(cached.wc_hash, snap.wc_hash);
6456
    assert_eq!(cached.statuses, snap.statuses);
6457
    assert!(
6458
        !cached.attributes.is_empty(),
6459
        "the .oxyattributes file was read"
6460
    );
6461
    let h = repo.commit("edit", &[]).unwrap();
6462
    let c = repo.store().get_change(&h).unwrap();
6463
    assert_eq!(
6464
        c.tree_ops.len() + c.edits.len(),
6465
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6466
    );
6467
    assert_eq!(
6468
        repo.status_by_manifest().unwrap(),
6469
        Some(vec![]),
6470
        "clean after the commit"
6471
    );
6472
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6473
}
6474
6475
/// oxygen#41: a clean check that verified racy entries restamps the
6476
/// manifest, so later checks can trust them, and a same-size rewrite
6477
/// straight afterwards is still found: entries within two seconds of the
6478
/// new time stay racy.
6479
#[test]
6480
fn a_verified_clean_check_restamps_the_manifest_safely() {
6481
    hermetic();
6482
    let dir = tempfile::tempdir().unwrap();
6483
    let root = dir.path();
6484
    let repo = Repo::init(root).unwrap();
6485
    write(root, "a.txt", b"one\n");
6486
    repo.commit("one", &[]).unwrap();
6487
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6488
    assert!(repo.clean_by_manifest().unwrap());
6489
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6490
    assert!(after > before, "restamped");
6491
    write(root, "a.txt", b"two\n");
6492
    assert!(
6493
        !repo.clean_by_manifest().unwrap(),
6494
        "a same-size rewrite is still seen"
6495
    );
6496
}
6497
6498
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6499
/// stored insert's text blob only when it builds that file's graph, and
6500
/// builds the same graph a full load does.
6501
#[test]
6502
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6503
    hermetic();
6504
    let dir = tempfile::tempdir().unwrap();
6505
    let root = dir.path();
6506
    let repo = Repo::init(root).unwrap();
6507
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6508
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6509
    write(root, "big.txt", big.as_bytes());
6510
    write(root, "other.txt", other.as_bytes());
6511
    let h = repo.commit("two large files", &[]).unwrap();
6512
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6513
    let h2 = repo.commit("append", &[]).unwrap();
6514
6515
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6516
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6517
        FileContent::Text { bytes, .. } => bytes.clone(),
6518
        other => panic!("{other:?}"),
6519
    };
6520
    // Built on demand, every graph renders as the full load's.
6521
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6522
    let big_node = full.files["big.txt"].node;
6523
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6524
    repo.load_all_graphs(&mut hist).unwrap();
6525
    let rendered = hist.materialize();
6526
    for p in ["big.txt", "other.txt"] {
6527
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6528
    }
6529
6530
    // Without other.txt's text blob, history still loads and big.txt still
6531
    // builds: nothing read the other text.
6532
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6533
    assert_eq!(texts.len(), 2);
6534
    let content = |r: &ObjectRef| -> Vec<u8> {
6535
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6536
        blob.chunks
6537
            .iter()
6538
            .flat_map(|c| repo.store().get(c).unwrap().1)
6539
            .collect()
6540
    };
6541
    let other_text = texts
6542
        .iter()
6543
        .filter_map(|t| match t {
6544
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6545
            _ => None,
6546
        })
6547
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6548
        .unwrap();
6549
    repo.store().remove_loose_for_test(&other_text).unwrap();
6550
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6551
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6552
    assert!(repo
6553
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6554
        .is_err());
6555
}
6556
6557
/// oxygen#35: the first status after a commit read and rendered every
6558
/// file (79 s and more than 14 GB on the Linux tree), because the
6559
/// manifest had no graph keys for files the commit added.
6560
#[test]
6561
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6562
    use std::os::unix::fs::PermissionsExt;
6563
    hermetic();
6564
    let dir = tempfile::tempdir().unwrap();
6565
    let root = dir.path();
6566
    let repo = Repo::init(root).unwrap();
6567
    let files = ["a.txt", "b.txt", "d/c.txt"];
6568
    for p in files {
6569
        write(root, p, format!("{p}\n").as_bytes());
6570
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6571
        fs::File::options()
6572
            .write(true)
6573
            .open(root.join(p))
6574
            .unwrap()
6575
            .set_modified(old)
6576
            .unwrap();
6577
    }
6578
    repo.commit("added", &[]).unwrap();
6579
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6580
    assert!(
6581
        m.entries.values().all(|e| e.graph.is_some()),
6582
        "keys recorded at commit"
6583
    );
6584
    // Unreadable files prove the next status reads none of them.
6585
    for p in files {
6586
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6587
    }
6588
    let snap = repo.snapshot_status("status").unwrap();
6589
    for p in files {
6590
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6591
    }
6592
    assert!(!snap.changed && snap.statuses.is_empty());
6593
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6594
}
6595
6596
/// oxygen#35: a checkout reads, renders and writes only the files whose
6597
/// graphs differ, and renders the rest a batch at a time.
6598
#[test]
6599
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6600
    use std::os::unix::fs::PermissionsExt;
6601
    hermetic();
6602
    let dir = tempfile::tempdir().unwrap();
6603
    let root = dir.path();
6604
    let origin = root.join("origin");
6605
    let mut repo = Repo::init(&origin).unwrap();
6606
    // More files than one batch holds.
6607
    let n = 2100;
6608
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6609
    for i in 0..n {
6610
        let p = format!("f/{i:04}.txt");
6611
        write(&origin, &p, format!("file {i}\n").as_bytes());
6612
        fs::File::options()
6613
            .write(true)
6614
            .open(origin.join(&p))
6615
            .unwrap()
6616
            .set_modified(old)
6617
            .unwrap();
6618
    }
6619
    repo.commit("many", &[]).unwrap();
6620
    repo.bookmark_create("feature", None).unwrap();
6621
    repo.bookmark_switch("feature", false).unwrap();
6622
    write(&origin, "f/0007.txt", b"changed\n");
6623
    repo.commit("one change", &[]).unwrap();
6624
6625
    // Switching back to main must not read the unchanged files.
6626
    for i in 0..n {
6627
        if i != 7 {
6628
            let p = origin.join(format!("f/{i:04}.txt"));
6629
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6630
        }
6631
    }
6632
    let r = repo.bookmark_switch("main", false).unwrap();
6633
    for i in 0..n {
6634
        let p = origin.join(format!("f/{i:04}.txt"));
6635
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6636
    }
6637
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6638
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6639
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6640
6641
    // A clone renders every file, across batches.
6642
    let c = root.join("clone");
6643
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6644
    for i in [0, 2047, 2048, n - 1] {
6645
        assert_eq!(
6646
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6647
            format!("file {i}\n").as_bytes()
6648
        );
6649
    }
6650
    let cloned = Repo::open(&c).unwrap();
6651
    assert!(cloned
6652
        .snapshot_status("status")
6653
        .unwrap()
6654
        .statuses
6655
        .is_empty());
6656
}
6657
6658
/// A file written just before the manifest (inside the racy window) is
6659
/// checked by its hash: trusted when equal, caught when edited in place
6660
/// with the same size and time.
6661
#[test]
6662
fn a_racy_manifest_entry_is_checked_by_hash() {
6663
    hermetic();
6664
    let dir = tempfile::tempdir().unwrap();
6665
    let root = dir.path();
6666
    let repo = Repo::init(root).unwrap();
6667
    write(root, "a.txt", b"one\n");
6668
    repo.commit("fresh", &[]).unwrap();
6669
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6670
    let t = fs::metadata(root.join("a.txt"))
6671
        .unwrap()
6672
        .modified()
6673
        .unwrap();
6674
    write(root, "a.txt", b"two\n");
6675
    fs::File::options()
6676
        .write(true)
6677
        .open(root.join("a.txt"))
6678
        .unwrap()
6679
        .set_modified(t)
6680
        .unwrap();
6681
    assert!(
6682
        !repo.clean_by_manifest().unwrap(),
6683
        "same size and time, other bytes"
6684
    );
6685
    assert_eq!(
6686
        statuses(&repo.snapshot_status("status").unwrap()),
6687
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6688
    );
6689
}
6690
6691
/// A fetch on one machine moves changes as stored, text blobs among the
6692
/// objects; a change whose text blob did not come is refused, not stored.
6693
#[test]
6694
fn a_raw_bundle_without_a_changes_text_is_refused() {
6695
    hermetic();
6696
    let dir = tempfile::tempdir().unwrap();
6697
    let root = dir.path();
6698
    let a = Repo::init(&root.join("a")).unwrap();
6699
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6700
    write(&root.join("a"), "big.txt", big.as_bytes());
6701
    let h = a.commit("big", &[]).unwrap();
6702
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6703
    assert_eq!(bundle.raw_changes.len(), 1);
6704
    assert!(bundle.changes.is_empty());
6705
    let b = Repo::init(&root.join("b")).unwrap();
6706
    let mut without = bundle.clone();
6707
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6708
    let e = b.import_bundle(&without, false).unwrap_err();
6709
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6710
    assert!(!b.store().has(&h));
6711
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6712
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6713
}
6714
6715
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6716
/// again was a second node for one Git path, so a file moved into it on
6717
/// another line, where the first node still stood, ended up in two places.
6718
/// An import now brings the directory back rather than make a new one.
6719
#[test]
6720
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6721
    hermetic();
6722
    if std::process::Command::new("git")
6723
        .arg("--version")
6724
        .output()
6725
        .is_err()
6726
    {
6727
        eprintln!("git not installed; skipping");
6728
        return;
6729
    }
6730
    let dir = tempfile::tempdir().unwrap();
6731
    let root = dir.path();
6732
    let g = root.join("src.git");
6733
    fs::create_dir_all(&g).unwrap();
6734
    let git = |args: &[&str]| -> String {
6735
        let out = std::process::Command::new("git")
6736
            .arg("-C")
6737
            .arg(&g)
6738
            .args([
6739
                "-c",
6740
                "user.name=Grace",
6741
                "-c",
6742
                "[email protected]",
6743
                "-c",
6744
                "commit.gpgsign=false",
6745
            ])
6746
            .args(args)
6747
            .output()
6748
            .unwrap();
6749
        assert!(
6750
            out.status.success(),
6751
            "git {args:?}: {}",
6752
            String::from_utf8_lossy(&out.stderr)
6753
        );
6754
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6755
    };
6756
    git(&["init", "-q", "-b", "main"]);
6757
    write(&g, "d/a.txt", b"a\n");
6758
    write(&g, "c/x.txt", b"x\n");
6759
    git(&["add", "."]);
6760
    git(&["commit", "-qm", "base"]);
6761
    // One line: move x into d while d still stands.
6762
    git(&["checkout", "-qb", "side"]);
6763
    git(&["mv", "c/x.txt", "d/x.txt"]);
6764
    git(&["commit", "-qm", "x into d"]);
6765
    // The other: d goes, comes back, and x moves into it too.
6766
    git(&["checkout", "-q", "main"]);
6767
    git(&["rm", "-q", "d/a.txt"]);
6768
    git(&["commit", "-qm", "d goes"]);
6769
    write(&g, "d/b.txt", b"b\n");
6770
    git(&["add", "."]);
6771
    git(&["commit", "-qm", "d comes back"]);
6772
    git(&["mv", "c/x.txt", "d/x.txt"]);
6773
    git(&["commit", "-qm", "x into d again"]);
6774
    git(&["merge", "-q", "--no-edit", "side"]);
6775
6776
    let repo = Repo::init(&root.join("o")).unwrap();
6777
    repo.import_git(&g, "main").unwrap();
6778
    let v = repo.verify_git_import(&g, "main").unwrap();
6779
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6780
    let st = repo
6781
        .load_state_history(&repo.bookmark_heads().unwrap())
6782
        .unwrap();
6783
    let view = st.tree().view();
6784
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6785
    // The directory is the one the first commit made.
6786
    // Commits made in one second tie on time: find the first by its message.
6787
    let first = repo
6788
        .log()
6789
        .unwrap()
6790
        .into_iter()
6791
        .find(|e| e.change.message.starts_with("base"))
6792
        .unwrap();
6793
    let base = repo
6794
        .load_state_history(&[first.hash])
6795
        .unwrap()
6796
        .tree()
6797
        .view();
6798
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6799
}
6800
6801
/// oxygen#30, the rest: a placement left under a directory another line
6802
/// removed is out of sight, so no diff reaches it; the merge that settles
6803
/// where the file is retires it.
6804
#[test]
6805
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6806
    hermetic();
6807
    if std::process::Command::new("git")
6808
        .arg("--version")
6809
        .output()
6810
        .is_err()
6811
    {
6812
        eprintln!("git not installed; skipping");
6813
        return;
6814
    }
6815
    let dir = tempfile::tempdir().unwrap();
6816
    let root = dir.path();
6817
    let g = root.join("src.git");
6818
    fs::create_dir_all(&g).unwrap();
6819
    let run = |args: &[&str]| {
6820
        std::process::Command::new("git")
6821
            .arg("-C")
6822
            .arg(&g)
6823
            .args([
6824
                "-c",
6825
                "user.name=Grace",
6826
                "-c",
6827
                "[email protected]",
6828
                "-c",
6829
                "commit.gpgsign=false",
6830
            ])
6831
            .args(args)
6832
            .output()
6833
            .unwrap()
6834
    };
6835
    let git = |args: &[&str]| {
6836
        let out = run(args);
6837
        assert!(
6838
            out.status.success(),
6839
            "git {args:?}: {}",
6840
            String::from_utf8_lossy(&out.stderr)
6841
        );
6842
    };
6843
    git(&["init", "-q", "-b", "main"]);
6844
    write(&g, "c/x.txt", b"x\n");
6845
    write(&g, "keep.txt", b"k\n");
6846
    git(&["add", "."]);
6847
    git(&["commit", "-qm", "base"]);
6848
    // One line renames the file within c; the other moves it out of c,
6849
    // which goes.
6850
    git(&["checkout", "-qb", "side"]);
6851
    git(&["mv", "c/x.txt", "c/y.txt"]);
6852
    git(&["commit", "-qm", "rename within c"]);
6853
    git(&["checkout", "-q", "main"]);
6854
    fs::create_dir_all(g.join("n")).unwrap();
6855
    git(&["mv", "c/x.txt", "n/x.txt"]);
6856
    git(&["commit", "-qm", "move out of c"]);
6857
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6858
    let _ = run(&["merge", "-q", "side"]);
6859
    let _ = run(&[
6860
        "rm",
6861
        "-q",
6862
        "--cached",
6863
        "--ignore-unmatch",
6864
        "c/y.txt",
6865
        "c/x.txt",
6866
    ]);
6867
    let _ = std::fs::remove_dir_all(g.join("c"));
6868
    write(&g, "n/x.txt", b"x\n");
6869
    git(&["add", "-A"]);
6870
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6871
6872
    let repo = Repo::init(&root.join("o")).unwrap();
6873
    repo.import_git(&g, "main").unwrap();
6874
    let v = repo.verify_git_import(&g, "main").unwrap();
6875
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6876
    let st = repo
6877
        .load_state_history(&repo.bookmark_heads().unwrap())
6878
        .unwrap();
6879
    let view = st.tree().view();
6880
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6881
    assert!(view.entries.contains_key("n/x.txt"));
6882
}
6883
6884
/// oxygen#30, orphans: a file added on one line into a directory the other
6885
/// line removed is placed where the tree cannot show it; Git's merge keeps
6886
/// the file, and the import's merge leaves exactly one of it.
6887
#[test]
6888
fn git_import_merge_leaves_no_orphan_behind() {
6889
    hermetic();
6890
    if std::process::Command::new("git")
6891
        .arg("--version")
6892
        .output()
6893
        .is_err()
6894
    {
6895
        eprintln!("git not installed; skipping");
6896
        return;
6897
    }
6898
    let dir = tempfile::tempdir().unwrap();
6899
    let root = dir.path();
6900
    let g = root.join("src.git");
6901
    fs::create_dir_all(&g).unwrap();
6902
    let git = |args: &[&str]| {
6903
        let out = std::process::Command::new("git")
6904
            .arg("-C")
6905
            .arg(&g)
6906
            .args([
6907
                "-c",
6908
                "user.name=Grace",
6909
                "-c",
6910
                "[email protected]",
6911
                "-c",
6912
                "commit.gpgsign=false",
6913
            ])
6914
            .args(args)
6915
            .output()
6916
            .unwrap();
6917
        assert!(
6918
            out.status.success(),
6919
            "git {args:?}: {}",
6920
            String::from_utf8_lossy(&out.stderr)
6921
        );
6922
    };
6923
    git(&["init", "-q", "-b", "main"]);
6924
    write(&g, "d/f.txt", b"f\n");
6925
    write(&g, "keep.txt", b"k\n");
6926
    git(&["add", "."]);
6927
    git(&["commit", "-qm", "base"]);
6928
    git(&["checkout", "-qb", "side"]);
6929
    write(&g, "d/new.txt", b"new\n");
6930
    git(&["add", "."]);
6931
    git(&["commit", "-qm", "add into d"]);
6932
    git(&["checkout", "-q", "main"]);
6933
    git(&["rm", "-q", "d/f.txt"]);
6934
    git(&["commit", "-qm", "d goes"]);
6935
    git(&["merge", "-q", "--no-edit", "side"]);
6936
6937
    let repo = Repo::init(&root.join("o")).unwrap();
6938
    repo.import_git(&g, "main").unwrap();
6939
    let v = repo.verify_git_import(&g, "main").unwrap();
6940
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6941
    let st = repo
6942
        .load_state_history(&repo.bookmark_heads().unwrap())
6943
        .unwrap();
6944
    let view = st.tree().view();
6945
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6946
    assert!(view.entries.contains_key("d/new.txt"));
6947
}
6948
6949
/// fsck checks a change's text as the blobs it is stored in, without
6950
/// decoding it: a missing text blob is an error named for the change.
6951
#[test]
6952
fn fsck_names_a_missing_text_blob() {
6953
    hermetic();
6954
    let dir = tempfile::tempdir().unwrap();
6955
    let root = dir.path();
6956
    let repo = Repo::init(root).unwrap();
6957
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6958
    write(root, "big.txt", big.as_bytes());
6959
    let h = repo.commit("big", &[]).unwrap();
6960
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6961
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6962
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6963
        panic!("a stored text")
6964
    };
6965
    repo.store().remove_loose_for_test(&b).unwrap();
6966
    let rep = repo.fsck().unwrap();
6967
    assert!(rep.errors() > 0);
6968
    assert!(
6969
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6970
        "{:?}",
6971
        rep.problems
6972
    );
6973
}
6974
6975
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6976
/// reached with that remote's token and CA (a private subrepo then clones
6977
/// for anyone who can read the parent); another hub gets none of them.
6978
#[test]
6979
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6980
    hermetic();
6981
    let dir = tempfile::tempdir().unwrap();
6982
    let mut repo = Repo::init(dir.path()).unwrap();
6983
    repo.config
6984
        .set(
6985
            "remote.origin.url",
6986
            "https://Hub.example:7343/doomsdayone/metalgear",
6987
        )
6988
        .unwrap();
6989
    repo.config.set("remote.origin.token", "secret").unwrap();
6990
    repo.config
6991
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6992
        .unwrap();
6993
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6994
    assert_eq!(same.token.as_deref(), Some("secret"));
6995
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6996
    for other in [
6997
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6998
        "https://hub.example/doomsdayone/rstar-api",
6999
        "http://hub.example:7343/doomsdayone/rstar-api",
7000
    ] {
7001
        let o = repo.credentials_for(other);
7002
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7003
    }
7004
}
7005
7006
/// oxygen#47: a remote with no token of its own uses the user's credential
7007
/// store for its hub, and a nested checkout finds its parent's remote
7008
/// token there instead of keeping a copy.
7009
#[test]
7010
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7011
    hermetic();
7012
    let home = tempfile::tempdir().unwrap();
7013
    let dir = tempfile::tempdir().unwrap();
7014
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7015
    parent
7016
        .config
7017
        .set("remote.origin.url", "https://hub.example/o/parent")
7018
        .unwrap();
7019
    parent.save_config().unwrap();
7020
    assert_eq!(parent.remote_options("origin").token, None);
7021
    crate::credentials::Credentials::at(home.path())
7022
        .save("https://hub.example", "stored", Some("andy"), None)
7023
        .unwrap();
7024
    assert_eq!(
7025
        parent.remote_options("origin").token.as_deref(),
7026
        Some("stored")
7027
    );
7028
7029
    let empty_home = tempfile::tempdir().unwrap();
7030
    let nested = dir.path().join("deps").join("child");
7031
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7032
    child
7033
        .config
7034
        .set("remote.origin.url", "https://hub.example/o/child")
7035
        .unwrap();
7036
    child.save_config().unwrap();
7037
    assert_eq!(child.remote_options("origin").token, None);
7038
    parent
7039
        .config
7040
        .set("remote.origin.token", "checkout")
7041
        .unwrap();
7042
    parent.save_config().unwrap();
7043
    assert_eq!(
7044
        child.remote_options("origin").token.as_deref(),
7045
        Some("checkout")
7046
    );
7047
    // Another hub's checkout token is not borrowed.
7048
    child
7049
        .config
7050
        .set("remote.origin.url", "https://other.example/o/child")
7051
        .unwrap();
7052
    assert_eq!(child.remote_options("origin").token, None);
7053
}
7054
7055
#[test]
7056
fn the_metadata_cache_survives_a_torn_tail() {
7057
    hermetic();
7058
    let dir = tempfile::tempdir().unwrap();
7059
    let root = dir.path();
7060
    let repo = Repo::init(root).unwrap();
7061
    write(root, "a.txt", b"1\n");
7062
    let h = repo.commit("first", &[]).unwrap();
7063
    let meta = repo.store().get_change_meta(&h).unwrap();
7064
    let cache = repo.store().dir().join("metas");
7065
    let len = fs::metadata(&cache).unwrap().len();
7066
    assert!(len > 0, "a change read is cached");
7067
    // A torn record at the end: the cache reads up to it and cuts it off.
7068
    fs::OpenOptions::new()
7069
        .append(true)
7070
        .open(&cache)
7071
        .unwrap()
7072
        .write_all(&[7; 20])
7073
        .unwrap();
7074
    let again = Repo::open(root).unwrap();
7075
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7076
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7077
}
7078
7079
#[test]
7080
fn a_manifest_that_does_not_check_reads_as_none() {
7081
    hermetic();
7082
    let dir = tempfile::tempdir().unwrap();
7083
    let root = dir.path();
7084
    let repo = Repo::init(root).unwrap();
7085
    write(root, "a.txt", b"1\n");
7086
    repo.commit("first", &[]).unwrap();
7087
    let path = repo.manifest_path();
7088
    let mut bytes = fs::read(&path).unwrap();
7089
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7090
    let last = bytes.len() - 1;
7091
    bytes[last] ^= 1;
7092
    fs::write(&path, &bytes).unwrap();
7093
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7094
    // The next status reads the files and writes it again.
7095
    let again = Repo::open(root).unwrap();
7096
    assert!(!again.snapshot("status").unwrap().changed);
7097
    assert!(again.read_manifest().unwrap().is_some());
7098
}
7099
7100
#[test]
7101
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7102
    hermetic();
7103
    let dir = tempfile::tempdir().unwrap();
7104
    let root = dir.path();
7105
    let repo = Repo::init(root).unwrap();
7106
    write(root, "a.txt", b"1\n");
7107
    write(root, "b.txt", b"2\n");
7108
    // b.txt outside the racy window, so snapshots take it as unchanged.
7109
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7110
    fs::File::options()
7111
        .write(true)
7112
        .open(root.join("b.txt"))
7113
        .unwrap()
7114
        .set_modified(old)
7115
        .unwrap();
7116
    repo.commit("first", &[]).unwrap();
7117
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7118
    repo.snapshot_status("status").unwrap();
7119
    write(root, "a.txt", b"1\n2\n");
7120
    repo.commit("second", &[]).unwrap();
7121
    assert!(
7122
        repo.clean_by_manifest().unwrap(),
7123
        "after a commit of one file"
7124
    );
7125
    // Edited, seen by a status, edited again, then committed: the status
7126
    // left the first edit's stat, which the commit must not keep.
7127
    write(root, "a.txt", b"1\n2\n3\n");
7128
    repo.snapshot_status("status").unwrap();
7129
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7130
    repo.commit("third", &[]).unwrap();
7131
    assert!(
7132
        repo.clean_by_manifest().unwrap(),
7133
        "after an edit a status saw"
7134
    );
7135
}
7136
7137
#[test]
7138
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7139
    hermetic();
7140
    let dir = tempfile::tempdir().unwrap();
7141
    let root = dir.path();
7142
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7143
    write(root, "a.txt", b"1\n2\n");
7144
    let a = repo.commit("A", &[]).unwrap();
7145
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7146
    write(root, "a.txt", b"1\nX\n");
7147
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7148
    repo.bookmark_switch("develop", false).unwrap();
7149
    write(root, "a.txt", b"1\nY\n");
7150
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7151
    repo.bookmark_switch("main", false).unwrap();
7152
7153
    let err = repo.rebase(&c, &[d]).unwrap_err();
7154
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7155
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7156
    assert!(r.changed && r.checked_out);
7157
    let snap = repo.snapshot_status("status").unwrap();
7158
    assert!(
7159
        snap.base_snapshot.is_conflicted(),
7160
        "the conflict is in the working copy"
7161
    );
7162
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7163
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7164
7165
    write(root, "a.txt", b"1\nXY\n");
7166
    repo.commit("Resolve", &[]).unwrap();
7167
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7168
    assert!(st.contains(&c) && st.contains(&d));
7169
    let files = st.materialize().files;
7170
    assert!(!files["a.txt"].is_conflicted());
7171
    assert!(
7172
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7173
    );
7174
7175
    // A change the current bookmark does not hold is refused.
7176
    repo.bookmark_switch("develop", false).unwrap();
7177
    write(root, "b.txt", b"b\n");
7178
    let e = repo.commit("E", &[]).unwrap();
7179
    repo.bookmark_switch("main", false).unwrap();
7180
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7181
    assert!(
7182
        err.to_string().contains("not on the current bookmark"),
7183
        "{err}"
7184
    );
7185
}
7186
7187
#[test]
7188
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7189
    hermetic();
7190
    let dir = tempfile::tempdir().unwrap();
7191
    let root = dir.path();
7192
    let repo = Repo::init(root).unwrap();
7193
    write(root, "a.txt", b"a\n");
7194
    write(root, "kept.log", b"tracked\n");
7195
    repo.commit("first", &[]).unwrap();
7196
    write(root, "build.log", b"made\n");
7197
    let snap = repo.snapshot_status("status").unwrap();
7198
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7199
    // A rule written afterwards leaves the added file out again, while the
7200
    // committed one stays tracked.
7201
    write(root, ".gitignore", b"*.log\n");
7202
    let snap = repo.snapshot_status("status").unwrap();
7203
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7204
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7205
    write(root, "kept.log", b"tracked, edited\n");
7206
    let snap = repo.snapshot_status("status").unwrap();
7207
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7208
}
7209
7210
#[test]
7211
fn shed_graphs_come_back_the_same() {
7212
    hermetic();
7213
    let dir = tempfile::tempdir().unwrap();
7214
    let root = dir.path();
7215
    let repo = Repo::init(root).unwrap();
7216
    write(root, "a.txt", b"1\n2\n3\n");
7217
    write(root, "b.txt", b"x\n");
7218
    repo.commit("first", &[]).unwrap();
7219
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7220
    repo.commit("second", &[]).unwrap();
7221
    let heads = repo.bookmark_heads().unwrap();
7222
    let mut st = repo.load_state_history(&heads).unwrap();
7223
    let view = st.tree().view();
7224
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7225
        .iter()
7226
        .map(|p| view.entries[*p].node)
7227
        .collect();
7228
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7229
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7230
    assert_eq!(st.built_count(), 2);
7231
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7232
    assert_eq!((shed, st.built_count()), (2, 0));
7233
    // A later change applies on top of the shed history.
7234
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7235
    let h3 = repo.commit("third", &[]).unwrap();
7236
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7237
    st.add_known(h3, skeleton, texts);
7238
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7239
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7240
    assert_eq!(after[1], before[1]);
7241
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7242
}
7243
7244
#[test]
7245
fn many_edited_files_diff_in_parallel() {
7246
    // Enough edited files that the builder diffs them in parallel; the
7247
    // commit must hold exactly what is on disk, and a second snapshot
7248
    // must find nothing left to commit.
7249
    hermetic();
7250
    let dir = tempfile::tempdir().unwrap();
7251
    let root = dir.path();
7252
    let repo = Repo::init(root).unwrap();
7253
    let text = |i: usize, round: usize| {
7254
        let mut s = String::new();
7255
        for line in 0..50 {
7256
            if round > 0 && line % 7 == i % 7 {
7257
                s.push_str(&format!("edited {round} {i} {line}\n"));
7258
            } else {
7259
                s.push_str(&format!("file {i} line {line}\n"));
7260
            }
7261
        }
7262
        if round > 0 && i.is_multiple_of(3) {
7263
            s.push_str("appended\n");
7264
        }
7265
        s
7266
    };
7267
    for i in 0..40 {
7268
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7269
    }
7270
    repo.commit("first", &[]).unwrap();
7271
    for i in 0..40 {
7272
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7273
    }
7274
    let h = repo.commit("edit every file", &[]).unwrap();
7275
    let snap = repo.load_state(&[h]).unwrap().materialize();
7276
    for i in 0..40 {
7277
        let want = text(i, 1);
7278
        assert!(
7279
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
7280
            "d/f{i}.txt as committed"
7281
        );
7282
    }
7283
    assert!(
7284
        repo.commit("nothing", &[]).is_err(),
7285
        "nothing left to commit"
7286
    );
7287
}
7288
7289
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7290
/// is known (fetch printed "up to date" while main was behind), a change
7291
/// only fetched resolves and says where it is, and a checkout whose only
7292
/// remote is not `origin` uses that one.
7293
#[test]
7294
fn a_fetched_change_shows_as_behind_and_resolves() {
7295
    hermetic();
7296
    let dir = tempfile::tempdir().unwrap();
7297
    let root = dir.path();
7298
    let origin = Repo::init(&root.join("origin")).unwrap();
7299
    drop(origin);
7300
    let url = root.join("origin").to_string_lossy().to_string();
7301
    let a = Repo::clone(&url, &root.join("a"))
7302
        .unwrap()
7303
        .with_home(root.join("home-a"));
7304
    write(&root.join("a"), "f.txt", b"one\n");
7305
    a.commit("one", &[]).unwrap();
7306
    a.push("origin", false).unwrap();
7307
    let b = Repo::clone(&url, &root.join("b"))
7308
        .unwrap()
7309
        .with_home(root.join("home-b"));
7310
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7311
7312
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7313
    let h2 = a.commit("two", &[]).unwrap();
7314
    a.push("origin", false).unwrap();
7315
    b.fetch("origin").unwrap();
7316
    // Fetched, not pulled: one behind, the change found and placed.
7317
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7318
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7319
    assert_eq!(
7320
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7321
            .unwrap(),
7322
        h2
7323
    );
7324
    assert_eq!(
7325
        b.remote_only_location(&h2).unwrap().as_deref(),
7326
        Some("origin/main")
7327
    );
7328
    // Fetching again changes nothing: still behind, which is what the
7329
    // CLI now says rather than "up to date".
7330
    b.fetch("origin").unwrap();
7331
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7332
    b.pull("origin").unwrap();
7333
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7334
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7335
7336
    // One remote, not called origin: it is the default.
7337
    let mut c = Repo::init(&root.join("c")).unwrap();
7338
    assert_eq!(c.default_remote(), "origin");
7339
    c.config.set("remote.earth.url", &url).unwrap();
7340
    assert_eq!(c.default_remote(), "earth");
7341
    c.config.set("remote.origin.url", &url).unwrap();
7342
    assert_eq!(c.default_remote(), "origin");
7343
}
7344
7345
/// oxygen#57: a clone from a relative local path records the remote as an
7346
/// absolute path, so fetch still finds it from inside the clone.
7347
#[test]
7348
fn a_clone_from_a_relative_path_records_it_absolute() {
7349
    hermetic();
7350
    let dir = tempfile::tempdir().unwrap();
7351
    let root = dir.path();
7352
    Repo::init(&root.join("origin")).unwrap();
7353
    let rel = crate::protocol::stored_url("relative/repo");
7354
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7355
    assert_eq!(
7356
        crate::protocol::stored_url("https://hub.example/o/n"),
7357
        "https://hub.example/o/n"
7358
    );
7359
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7360
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7361
    // A bucket is kept as written: it is not a path.
7362
    assert_eq!(
7363
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7364
        "s3://bucket/prefix?profile=p"
7365
    );
7366
    let url = root.join("origin").to_string_lossy().to_string();
7367
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7368
    assert_eq!(b.config.remotes["origin"], url);
7369
    b.fetch("origin").unwrap();
7370
}
7371
7372
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7373
/// and gets its subrepos at their pins from this workspace's copies, with
7374
/// their remotes pointing where the subrepos come from.
7375
#[test]
7376
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7377
    hermetic();
7378
    let dir = tempfile::tempdir().unwrap();
7379
    let root = dir.path();
7380
    Repo::init(&root.join("lib-origin")).unwrap();
7381
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7382
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7383
        .unwrap()
7384
        .with_home(root.join("home"));
7385
    write(&root.join("lib"), "lib.txt", b"v1\n");
7386
    let l1 = lib.commit("lib v1", &[]).unwrap();
7387
    assert!(lib.push("origin", false).unwrap()[0].ok);
7388
7389
    let app_dir = root.join("app");
7390
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7391
    write(&app_dir, "main.txt", b"app\n");
7392
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7393
    app.commit("app with lib", &[]).unwrap();
7394
    // A second bookmark, and the main workspace on another.
7395
    app.bookmark_create("develop", None).unwrap();
7396
    app.bookmark_create("feature", None).unwrap();
7397
    let mut app = app;
7398
    app.bookmark_switch("feature", false).unwrap();
7399
    assert_eq!(app.config.bookmark, "feature");
7400
7401
    // The library's origin goes away: the subrepo must come from here.
7402
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7403
    let heads = app.resolve_heads("develop").unwrap();
7404
    let ws = app
7405
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7406
        .unwrap();
7407
    assert_eq!(
7408
        ws.config.bookmark, "develop",
7409
        "the new workspace is on develop"
7410
    );
7411
    assert_eq!(
7412
        app.config.bookmark, "feature",
7413
        "and this one stays on its own"
7414
    );
7415
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7416
    assert_eq!(
7417
        sub.config.remotes["origin"], lib_url,
7418
        "its origin is the subrepo's URL"
7419
    );
7420
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7421
    assert_eq!(
7422
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7423
        b"v1\n"
7424
    );
7425
}
7426
7427
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7428
/// operators and the predicates, over a small graph with two heads and
7429
/// a rename.
7430
#[test]
7431
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7432
    hermetic();
7433
    let dir = tempfile::tempdir().unwrap();
7434
    let root = dir.path();
7435
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7436
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7437
        .unwrap();
7438
    write(root, "src/a.rs", b"one\n");
7439
    let a = repo.commit("first: add a", &[]).unwrap();
7440
    write(root, "src/a.rs", b"one\ntwo\n");
7441
    let b = repo.commit("second: grow a", &[]).unwrap();
7442
    // A second head, independent of b: a new file on top of a.
7443
    repo.checkout(&[a], false, "checkout a").unwrap();
7444
    write(root, "docs/notes.md", b"notes\n");
7445
    let c = repo.commit("third: notes", &[]).unwrap();
7446
    // Back to both heads, then rename a.rs: the node keeps its identity.
7447
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7448
        .unwrap();
7449
    fs::remove_file(root.join("src/a.rs")).unwrap();
7450
    write(root, "src/z.rs", b"one\ntwo\n");
7451
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7452
    let wc = repo.working_copy().unwrap().0;
7453
    // A saved revset is checked when set.
7454
    repo.set_user_config("revset.mine", "author(me) & ::main")
7455
        .unwrap();
7456
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7457
    let set = |src: &str| -> Vec<ChangeHash> {
7458
        let mut v = repo.revset(src).unwrap().hashes;
7459
        v.sort();
7460
        v
7461
    };
7462
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7463
        let mut v = hs.to_vec();
7464
        v.sort();
7465
        v
7466
    };
7467
7468
    // Changes commute: a new file depends on nothing and the rename on the
7469
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7470
    // copy on the three heads b, c, d.
7471
    let heads = sorted(&repo.bookmark_heads().unwrap());
7472
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7473
    assert!(heads.contains(&d) && heads.contains(&c));
7474
    // Symbols and closures.
7475
    assert_eq!(set("main"), heads);
7476
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7477
    assert_eq!(set("@"), vec![wc]);
7478
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7479
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7480
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7481
    assert_eq!(
7482
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7483
        sorted(&[a, b])
7484
    );
7485
    // Ranges: what main has beyond b, and `..` forms.
7486
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7487
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7488
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7489
    // Operators and precedence: ~ binds tighter than &, & than |.
7490
    assert_eq!(
7491
        set(&format!("::main ~ #{}", d.short(12))),
7492
        sorted(&[a, b, c])
7493
    );
7494
    assert_eq!(
7495
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7496
        sorted(&[b, c])
7497
    );
7498
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7499
    // Relations.
7500
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7501
    head_deps.sort();
7502
    head_deps.dedup();
7503
    assert_eq!(set("deps(main)"), head_deps);
7504
    let on_a: Vec<ChangeHash> = [b, c, d]
7505
        .into_iter()
7506
        .filter(|h| meta(h).deps.contains(&a))
7507
        .collect();
7508
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7509
    assert_eq!(set("heads(::main)"), heads);
7510
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7511
    assert_eq!(
7512
        set(&format!(
7513
            "heads(#{} | #{} | #{})",
7514
            a.short(12),
7515
            b.short(12),
7516
            c.short(12)
7517
        )),
7518
        sorted(&[b, c])
7519
    );
7520
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7521
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7522
    assert_eq!(set("none()"), vec![]);
7523
    // Predicates: author by name, email, key prefix and `me`.
7524
    let key = repo.config.author_key.unwrap();
7525
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7526
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7527
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7528
    assert_eq!(set("author(me) & ::main").len(), 4);
7529
    assert_eq!(set("author(nobody)"), vec![]);
7530
    assert_eq!(set("description(notes)"), vec![c]);
7531
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7532
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7533
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7534
    // touches follows the node through the rename, in the current state.
7535
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7536
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7537
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7538
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7539
    // Newest first in the result order.
7540
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7541
    // The saved revset, and errors that say what is wrong.
7542
    assert_eq!(set("mine()").len(), 4);
7543
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7544
    assert!(e.contains("unknown function nosuch()"), "{e}");
7545
    let e = repo.revset("main &").unwrap_err().to_string();
7546
    assert!(e.contains("at character"), "{e}");
7547
    let e = repo.revset("zzzz").unwrap_err().to_string();
7548
    assert!(e.contains("no change matches"), "{e}");
7549
    let e = repo
7550
        .revset_with_budget("::main", std::time::Duration::ZERO)
7551
        .unwrap_err()
7552
        .to_string();
7553
    assert!(e.contains("budget"), "{e}");
7554
    // The log entries carry the bookmark's heads and the working copy.
7555
    let entries = repo.log_revset("::@").unwrap();
7556
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7557
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7558
    // push); then a signed change, a tag, and a revocation.
7559
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7560
    assert_eq!(set("signed_by(me)"), vec![]);
7561
    repo.sign_change(&d).unwrap();
7562
    assert_eq!(set("signed_by(me)"), vec![d]);
7563
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7564
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7565
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7566
    assert_eq!(set("delegated()"), vec![]);
7567
    assert_eq!(set("revoked()"), vec![]);
7568
    assert_eq!(set("attested(tag)"), vec![]);
7569
    repo.tag_create("v1", &[b], "first").unwrap();
7570
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7571
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7572
    assert_eq!(set("attested(receipt)"), vec![]);
7573
    assert_eq!(set("built(test)"), vec![]);
7574
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7575
    assert!(e.contains("tag, receipt or ref"), "{e}");
7576
    repo.revoke_identity(&key, "test").unwrap();
7577
    assert_eq!(set("revoked()"), vec![d]);
7578
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7579
}
7580
7581
#[test]
7582
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7583
    let dir = tempfile::tempdir().unwrap();
7584
    let root = dir.path();
7585
    let home = root.join("home");
7586
    // Ada's identity lives in the user file; repository `a` pins the same
7587
    // key in its own file, repository `b` names none.
7588
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7589
    let (key, _) = a
7590
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7591
        .unwrap();
7592
    a.config.set("author.key", &key.to_hex()).unwrap();
7593
    a.save_config().unwrap();
7594
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7595
    let r = a
7596
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7597
        .unwrap();
7598
    assert_eq!(
7599
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7600
        r.new.to_hex(),
7601
        "the user file follows"
7602
    );
7603
    assert_eq!(
7604
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7605
        r.new.to_hex(),
7606
        "the pinning repository follows"
7607
    );
7608
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7609
    assert_eq!(
7610
        b.config.author_key,
7611
        Some(r.new),
7612
        "a checkout without a pin follows the user file"
7613
    );
7614
    // A repository-scoped identity leaves the user file alone.
7615
    let other_home = root.join("home2");
7616
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7617
    let (ck, _) = c
7618
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7619
        .unwrap();
7620
    assert!(!other_home.join("config.toml").exists());
7621
    let r2 = c.rotate_identity().unwrap();
7622
    assert_ne!(r2.new, ck);
7623
    assert_eq!(
7624
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7625
        r2.new.to_hex()
7626
    );
7627
    assert!(
7628
        !other_home.join("config.toml").exists(),
7629
        "a repository-scoped identity stays repository-scoped"
7630
    );
7631
    // Several delegates in one rotation; a repeat is refused.
7632
    let (d1, d2) = (
7633
        SecretKey::generate().identity("D1", "d1@x", 1),
7634
        SecretKey::generate().identity("D2", "d2@x", 1),
7635
    );
7636
    let r3 = c
7637
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7638
        .unwrap();
7639
    assert_eq!(r3.identity.delegates.len(), 2);
7640
    assert!(c
7641
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7642
        .is_err());
7643
}
7644
7645
/// Two unrelated histories that both add the same file, joined by two
7646
/// independent merges on two branches, then those branches merged: Git
7647
/// merges identical additions cleanly, and the import must too (#71,
7648
/// found in VS Code's history).
7649
#[test]
7650
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7651
    // Batches of one: every merge renders apart from the state, where a
7652
    // file whose graph the state had built came out empty (#71).
7653
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7654
    hermetic();
7655
    if std::process::Command::new("git")
7656
        .arg("--version")
7657
        .output()
7658
        .is_err()
7659
    {
7660
        eprintln!("git not installed; skipping");
7661
        return;
7662
    }
7663
    let dir = tempfile::tempdir().unwrap();
7664
    let root = dir.path();
7665
    let g = root.join("src.git");
7666
    fs::create_dir_all(&g).unwrap();
7667
    let git = |args: &[&str]| -> String {
7668
        let out = std::process::Command::new("git")
7669
            .arg("-C")
7670
            .arg(&g)
7671
            .args([
7672
                "-c",
7673
                "user.name=Grace",
7674
                "-c",
7675
                "[email protected]",
7676
                "-c",
7677
                "commit.gpgsign=false",
7678
            ])
7679
            .args(args)
7680
            .output()
7681
            .unwrap();
7682
        assert!(
7683
            out.status.success(),
7684
            "git {args:?}: {}",
7685
            String::from_utf8_lossy(&out.stderr)
7686
        );
7687
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7688
    };
7689
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7690
    // History A: main.
7691
    git(&["init", "-q", "-b", "main"]);
7692
    write(&g, "gulpfile.js", text);
7693
    write(&g, "a.txt", b"a\n");
7694
    git(&["add", "."]);
7695
    git(&["commit", "-q", "-m", "A root"]);
7696
    // History B: an unrelated root adding the same file, identical.
7697
    git(&["checkout", "-q", "--orphan", "fork"]);
7698
    git(&["rm", "-q", "-r", "--cached", "."]);
7699
    for f in ["gulpfile.js", "a.txt"] {
7700
        let _ = fs::remove_file(g.join(f));
7701
    }
7702
    write(&g, "gulpfile.js", text);
7703
    write(&g, "b.txt", b"b\n");
7704
    git(&["add", "."]);
7705
    git(&["commit", "-q", "-m", "B root"]);
7706
    // Two branches from main, each joining B on its own.
7707
    git(&["checkout", "-q", "-b", "one", "main"]);
7708
    git(&[
7709
        "merge",
7710
        "-q",
7711
        "--no-ff",
7712
        "--allow-unrelated-histories",
7713
        "-m",
7714
        "join on one",
7715
        "fork",
7716
    ]);
7717
    git(&["checkout", "-q", "-b", "two", "main"]);
7718
    write(&g, "a.txt", b"a\ntwo\n");
7719
    git(&["commit", "-q", "-am", "work on two"]);
7720
    git(&[
7721
        "merge",
7722
        "-q",
7723
        "--no-ff",
7724
        "--allow-unrelated-histories",
7725
        "-m",
7726
        "join on two",
7727
        "fork",
7728
    ]);
7729
    // Then the two joins meet, and the file is reformatted after.
7730
    git(&["checkout", "-q", "main"]);
7731
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7732
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7733
    write(
7734
        &g,
7735
        "gulpfile.js",
7736
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7737
    );
7738
    git(&["commit", "-q", "-am", "after"]);
7739
7740
    let dest = root.join("dest");
7741
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7742
    repo.import_git(&g, "main").unwrap();
7743
    let v = repo.verify_git_import(&g, "main").unwrap();
7744
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7745
    assert_eq!(
7746
        fs::read(dest.join("gulpfile.js")).unwrap(),
7747
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7748
    );
7749
}
7750
7751
/// As above, but the two joins keep different copies (each branch had a
7752
/// different version when it joined), and later work edits each copy:
7753
/// the shape of VS Code's c67ef57cda90 (#71).
7754
#[test]
7755
fn git_import_joins_where_each_join_kept_a_different_copy() {
7756
    // Batches of one: every merge renders apart from the state, where a
7757
    // file whose graph the state had built came out empty (#71).
7758
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7759
    hermetic();
7760
    if std::process::Command::new("git")
7761
        .arg("--version")
7762
        .output()
7763
        .is_err()
7764
    {
7765
        eprintln!("git not installed; skipping");
7766
        return;
7767
    }
7768
    let dir = tempfile::tempdir().unwrap();
7769
    let root = dir.path();
7770
    let g = root.join("src.git");
7771
    fs::create_dir_all(&g).unwrap();
7772
    let run = |args: &[&str]| {
7773
        std::process::Command::new("git")
7774
            .arg("-C")
7775
            .arg(&g)
7776
            .args([
7777
                "-c",
7778
                "user.name=Grace",
7779
                "-c",
7780
                "[email protected]",
7781
                "-c",
7782
                "commit.gpgsign=false",
7783
            ])
7784
            .args(args)
7785
            .output()
7786
            .unwrap()
7787
    };
7788
    let git = |args: &[&str]| -> String {
7789
        let out = run(args);
7790
        assert!(
7791
            out.status.success(),
7792
            "git {args:?}: {}",
7793
            String::from_utf8_lossy(&out.stderr)
7794
        );
7795
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7796
    };
7797
    git(&["init", "-q", "-b", "main"]);
7798
    write(
7799
        &g,
7800
        "gulpfile.js",
7801
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7802
    );
7803
    git(&["add", "."]);
7804
    git(&["commit", "-q", "-m", "A root"]);
7805
    write(
7806
        &g,
7807
        "gulpfile.js",
7808
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7809
    );
7810
    git(&["commit", "-q", "-am", "whitespace"]);
7811
    git(&["checkout", "-q", "--orphan", "fork"]);
7812
    git(&["rm", "-q", "-r", "--cached", "."]);
7813
    let _ = fs::remove_file(g.join("gulpfile.js"));
7814
    write(
7815
        &g,
7816
        "gulpfile.js",
7817
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7818
    );
7819
    git(&["add", "."]);
7820
    git(&["commit", "-q", "-m", "B root"]);
7821
    // Branch one joins B keeping main's copy; branch two keeps B's.
7822
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7823
        git(&["checkout", "-q", "-b", branch, "main"]);
7824
        let _ = run(&[
7825
            "merge",
7826
            "-q",
7827
            "--no-ff",
7828
            "--allow-unrelated-histories",
7829
            "-m",
7830
            "join",
7831
            "fork",
7832
        ]);
7833
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7834
        git(&["add", "gulpfile.js"]);
7835
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7836
    }
7837
    // Each branch then edits its copy.
7838
    git(&["checkout", "-q", "one"]);
7839
    write(
7840
        &g,
7841
        "gulpfile.js",
7842
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7843
    );
7844
    git(&["commit", "-q", "-am", "tslint on one"]);
7845
    git(&["checkout", "-q", "two"]);
7846
    write(
7847
        &g,
7848
        "gulpfile.js",
7849
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7850
    );
7851
    write(&g, "extra.txt", b"x\n");
7852
    write(&g, "more.txt", b"m\n");
7853
    git(&["add", "."]);
7854
    git(&["commit", "-q", "-am", "fmt on two"]);
7855
    // They meet: resolved by hand.
7856
    git(&["checkout", "-q", "one"]);
7857
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7858
    write(
7859
        &g,
7860
        "gulpfile.js",
7861
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7862
    );
7863
    git(&["add", "gulpfile.js"]);
7864
    git(&["commit", "-q", "-m", "merge two into one"]);
7865
7866
    let dest = root.join("dest");
7867
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7868
    repo.import_git(&g, "one").unwrap();
7869
    let v = repo.verify_git_import(&g, "one").unwrap();
7870
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7871
}
7872
7873
/// oxygen#68: on a store that is not this disk's directory, the operation
7874
/// head is the store's reference record, moved by compare-and-swap. Two
7875
/// handles recording from the same head both get through, merged; a swap
7876
/// from a stale version is refused; a second repository cannot start on a
7877
/// store that already holds one.
7878
#[test]
7879
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
7880
    use crate::strata::{MemoryStore, Store as _};
7881
    let backend = std::sync::Arc::new(MemoryStore::new());
7882
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
7883
    let dir = tempfile::tempdir().unwrap();
7884
    let a = Repo::init(dir.path()).unwrap();
7885
    assert!(
7886
        !dir.path().join(".oxy/ops/head").exists(),
7887
        "the head is not a file"
7888
    );
7889
    let (h0, op0) = a.head_op().unwrap();
7890
    let record = backend
7891
        .read_ref(HEAD_RECORD)
7892
        .unwrap()
7893
        .expect("the head is the store's record");
7894
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
7895
7896
    let b = Repo::open(dir.path()).unwrap();
7897
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
7898
    let mut va = op0.view.clone();
7899
    va.bookmarks.insert("from-a".into(), state);
7900
    let mut vb = op0.view.clone();
7901
    vb.bookmarks.insert("from-b".into(), state);
7902
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
7903
    assert_eq!(b.head_ref().unwrap(), rb);
7904
    // a recorded from h0 too: the head moved, so the two are merged.
7905
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
7906
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
7907
    assert_eq!(head, ra);
7908
    assert!(
7909
        op.command.ends_with("(merged with a concurrent operation)"),
7910
        "{}",
7911
        op.command
7912
    );
7913
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
7914
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
7915
7916
    // A swap from a version that is no longer current moves nothing.
7917
    let (h, v) = a.read_head().unwrap();
7918
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
7919
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
7920
    assert_eq!(a.head_ref().unwrap(), rb);
7921
7922
    let other = tempfile::tempdir().unwrap();
7923
    let err = Repo::init(other.path())
7924
        .err()
7925
        .expect("the store already holds a log")
7926
        .to_string();
7927
    assert!(
7928
        err.contains("already holds a repository's operation log"),
7929
        "{err}"
7930
    );
7931
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
7932
}
7933
7934
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
7935
/// objects and operation head there, with `.oxy/cache` in front: it works
7936
/// as one on disk does, reopens, and survives losing its cache.
7937
#[test]
7938
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
7939
    hermetic();
7940
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
7941
        return;
7942
    }
7943
    let dir = tempfile::tempdir().unwrap();
7944
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
7945
    let url = format!("dir://{}", bucket.display());
7946
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
7947
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
7948
    write(&root, "a.txt", b"one\n");
7949
    let h1 = repo.commit("First", &[]).unwrap();
7950
    write(&root, "a.txt", b"one\ntwo\n");
7951
    let h2 = repo.commit("Second", &[]).unwrap();
7952
    assert!(
7953
        !root.join(".oxy/ops/head").exists(),
7954
        "the head is in the store"
7955
    );
7956
    assert!(bucket.join("ops/head").is_file());
7957
    assert!(root.join(".oxy/cache").is_dir());
7958
    drop(repo);
7959
7960
    // Reopened, and again with no cache at all: everything comes from the store.
7961
    for drop_cache in [false, true] {
7962
        if drop_cache {
7963
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
7964
        }
7965
        let repo = Repo::open(&root).unwrap();
7966
        let log: Vec<String> = repo
7967
            .op_log()
7968
            .unwrap()
7969
            .into_iter()
7970
            .map(|(_, op)| op.command)
7971
            .collect();
7972
        assert!(log.len() >= 3, "{log:?}");
7973
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
7974
        let heads = repo
7975
            .store()
7976
            .get_state(&repo.view().unwrap().bookmarks["main"])
7977
            .unwrap()
7978
            .heads;
7979
        assert_eq!(heads, vec![h2]);
7980
        assert_eq!(
7981
            repo.load_state(&heads).unwrap().materialize().files.len(),
7982
            1
7983
        );
7984
    }
7985
7986
    // A second repository cannot start on the same store.
7987
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
7988
        .err()
7989
        .unwrap()
7990
        .to_string();
7991
    assert!(
7992
        err.contains("already holds a repository's operation log"),
7993
        "{err}"
7994
    );
7995
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
7996
        .err()
7997
        .unwrap()
7998
        .to_string();
7999
    assert!(err.contains("cannot open that kind of store"), "{err}");
8000
}
8001
8002
/// oxygen#75: the prompt's quick check agrees with status in a repository
8003
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8004
/// another state, clean again once that pin is committed. (It compared the
8005
/// subrepo's directory as if it were a file, so it was always dirty.)
8006
#[test]
8007
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8008
    hermetic();
8009
    let dir = tempfile::tempdir().unwrap();
8010
    let root = dir.path();
8011
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8012
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8013
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8014
        .unwrap()
8015
        .with_home(root.join("home"));
8016
    write(&root.join("lib"), "lib.txt", b"v1\n");
8017
    lib.commit("lib v1", &[]).unwrap();
8018
    assert!(lib.push("origin", false).unwrap()[0].ok);
8019
    let app_dir = root.join("app");
8020
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8021
    write(&app_dir, "main.txt", b"app\n");
8022
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8023
    app.commit("app with lib", &[]).unwrap();
8024
    // Out of the racy window, so the stat-only path decides.
8025
    std::thread::sleep(std::time::Duration::from_millis(2100));
8026
    let reopen = || Repo::open(&app_dir).unwrap();
8027
    assert_eq!(
8028
        reopen().quick_dirty().unwrap(),
8029
        Some(false),
8030
        "clean, as status says"
8031
    );
8032
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8033
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8034
    nested.commit("lib v2", &[]).unwrap();
8035
    assert_eq!(
8036
        reopen().quick_dirty().unwrap(),
8037
        Some(true),
8038
        "the subrepo moved"
8039
    );
8040
    reopen().commit("pin lib v2", &[]).unwrap();
8041
    std::thread::sleep(std::time::Duration::from_millis(2100));
8042
    assert_eq!(
8043
        reopen().quick_dirty().unwrap(),
8044
        Some(false),
8045
        "the new pin is committed"
8046
    );
8047
}
8048
8049
#[test]
8050
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8051
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8052
    hermetic();
8053
    let dir = tempfile::tempdir().unwrap();
8054
    let root = dir.path();
8055
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8056
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8057
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8058
        .unwrap()
8059
        .with_home(root.join("home"));
8060
    write(&root.join("lib"), "lib.txt", b"v1\n");
8061
    lib.commit("lib v1", &[]).unwrap();
8062
    assert!(lib.push("origin", false).unwrap()[0].ok);
8063
    let app_dir = root.join("app");
8064
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8065
    write(
8066
        &app_dir,
8067
        ".oxymodules",
8068
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8069
    );
8070
    let unpinned = app.unpinned_modules().unwrap();
8071
    assert_eq!(unpinned.len(), 1);
8072
    assert_eq!(unpinned[0].0, "libs/lib");
8073
    assert_eq!(unpinned[0].1.url, lib_url);
8074
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8075
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8076
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8077
}
8078
8079
#[test]
8080
fn the_bookmark_revset_function_names_only_bookmarks() {
8081
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8082
    hermetic();
8083
    let dir = tempfile::tempdir().unwrap();
8084
    let repo = Repo::init(dir.path()).unwrap();
8085
    write(dir.path(), "a.txt", b"a\n");
8086
    let a = repo.commit("A", &[]).unwrap();
8087
    write(dir.path(), "b.txt", b"b\n");
8088
    let b = repo.commit("B", &[]).unwrap();
8089
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8090
    heads.sort();
8091
    let mut want = repo.bookmark_heads().unwrap();
8092
    want.sort();
8093
    assert_eq!(heads, want);
8094
    assert!(heads.contains(&b));
8095
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8096
    // A change prefix is a symbol, not a bookmark.
8097
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8098
    assert!(repo.revset(&prefix).is_ok());
8099
    let e = repo
8100
        .revset(&format!("bookmark({prefix})"))
8101
        .unwrap_err()
8102
        .to_string();
8103
    assert!(e.contains("no such bookmark"), "{e}");
8104
}
8105
8106
#[test]
8107
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8108
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8109
    // pinning the subrepo, and the nested repository on disk at that pin.
8110
    hermetic();
8111
    let dir = tempfile::tempdir().unwrap();
8112
    let root = dir.path();
8113
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8114
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8115
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8116
        .unwrap()
8117
        .with_home(root.join("home"));
8118
    write(&root.join("lib"), "lib.txt", b"v1\n");
8119
    lib.commit("lib v1", &[]).unwrap();
8120
    assert!(lib.push("origin", false).unwrap()[0].ok);
8121
    let app_dir = root.join("app");
8122
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8123
    write(&app_dir, "main.txt", b"app\n");
8124
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8125
    // The stale state: registered in .oxymodules, never pinned.
8126
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8127
    app.commit("initial", &[]).unwrap();
8128
    let stale = app.bookmark_heads().unwrap();
8129
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8130
    app.commit("pin lib", &[]).unwrap();
8131
    let newer = app.bookmark_heads().unwrap();
8132
    app.checkout(&stale, false, "test").unwrap();
8133
    write(&app_dir, "notes.txt", b"mine\n");
8134
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8135
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8136
    assert!(app_dir.join("notes.txt").exists());
8137
}
8138
8139
#[test]
8140
fn a_bookmark_only_behind_its_remote_catches_up() {
8141
    // oxygen#74: switch takes the remote's state rather than a stale one.
8142
    hermetic();
8143
    let dir = tempfile::tempdir().unwrap();
8144
    let root = dir.path();
8145
    let _origin = Repo::init(&root.join("origin")).unwrap();
8146
    let url = root.join("origin").to_string_lossy().to_string();
8147
    let one = Repo::clone(&url, &root.join("one"))
8148
        .unwrap()
8149
        .with_home(root.join("home"));
8150
    write(&root.join("one"), "a.txt", b"a\n");
8151
    one.commit("A", &[]).unwrap();
8152
    assert!(one.push("origin", false).unwrap()[0].ok);
8153
    let two = Repo::clone(&url, &root.join("two"))
8154
        .unwrap()
8155
        .with_home(root.join("home"));
8156
    write(&root.join("two"), "b.txt", b"b\n");
8157
    two.commit("B", &[]).unwrap();
8158
    assert!(two.push("origin", false).unwrap()[0].ok);
8159
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8160
    one.fetch("origin").unwrap();
8161
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8162
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8163
    // Local work the remote lacks: left alone.
8164
    write(&root.join("one"), "c.txt", b"c\n");
8165
    one.commit("C", &[]).unwrap();
8166
    write(&root.join("two"), "d.txt", b"d\n");
8167
    two.commit("D", &[]).unwrap();
8168
    assert!(two.push("origin", false).unwrap()[0].ok);
8169
    one.fetch("origin").unwrap();
8170
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8171
}
8172
8173
#[test]
8174
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8175
    // oxygen#83: remotes earth and gcs, origin removed.
8176
    hermetic();
8177
    let dir = tempfile::tempdir().unwrap();
8178
    let root = dir.path();
8179
    let _up = Repo::init(&root.join("up")).unwrap();
8180
    let url = root.join("up").to_string_lossy().to_string();
8181
    let other = Repo::clone(&url, &root.join("other"))
8182
        .unwrap()
8183
        .with_home(root.join("home"));
8184
    write(&root.join("other"), "a.txt", b"a\n");
8185
    other.commit("a", &[]).unwrap();
8186
    assert!(other.push("origin", false).unwrap()[0].ok);
8187
    let mut one = Repo::clone(&url, &root.join("one"))
8188
        .unwrap()
8189
        .with_home(root.join("home"));
8190
    one.config.set("remote.earth.url", &url).unwrap();
8191
    one.config.set("remote.gcs.url", &url).unwrap();
8192
    one.config.set("remote.origin.url", "").unwrap();
8193
    one.save_config().unwrap();
8194
    write(&root.join("other"), "b.txt", b"b\n");
8195
    other.commit("b", &[]).unwrap();
8196
    assert!(other.push("origin", false).unwrap()[0].ok);
8197
    one.fetch("earth").unwrap();
8198
    let b = one
8199
        .bookmarks()
8200
        .unwrap()
8201
        .into_iter()
8202
        .find(|b| b.name == "main")
8203
        .unwrap();
8204
    assert_eq!(
8205
        (b.remote.as_deref(), b.behind),
8206
        (Some("earth"), Some(1)),
8207
        "a stale origin copy is not used"
8208
    );
8209
    assert_eq!(
8210
        one.default_remote(),
8211
        "origin",
8212
        "no default chosen among several"
8213
    );
8214
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8215
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8216
    one.config.set("core.remote", "earth").unwrap();
8217
    assert_eq!(one.default_remote(), "earth");
8218
}
8219
8220
#[test]
8221
fn a_missing_author_identity_says_how_to_fix_it() {
8222
    // oxygen#82: an agent home's author.key naming an identity the
8223
    // repository does not hold.
8224
    hermetic();
8225
    let dir = tempfile::tempdir().unwrap();
8226
    let mut repo = Repo::init(dir.path()).unwrap();
8227
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8228
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8229
    let e = repo.identity(&missing).unwrap_err().to_string();
8230
    assert!(
8231
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8232
        "{e}"
8233
    );
8234
    assert!(e.contains("this repository's config"), "{e}");
8235
}
8236
8237
#[test]
8238
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8239
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8240
    // the working copy, a pull with nothing new left it there, and status
8241
    // said "clean".
8242
    hermetic();
8243
    let dir = tempfile::tempdir().unwrap();
8244
    let root = dir.path();
8245
    let _up = Repo::init(&root.join("up")).unwrap();
8246
    let url = root.join("up").to_string_lossy().to_string();
8247
    let other = Repo::clone(&url, &root.join("other"))
8248
        .unwrap()
8249
        .with_home(root.join("home"));
8250
    write(&root.join("other"), "a.txt", b"a\n");
8251
    other.commit("a", &[]).unwrap();
8252
    assert!(other.push("origin", false).unwrap()[0].ok);
8253
    let one = Repo::clone(&url, &root.join("one"))
8254
        .unwrap()
8255
        .with_home(root.join("home"));
8256
    write(&root.join("other"), "b.txt", b"b\n");
8257
    other.commit("b", &[]).unwrap();
8258
    assert!(other.push("origin", false).unwrap()[0].ok);
8259
    one.fetch("origin").unwrap();
8260
    // The bookmark moves; the working copy does not.
8261
    let theirs = one.resolve_heads("origin/main").unwrap();
8262
    one.bookmark_set("main", &theirs).unwrap();
8263
    assert!(!root.join("one/b.txt").exists());
8264
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8265
    let r = one.pull("origin").unwrap();
8266
    assert!(
8267
        !r.changed && r.checked_out,
8268
        "nothing new, but the working copy caught up"
8269
    );
8270
    assert!(root.join("one/b.txt").exists());
8271
    assert_eq!(one.working_copy_behind().unwrap(), None);
8272
}
8273
8274
#[test]
8275
fn touched_nodes_cache_answers_as_the_changes_do() {
8276
    hermetic();
8277
    let dir = tempfile::tempdir().unwrap();
8278
    let repo = Repo::init(dir.path()).unwrap();
8279
    write(dir.path(), "a.txt", b"one\n");
8280
    write(dir.path(), "b.txt", b"x\n");
8281
    repo.snapshot("t").unwrap();
8282
    let c1 = repo.commit("first", &[]).unwrap();
8283
    write(dir.path(), "b.txt", b"y\n");
8284
    repo.snapshot("t").unwrap();
8285
    repo.commit("b only", &[]).unwrap();
8286
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8287
    write(dir.path(), "c.txt", b"one\ntwo\n");
8288
    repo.snapshot("t").unwrap();
8289
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8290
    // Uncommitted work, so the working copy touches a file too.
8291
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8292
    repo.snapshot("t").unwrap();
8293
8294
    let path = dir.path().join(".oxy/index/touched");
8295
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8296
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8297
    assert!(path.exists(), "the first query writes the cache");
8298
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8299
    assert_eq!(cold, warm, "the cache answers as the changes do");
8300
    let (wc, _) = repo.working_copy().unwrap();
8301
    assert_eq!(
8302
        cold,
8303
        vec![wc, c3, c1],
8304
        "renames followed, the working copy included"
8305
    );
8306
8307
    // Working-copy changes are not kept: they are replaced by every snapshot.
8308
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8309
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8310
    assert!(cached.contains(&c1) && cached.contains(&c3));
8311
8312
    // A damaged cache is ignored, not trusted.
8313
    let mut bytes = fs::read(&path).unwrap();
8314
    let last = bytes.len() - 40;
8315
    bytes[last] ^= 1;
8316
    fs::write(&path, &bytes).unwrap();
8317
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8318
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8319
    assert_eq!(hashes(touches), vec![c3, c1]);
8320
}
8321
8322
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8323
/// file back where it was leave two placements at one place, which the
8324
/// tree shows as one file. Removing it, and then its directory, retires
8325
/// both, so no copy is left under a directory that is gone.
8326
#[test]
8327
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8328
    hermetic();
8329
    if std::process::Command::new("git")
8330
        .arg("--version")
8331
        .output()
8332
        .is_err()
8333
    {
8334
        eprintln!("git not installed; skipping");
8335
        return;
8336
    }
8337
    let dir = tempfile::tempdir().unwrap();
8338
    let root = dir.path();
8339
    let g = root.join("src.git");
8340
    fs::create_dir_all(&g).unwrap();
8341
    let git = |args: &[&str]| {
8342
        let out = std::process::Command::new("git")
8343
            .arg("-C")
8344
            .arg(&g)
8345
            .args([
8346
                "-c",
8347
                "user.name=Grace",
8348
                "-c",
8349
                "[email protected]",
8350
                "-c",
8351
                "commit.gpgsign=false",
8352
            ])
8353
            .args(args)
8354
            .output()
8355
            .unwrap();
8356
        assert!(
8357
            out.status.success(),
8358
            "git {args:?}: {}",
8359
            String::from_utf8_lossy(&out.stderr)
8360
        );
8361
    };
8362
    git(&["init", "-q", "-b", "main"]);
8363
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8364
    write(&g, "keep.txt", b"k\n");
8365
    git(&["add", "."]);
8366
    git(&["commit", "-qm", "base"]);
8367
    fs::create_dir_all(g.join("d/sub")).unwrap();
8368
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8369
    git(&["commit", "-qm", "into sub"]);
8370
    git(&["checkout", "-qb", "side"]);
8371
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8372
    git(&["commit", "-qm", "back, on side"]);
8373
    git(&["checkout", "-q", "main"]);
8374
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8375
    git(&["commit", "-qm", "back, on main"]);
8376
    git(&["merge", "-q", "--no-edit", "side"]);
8377
    git(&["rm", "-rq", "d"]);
8378
    git(&["commit", "-qm", "d goes"]);
8379
8380
    let repo = Repo::init(&root.join("o")).unwrap();
8381
    repo.import_git(&g, "main").unwrap();
8382
    let v = repo.verify_git_import(&g, "main").unwrap();
8383
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8384
    let st = repo
8385
        .load_state_history(&repo.bookmark_heads().unwrap())
8386
        .unwrap();
8387
    let view = st.tree().view();
8388
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8389
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8390
}
8391
8392
/// oxygen#94: a state index's file histories are read, and checked by
8393
/// their own hashes, only when a file is built. One found damaged is an
8394
/// error that says so, the index is removed, and the next read rebuilds it.
8395
#[test]
8396
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8397
    hermetic();
8398
    let dir = tempfile::tempdir().unwrap();
8399
    let repo = Repo::init(dir.path()).unwrap();
8400
    for i in 0..6 {
8401
        write(
8402
            dir.path(),
8403
            &format!("f{i}.txt"),
8404
            format!("one {i}\n").as_bytes(),
8405
        );
8406
    }
8407
    repo.snapshot("t").unwrap();
8408
    repo.commit("first", &[]).unwrap();
8409
    for i in 0..6 {
8410
        write(
8411
            dir.path(),
8412
            &format!("f{i}.txt"),
8413
            format!("one {i}\ntwo\n").as_bytes(),
8414
        );
8415
    }
8416
    repo.snapshot("t").unwrap();
8417
    repo.commit("second", &[]).unwrap();
8418
    let want: Vec<Vec<u8>> = (0..6)
8419
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8420
        .collect();
8421
    // The index of the working copy's base, holding every file's history
8422
    // (a few changes behind, an index is replayed onto, not rewritten).
8423
    let (_, wc) = repo.working_copy().unwrap();
8424
    let base = repo.load_state_history(&wc.deps).unwrap();
8425
    repo.write_state_index(&wc.deps, &base);
8426
    for (i, w) in want.iter().enumerate() {
8427
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8428
    }
8429
    let index = repo.state_indexes();
8430
    assert!(!index.is_empty(), "a state index was written");
8431
    // The histories are last in the file: damage the last of them.
8432
    let mut bytes = fs::read(&index[0]).unwrap();
8433
    let last = bytes.len() - 1;
8434
    bytes[last] ^= 0x40;
8435
    fs::write(&index[0], &bytes).unwrap();
8436
8437
    let reads: Vec<_> = (0..6)
8438
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8439
        .collect();
8440
    let damaged: Vec<String> = reads
8441
        .iter()
8442
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8443
        .collect();
8444
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8445
    assert!(
8446
        damaged[0].contains("state index was damaged")
8447
            && damaged[0].contains("run the command again"),
8448
        "{}",
8449
        damaged[0]
8450
    );
8451
    // Every file reads right again, from an index rebuilt from history.
8452
    for (i, w) in want.iter().enumerate() {
8453
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8454
    }
8455
}
8456
8457
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8458
/// objects alone and in dependency order, and the last moves the bookmark.
8459
/// The remote ends with every change and the same state, and says how each
8460
/// part went.
8461
#[test]
8462
fn a_long_push_goes_in_parts() {
8463
    hermetic();
8464
    let dir = tempfile::tempdir().unwrap();
8465
    let root = dir.path();
8466
    let origin = root.join("origin");
8467
    Repo::init_bare_unbound(&origin).unwrap();
8468
    let main = root.join("main");
8469
    let mut repo = Repo::init(&main).unwrap();
8470
    repo.config
8471
        .set("remote.origin.url", &origin.to_string_lossy())
8472
        .unwrap();
8473
    // One byte: every change is a part of its own.
8474
    repo.config.set("push.batch-bytes", "1").unwrap();
8475
    repo.save_config().unwrap();
8476
    for i in 0..6 {
8477
        write(
8478
            &main,
8479
            &format!("f{i}.txt"),
8480
            format!("file {i}\n").as_bytes(),
8481
        );
8482
        repo.commit(&format!("c{i}"), &[]).unwrap();
8483
    }
8484
    let mut parts = Vec::new();
8485
    let results = repo
8486
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8487
        .unwrap();
8488
    assert!(
8489
        results.iter().any(|r| r.ok && r.name == "main"),
8490
        "{results:?}"
8491
    );
8492
    assert_eq!(parts.len(), 6, "{parts:?}");
8493
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8494
8495
    let remote = Repo::open(&origin).unwrap();
8496
    let heads = repo.bookmark_heads().unwrap();
8497
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8498
    assert_eq!(
8499
        remote.log_state(&heads).unwrap().len(),
8500
        repo.log_state(&heads).unwrap().len()
8501
    );
8502
    // A push of objects alone reports how it went, as `objects`.
8503
    let got = remote
8504
        .receive_push(Bundle::default(), vec![], None, vec![])
8505
        .unwrap();
8506
    assert_eq!(got.len(), 1);
8507
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8508
}
8509
8510
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8511
/// own commits (Git author email = its email, any case) with its key, and
8512
/// leaves anyone else's with the zero key; the history verifies as before.
8513
#[test]
8514
fn git_import_claims_your_own_commits() {
8515
    hermetic();
8516
    if std::process::Command::new("git")
8517
        .arg("--version")
8518
        .output()
8519
        .is_err()
8520
    {
8521
        eprintln!("git not installed; skipping");
8522
        return;
8523
    }
8524
    let dir = tempfile::tempdir().unwrap();
8525
    let root = dir.path();
8526
    let g = root.join("src.git");
8527
    fs::create_dir_all(&g).unwrap();
8528
    let git = |who: &str, args: &[&str]| {
8529
        let (name, email) = who.split_once(' ').unwrap();
8530
        let out = std::process::Command::new("git")
8531
            .arg("-C")
8532
            .arg(&g)
8533
            .args([
8534
                "-c",
8535
                &format!("user.name={name}"),
8536
                "-c",
8537
                &format!("user.email={email}"),
8538
                "-c",
8539
                "commit.gpgsign=false",
8540
            ])
8541
            .args(args)
8542
            .output()
8543
            .unwrap();
8544
        assert!(
8545
            out.status.success(),
8546
            "git {args:?}: {}",
8547
            String::from_utf8_lossy(&out.stderr)
8548
        );
8549
    };
8550
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8551
    write(&g, "a.txt", b"a\n");
8552
    git("Grace [email protected]", &["add", "."]);
8553
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8554
    write(&g, "b.txt", b"b\n");
8555
    git("Ada [email protected]", &["add", "."]);
8556
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8557
8558
    let mut repo = Repo::init(&root.join("o")).unwrap();
8559
    let (key, _) = repo
8560
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8561
        .unwrap();
8562
    repo.config.set("git.claim", "true").unwrap();
8563
    repo.save_config().unwrap();
8564
    let repo = Repo::open(&root.join("o")).unwrap();
8565
    repo.import_git(&g, "main").unwrap();
8566
    let v = repo.verify_git_import(&g, "main").unwrap();
8567
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8568
    let heads = repo.bookmark_heads().unwrap();
8569
    let by_message: std::collections::HashMap<String, KeyId> = repo
8570
        .log_state(&heads)
8571
        .unwrap()
8572
        .into_iter()
8573
        .map(|e| {
8574
            (
8575
                e.change.message.lines().next().unwrap_or("").to_string(),
8576
                e.change.author,
8577
            )
8578
        })
8579
        .collect();
8580
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8581
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8582
}
8583
8584
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8585
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8586
#[test]
8587
fn removing_a_remote_leaves_nothing_of_it() {
8588
    hermetic();
8589
    let dir = tempfile::tempdir().unwrap();
8590
    let origin = dir.path().join("origin");
8591
    Repo::init_bare_unbound(&origin).unwrap();
8592
    let main = dir.path().join("main");
8593
    let mut repo = Repo::init(&main).unwrap();
8594
    repo.config
8595
        .set("remote.origin.url", &origin.to_string_lossy())
8596
        .unwrap();
8597
    repo.config
8598
        .set("remote.origin.token", "secret-ish")
8599
        .unwrap();
8600
    repo.config
8601
        .set("remote.keep.url", &origin.to_string_lossy())
8602
        .unwrap();
8603
    repo.save_config().unwrap();
8604
    write(&main, "a.txt", b"a\n");
8605
    repo.commit("a", &[]).unwrap();
8606
    assert!(repo.push("origin", false).unwrap()[0].ok);
8607
    assert!(
8608
        repo.view().unwrap().remotes.contains_key("origin"),
8609
        "a tracking bookmark"
8610
    );
8611
8612
    repo.remove_remote("origin").unwrap();
8613
    let again = Repo::open(&main).unwrap();
8614
    assert!(
8615
        !again
8616
            .config
8617
            .repo_layer()
8618
            .keys()
8619
            .any(|k| k.starts_with("remote.origin.")),
8620
        "{:?}",
8621
        again.config.repo_layer()
8622
    );
8623
    assert!(!again.config.remotes.contains_key("origin"));
8624
    assert!(
8625
        !again.view().unwrap().remotes.contains_key("origin"),
8626
        "its tracking bookmarks go"
8627
    );
8628
    assert!(
8629
        again.config.remotes.contains_key("keep"),
8630
        "another remote stays"
8631
    );
8632
    let mut again = again;
8633
    assert!(
8634
        again.remove_remote("origin").is_err(),
8635
        "a second removal is refused"
8636
    );
8637
}
8638
8639
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
8640
/// unreachable from history, so gc prunes it, unless the host names it:
8641
/// then it and its chunks stay, and it reads back whole.
8642
#[test]
8643
fn gc_keeps_the_blobs_a_host_names() {
8644
    hermetic();
8645
    let dir = tempfile::tempdir().unwrap();
8646
    let repo = Repo::init(dir.path()).unwrap();
8647
    write(dir.path(), "a.txt", b"a\n");
8648
    repo.commit("a", &[]).unwrap();
8649
    // Large enough to be several chunks.
8650
    let body: Vec<u8> = (0..400_000u32)
8651
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
8652
        .collect();
8653
    let kept = repo.store_blob(&body).unwrap();
8654
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
8655
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
8656
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
8657
    assert!(!repo.store().has(&lost), "not named: pruned");
8658
    repo.gc(true).unwrap();
8659
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
8660
}
8661
8662
/// oxygen#99: undo in one workspace undoes that workspace's last command,
8663
/// never another workspace's, says what it undid, and goes further back
8664
/// when run again.
8665
#[test]
8666
fn undo_is_scoped_to_its_workspace() {
8667
    hermetic();
8668
    let dir = tempfile::tempdir().unwrap();
8669
    let root = dir.path().join("main");
8670
    let a = Repo::init(&root).unwrap();
8671
    write(&root, "base.txt", b"base\n");
8672
    let base = a.commit("base", &[]).unwrap();
8673
    a.bookmark_create("feature", None).unwrap();
8674
    let ws_dir = dir.path().join("ws");
8675
    let heads = a.resolve_heads("feature").unwrap();
8676
    let b = a
8677
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
8678
        .unwrap();
8679
8680
    // A commits on main, then B commits on feature: B's is the newest.
8681
    write(&root, "a.txt", b"a\n");
8682
    let ca = a.commit("from a", &[]).unwrap();
8683
    write(&ws_dir, "b.txt", b"b\n");
8684
    let cb = b.commit("from b", &[]).unwrap();
8685
8686
    // A's undo undoes A's commit and leaves B's.
8687
    let u = a.undo().unwrap();
8688
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8689
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
8690
    assert!(!u.changes.is_empty());
8691
    let view = a.view().unwrap();
8692
    // (Independent changes commute, so a bookmark's heads may hold base too.)
8693
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
8694
    assert!(
8695
        a.heads_of(&view, "feature").unwrap().contains(&cb),
8696
        "B's commit stands"
8697
    );
8698
    assert!(
8699
        a.store().get_change(&ca).is_ok(),
8700
        "the change itself is still in the store"
8701
    );
8702
    // A's working copy was clean, so its files followed; B's are untouched.
8703
    assert!(!root.join("a.txt").exists());
8704
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
8705
    assert!(ws_dir.join("b.txt").exists());
8706
8707
    // B's undo still finds B's own commit, under A's undo.
8708
    let u = b.undo().unwrap();
8709
    assert_eq!(u.command, "oxy commit -m \"from b\"");
8710
    assert!(!b
8711
        .heads_of(&b.view().unwrap(), "feature")
8712
        .unwrap()
8713
        .contains(&cb));
8714
    assert_eq!(
8715
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
8716
        vec![base],
8717
        "A's undo stands"
8718
    );
8719
8720
    // A's next undo goes past the commit it already undid, to adding B's
8721
    // workspace: refused, since B has worked there since.
8722
    let e = a.undo().unwrap_err().to_string();
8723
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
8724
}
8725
8726
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
8727
/// own commit's head, and the other workspace's head stays.
8728
#[test]
8729
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
8730
    hermetic();
8731
    let dir = tempfile::tempdir().unwrap();
8732
    let root = dir.path().join("main");
8733
    let a = Repo::init(&root).unwrap();
8734
    write(&root, "base.txt", b"base\n");
8735
    a.commit("base", &[]).unwrap();
8736
    let ws_dir = dir.path().join("ws");
8737
    let b = a.workspace_add(&ws_dir, None).unwrap();
8738
    write(&root, "a.txt", b"a\n");
8739
    let ca = a.commit("from a", &[]).unwrap();
8740
    write(&ws_dir, "b.txt", b"b\n");
8741
    let cb = b.commit("from b", &[]).unwrap();
8742
    let u = a.undo().unwrap();
8743
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8744
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
8745
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
8746
}
8747
8748
/// oxygen#99: an undo that would also take back what another workspace
8749
/// did since to the same bookmark is refused, naming it.
8750
#[test]
8751
fn undo_refuses_to_take_back_another_workspaces_work() {
8752
    hermetic();
8753
    let dir = tempfile::tempdir().unwrap();
8754
    let root = dir.path().join("main");
8755
    let a = Repo::init(&root).unwrap();
8756
    write(&root, "base.txt", b"base\n");
8757
    a.commit("base", &[]).unwrap();
8758
    let ws_dir = dir.path().join("ws");
8759
    let b = a.workspace_add(&ws_dir, None).unwrap();
8760
    // Both on main: A commits, then B builds on it, editing A's file.
8761
    write(&root, "a.txt", b"a\n");
8762
    a.commit("from a", &[]).unwrap();
8763
    let heads = b.resolve_heads("main").unwrap();
8764
    b.checkout(&heads, false, "oxy checkout").unwrap();
8765
    write(&ws_dir, "a.txt", b"a, then b\n");
8766
    b.commit("from b", &[]).unwrap();
8767
    let e = a.undo().unwrap_err().to_string();
8768
    assert!(
8769
        e.contains("bookmark main") && e.contains("builds on"),
8770
        "{e}"
8771
    );
8772
    assert!(e.contains("oxy op restore"), "{e}");
8773
}
8774
8775
/// oxygen#99: undoing a commit that was already pushed says so: the remote
8776
/// still has it.
8777
#[test]
8778
fn undo_says_when_the_commit_was_pushed() {
8779
    hermetic();
8780
    let dir = tempfile::tempdir().unwrap();
8781
    let root = dir.path();
8782
    Repo::init(&root.join("origin")).unwrap();
8783
    let url = root.join("origin").to_string_lossy().to_string();
8784
    let repo = Repo::clone(&url, &root.join("work"))
8785
        .unwrap()
8786
        .with_home(root.join("home"));
8787
    write(&root.join("work"), "a.txt", b"a\n");
8788
    repo.commit("a", &[]).unwrap();
8789
    assert!(repo.push("origin", false).unwrap()[0].ok);
8790
    // The push itself is passed over: the remote keeps what it was sent.
8791
    let u = repo.undo().unwrap();
8792
    assert_eq!(u.command, "oxy commit -m \"a\"");
8793
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
8794
}