OXYGENHUB
# 27825564bc16 oxygen / crates / oxy-core / src / repo / tests.rs
329.9 KiB · Rust · last changed Release 0.4.6: agents push as themselves 18 days ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
use crate::protocol::SignedPolicy;
5
use crate::repo::{BisectStep, Selection};
6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
137
    assert!(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
            removed_paths: vec!["bin.dat".into()],
436
            conflicted: false,
437
            notes: vec![],
438
            lacks: 1,
439
        }
440
    );
441
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
442
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
443
    assert!(!root.join("bin.dat").exists());
444
    let (_, wc) = repo.working_copy().unwrap();
445
    assert_eq!(wc.deps, vec![h1]);
446
    assert!(
447
        !repo.snapshot("status").unwrap().changed,
448
        "checkout leaves a clean working copy"
449
    );
450
    // The bookmark still points at h2.
451
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
452
453
    // Dirty working copy refuses without --discard.
454
    write(root, "a.txt", b"dirty\n");
455
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
456
    let r = repo
457
        .checkout(&[h2], true, "oxy checkout --discard")
458
        .unwrap();
459
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
460
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
461
    assert!(!root.join("sub").exists(), "empty directories are pruned");
462
    assert_eq!(r.removed, 1);
463
    assert!(!repo.snapshot("status").unwrap().changed);
464
465
    // Refuses to write through a symlinked directory.
466
    #[cfg(unix)]
467
    {
468
        fs::remove_dir_all(root.join("sub")).ok();
469
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
470
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
471
    }
472
}
473
474
#[test]
475
fn large_files_are_chunked_and_read_back() {
476
    hermetic();
477
    let dir = tempfile::tempdir().unwrap();
478
    let repo = Repo::init(dir.path()).unwrap();
479
    let mut big = vec![0u8; 700 * 1024];
480
    for (i, b) in big.iter_mut().enumerate() {
481
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
482
    }
483
    let r = repo.store_blob(&big).unwrap();
484
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
485
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
486
    assert_eq!(repo.read_blob(&r).unwrap(), big);
487
    assert_eq!(Repo::blob_ref(&big), r);
488
}
489
490
#[test]
491
fn clone_push_pull_with_seals_and_attestations() {
492
    hermetic();
493
    let dir = tempfile::tempdir().unwrap();
494
    let root = dir.path();
495
    let origin_path = root.join("origin");
496
    let origin = Repo::init(&origin_path).unwrap();
497
    let origin_url = origin_path.to_string_lossy().to_string();
498
499
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
500
    let mut a = Repo::clone(&origin_url, &root.join("a"))
501
        .unwrap()
502
        .with_home(root.join("home-a"));
503
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
504
    let (key_a, _) = a
505
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
506
        .unwrap();
507
    write(&root.join("a"), "f.txt", b"a\n");
508
    let h1 = a.commit("first", &[]).unwrap();
509
    let results = a.push("origin", false).unwrap();
510
    assert!(results[0].ok, "{}", results[0].reason);
511
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
512
    // The change was sealed at push and the reference attested.
513
    assert!(
514
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
515
    );
516
    assert_eq!(
517
        origin.verify_change(&h1).unwrap(),
518
        SignatureStatus::Unsigned
519
    );
520
    let serial_of = |att: &SignedAttest| match att.attest.body {
521
        AttestBody::Ref { serial, .. } => serial,
522
        _ => unreachable!(),
523
    };
524
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
525
    // A bookmark new to the remote starts at the clock (past any deleted
526
    // namesake's serial); later updates count up from there.
527
    let first = serial_of(&att);
528
    assert!(first > 1_000_000_000_000, "{first}");
529
    let again = a.push("origin", false).unwrap();
530
    assert!(again[0].ok && again[0].reason.contains("up to date"));
531
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
532
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
533
534
    // B clones and sees the file and the seal.
535
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
536
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
537
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
538
    assert!(matches!(
539
        b.authenticate_change(&h1).unwrap(),
540
        SignatureStatus::Valid { sealed: true, .. }
541
    ));
542
543
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
544
    write(&root.join("b"), "f.txt", b"a\nb\n");
545
    let h2 = b.commit("second", &[]).unwrap();
546
    assert!(b.push("origin", false).unwrap()[0].ok);
547
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
548
549
    // A commits an independent change; push is refused until A pulls.
550
    write(&root.join("a"), "g.txt", b"g\n");
551
    let h3 = a.commit("third", &[]).unwrap();
552
    assert!(a.push("origin", false).is_err());
553
    let pr = a.pull("origin").unwrap();
554
    assert!(pr.changed && pr.checked_out);
555
    let mut want = vec![h2, h3];
556
    want.sort();
557
    assert_eq!(pr.heads, want);
558
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
559
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
560
    let results = a.push("origin", false).unwrap();
561
    assert!(results[0].ok, "{}", results[0].reason);
562
    let mut origin_heads = origin.bookmark_heads().unwrap();
563
    origin_heads.sort();
564
    assert_eq!(origin_heads, want);
565
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
566
    assert_eq!(serial_of(&att), first + 1);
567
568
    // B pulls and ends up identical.
569
    let pr = b.pull("origin").unwrap();
570
    assert_eq!(pr.heads, want);
571
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
572
    assert!(!b.snapshot("status").unwrap().changed);
573
574
    // Concurrent edits of the same line: the union is a reified conflict.
575
    write(&root.join("a"), "f.txt", b"a\nA\n");
576
    a.commit("a-edit", &[]).unwrap();
577
    a.push("origin", false).unwrap();
578
    write(&root.join("b"), "f.txt", b"a\nB\n");
579
    b.commit("b-edit", &[]).unwrap();
580
    let pr = b.pull("origin").unwrap();
581
    assert!(pr.changed && pr.checked_out);
582
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
583
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
584
    write(&root.join("b"), "f.txt", b"a\nAB\n");
585
    let hr = b.commit("resolve", &[]).unwrap();
586
    assert_eq!(
587
        b.store().get_change(&hr).unwrap().kind,
588
        ChangeKind::Resolution
589
    );
590
    assert!(b.push("origin", false).unwrap()[0].ok);
591
    a.pull("origin").unwrap();
592
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
593
    // The resolution depends on the conflicting edits, but nothing depends
594
    // on "third" (it only added g.txt), so it stays a head beside it.
595
    let mut want = vec![hr, h3];
596
    want.sort();
597
    assert_eq!(a.bookmark_heads().unwrap(), want);
598
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
599
}
600
601
#[test]
602
fn receive_push_rejects_bad_updates() {
603
    hermetic();
604
    let dir = tempfile::tempdir().unwrap();
605
    let root = dir.path();
606
    let origin = Repo::init(&root.join("origin")).unwrap();
607
    let url = root.join("origin").to_string_lossy().to_string();
608
    let mut a = Repo::clone(&url, &root.join("a"))
609
        .unwrap()
610
        .with_home(root.join("home"));
611
    let (key, _) = a
612
        .create_identity("Ada", "a@b", IdentityScope::Repo)
613
        .unwrap();
614
    write(&root.join("a"), "f.txt", b"x\n");
615
    let h1 = a.commit("one", &[]).unwrap();
616
    assert!(a.push("origin", false).unwrap()[0].ok);
617
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
618
    let s1 = origin
619
        .store()
620
        .put_state(&StateObject::new(vec![h1]))
621
        .unwrap();
622
623
    // Missing head.
624
    let ghost = origin
625
        .store()
626
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
627
        .unwrap();
628
    let r = origin
629
        .receive_push(
630
            Bundle::default(),
631
            vec![RefUpdate {
632
                name: "main".into(),
633
                old_state: s1,
634
                new_state: ghost,
635
                force: false,
636
                attestation: None,
637
            }],
638
            None,
639
            vec![],
640
        )
641
        .unwrap();
642
    assert!(
643
        !r[0].ok && r[0].reason.contains("missing"),
644
        "{}",
645
        r[0].reason
646
    );
647
648
    // Stale old_state.
649
    let r = origin
650
        .receive_push(
651
            Bundle::default(),
652
            vec![RefUpdate {
653
                name: "main".into(),
654
                old_state: empty,
655
                new_state: s1,
656
                force: false,
657
                attestation: None,
658
            }],
659
            None,
660
            vec![],
661
        )
662
        .unwrap();
663
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
664
665
    // Non-fast-forward without force is refused; with force it passes.
666
    let r = origin
667
        .receive_push(
668
            Bundle::default(),
669
            vec![RefUpdate {
670
                name: "main".into(),
671
                old_state: s1,
672
                new_state: empty,
673
                force: false,
674
                attestation: None,
675
            }],
676
            None,
677
            vec![],
678
        )
679
        .unwrap();
680
    assert!(
681
        !r[0].ok && r[0].reason.contains("fast-forward"),
682
        "{}",
683
        r[0].reason
684
    );
685
    let r = origin
686
        .receive_push(
687
            Bundle::default(),
688
            vec![RefUpdate {
689
                name: "main".into(),
690
                old_state: s1,
691
                new_state: empty,
692
                force: true,
693
                attestation: None,
694
            }],
695
            None,
696
            vec![],
697
        )
698
        .unwrap();
699
    assert!(r[0].ok);
700
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
701
702
    // Attestation with a stale serial is a rollback and is refused.
703
    let sa = a
704
        .sign_attest(&Attest {
705
            repo: a.id().unwrap(),
706
            hlc: Hlc::now(),
707
            body: AttestBody::Ref {
708
                name: "main".into(),
709
                old_state: empty,
710
                new_state: s1,
711
                serial: 1,
712
            },
713
        })
714
        .unwrap();
715
    let r = origin
716
        .receive_push(
717
            Bundle::default(),
718
            vec![RefUpdate {
719
                name: "main".into(),
720
                old_state: empty,
721
                new_state: s1,
722
                force: false,
723
                attestation: Some(sa.clone()),
724
            }],
725
            None,
726
            vec![],
727
        )
728
        .unwrap();
729
    assert!(
730
        !r[0].ok && r[0].reason.contains("serial"),
731
        "{}",
732
        r[0].reason
733
    );
734
    // An attestation for a different update is refused too.
735
    let sa2 = a
736
        .sign_attest(&Attest {
737
            repo: a.id().unwrap(),
738
            hlc: Hlc::now(),
739
            body: AttestBody::Ref {
740
                name: "main".into(),
741
                old_state: s1,
742
                new_state: empty,
743
                serial: 5,
744
            },
745
        })
746
        .unwrap();
747
    let r = origin
748
        .receive_push(
749
            Bundle::default(),
750
            vec![RefUpdate {
751
                name: "main".into(),
752
                old_state: empty,
753
                new_state: s1,
754
                force: false,
755
                attestation: Some(sa2),
756
            }],
757
            None,
758
            vec![],
759
        )
760
        .unwrap();
761
    assert!(
762
        !r[0].ok && r[0].reason.contains("describe"),
763
        "{}",
764
        r[0].reason
765
    );
766
    let _ = key;
767
}
768
769
#[test]
770
fn user_config_supplies_defaults_and_clones_sign() {
771
    hermetic();
772
    let dir = tempfile::tempdir().unwrap();
773
    let root = dir.path();
774
    let home = root.join("home");
775
    let origin = Repo::init(&root.join("origin")).unwrap();
776
    let url = root.join("origin").to_string_lossy().to_string();
777
778
    // Identity at user scope: the repository file stays free of author keys.
779
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
780
    let (key, _) = a
781
        .create_identity("Ada", "[email protected]", IdentityScope::User)
782
        .unwrap();
783
    assert!(!a.config.repo_layer().contains_key("author.key"));
784
    assert_eq!(a.config.author_key, Some(key));
785
    assert!(home.join("config.toml").exists());
786
    a.set_user_config("core.sign", "change").unwrap();
787
    assert!(a.config.sign_changes);
788
789
    // Repository settings override user settings and are the only ones saved.
790
    a.config.set("core.sign", "seal").unwrap();
791
    a.save_config().unwrap();
792
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
793
    assert!(!again.config.sign_changes);
794
    assert_eq!(again.config.author_key, Some(key));
795
    assert_eq!(
796
        read_config_file(&root.join("a/.oxy/config"))
797
            .unwrap()
798
            .get("core.sign")
799
            .map(String::as_str),
800
        Some("seal")
801
    );
802
803
    // A fresh clone made by this user signs with the user-level identity,
804
    // even though the clone's store has never seen the identity object.
805
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
806
    assert!(b.config.sign_changes);
807
    write(&root.join("b"), "f.txt", b"f\n");
808
    let h = b.commit("signed from a clone", &[]).unwrap();
809
    assert!(
810
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
811
    );
812
    assert!(b.push("origin", false).unwrap()[0].ok);
813
    assert!(matches!(
814
        origin.verify_change(&h).unwrap(),
815
        SignatureStatus::Valid { .. }
816
    ));
817
}
818
819
#[test]
820
fn format1_repositories_are_migrated_on_open() {
821
    hermetic();
822
    use crate::oplog::{Format1Op, Format1View};
823
    let dir = tempfile::tempdir().unwrap();
824
    let root = dir.path();
825
    let repo = Repo::init(root).unwrap();
826
    write(root, "a.txt", b"a\n");
827
    let h1 = repo.commit("one", &[]).unwrap();
828
    let (wc_hash, _) = repo.working_copy().unwrap();
829
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
830
    let mut v1 = Format1View::default();
831
    v1.bookmarks.insert("main".into(), vec![]);
832
    v1.workspaces.insert(repo.workspace(), wc_hash);
833
    let init = Format1Op {
834
        parents: vec![],
835
        hlc: Hlc::default(),
836
        command: "oxy init".into(),
837
        view: v1.clone(),
838
    };
839
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
840
    v1.bookmarks.insert("main".into(), vec![h1]);
841
    let commit = Format1Op {
842
        parents: vec![init_ref],
843
        hlc: Hlc::default(),
844
        command: "oxy commit".into(),
845
        view: v1,
846
    };
847
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
848
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
849
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
850
    drop(repo);
851
852
    let repo = Repo::open(root).unwrap();
853
    assert_eq!(
854
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
855
        FORMAT_LINE
856
    );
857
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
858
    let ops = repo.op_log().unwrap();
859
    assert_eq!(
860
        ops.iter()
861
            .map(|(_, o)| o.command.as_str())
862
            .collect::<Vec<_>>(),
863
        ["oxy commit", "oxy init"]
864
    );
865
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
866
    assert!(!repo.snapshot("status").unwrap().changed);
867
    // Reopening again is a no-op.
868
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
869
}
870
871
#[test]
872
fn undo_skips_snapshot_operations() {
873
    hermetic();
874
    let dir = tempfile::tempdir().unwrap();
875
    let root = dir.path();
876
    let repo = Repo::init(root).unwrap();
877
    write(root, "a.txt", b"a\n");
878
    let h1 = repo.commit("a", &[]).unwrap();
879
    // A later command snapshots new edits on top of the commit.
880
    write(root, "b.txt", b"b\n");
881
    let s = repo.snapshot("oxy status").unwrap();
882
    assert!(s.changed);
883
    assert!(repo.head_op().unwrap().1.is_snapshot());
884
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
885
    // Undo must undo the commit, not the snapshot.
886
    repo.undo().unwrap();
887
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
888
    let s = repo.snapshot("oxy status").unwrap();
889
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
890
    assert_eq!(
891
        paths,
892
        ["a.txt", "b.txt"],
893
        "both files are back in the working copy"
894
    );
895
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
896
    // Only snapshots remain above `init`, so there is nothing left to undo.
897
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
898
    assert!(repo.undo().is_err());
899
}
900
901
#[test]
902
fn independent_changes_commute_and_make_multiple_heads() {
903
    hermetic();
904
    let dir = tempfile::tempdir().unwrap();
905
    let root = dir.path();
906
    let repo = Repo::init(root).unwrap();
907
    write(root, "a.txt", b"a\n");
908
    let h1 = repo.commit("a", &[]).unwrap();
909
    write(root, "b.txt", b"b\n");
910
    let h2 = repo.commit("b", &[]).unwrap();
911
    let c2 = repo.store().get_change(&h2).unwrap();
912
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
913
    let mut heads = repo.bookmark_heads().unwrap();
914
    heads.sort();
915
    let mut want = vec![h1, h2];
916
    want.sort();
917
    assert_eq!(heads, want);
918
    // Editing a.txt depends on h1 only.
919
    write(root, "a.txt", b"a\na2\n");
920
    let h3 = repo.commit("a2", &[]).unwrap();
921
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
922
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
923
    assert_eq!(heads, [h2, h3].into_iter().collect());
924
    // Explicit dependency.
925
    write(root, "c.txt", b"c\n");
926
    let h4 = repo.commit("c", &[h2]).unwrap();
927
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
928
}
929
930
#[test]
931
fn mode_change_and_text_binary_switch() {
932
    hermetic();
933
    let dir = tempfile::tempdir().unwrap();
934
    let root = dir.path();
935
    let repo = Repo::init(root).unwrap();
936
    write(root, "run.sh", b"#!/bin/sh\n");
937
    repo.commit("add script", &[]).unwrap();
938
    #[cfg(unix)]
939
    {
940
        use std::os::unix::fs::PermissionsExt;
941
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
942
        let s = repo.snapshot("status").unwrap();
943
        assert_eq!(
944
            statuses(&s),
945
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
946
        );
947
        let h = repo.commit("exec", &[]).unwrap();
948
        let snap = repo.load_state(&[h]).unwrap().materialize();
949
        assert!(snap.files["run.sh"].mode.exec);
950
    }
951
    // Text → binary → text.
952
    write(root, "run.sh", b"\0binary");
953
    let h = repo.commit("binary", &[]).unwrap();
954
    let snap = repo.load_state(&[h]).unwrap().materialize();
955
    assert!(snap.files["run.sh"].mode.opaque);
956
    write(root, "run.sh", b"text again\n");
957
    let h = repo.commit("text", &[]).unwrap();
958
    let snap = repo.load_state(&[h]).unwrap().materialize();
959
    assert!(!snap.files["run.sh"].mode.opaque);
960
    assert!(
961
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
962
    );
963
    assert!(!snap.is_conflicted());
964
}
965
966
/// oxygen#87: a binary file given new contents and the executable bit in
967
/// one commit kept the contents and lost the bit.
968
#[cfg(unix)]
969
#[test]
970
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
971
    use std::os::unix::fs::PermissionsExt;
972
    hermetic();
973
    let dir = tempfile::tempdir().unwrap();
974
    let root = dir.path();
975
    let repo = Repo::init(root).unwrap();
976
    write(root, "tool.exe", b"MZ\0one");
977
    repo.commit("add", &[]).unwrap();
978
    write(root, "tool.exe", b"MZ\0two");
979
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
980
    let h = repo.commit("update and +x", &[]).unwrap();
981
    let snap = repo.load_state(&[h]).unwrap().materialize();
982
    let f = &snap.files["tool.exe"];
983
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
984
    assert!(
985
        repo.snapshot("status").unwrap().statuses.is_empty(),
986
        "nothing left to commit"
987
    );
988
}
989
990
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
991
/// key whose certificate an issuer gave pushes when the policy grants its
992
/// subject, and a fetch accepts what it attested; an expired certificate,
993
/// or a subject the policy does not grant, may not move the bookmark.
994
#[test]
995
fn a_certified_key_pushes_under_a_subject_grant() {
996
    use crate::cert::{Certificate, SignedCertificate};
997
    use crate::identity::Scope;
998
    hermetic();
999
    let dir = tempfile::tempdir().unwrap();
1000
    let root = dir.path();
1001
    let _origin = Repo::init(&root.join("origin")).unwrap();
1002
    let url = root.join("origin").to_string_lossy().to_string();
1003
    let mut a = Repo::clone(&url, &root.join("a"))
1004
        .unwrap()
1005
        .with_home(root.join("home-a"));
1006
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1007
        .unwrap();
1008
    write(&root.join("a"), "a.txt", b"a\n");
1009
    a.commit("a", &[]).unwrap();
1010
    a.policy_init().unwrap();
1011
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1012
    let hub_sk = SecretKey::generate();
1013
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1014
    a.policy_grant_subject(
1015
        "agent:claude@ada",
1016
        hub.clone(),
1017
        Scope::CHANGES | Scope::REFS,
1018
        None,
1019
    )
1020
    .unwrap();
1021
    assert!(a
1022
        .push("origin", false)
1023
        .unwrap()
1024
        .iter()
1025
        .any(|r| r.name == "policy" && r.ok));
1026
1027
    let now = Hlc::now().wall_ms;
1028
    // An agent repository whose key the hub certified for `subject`, from
1029
    // `from` to `to`.
1030
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1031
        let mut r = Repo::clone(&url, &root.join(name))
1032
            .unwrap()
1033
            .with_home(root.join(format!("home-{name}")));
1034
        let (_, id) = r
1035
            .create_identity(name, "[email protected]", IdentityScope::User)
1036
            .unwrap();
1037
        let cert = SignedCertificate::sign(
1038
            Certificate {
1039
                key: id,
1040
                issuer: hub.hash(),
1041
                subject: subject.into(),
1042
                claims: vec![],
1043
                scope: Scope::CHANGES | Scope::REFS,
1044
                not_before: from,
1045
                expires: to,
1046
                grant: None,
1047
            },
1048
            &hub,
1049
            &hub_sk,
1050
        );
1051
        r.store().put_identity(&hub).unwrap();
1052
        r.store().put_certificate(&cert).unwrap();
1053
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1054
        r.commit("work", &[]).unwrap();
1055
        r
1056
    };
1057
1058
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1059
    let r = claude.push("origin", false).unwrap();
1060
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1061
    // Ada's fetch accepts the bookmark the certified key attested.
1062
    a.pull("origin").unwrap();
1063
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1064
        .store()
1065
        .get_change(h)
1066
        .map(|c| c.message == "work")
1067
        .unwrap_or(false)));
1068
1069
    // Step 4c: a host with an acceptor key records when it accepted the
1070
    // certified update and serves it; a fetch checks the certificate at
1071
    // that time only when the certificate's issuer signed it for exactly
1072
    // this attestation, else at the attestation's own time.
1073
    let host = Repo::open(&root.join("origin"))
1074
        .unwrap()
1075
        .with_acceptor(hub.clone(), hub_sk.clone());
1076
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1077
    host.record_acceptance(&attest_ref).unwrap();
1078
    let served = host.remote_refs().unwrap();
1079
    let acc = served
1080
        .refs
1081
        .iter()
1082
        .find(|r| r.name == "main")
1083
        .unwrap()
1084
        .accepted
1085
        .clone()
1086
        .expect("served with the refs");
1087
    let signer = sa.sigs[0].key;
1088
    assert_eq!(
1089
        a.certified_time(&signer, &sa, Some(&acc)),
1090
        acc.attest.hlc.wall_ms
1091
    );
1092
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1093
    let stranger_sk = SecretKey::generate();
1094
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1095
    let mut forged = acc.clone();
1096
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1097
    assert_eq!(
1098
        a.certified_time(&signer, &sa, Some(&forged)),
1099
        sa.attest.hlc.wall_ms,
1100
        "not the issuer's"
1101
    );
1102
    let mut elsewhere = acc.clone();
1103
    elsewhere.attest.body = AttestBody::Accepted {
1104
        attest: ObjectRef([7; 32]),
1105
    };
1106
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1107
    assert_eq!(
1108
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1109
        sa.attest.hlc.wall_ms,
1110
        "another attestation's"
1111
    );
1112
    a.pull("origin").unwrap();
1113
    // gc keeps the acceptance with the attestation.
1114
    host.gc(true).unwrap();
1115
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1116
1117
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1118
    let r = late.push("origin", false).unwrap();
1119
    assert!(
1120
        !r[0].ok && r[0].reason.contains("may not update"),
1121
        "an expired certificate: {r:?}"
1122
    );
1123
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1124
    let r = other.push("origin", false).unwrap();
1125
    assert!(
1126
        !r[0].ok && r[0].reason.contains("may not update"),
1127
        "a subject not granted: {r:?}"
1128
    );
1129
}
1130
1131
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1132
/// subject the author granted, seals changes in the author's name; with
1133
/// no grant, a stranger's, or one that had ended, it is neither the
1134
/// author nor a delegate.
1135
#[test]
1136
fn a_certified_key_acts_for_its_author_under_a_grant() {
1137
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1138
    use crate::identity::{Identity, Scope};
1139
    hermetic();
1140
    let dir = tempfile::tempdir().unwrap();
1141
    let root = dir.path();
1142
    let _origin = Repo::init(&root.join("origin")).unwrap();
1143
    let url = root.join("origin").to_string_lossy().to_string();
1144
    let mut a = Repo::clone(&url, &root.join("a"))
1145
        .unwrap()
1146
        .with_home(root.join("home-a"));
1147
    let (ada, _) = a
1148
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1149
        .unwrap();
1150
    write(&root.join("a"), "a.txt", b"a\n");
1151
    a.commit("a", &[]).unwrap();
1152
    a.policy_init().unwrap();
1153
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1154
    let hub_sk = SecretKey::generate();
1155
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1156
    a.policy_grant_subject(
1157
        "agent:claude@ada",
1158
        hub.clone(),
1159
        Scope::CHANGES | Scope::REFS,
1160
        None,
1161
    )
1162
    .unwrap();
1163
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1164
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1165
    let ada_id = a.identity(&ada).unwrap();
1166
1167
    let now = Hlc::now().wall_ms;
1168
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1169
        SignedGrant::sign(
1170
            Grant {
1171
                grantor: by.hash(),
1172
                subject: "agent:claude@ada".into(),
1173
                issuer: hub.hash(),
1174
                scope: Scope::CHANGES | Scope::SEAL,
1175
                not_before: from,
1176
                expires: to,
1177
            },
1178
            by,
1179
            sk,
1180
        )
1181
    };
1182
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1183
    // certified (with `g` inside) the signer.
1184
    let agent = |name: &str, g: Option<SignedGrant>| {
1185
        let mut r = Repo::clone(&url, &root.join(name))
1186
            .unwrap()
1187
            .with_home(root.join(format!("home-{name}")));
1188
        let (key, id) = r
1189
            .create_identity(name, "[email protected]", IdentityScope::User)
1190
            .unwrap();
1191
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1192
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1193
        let cert = SignedCertificate::sign(
1194
            Certificate {
1195
                key: id,
1196
                issuer: hub.hash(),
1197
                subject: "agent:claude@ada".into(),
1198
                claims: vec![],
1199
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1200
                not_before: now - 60_000,
1201
                expires: now + 600_000,
1202
                grant: g,
1203
            },
1204
            &hub,
1205
            &hub_sk,
1206
        );
1207
        r.store().put_identity(&hub).unwrap();
1208
        r.store().put_certificate(&cert).unwrap();
1209
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1210
        let h = r.commit("work", &[]).unwrap();
1211
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1212
        (r, key, h)
1213
    };
1214
1215
    let (claude, key, h) = agent(
1216
        "claude",
1217
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1218
    );
1219
    let r = claude.push("origin", false).unwrap();
1220
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1221
    let host = Repo::open(&root.join("origin")).unwrap();
1222
    assert!(
1223
        matches!(
1224
            host.authenticate_change(&h).unwrap(),
1225
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
1226
        ),
1227
        "named by its certificate's subject"
1228
    );
1229
    a.pull("origin").unwrap();
1230
    assert!(matches!(
1231
        a.authenticate_change(&h).unwrap(),
1232
        SignatureStatus::Valid { key: k, .. } if k == key
1233
    ));
1234
1235
    let (none, _, _) = agent("none", None);
1236
    let r = none.push("origin", false).unwrap();
1237
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1238
    let mallory_sk = SecretKey::generate();
1239
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1240
    let (stranger, _, _) = agent(
1241
        "stranger",
1242
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1243
    );
1244
    let r = stranger.push("origin", false).unwrap();
1245
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1246
    let (ended, _, eh) = agent(
1247
        "ended",
1248
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1249
    );
1250
    let r = ended.push("origin", false).unwrap();
1251
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1252
    assert!(matches!(
1253
        ended.authenticate_change(&eh).unwrap(),
1254
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1255
    ));
1256
}
1257
1258
#[test]
1259
fn trust_policy_governs_pushes_and_fetches() {
1260
    hermetic();
1261
    let dir = tempfile::tempdir().unwrap();
1262
    let root = dir.path();
1263
    let origin = Repo::init(&root.join("origin")).unwrap();
1264
    let url = root.join("origin").to_string_lossy().to_string();
1265
1266
    // A is the root. Before the policy, an unsigned push from B is fine.
1267
    let mut a = Repo::clone(&url, &root.join("a"))
1268
        .unwrap()
1269
        .with_home(root.join("home-a"));
1270
    let (key_a, _) = a
1271
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1272
        .unwrap();
1273
    let mut b = Repo::clone(&url, &root.join("b"))
1274
        .unwrap()
1275
        .with_home(root.join("home-b"));
1276
    write(&root.join("b"), "b.txt", b"b\n");
1277
    b.commit("unsigned before policy", &[]).unwrap();
1278
    assert!(b.push("origin", false).unwrap()[0].ok);
1279
1280
    // A creates the policy and pushes it; origin now enforces it.
1281
    write(&root.join("a"), "a.txt", b"a\n");
1282
    a.commit("a", &[]).unwrap();
1283
    let sp = a.policy_init().unwrap();
1284
    assert_eq!(sp.policy.serial, 1);
1285
    a.pull("origin").unwrap();
1286
    let results = a.push("origin", false).unwrap();
1287
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1288
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1289
1290
    // B pulls the policy. Without an identity B cannot push at all.
1291
    b.pull("origin").unwrap();
1292
    assert!(
1293
        b.current_policy().unwrap().is_some(),
1294
        "the policy arrived with the fetch"
1295
    );
1296
    assert!(b.push("origin", false).is_err());
1297
    // With an identity the policy does not list, the push is rejected by origin.
1298
    let (key_b, id_b) = b
1299
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1300
        .unwrap();
1301
    write(&root.join("b"), "b.txt", b"b2\n");
1302
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1303
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1304
    let r = b.push("origin", false).unwrap();
1305
    assert!(
1306
        !r[0].ok && r[0].reason.contains("may not update"),
1307
        "{:?}",
1308
        r
1309
    );
1310
1311
    // A grants B (identity handed over as a file) and publishes the policy.
1312
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1313
    assert_eq!(sp.policy.serial, 2);
1314
    let r = a.push("origin", false).unwrap();
1315
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1316
    // B must fetch the new policy before pushing.
1317
    assert!(b
1318
        .push("origin", false)
1319
        .unwrap_or_else(|e| vec![RefResult {
1320
            name: "main".into(),
1321
            ok: false,
1322
            reason: e.to_string()
1323
        }])
1324
        .iter()
1325
        .all(|x| !x.ok));
1326
    b.pull("origin").unwrap();
1327
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1328
    let r = b.push("origin", false).unwrap();
1329
    assert!(r[0].ok, "{:?}", r);
1330
    // Origin verified B's change under the policy.
1331
    let heads = origin.bookmark_heads().unwrap();
1332
    for h in &heads {
1333
        let c = origin.store().get_change(h).unwrap();
1334
        if c.author == key_b {
1335
            origin
1336
                .change_allowed(
1337
                    h,
1338
                    &origin.current_policy().unwrap().unwrap().1.policy,
1339
                    "main",
1340
                )
1341
                .unwrap();
1342
        }
1343
    }
1344
1345
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1346
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1347
    forged.serial = 3;
1348
    forged.roots = vec![key_b];
1349
    let fh = forged.hash();
1350
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1351
    let forged = SignedPolicy {
1352
        policy: forged,
1353
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1354
    };
1355
    let r = origin
1356
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1357
        .unwrap();
1358
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1359
    let stale = a.current_policy().unwrap().unwrap().1;
1360
    let mut old = stale.clone();
1361
    old.policy.serial = 1;
1362
    let r = origin
1363
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1364
        .unwrap();
1365
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1366
1367
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1368
    a.pull("origin").unwrap();
1369
    a.policy_revoke(&key_b).unwrap();
1370
    let r = a.push("origin", false).unwrap();
1371
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1372
    b.pull("origin").unwrap();
1373
    write(&root.join("b"), "b.txt", b"b3\n");
1374
    b.commit("b3", &[]).unwrap();
1375
    let r = b.push("origin", false).unwrap();
1376
    assert!(!r[0].ok, "{:?}", r);
1377
1378
    // A clone by a third party receives and verifies everything.
1379
    let c = Repo::clone(&url, &root.join("c"))
1380
        .unwrap()
1381
        .with_home(root.join("home-c"));
1382
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1383
    assert!(c
1384
        .current_policy()
1385
        .unwrap()
1386
        .unwrap()
1387
        .1
1388
        .policy
1389
        .roots
1390
        .contains(&key_a));
1391
    assert!(!c.snapshot("status").unwrap().changed);
1392
}
1393
1394
/// oxygen#66: a gc says what it is doing, phase by phase.
1395
#[test]
1396
fn gc_reports_its_phases() {
1397
    hermetic();
1398
    let dir = tempfile::tempdir().unwrap();
1399
    let repo = Repo::init(dir.path()).unwrap();
1400
    for i in 0..3 {
1401
        write(
1402
            dir.path(),
1403
            &format!("f{i}.txt"),
1404
            format!("{i}\n").as_bytes(),
1405
        );
1406
        repo.commit(&format!("c{i}"), &[]).unwrap();
1407
    }
1408
    let mut phases = Vec::new();
1409
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1410
        .unwrap();
1411
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1412
    assert!(
1413
        phases.iter().any(|p| p.starts_with("pruning")),
1414
        "{phases:?}"
1415
    );
1416
    assert!(
1417
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1418
        "{phases:?}"
1419
    );
1420
    assert!(
1421
        phases
1422
            .iter()
1423
            .any(|p| p.starts_with("writing the index of ")),
1424
        "{phases:?}"
1425
    );
1426
}
1427
1428
#[test]
1429
fn gc_packs_objects_and_history_still_works() {
1430
    hermetic();
1431
    let dir = tempfile::tempdir().unwrap();
1432
    let root = dir.path();
1433
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1434
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1435
        .unwrap();
1436
    repo.set_user_config("core.sign", "change").unwrap();
1437
    write(root, "a.txt", b"one\n");
1438
    let h1 = repo.commit("one", &[]).unwrap();
1439
    write(root, "a.txt", b"two\n");
1440
    write(root, "big.bin", &vec![0u8; 100_000]);
1441
    let h2 = repo.commit("two", &[]).unwrap();
1442
    // Several snapshots leave superseded working-copy versions behind.
1443
    for i in 0..5 {
1444
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1445
        repo.snapshot("status").unwrap();
1446
    }
1447
    write(root, "a.txt", b"two\n");
1448
    repo.snapshot("status").unwrap();
1449
    let before = repo.store().list().unwrap();
1450
    assert!(repo.store().loose_count().unwrap() > 0);
1451
1452
    // With the default retention every operation's view is a root: nothing prunes.
1453
    let r = repo.gc(true).unwrap();
1454
    assert_eq!(r.packed.objects, before.len());
1455
    assert_eq!(r.pruned.objects, 0);
1456
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1457
    assert_eq!(repo.store().list().unwrap(), before);
1458
1459
    // With zero retention only the current view is a root: superseded
1460
    // working copies go, everything reachable stays.
1461
    repo.config.set("core.op-retention", "0").unwrap();
1462
    repo.save_config().unwrap();
1463
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1464
    let r = repo.gc(true).unwrap();
1465
    assert!(r.pruned.objects >= 5, "{r:?}");
1466
    let after = repo.store().list().unwrap();
1467
    assert!(after.len() < before.len());
1468
    assert!(after.contains(&h1) && after.contains(&h2));
1469
    for (_, op) in repo.op_log().unwrap() {
1470
        assert!(!op.command.is_empty(), "operation objects are all kept");
1471
    }
1472
    // Everything still works from the pruned, packed store.
1473
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1474
    assert!(matches!(
1475
        repo.verify_change(&h2).unwrap(),
1476
        SignatureStatus::Valid { .. }
1477
    ));
1478
    assert_eq!(repo.log().unwrap().len(), 3);
1479
    repo.checkout(&[h1], false, "checkout").unwrap();
1480
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1481
    repo.checkout(&[h2], false, "checkout").unwrap();
1482
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1483
    assert!(!repo.snapshot("status").unwrap().changed);
1484
    // Grace period defers pruning of young garbage.
1485
    write(root, "a.txt", b"three\n");
1486
    repo.commit("three", &[]).unwrap();
1487
    let r = repo.gc(false).unwrap();
1488
    assert_eq!(r.pruned.objects, 0);
1489
    assert!(r.pruned.deferred > 0);
1490
    let r = repo.gc(true).unwrap();
1491
    assert!(r.pruned.objects > 0);
1492
    assert_eq!(repo.log().unwrap().len(), 4);
1493
    // Restoring the default retention makes the old views roots again; the
1494
    // working copies they name were pruned, which gc tolerates.
1495
    repo.config.set("core.op-retention", "90").unwrap();
1496
    repo.save_config().unwrap();
1497
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1498
    let r = repo.gc(false).unwrap();
1499
    assert_eq!(r.pruned.objects, 0);
1500
    assert_eq!(repo.log().unwrap().len(), 4);
1501
}
1502
1503
#[test]
1504
fn describe_amend_abandon_heads() {
1505
    hermetic();
1506
    let dir = tempfile::tempdir().unwrap();
1507
    let root = dir.path();
1508
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1509
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1510
        .unwrap();
1511
    repo.set_user_config("core.sign", "change").unwrap();
1512
    write(root, "a.txt", b"one\n");
1513
    let h1 = repo.commit("first", &[]).unwrap();
1514
    write(root, "a.txt", b"one\ntwo\n");
1515
    let h2 = repo.commit("secnod", &[]).unwrap();
1516
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1517
1518
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1519
    let h2b = repo.describe(&h2, "second").unwrap();
1520
    assert_ne!(h2b, h2);
1521
    let c = repo.store().get_change(&h2b).unwrap();
1522
    assert_eq!(
1523
        (c.change_id, c.message.as_str(), c.deps.clone()),
1524
        (id2, "second", vec![h1])
1525
    );
1526
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1527
    assert!(matches!(
1528
        repo.verify_change(&h2b).unwrap(),
1529
        SignatureStatus::Valid { .. }
1530
    ));
1531
    let s = repo.snapshot("status").unwrap();
1532
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1533
    assert_eq!(
1534
        repo.resolve_change(&id2.short(8)).unwrap(),
1535
        h2b,
1536
        "the old object is no longer reachable from the log"
1537
    );
1538
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1539
    let h1b = repo.describe(&h1, "first, described").unwrap();
1540
    assert_ne!(h1b, h1);
1541
    let heads = repo.bookmark_heads().unwrap();
1542
    assert_eq!(heads.len(), 1);
1543
    let top = repo.store().get_change(&heads[0]).unwrap();
1544
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1545
    assert!(
1546
        matches!(
1547
            repo.verify_change(&heads[0]).unwrap(),
1548
            SignatureStatus::Valid { .. }
1549
        ),
1550
        "rewritten own change is re-signed"
1551
    );
1552
    let (_, wc) = repo.working_copy().unwrap();
1553
    assert_eq!(
1554
        wc.deps,
1555
        vec![heads[0]],
1556
        "the working copy follows the rewrite"
1557
    );
1558
    assert!(!repo.snapshot("status").unwrap().changed);
1559
    let snap = repo.load_state(&heads).unwrap().materialize();
1560
    assert!(
1561
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1562
    );
1563
1564
    // amend: fold an edit into the head; the result is one change from h1.
1565
    write(root, "a.txt", b"one\ntwo\nthree\n");
1566
    write(root, "b.txt", b"b\n");
1567
    let h2c = repo.amend(None).unwrap();
1568
    let c = repo.store().get_change(&h2c).unwrap();
1569
    assert_eq!(c.change_id, id2);
1570
    assert_eq!(c.message, "second");
1571
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1572
    assert_eq!(
1573
        repo.log().unwrap().len(),
1574
        3,
1575
        "working copy, amended head, first"
1576
    );
1577
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1578
    assert!(
1579
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1580
    );
1581
    assert!(snap.files.contains_key("b.txt"));
1582
    assert!(!repo.snapshot("status").unwrap().changed);
1583
    assert!(
1584
        repo.amend(None).is_err(),
1585
        "clean working copy and no message"
1586
    );
1587
    let h2d = repo.amend(Some("second, amended")).unwrap();
1588
    assert_eq!(
1589
        repo.store().get_change(&h2d).unwrap().message,
1590
        "second, amended"
1591
    );
1592
1593
    // abandon: the head goes, its content stays as uncommitted work.
1594
    repo.abandon(&h2d).unwrap();
1595
    assert_eq!(
1596
        repo.bookmark_heads().unwrap(),
1597
        vec![h1b],
1598
        "the described first change is the head again"
1599
    );
1600
    let s = repo.snapshot("status").unwrap();
1601
    let paths: Vec<_> = s
1602
        .statuses
1603
        .iter()
1604
        .map(|p| (p.path.as_str(), p.status))
1605
        .collect();
1606
    assert_eq!(
1607
        paths,
1608
        vec![
1609
            ("a.txt", ChangeStatus::Modified),
1610
            ("b.txt", ChangeStatus::Added)
1611
        ]
1612
    );
1613
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1614
    let h3 = repo.commit("recommitted", &[]).unwrap();
1615
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1616
    // undo brings the abandoned head back.
1617
    repo.undo().unwrap();
1618
    repo.undo().unwrap();
1619
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1620
1621
    // Abandoning a non-head whose dependent references its atoms reifies
1622
    // the references (here: a.txt vanishes with it, so the dependent's edit
1623
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1624
    let base = repo.bookmark_heads().unwrap()[0];
1625
    let base_change = repo.store().get_change(&base).unwrap();
1626
    let h1_now = base_change.deps[0];
1627
    let notes = repo.abandon(&h1_now).unwrap();
1628
    assert!(
1629
        !notes.is_empty(),
1630
        "the dependent's edit of a.txt was reified"
1631
    );
1632
    let heads = repo.bookmark_heads().unwrap();
1633
    let after = repo.load_state(&heads).unwrap().materialize();
1634
    assert!(
1635
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1636
        "{:?}",
1637
        after.files.keys()
1638
    );
1639
    repo.undo().unwrap();
1640
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1641
    write(root, "c.txt", b"c\n");
1642
    let hc = repo.commit("c", &[]).unwrap();
1643
    write(root, "d.txt", b"d\n");
1644
    let hd = repo.commit("d", &[hc]).unwrap();
1645
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1646
    repo.abandon(&hc).unwrap();
1647
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1648
    assert!(!heads.contains(&hc));
1649
    let d_now = heads
1650
        .iter()
1651
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1652
        .copied()
1653
        .unwrap();
1654
    assert!(
1655
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1656
        "d inherited c's (empty) dependencies"
1657
    );
1658
    let s = repo.snapshot("status").unwrap();
1659
    assert_eq!(
1660
        s.statuses
1661
            .iter()
1662
            .map(|p| p.path.as_str())
1663
            .collect::<Vec<_>>(),
1664
        vec!["c.txt"],
1665
        "c's content is now uncommitted work"
1666
    );
1667
}
1668
1669
#[test]
1670
fn git_export_mirrors_history() {
1671
    hermetic();
1672
    if std::process::Command::new("git")
1673
        .arg("--version")
1674
        .output()
1675
        .is_err()
1676
    {
1677
        eprintln!("git not installed; skipping");
1678
        return;
1679
    }
1680
    let dir = tempfile::tempdir().unwrap();
1681
    let root = dir.path();
1682
    let mut repo = Repo::init(&root.join("r"))
1683
        .unwrap()
1684
        .with_home(root.join("home"));
1685
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1686
        .unwrap();
1687
    let r = root.join("r");
1688
    write(&r, "README.md", b"hello\n");
1689
    write(&r, "src/main.rs", b"fn main() {}\n");
1690
    let h1 = repo.commit("first", &[]).unwrap();
1691
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1692
    write(&r, "logo.png", b"\x89PNG\0\0");
1693
    let h2 = repo.commit("second", &[]).unwrap();
1694
1695
    let git_dir = root.join("mirror.git");
1696
    let rep = repo.git_export(&git_dir).unwrap();
1697
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1698
    let git = |args: &[&str]| -> String {
1699
        let out = std::process::Command::new("git")
1700
            .arg("-C")
1701
            .arg(&git_dir)
1702
            .args(args)
1703
            .output()
1704
            .unwrap();
1705
        assert!(
1706
            out.status.success(),
1707
            "{}",
1708
            String::from_utf8_lossy(&out.stderr)
1709
        );
1710
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1711
    };
1712
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1713
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1714
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1715
    let body = git(&["log", "-1", "--format=%B", "main"]);
1716
    assert!(
1717
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1718
        "{body}"
1719
    );
1720
    assert!(body.contains("Change-Id: "), "{body}");
1721
    assert_eq!(
1722
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1723
        "Ada Lovelace <[email protected]>"
1724
    );
1725
    assert_eq!(
1726
        git(&["ls-tree", "--name-only", "main"]),
1727
        "README.md\nlogo.png\nsrc"
1728
    );
1729
1730
    // Re-export is incremental.
1731
    let rep = repo.git_export(&git_dir).unwrap();
1732
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1733
1734
    // An independent change makes two heads; the next state is one more
1735
    // commit on the linear branch whose tree is the union.
1736
    repo.checkout(&[h1], false, "checkout").unwrap();
1737
    write(&r, "other.txt", b"o\n");
1738
    let h3 = repo.commit("third", &[]).unwrap();
1739
    let rep = repo.git_export(&git_dir).unwrap();
1740
    assert_eq!((rep.exported, rep.heads), (1, 2));
1741
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1742
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1743
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1744
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1745
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1746
    assert_eq!(
1747
        git(&["ls-tree", "--name-only", "main"]),
1748
        "README.md\nlogo.png\nother.txt\nsrc"
1749
    );
1750
    let body = git(&["log", "-1", "--format=%B", "main"]);
1751
    assert!(
1752
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1753
        "{body}"
1754
    );
1755
    // A rewrite is a new state whose one new change is the rewritten one.
1756
    repo.describe(&h3, "third, described").unwrap();
1757
    let rep = repo.git_export(&git_dir).unwrap();
1758
    assert_eq!(rep.exported, 1);
1759
    assert_eq!(
1760
        git(&["log", "-1", "--format=%s", "main"]),
1761
        "third, described"
1762
    );
1763
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1764
    let _ = h2;
1765
}
1766
1767
#[test]
1768
fn git_import_reproduces_trees() {
1769
    git_import_reproduces_trees_with(None);
1770
}
1771
1772
/// The same import with every merge rendered in batches of one file
1773
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1774
#[test]
1775
fn git_import_reproduces_trees_in_batches() {
1776
    git_import_reproduces_trees_with(Some(1));
1777
}
1778
1779
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1780
    crate::repo::git::set_merge_batch_for_tests(batch);
1781
    hermetic();
1782
    if std::process::Command::new("git")
1783
        .arg("--version")
1784
        .output()
1785
        .is_err()
1786
    {
1787
        eprintln!("git not installed; skipping");
1788
        return;
1789
    }
1790
    let dir = tempfile::tempdir().unwrap();
1791
    let root = dir.path();
1792
    let g = root.join("src.git");
1793
    fs::create_dir_all(&g).unwrap();
1794
    let git = |args: &[&str]| -> String {
1795
        let out = std::process::Command::new("git")
1796
            .arg("-C")
1797
            .arg(&g)
1798
            .args([
1799
                "-c",
1800
                "user.name=Grace",
1801
                "-c",
1802
                "[email protected]",
1803
                "-c",
1804
                "commit.gpgsign=false",
1805
            ])
1806
            .args(args)
1807
            .output()
1808
            .unwrap();
1809
        assert!(
1810
            out.status.success(),
1811
            "git {args:?}: {}",
1812
            String::from_utf8_lossy(&out.stderr)
1813
        );
1814
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1815
    };
1816
    git(&["init", "-q", "-b", "main"]);
1817
    write(&g, "README.md", b"# Hi\n");
1818
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1819
    git(&["add", "."]);
1820
    git(&["commit", "-q", "-m", "initial"]);
1821
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1822
    write(&g, "run.sh", b"#!/bin/sh\n");
1823
    #[cfg(unix)]
1824
    {
1825
        use std::os::unix::fs::PermissionsExt;
1826
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1827
    }
1828
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1829
    git(&["add", "."]);
1830
    git(&[
1831
        "commit",
1832
        "-q",
1833
        "-m",
1834
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1835
    ]);
1836
    // A branch that edits README, merged back with a conflict-free merge.
1837
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1838
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1839
    git(&["commit", "-q", "-am", "readme"]);
1840
    git(&["checkout", "-q", "main"]);
1841
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1842
    // A branch from the initial commit inserting at the same place as
1843
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1844
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1845
    git(&["checkout", "-q", "-b", "clash", &initial]);
1846
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1847
    git(&["commit", "-q", "-am", "clash"]);
1848
    git(&["checkout", "-q", "main"]);
1849
    let _ = std::process::Command::new("git")
1850
        .arg("-C")
1851
        .arg(&g)
1852
        .args(["merge", "-q", "clash"])
1853
        .output();
1854
    write(
1855
        &g,
1856
        "src/lib.rs",
1857
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1858
    );
1859
    git(&["add", "."]);
1860
    git(&["commit", "-q", "-m", "resolve clash"]);
1861
    git(&["rm", "-q", "logo.png"]);
1862
    git(&["commit", "-q", "-m", "drop logo"]);
1863
    // A rename with a small edit is imported as a move of the same node.
1864
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1865
    write(
1866
        &g,
1867
        "src/lib2.rs",
1868
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1869
    );
1870
    git(&["add", "."]);
1871
    git(&["commit", "-q", "-m", "rename lib"]);
1872
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1873
    // run.sh is the same as in the first parent's tree, but the merged
1874
    // change touched it, so the importer must compare it, not skip it.
1875
    git(&["checkout", "-q", "-b", "discarded"]);
1876
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1877
    git(&["commit", "-q", "-am", "discarded edit"]);
1878
    git(&["checkout", "-q", "main"]);
1879
    git(&[
1880
        "merge",
1881
        "-q",
1882
        "-s",
1883
        "ours",
1884
        "-m",
1885
        "merge discarded, keeping ours",
1886
        "discarded",
1887
    ]);
1888
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1889
1890
    let dest = root.join("oxy");
1891
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1892
    let rep = repo.import_git(&g, "main").unwrap();
1893
    assert_eq!(rep.commits, expected_count);
1894
    assert_eq!(rep.merges, 3);
1895
    assert_eq!(
1896
        fs::read(dest.join("run.sh")).unwrap(),
1897
        b"#!/bin/sh\n",
1898
        "the ours merge kept main's run.sh"
1899
    );
1900
    let v = repo.verify_git_import(&g, "main").unwrap();
1901
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1902
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1903
    // The working copy equals the Git tree at main.
1904
    assert_eq!(
1905
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1906
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1907
    );
1908
    assert!(!dest.join("src/lib.rs").exists());
1909
    assert_eq!(
1910
        fs::read(dest.join("README.md")).unwrap(),
1911
        b"# Hi\n\nMore.\n"
1912
    );
1913
    assert!(!dest.join("logo.png").exists());
1914
    #[cfg(unix)]
1915
    {
1916
        use std::os::unix::fs::PermissionsExt;
1917
        assert!(
1918
            fs::metadata(dest.join("run.sh"))
1919
                .unwrap()
1920
                .permissions()
1921
                .mode()
1922
                & 0o111
1923
                != 0
1924
        );
1925
    }
1926
    assert!(
1927
        !repo.snapshot("status").unwrap().changed,
1928
        "clean after import"
1929
    );
1930
    let heads = repo.bookmark_heads().unwrap();
1931
    let st = repo.load_state(&heads).unwrap();
1932
    assert!(!st.materialize().is_conflicted());
1933
    assert_eq!(st.len(), expected_count);
1934
    let tip = repo
1935
        .log()
1936
        .unwrap()
1937
        .into_iter()
1938
        .find(|e| e.change.message.starts_with("rename lib"))
1939
        .unwrap();
1940
    let c = repo.store().get_change(&tip.hash).unwrap();
1941
    assert!(
1942
        c.tree_ops
1943
            .iter()
1944
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1945
        "{:?}",
1946
        c.tree_ops
1947
    );
1948
    assert!(!c
1949
        .tree_ops
1950
        .iter()
1951
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1952
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1953
    let log = repo.log().unwrap();
1954
    let second = log
1955
        .iter()
1956
        .find(|e| e.change.message.starts_with("second"))
1957
        .unwrap();
1958
    assert_eq!(
1959
        second.change.change_id,
1960
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1961
    );
1962
    assert!(second
1963
        .change
1964
        .message
1965
        .contains("Git-Author: Grace <[email protected]>"));
1966
    let resolve = log
1967
        .iter()
1968
        .find(|e| e.change.message.starts_with("resolve clash"))
1969
        .unwrap();
1970
    assert_eq!(
1971
        resolve.change.kind,
1972
        ChangeKind::Resolution,
1973
        "a conflicting Git merge becomes a resolution"
1974
    );
1975
    // Re-importing into another fresh repository gives the same ChangeIds.
1976
    let repo2 = Repo::init(&root.join("oxy2"))
1977
        .unwrap()
1978
        .with_home(root.join("home"));
1979
    repo2.import_git(&g, "main").unwrap();
1980
    // New nodes' identifiers derive from the commit (spec §23), so the
1981
    // re-import is not just the same ChangeIds but the same changes.
1982
    assert_eq!(
1983
        repo2.bookmark_heads().unwrap(),
1984
        repo.bookmark_heads().unwrap()
1985
    );
1986
    let ids: BTreeSet<ChangeId> = repo
1987
        .log()
1988
        .unwrap()
1989
        .iter()
1990
        .filter(|e| !e.is_working_copy)
1991
        .map(|e| e.change.change_id)
1992
        .collect();
1993
    let ids2: BTreeSet<ChangeId> = repo2
1994
        .log()
1995
        .unwrap()
1996
        .iter()
1997
        .filter(|e| !e.is_working_copy)
1998
        .map(|e| e.change.change_id)
1999
        .collect();
2000
    assert_eq!(ids, ids2);
2001
    // Round trip back out to Git reproduces the tip tree.
2002
    let mirror = root.join("mirror.git");
2003
    repo.git_export(&mirror).unwrap();
2004
    let out = std::process::Command::new("git")
2005
        .arg("-C")
2006
        .arg(&mirror)
2007
        .args(["show", "main:src/lib2.rs"])
2008
        .output()
2009
        .unwrap();
2010
    assert_eq!(
2011
        String::from_utf8_lossy(&out.stdout),
2012
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2013
    );
2014
    let out = std::process::Command::new("git")
2015
        .arg("-C")
2016
        .arg(&mirror)
2017
        .args(["show", "main:src/lib.rs"])
2018
        .output()
2019
        .unwrap();
2020
    assert!(
2021
        !out.status.success(),
2022
        "the old path is gone from the export"
2023
    );
2024
}
2025
2026
#[test]
2027
fn checkpoints_accelerate_loading_and_stay_correct() {
2028
    hermetic();
2029
    let dir = tempfile::tempdir().unwrap();
2030
    let root = dir.path();
2031
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2032
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2033
    repo.save_config().unwrap();
2034
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2035
    let mut hashes = Vec::new();
2036
    for i in 0..12 {
2037
        write(
2038
            root,
2039
            "a.txt",
2040
            format!(
2041
                "{}\n",
2042
                (0..=i)
2043
                    .map(|k| k.to_string())
2044
                    .collect::<Vec<_>>()
2045
                    .join("\n")
2046
            )
2047
            .as_bytes(),
2048
        );
2049
        write(root, &format!("f{i}.txt"), b"x\n");
2050
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2051
    }
2052
    let (_, cp) = repo
2053
        .latest_checkpoint("main")
2054
        .unwrap()
2055
        .expect("automatic checkpoint");
2056
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2057
    // Loading through the checkpoint equals loading everything.
2058
    let heads = repo.bookmark_heads().unwrap();
2059
    let fast = repo.load_state(&heads).unwrap();
2060
    let full = repo.load_state_full(&heads).unwrap();
2061
    assert_eq!(fast.len(), full.len());
2062
    assert_eq!(fast.heads(), full.heads());
2063
    let (a, b) = (fast.materialize(), full.materialize());
2064
    assert_eq!(
2065
        a.files.keys().collect::<Vec<_>>(),
2066
        b.files.keys().collect::<Vec<_>>()
2067
    );
2068
    for (p, f) in &a.files {
2069
        assert_eq!(f.content, b.files[p].content, "{p}");
2070
    }
2071
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2072
    // A head set that does not contain the checkpoint's heads falls back.
2073
    assert!(repo
2074
        .load_state_checkpointed(&[hashes[0]])
2075
        .unwrap()
2076
        .is_none());
2077
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2078
    // Everything else keeps working on top of the checkpoint.
2079
    assert!(!repo.snapshot("status").unwrap().changed);
2080
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2081
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2082
    let (r, n, bytes) = repo.checkpoint().unwrap();
2083
    assert!(n >= 12 && bytes > 0);
2084
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2085
    write(root, "a.txt", b"after\n");
2086
    let h_after = repo.commit("after", &[]).unwrap();
2087
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2088
    assert!(st.contains(&h_after));
2089
    assert!(
2090
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2091
    );
2092
    assert_eq!(repo.log().unwrap().len(), 14);
2093
    // Checkpoints survive gc.
2094
    repo.gc(true).unwrap();
2095
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
2096
    assert!(repo
2097
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2098
        .unwrap()
2099
        .is_some());
2100
}
2101
2102
#[test]
2103
fn quick_status_for_prompts() {
2104
    hermetic();
2105
    let dir = tempfile::tempdir().unwrap();
2106
    let root = dir.path();
2107
    let origin = Repo::init(&root.join("origin")).unwrap();
2108
    let url = root.join("origin").to_string_lossy().to_string();
2109
    let a = Repo::clone(&url, &root.join("a"))
2110
        .unwrap()
2111
        .with_home(root.join("home"));
2112
    let ops_before = a.op_log().unwrap().len();
2113
    let info = a.quick_status().unwrap();
2114
    assert_eq!(
2115
        (
2116
            info.bookmark.as_str(),
2117
            info.heads,
2118
            info.dirty,
2119
            info.conflicted,
2120
            info.ahead,
2121
            info.behind
2122
        ),
2123
        ("main", 0, false, false, Some(0), Some(0))
2124
    );
2125
    write(&root.join("a"), "f.txt", b"f\n");
2126
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
2127
    assert_eq!(
2128
        a.op_log().unwrap().len(),
2129
        ops_before,
2130
        "quick_status records nothing"
2131
    );
2132
    // A snapshotted but uncommitted change is still dirty.
2133
    a.snapshot("status").unwrap();
2134
    assert!(a.quick_status().unwrap().dirty);
2135
    a.commit("f", &[]).unwrap();
2136
    let info = a.quick_status().unwrap();
2137
    assert!(!info.dirty, "clean right after a commit");
2138
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
2139
    assert_eq!(
2140
        info.format("%b %c%d%x%A%D"),
2141
        format!("main {}+1", info.change_id)
2142
    );
2143
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2144
    // Touching a file without changing it is not dirty; changing content of
2145
    // the same size is.
2146
    let p = root.join("a/f.txt");
2147
    let content = fs::read(&p).unwrap();
2148
    fs::write(&p, &content).unwrap();
2149
    assert!(!a.quick_status().unwrap().dirty);
2150
    fs::write(&p, b"g\n").unwrap();
2151
    assert!(a.quick_status().unwrap().dirty);
2152
    fs::write(&p, b"f\n").unwrap();
2153
    // Push, then a second clone commits and pushes: we are behind.
2154
    assert!(a.push("origin", false).unwrap()[0].ok);
2155
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
2156
    let b = Repo::clone(&url, &root.join("b"))
2157
        .unwrap()
2158
        .with_home(root.join("home-b"));
2159
    write(&root.join("b"), "g.txt", b"g\n");
2160
    b.commit("g", &[]).unwrap();
2161
    b.push("origin", false).unwrap();
2162
    a.fetch("origin").unwrap();
2163
    let info = a.quick_status().unwrap();
2164
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2165
    assert_eq!(info.format("%A%D"), "-1");
2166
    let _ = origin;
2167
}
2168
2169
#[test]
2170
fn lazy_blobs_are_fetched_on_first_read() {
2171
    hermetic();
2172
    let dir = tempfile::tempdir().unwrap();
2173
    let root = dir.path();
2174
    let origin_dir = root.join("origin");
2175
    let origin = Repo::init(&origin_dir)
2176
        .unwrap()
2177
        .with_home(root.join("home"));
2178
    let url = origin_dir.to_string_lossy().to_string();
2179
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2180
    write(&origin_dir, "big.bin", &big);
2181
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2182
    write(&origin_dir, "t.txt", b"t\n");
2183
    let h = origin.commit("blobs", &[]).unwrap();
2184
    let big_ref = Repo::blob_ref(&big);
2185
2186
    // Fetch only (no checkout) with a filter: the big blob stays absent.
2187
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2188
        .unwrap()
2189
        .with_home(root.join("home"));
2190
    let a = {
2191
        let mut a = a;
2192
        a.config.set("remote.origin.url", &url).unwrap();
2193
        a.config.set("filter.max-blob", "100K").unwrap();
2194
        a.save_config().unwrap();
2195
        a
2196
    };
2197
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2198
    a.fetch("origin").unwrap();
2199
    assert!(a.store().has(&h));
2200
    assert!(!a.store().has(&big_ref), "withheld");
2201
    assert!(
2202
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2203
        "small blob came along"
2204
    );
2205
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2206
2207
    // status and commit do not need it: adopt the state, edit a text file, commit.
2208
    let (op_ref, op) = a.head_op().unwrap();
2209
    let mut view = op.view.clone();
2210
    view.bookmarks.insert(
2211
        "main".into(),
2212
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2213
    );
2214
    a.record_op(&[op_ref], "adopt", view).unwrap();
2215
    // Checkout reads the blob lazily, which fetches it.
2216
    a.checkout(&[h], true, "checkout").unwrap();
2217
    assert!(a.store().has(&big_ref), "fetched on first read");
2218
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2219
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2220
    write(&root.join("a"), "t.txt", b"t2\n");
2221
    a.commit("text edit", &[]).unwrap();
2222
2223
    // clone --max-blob records the filter; the checkout fetches lazily.
2224
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
2225
    assert_eq!(b.config.max_blob, Some(1024));
2226
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2227
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2228
    assert!(parse_size("lots").is_err());
2229
}
2230
2231
#[test]
2232
fn sparse_checkout_materializes_only_chosen_paths() {
2233
    hermetic();
2234
    let dir = tempfile::tempdir().unwrap();
2235
    let root = dir.path();
2236
    let origin_dir = root.join("origin");
2237
    let origin = Repo::init(&origin_dir)
2238
        .unwrap()
2239
        .with_home(root.join("home"));
2240
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2241
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2242
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2243
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2244
    write(&origin_dir, "docs/logo.png", &logo);
2245
    write(&origin_dir, "README.md", b"# top\n");
2246
    let h1 = origin.commit("tree", &[]).unwrap();
2247
    let url = origin_dir.to_string_lossy().to_string();
2248
2249
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2250
        .unwrap()
2251
        .with_home(root.join("home"));
2252
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2253
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2254
    assert!(root.join("a/src/main.rs").exists());
2255
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
2256
    assert!(
2257
        !a.store().has(&Repo::blob_ref(&logo)),
2258
        "out-of-scope blob never fetched"
2259
    );
2260
    assert!(
2261
        !a.snapshot("status").unwrap().changed,
2262
        "out-of-scope files are not removals"
2263
    );
2264
    assert!(!a.quick_status().unwrap().dirty);
2265
2266
    // Edits in scope commit normally and keep the rest of the tree intact.
2267
    write(
2268
        &root.join("a"),
2269
        "src/lib.rs",
2270
        b"pub fn a() {}\npub fn b() {}\n",
2271
    );
2272
    let h2 = a.commit("edit lib", &[]).unwrap();
2273
    let st = a.load_state(&[h2]).unwrap().materialize();
2274
    assert!(
2275
        st.files.contains_key("docs/guide.md"),
2276
        "the state still has everything"
2277
    );
2278
    assert!(a.push("origin", false).unwrap()[0].ok);
2279
    // Files created outside the scope are ignored by status.
2280
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2281
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2282
2283
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2284
    let mut a = a;
2285
    a.config.set("filter.paths", "src,docs").unwrap();
2286
    a.save_config().unwrap();
2287
    let r = a
2288
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2289
        .unwrap();
2290
    assert!(r.written >= 2);
2291
    assert_eq!(
2292
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2293
        logo,
2294
        "now fetched lazily"
2295
    );
2296
    assert!(!root.join("a/README.md").exists());
2297
    // Origin sees the change made under a sparse checkout with the full tree intact.
2298
    origin.pull("origin").err();
2299
    let full = origin
2300
        .load_state(&origin.bookmark_heads().unwrap())
2301
        .unwrap()
2302
        .materialize();
2303
    assert!(
2304
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2305
    );
2306
    assert!(full.files.contains_key("README.md"));
2307
    let _ = h1;
2308
}
2309
2310
#[test]
2311
fn shallow_clone_and_deepen() {
2312
    hermetic();
2313
    let dir = tempfile::tempdir().unwrap();
2314
    let root = dir.path();
2315
    let origin_dir = root.join("origin");
2316
    let origin = Repo::init(&origin_dir)
2317
        .unwrap()
2318
        .with_home(root.join("home"));
2319
    let mut hashes = Vec::new();
2320
    for i in 0..8 {
2321
        write(
2322
            &origin_dir,
2323
            "a.txt",
2324
            format!(
2325
                "{}\n",
2326
                (0..=i)
2327
                    .map(|k| k.to_string())
2328
                    .collect::<Vec<_>>()
2329
                    .join("\n")
2330
            )
2331
            .as_bytes(),
2332
        );
2333
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2334
    }
2335
    let url = origin_dir.to_string_lossy().to_string();
2336
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2337
        .unwrap()
2338
        .with_home(root.join("home"));
2339
    assert!(a.is_shallow());
2340
    assert_eq!(
2341
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2342
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2343
    );
2344
    assert!(
2345
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2346
        "three levels present"
2347
    );
2348
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2349
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2350
    assert_eq!(
2351
        a.log().unwrap().len(),
2352
        9,
2353
        "the log shows every change from the checkpoint's metadata"
2354
    );
2355
    assert!(!a.snapshot("status").unwrap().changed);
2356
    assert_eq!(a.quick_status().unwrap().heads, 1);
2357
2358
    // Work continues on top of the shallow history and pushes back.
2359
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2360
    let h_new = a.commit("c8", &[]).unwrap();
2361
    assert!(a.push("origin", false).unwrap()[0].ok);
2362
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2363
    // Fetching new work from origin into the shallow clone works too.
2364
    write(&origin_dir, "b.txt", b"b\n");
2365
    origin.pull("origin").err();
2366
    let (_, wc) = origin.working_copy().unwrap();
2367
    let _ = wc;
2368
    origin
2369
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2370
        .unwrap();
2371
    write(&origin_dir, "b.txt", b"b\n");
2372
    let h_b = origin.commit("b", &[]).unwrap();
2373
    let pr = a.pull("origin").unwrap();
2374
    assert!(pr.changed);
2375
    assert!(a.store().has(&h_b));
2376
    assert!(root.join("a/b.txt").exists());
2377
2378
    // Deepening fetches older history until the boundary is gone.
2379
    // Every commit also depends on the change that created the file, so two
2380
    // levels below the boundary hold h4, h3, and the root.
2381
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2382
    assert!(a.store().has(&hashes[3]));
2383
    assert!(a.is_shallow());
2384
    a.deepen("origin", 100).unwrap();
2385
    assert!(!a.is_shallow(), "boundary reached the root");
2386
    assert!(a.store().has(&hashes[0]));
2387
    assert_eq!(
2388
        a.load_state_full(&a.bookmark_heads().unwrap())
2389
            .unwrap()
2390
            .len(),
2391
        10
2392
    );
2393
}
2394
2395
#[test]
2396
fn tags_are_immutable_named_states_and_travel() {
2397
    hermetic();
2398
    let dir = tempfile::tempdir().unwrap();
2399
    let root = dir.path();
2400
    let origin = Repo::init(&root.join("origin")).unwrap();
2401
    let url = root.join("origin").to_string_lossy().to_string();
2402
    let mut a = Repo::clone(&url, &root.join("a"))
2403
        .unwrap()
2404
        .with_home(root.join("home-a"));
2405
    let (key_a, _) = a
2406
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2407
        .unwrap();
2408
    write(&root.join("a"), "f.txt", b"1\n");
2409
    let h1 = a.commit("one", &[]).unwrap();
2410
    write(&root.join("a"), "f.txt", b"1\n2\n");
2411
    let h2 = a.commit("two", &[]).unwrap();
2412
2413
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2414
    assert_eq!(
2415
        (t.heads.clone(), t.signer.as_deref()),
2416
        (vec![h1], Some("Ada"))
2417
    );
2418
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2419
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2420
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2421
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2422
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2423
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2424
    assert_eq!(sa.sigs[0].key, key_a);
2425
    // Checkout by tag.
2426
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2427
        .unwrap();
2428
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2429
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2430
        .unwrap();
2431
2432
    // Push carries the tag; a second attestation for the name is refused.
2433
    let r = a.push("origin", false).unwrap();
2434
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2435
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2436
    let mut forged = a
2437
        .tag_refs()
2438
        .unwrap()
2439
        .into_iter()
2440
        .find(|t| t.name == "v1")
2441
        .unwrap();
2442
    forged.state = origin
2443
        .store()
2444
        .put_state(&StateObject::new(vec![h2]))
2445
        .unwrap();
2446
    forged.heads = vec![h2];
2447
    forged.attestation = None;
2448
    let r = origin
2449
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2450
        .unwrap();
2451
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2452
2453
    // A clone gets the tag; a later tag arrives on fetch.
2454
    let b = Repo::clone(&url, &root.join("b"))
2455
        .unwrap()
2456
        .with_home(root.join("home-b"));
2457
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2458
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2459
    a.tag_create("v2", &[h2], "second").unwrap();
2460
    a.push("origin", false).unwrap();
2461
    let rep = b.fetch("origin").unwrap();
2462
    assert_eq!(rep.new_tags, 1);
2463
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2464
2465
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2466
    a.policy_init().unwrap();
2467
    a.push("origin", false).unwrap();
2468
    let unattested = crate::protocol::TagRef {
2469
        name: "v3".into(),
2470
        state: origin
2471
            .store()
2472
            .put_state(&StateObject::new(vec![h2]))
2473
            .unwrap(),
2474
        heads: vec![h2],
2475
        attestation: None,
2476
    };
2477
    let r = origin
2478
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2479
        .unwrap();
2480
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2481
    a.tag_create("v3", &[h2], "").unwrap();
2482
    let r = a.push("origin", false).unwrap();
2483
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2484
    assert!(a.gc(true).is_ok());
2485
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2486
}
2487
2488
#[test]
2489
fn multiple_workspaces_share_a_repository() {
2490
    hermetic();
2491
    let dir = tempfile::tempdir().unwrap();
2492
    let root = dir.path();
2493
    let main_dir = root.join("main");
2494
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2495
    write(&main_dir, "a.txt", b"a\n");
2496
    let h1 = repo.commit("a", &[]).unwrap();
2497
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2498
2499
    // A second workspace elsewhere, checked out on the bookmark.
2500
    let ws_dir = root.join("ws2");
2501
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2502
    assert!(ws_dir.join(".oxy").is_file());
2503
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2504
    assert_ne!(ws.workspace(), repo.workspace());
2505
    let list = repo.workspaces().unwrap();
2506
    assert_eq!(list.len(), 2);
2507
    assert!(list
2508
        .iter()
2509
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2510
    assert!(!ws.snapshot("status").unwrap().changed);
2511
2512
    // Work in the second workspace: its own working copy, shared bookmark.
2513
    write(&ws_dir, "b.txt", b"b\n");
2514
    let s = ws.snapshot("status").unwrap();
2515
    assert_eq!(s.statuses.len(), 1);
2516
    assert!(
2517
        !repo.snapshot("status").unwrap().changed,
2518
        "the first workspace is untouched"
2519
    );
2520
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2521
    let mut heads = repo.bookmark_heads().unwrap();
2522
    heads.sort();
2523
    let mut want = vec![h1, h2];
2524
    want.sort();
2525
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2526
    assert!(!main_dir.join("b.txt").exists());
2527
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2528
        .unwrap();
2529
    assert!(main_dir.join("b.txt").exists());
2530
2531
    // Reopening from inside the second workspace finds the shared repository.
2532
    let reopened = Repo::open(&ws_dir).unwrap();
2533
    assert_eq!(reopened.workspace(), ws.workspace());
2534
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2535
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2536
2537
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2538
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2539
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2540
    repo.workspace_forget(&ws.workspace()).unwrap();
2541
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2542
    assert!(ws_dir.join("b.txt").exists());
2543
    assert!(
2544
        ws.snapshot("status").is_err(),
2545
        "a forgotten workspace is no longer in the view"
2546
    );
2547
2548
    // The working-copy lock: re-entrant in a thread; a lock whose process
2549
    // is gone is taken over, and a live process's is not, however old.
2550
    let lock = repo.lock_snapshot().unwrap();
2551
    let again = repo.lock_working_copy().unwrap();
2552
    drop(again);
2553
    drop(lock);
2554
    let lock_path = main_dir
2555
        .join(".oxy/workspaces")
2556
        .join(repo.workspace().to_hex())
2557
        .join("lock");
2558
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2559
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2560
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2561
    age(&lock_path);
2562
    assert!(
2563
        !super::workspace::lock_is_stale(&lock_path),
2564
        "a live process keeps its lock"
2565
    );
2566
    fs::write(&lock_path, "4294967295").unwrap();
2567
    age(&lock_path);
2568
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2569
}
2570
2571
#[test]
2572
fn attributes_binary_eol_nocompress_lockable() {
2573
    hermetic();
2574
    let dir = tempfile::tempdir().unwrap();
2575
    let root = dir.path();
2576
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2577
    write(
2578
        root,
2579
        ".oxyattributes",
2580
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2581
    );
2582
    write(root, "plain.dat", b"no nul bytes here\n");
2583
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2584
    write(root, "assets/model.bin", b"\0model");
2585
    let h = repo.commit("attrs", &[]).unwrap();
2586
    let snap = repo.load_state(&[h]).unwrap().materialize();
2587
    assert!(
2588
        snap.files["plain.dat"].mode.opaque,
2589
        "binary attribute forces opaque without NUL bytes"
2590
    );
2591
    assert!(
2592
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2593
        "stored with LF"
2594
    );
2595
    assert!(
2596
        !repo.snapshot("status").unwrap().changed,
2597
        "CRLF on disk equals LF in the state"
2598
    );
2599
    // nocompress chunks pack raw.
2600
    let r = repo.gc(true).unwrap();
2601
    assert!(r.packed.objects > 0);
2602
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2603
    fs::remove_file(root.join("notes.txt")).unwrap();
2604
    repo.checkout(&[h], true, "co").unwrap();
2605
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2606
    assert!(fs::metadata(root.join("assets/model.bin"))
2607
        .unwrap()
2608
        .permissions()
2609
        .readonly());
2610
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2611
    repo.lock_path("assets/model.bin").unwrap();
2612
    assert!(!fs::metadata(root.join("assets/model.bin"))
2613
        .unwrap()
2614
        .permissions()
2615
        .readonly());
2616
    assert!(repo.is_locked("assets/model.bin"));
2617
    write(root, "assets/model.bin", b"\0model2");
2618
    repo.commit("edit model", &[]).unwrap();
2619
    repo.unlock_path("assets/model.bin").unwrap();
2620
    assert!(fs::metadata(root.join("assets/model.bin"))
2621
        .unwrap()
2622
        .permissions()
2623
        .readonly());
2624
    // A later checkout can still overwrite a read-only lockable file.
2625
    repo.checkout(&[h], true, "co").unwrap();
2626
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2627
}
2628
2629
#[cfg(unix)]
2630
#[test]
2631
fn hooks_can_veto_observe_and_add_dependencies() {
2632
    use std::os::unix::fs::PermissionsExt;
2633
    hermetic();
2634
    let dir = tempfile::tempdir().unwrap();
2635
    let root = dir.path();
2636
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2637
    let hooks = root.join(".oxy/hooks");
2638
    fs::create_dir_all(&hooks).unwrap();
2639
    let hook = |name: &str, body: &str| {
2640
        let p = hooks.join(name);
2641
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2642
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2643
    };
2644
    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");
2645
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2646
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2647
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2648
    write(root, ".oxyignore", b".last-*\n");
2649
    write(root, "a.txt", b"a\n");
2650
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2651
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2652
    let h1 = repo.commit("first", &[]).unwrap();
2653
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2654
    assert!(
2655
        pre.contains("\"event\":\"pre-commit\"")
2656
            && pre.contains("\"path\":\"a.txt\"")
2657
            && pre.contains("\"message\":\"first\""),
2658
        "{pre}"
2659
    );
2660
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2661
    assert!(post.contains(&h1.to_hex()), "{post}");
2662
    repo.checkout(&[h1], false, "co").unwrap();
2663
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2664
        .unwrap()
2665
        .contains("post-checkout"));
2666
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2667
    repo.save_config().unwrap();
2668
    let err = repo.push("origin", false).unwrap_err().to_string();
2669
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2670
2671
    // semantic-deps: only when enabled; adds an explicit dependency.
2672
    write(root, "b.txt", b"b\n");
2673
    hook(
2674
        "semantic-deps",
2675
        &format!(
2676
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2677
            h1.to_hex()
2678
        ),
2679
    );
2680
    let h2 = repo.commit("b without hook", &[]).unwrap();
2681
    assert!(
2682
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2683
        "hook disabled by default"
2684
    );
2685
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2686
    repo.save_config().unwrap();
2687
    write(root, "c.txt", b"c\n");
2688
    let h3 = repo.commit("c with hook", &[]).unwrap();
2689
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2690
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2691
    assert!(
2692
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2693
        "{sem}"
2694
    );
2695
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2696
}
2697
2698
#[test]
2699
fn amend_into_older_change_and_split() {
2700
    hermetic();
2701
    let dir = tempfile::tempdir().unwrap();
2702
    let root = dir.path();
2703
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2704
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2705
        .unwrap();
2706
    repo.set_user_config("core.sign", "change").unwrap();
2707
    write(root, "a.txt", b"one\ntwo\n");
2708
    let h0 = repo.commit("base", &[]).unwrap();
2709
    write(root, "a.txt", b"one\nTWO\n");
2710
    let h1 = repo.commit("edit two", &[]).unwrap();
2711
    write(root, "a.txt", b"one\nTWO\nthree\n");
2712
    let h2 = repo.commit("add three", &[]).unwrap();
2713
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2714
2715
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2716
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2717
    let h1b = repo.amend_into(&h1, None).unwrap();
2718
    assert_ne!(h1b, h1);
2719
    let c1b = repo.store().get_change(&h1b).unwrap();
2720
    assert_eq!(c1b.change_id, id1);
2721
    assert_eq!(c1b.deps, vec![h0]);
2722
    assert!(matches!(
2723
        repo.verify_change(&h1b).unwrap(),
2724
        SignatureStatus::Valid { .. }
2725
    ));
2726
    let heads = repo.bookmark_heads().unwrap();
2727
    assert_eq!(heads.len(), 1);
2728
    let top = repo.store().get_change(&heads[0]).unwrap();
2729
    assert_eq!(top.message, "add three");
2730
    assert_eq!(
2731
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2732
        [h0, h1b].into_iter().collect(),
2733
        "depends on the file's creator and the rewritten line"
2734
    );
2735
    let snap = repo.load_state(&heads).unwrap().materialize();
2736
    assert!(
2737
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2738
    );
2739
    assert!(
2740
        !repo.snapshot("status").unwrap().changed,
2741
        "the working copy is clean after folding"
2742
    );
2743
    // Only h1b's own state shows the fix without "three".
2744
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2745
    assert!(
2746
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2747
    );
2748
    assert_eq!(repo.log().unwrap().len(), 4);
2749
2750
    // An edit to a line introduced by h2 cannot fold into h1.
2751
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2752
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2753
    assert!(err.contains("introduced after"), "{err}");
2754
    assert!(
2755
        repo.snapshot("status").unwrap().statuses.len() == 1,
2756
        "nothing was changed by the refusal"
2757
    );
2758
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2759
2760
    // Split the head that touches two files.
2761
    write(root, "b.txt", b"b\n");
2762
    write(root, "c.txt", b"c\n");
2763
    let h3 = repo.commit("b and c", &[]).unwrap();
2764
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2765
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2766
    let c_1 = repo.store().get_change(&p1).unwrap();
2767
    let c_2 = repo.store().get_change(&p2).unwrap();
2768
    assert!(c_1.message.contains("part 1: b.txt"));
2769
    assert_eq!(c_2.change_id, id3);
2770
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2771
    assert!(
2772
        heads.contains(&p1) && heads.contains(&p2),
2773
        "independent parts are both heads"
2774
    );
2775
    let snap = repo
2776
        .load_state(&repo.bookmark_heads().unwrap())
2777
        .unwrap()
2778
        .materialize();
2779
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2780
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2781
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2782
    assert!(!repo.snapshot("status").unwrap().changed);
2783
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2784
    let _ = h2;
2785
}
2786
2787
#[test]
2788
fn identity_lifecycle() {
2789
    hermetic();
2790
    let dir = tempfile::tempdir().unwrap();
2791
    let root = dir.path();
2792
    let origin = Repo::init(&root.join("origin")).unwrap();
2793
    let url = root.join("origin").to_string_lossy().to_string();
2794
    let mut a = Repo::clone(&url, &root.join("a"))
2795
        .unwrap()
2796
        .with_home(root.join("home-a"));
2797
    a.set_user_config("core.sign", "change").unwrap();
2798
    let (key_a, _) = a
2799
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2800
        .unwrap();
2801
    write(&root.join("a"), "a.txt", b"a\n");
2802
    let h1 = a.commit("one", &[]).unwrap();
2803
    assert!(a.policy_init().unwrap().applied);
2804
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2805
2806
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2807
    let mut e = Repo::init(&root.join("e"))
2808
        .unwrap()
2809
        .with_home(root.join("home-e"));
2810
    e.set_user_config("core.sign", "change").unwrap();
2811
    e.create_identity_with(
2812
        "Eve",
2813
        "[email protected]",
2814
        IdentityScope::User,
2815
        Some(Hlc::now().wall_ms - 1),
2816
    )
2817
    .unwrap();
2818
    write(&root.join("e"), "e.txt", b"e\n");
2819
    let he = e.commit("late", &[]).unwrap();
2820
    assert!(
2821
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2822
    );
2823
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2824
    let r = e
2825
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2826
        .unwrap();
2827
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2828
    write(&root.join("e"), "e.txt", b"e2\n");
2829
    let he2 = e.commit("in time", &[]).unwrap();
2830
    assert!(
2831
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2832
    );
2833
2834
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2835
    let r = a.rotate_identity().unwrap();
2836
    assert_eq!(r.old, key_a);
2837
    assert_eq!(a.config.author_key, Some(r.new));
2838
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2839
    assert!(r.policy.as_ref().unwrap().applied);
2840
    let (_, sp) = a.current_policy().unwrap().unwrap();
2841
    assert_eq!(
2842
        (sp.policy.serial, sp.policy.roots.clone()),
2843
        (2, vec![r.new])
2844
    );
2845
    assert!(
2846
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2847
        "superseded, not revoked"
2848
    );
2849
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2850
    assert!(
2851
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2852
    );
2853
    write(&root.join("a"), "a.txt", b"a2\n");
2854
    let h2 = a.commit("two", &[]).unwrap();
2855
    assert!(
2856
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2857
    );
2858
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2859
    let res = a.push("origin", false).unwrap();
2860
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2861
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2862
    let key_a = r.new;
2863
2864
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2865
    // identity object, so Ada's KeyId changes while her keys stay the same.
2866
    let mut b = Repo::clone(&url, &root.join("b"))
2867
        .unwrap()
2868
        .with_home(root.join("home-b"));
2869
    let (key_b, id_b) = b
2870
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2871
        .unwrap();
2872
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
2873
    assert_eq!(r.old, key_a);
2874
    let key_a2 = r.new;
2875
    assert_eq!(
2876
        a.identity(&key_a2).unwrap().delegates,
2877
        vec![Delegate::full(key_b)]
2878
    );
2879
    assert_eq!(
2880
        a.identity(&key_a2).unwrap().ed25519_pk,
2881
        a.identity(&key_a).unwrap().ed25519_pk
2882
    );
2883
    assert!(
2884
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2885
        "already a delegate"
2886
    );
2887
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2888
    write(&root.join("a"), "a.txt", b"a3\n");
2889
    let h3 = a.commit("three", &[]).unwrap();
2890
    assert!(
2891
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2892
        "the same secret signs under the new KeyId"
2893
    );
2894
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2895
    a.set_user_config("core.sign", "seal").unwrap();
2896
    write(&root.join("a"), "a.txt", b"a4\n");
2897
    let h4 = a.commit("four", &[]).unwrap();
2898
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2899
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2900
    a.store()
2901
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2902
        .unwrap();
2903
    assert!(
2904
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2905
    );
2906
    a.set_user_config("core.sign", "change").unwrap();
2907
    // Withdrawing the delegation re-issues the identity again.
2908
    let r = a.delegate_remove(&key_b).unwrap();
2909
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2910
    assert!(a.delegate_remove(&key_b).is_err());
2911
    let key_a3 = r.new;
2912
    let res = a.push("origin", false).unwrap();
2913
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2914
2915
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2916
    // both applied under the old threshold of 1. A grant then needs Bob too.
2917
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2918
    assert!(a.policy_root_add(id_b.clone()).is_err());
2919
    assert!(a.policy_set_threshold(3).is_err());
2920
    assert!(a.policy_set_threshold(2).unwrap().applied);
2921
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2922
    b.pull("origin").unwrap();
2923
    assert_eq!(
2924
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2925
        2
2926
    );
2927
    let mut c = Repo::init(&root.join("c"))
2928
        .unwrap()
2929
        .with_home(root.join("home-c"));
2930
    let (key_c, id_c) = c
2931
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2932
        .unwrap();
2933
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2934
    let proposal = a.policy_grant(id_c, None).unwrap();
2935
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2936
    assert_eq!(proposal.policy.serial, serial_before + 1);
2937
    assert_eq!(
2938
        a.current_policy().unwrap().unwrap().1.policy.serial,
2939
        serial_before,
2940
        "a proposal changes nothing yet"
2941
    );
2942
    // Bob signs the proposal, handed over as a file, and it applies for him.
2943
    let bytes = proposal.signed().encode();
2944
    let signed = b
2945
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2946
        .unwrap();
2947
    assert!(signed.applied && signed.sigs.len() == 2);
2948
    assert!(b
2949
        .current_policy()
2950
        .unwrap()
2951
        .unwrap()
2952
        .1
2953
        .policy
2954
        .authorizes(&key_c, "main"));
2955
    assert!(
2956
        b.policy_sign(signed.signed()).is_err(),
2957
        "a stale proposal is refused"
2958
    );
2959
    // Bob publishes it and Ada picks it up.
2960
    assert!(b
2961
        .push("origin", false)
2962
        .unwrap()
2963
        .iter()
2964
        .any(|x| x.name == "policy" && x.ok));
2965
    a.pull("origin").unwrap();
2966
    assert_eq!(
2967
        a.current_policy().unwrap().unwrap().1.policy.serial,
2968
        serial_before + 1
2969
    );
2970
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2971
    assert!(a.policy_revoke(&key_a3).is_err());
2972
    let u = a
2973
        .revoke_identity(&key_c, "left the project")
2974
        .unwrap()
2975
        .unwrap();
2976
    assert!(!u.applied);
2977
    assert!(a.is_revoked(&key_c).unwrap());
2978
    assert!(!b.is_revoked(&key_c).unwrap());
2979
    let u = b.policy_sign(u.signed()).unwrap();
2980
    assert!(u.applied && u.policy.is_revoked(&key_c));
2981
    assert!(b.is_revoked(&key_c).unwrap());
2982
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2983
    assert!(
2984
        b.policy_revoke(&key_a3).is_err(),
2985
        "would leave one root for a threshold of 2"
2986
    );
2987
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2988
    let key_c_own = c.config.author_key.unwrap();
2989
    assert!(c
2990
        .revoke_identity(&key_c_own, "lost laptop")
2991
        .unwrap()
2992
        .is_none());
2993
    assert!(c.is_revoked(&key_c_own).unwrap());
2994
    assert_eq!(key_c_own, key_c);
2995
}
2996
2997
#[test]
2998
fn renames_are_detected_and_tracked_as_moves() {
2999
    hermetic();
3000
    let dir = tempfile::tempdir().unwrap();
3001
    let root = dir.path();
3002
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3003
    write(
3004
        root,
3005
        "src/old.rs",
3006
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3007
    );
3008
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3009
    write(root, "tiny.txt", b"x\n");
3010
    let h1 = repo.commit("base", &[]).unwrap();
3011
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3012
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3013
3014
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3015
    // that shares nothing with the removed file.
3016
    fs::remove_file(root.join("src/old.rs")).unwrap();
3017
    write(
3018
        root,
3019
        "lib/new.rs",
3020
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3021
    );
3022
    fs::remove_file(root.join("img.bin")).unwrap();
3023
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3024
    fs::remove_file(root.join("tiny.txt")).unwrap();
3025
    write(root, "other.txt", b"completely different\n");
3026
    let snap = repo.snapshot("status").unwrap();
3027
    let statuses: Vec<(&str, ChangeStatus)> = snap
3028
        .statuses
3029
        .iter()
3030
        .map(|s| (s.path.as_str(), s.status))
3031
        .collect();
3032
    assert_eq!(
3033
        statuses,
3034
        vec![
3035
            ("assets/img.bin", ChangeStatus::Renamed),
3036
            ("lib/new.rs", ChangeStatus::Renamed),
3037
            ("other.txt", ChangeStatus::Added),
3038
            ("src", ChangeStatus::Removed),
3039
            ("tiny.txt", ChangeStatus::Removed)
3040
        ]
3041
    );
3042
    let h2 = repo.commit("move things", &[]).unwrap();
3043
    let c = repo.store().get_change(&h2).unwrap();
3044
    let moves: Vec<_> = c
3045
        .tree_ops
3046
        .iter()
3047
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3048
        .collect();
3049
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
3050
    assert!(c.tree_ops.iter().any(
3051
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3052
    ));
3053
    assert!(c.tree_ops.iter().any(
3054
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3055
    ));
3056
    let snap = repo.load_state(&[h2]).unwrap().materialize();
3057
    assert_eq!(
3058
        snap.files["lib/new.rs"].node, node_old,
3059
        "the node survives the rename"
3060
    );
3061
    assert!(
3062
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3063
    );
3064
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
3065
    assert!(render_change(
3066
        &c,
3067
        &repo.load_state(&[h1]).unwrap(),
3068
        &repo.load_state(&[h1]).unwrap().materialize()
3069
    )
3070
    .contains("R "));
3071
    // A fresh checkout reproduces the tree.
3072
    let other = tempfile::tempdir().unwrap();
3073
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
3074
    assert_eq!(
3075
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3076
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3077
    );
3078
    assert!(!other.path().join("src").exists());
3079
    assert!(!clone.snapshot("status").unwrap().changed);
3080
    // Similarity is line based, byte weighted.
3081
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3082
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3083
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3084
    assert_eq!(similarity(b"", b"x\n"), 0);
3085
}
3086
3087
#[test]
3088
fn git_fetch_and_push_round_trip() {
3089
    hermetic();
3090
    if std::process::Command::new("git")
3091
        .arg("--version")
3092
        .output()
3093
        .is_err()
3094
    {
3095
        eprintln!("git not installed; skipping");
3096
        return;
3097
    }
3098
    let dir = tempfile::tempdir().unwrap();
3099
    let root = dir.path();
3100
    let git_in = |d: &Path, args: &[&str]| -> String {
3101
        let out = std::process::Command::new("git")
3102
            .arg("-C")
3103
            .arg(d)
3104
            .args([
3105
                "-c",
3106
                "user.name=Grace",
3107
                "-c",
3108
                "[email protected]",
3109
                "-c",
3110
                "commit.gpgsign=false",
3111
            ])
3112
            .args(args)
3113
            .output()
3114
            .unwrap();
3115
        assert!(
3116
            out.status.success(),
3117
            "git {args:?}: {}",
3118
            String::from_utf8_lossy(&out.stderr)
3119
        );
3120
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3121
    };
3122
    // A bare "remote" and a work tree that pushes to it.
3123
    let remote = root.join("remote.git");
3124
    fs::create_dir_all(&remote).unwrap();
3125
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3126
    let work = root.join("work");
3127
    git_in(
3128
        root,
3129
        &[
3130
            "clone",
3131
            "-q",
3132
            remote.to_str().unwrap(),
3133
            work.to_str().unwrap(),
3134
        ],
3135
    );
3136
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3137
    write(&work, "README.md", b"# Project\n");
3138
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3139
    git_in(&work, &["add", "."]);
3140
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3141
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3142
    git_in(&work, &["commit", "-q", "-am", "second"]);
3143
    git_in(&work, &["push", "-q", "origin", "main"]);
3144
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3145
3146
    // Fetch into a fresh oxy repository.
3147
    let o = root.join("oxy");
3148
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
3149
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3150
        .unwrap();
3151
    let url = remote.to_string_lossy().to_string();
3152
    let r = repo.git_fetch(&url, "main").unwrap();
3153
    assert_eq!((r.commits, r.heads), (2, 1));
3154
    assert_eq!(
3155
        fs::read(o.join("src/lib.rs")).unwrap(),
3156
        b"pub fn a() {}\npub fn b() {}\n"
3157
    );
3158
    assert!(!repo.snapshot("status").unwrap().changed);
3159
    assert_eq!(
3160
        repo.git_fetch(&url, "main").unwrap().commits,
3161
        0,
3162
        "nothing new"
3163
    );
3164
3165
    // An oxy change, pushed back: one commit on top of the Git tip.
3166
    write(
3167
        &o,
3168
        "src/lib.rs",
3169
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3170
    );
3171
    write(&o, "NOTES.md", b"from oxy\n");
3172
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3173
    let r = repo.git_push(&url, "main").unwrap();
3174
    assert_eq!(r.exported, 1, "{r:?}");
3175
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3176
    assert_eq!(
3177
        git_in(&work, &["log", "--format=%s", "main"]),
3178
        "add c and notes\nsecond\ninitial"
3179
    );
3180
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3181
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3182
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
3183
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3184
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3185
    assert_eq!(
3186
        repo.git_push(&url, "main").unwrap().exported,
3187
        0,
3188
        "already pushed"
3189
    );
3190
3191
    // Git moves on; pushing without fetching is refused, fetching brings
3192
    // the commit in and the working copy follows.
3193
    write(&work, "README.md", b"# Project\n\nMore.\n");
3194
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3195
    git_in(&work, &["push", "-q", "origin", "main"]);
3196
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
3197
    assert!(repo
3198
        .git_push(&url, "main")
3199
        .unwrap_err()
3200
        .to_string()
3201
        .contains("fetch"));
3202
    let r = repo.git_fetch(&url, "main").unwrap();
3203
    assert_eq!(
3204
        (r.commits, r.heads),
3205
        (1, 2),
3206
        "the Git change and the oxy change commute"
3207
    );
3208
    assert_eq!(
3209
        fs::read(o.join("README.md")).unwrap(),
3210
        b"# Project\n\nMore.\n"
3211
    );
3212
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3213
    assert!(!repo.snapshot("status").unwrap().changed);
3214
    // Another oxy change pushes on top of Git's newest commit.
3215
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3216
    repo.commit("notes again", &[]).unwrap();
3217
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3218
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3219
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
3220
    assert_eq!(
3221
        fs::read(work.join("NOTES.md")).unwrap(),
3222
        b"from oxy\nagain\n"
3223
    );
3224
    assert_eq!(
3225
        git_in(&work, &["log", "--format=%s", "main"])
3226
            .lines()
3227
            .count(),
3228
        5
3229
    );
3230
}
3231
3232
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3233
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3234
#[test]
3235
#[ignore]
3236
fn bench_one_gibibyte_file() {
3237
    hermetic();
3238
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3239
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3240
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3241
        None => tempfile::tempdir().unwrap(),
3242
    };
3243
    let root = dir.path();
3244
    let repo = Repo::init(&root.join("r"))
3245
        .unwrap()
3246
        .with_home(root.join("home"));
3247
    let size = 1usize << 30;
3248
    let mut data = vec![0u8; size];
3249
    let mut x = 0x9e3779b97f4a7c15u64;
3250
    for chunk in data.chunks_mut(8) {
3251
        x ^= x << 13;
3252
        x ^= x >> 7;
3253
        x ^= x << 17;
3254
        let b = x.to_le_bytes();
3255
        chunk.copy_from_slice(&b[..chunk.len()]);
3256
    }
3257
    let t = std::time::Instant::now();
3258
    write(&root.join("r"), "big.bin", &data);
3259
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3260
    let t = std::time::Instant::now();
3261
    let h = repo.commit("big", &[]).unwrap();
3262
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3263
    let t = std::time::Instant::now();
3264
    assert!(!repo.snapshot("status").unwrap().changed);
3265
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3266
    let t = std::time::Instant::now();
3267
    let objects = repo.store().list().unwrap().len();
3268
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3269
    let t = std::time::Instant::now();
3270
    let g = repo.gc(true).unwrap();
3271
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3272
    let t = std::time::Instant::now();
3273
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3274
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3275
    let t = std::time::Instant::now();
3276
    let back = fs::read(root.join("c/big.bin")).unwrap();
3277
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3278
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3279
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3280
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
3281
    eprintln!(
3282
        "store size: {:.1} MiB for 1 GiB of data",
3283
        store_bytes as f64 / (1024.0 * 1024.0)
3284
    );
3285
}
3286
3287
fn walkdir_size(p: &Path) -> u64 {
3288
    let mut total = 0;
3289
    if let Ok(rd) = fs::read_dir(p) {
3290
        for e in rd.flatten() {
3291
            let path = e.path();
3292
            if path.is_dir() {
3293
                total += walkdir_size(&path);
3294
            } else if let Ok(m) = fs::metadata(&path) {
3295
                total += m.len();
3296
            }
3297
        }
3298
    }
3299
    total
3300
}
3301
3302
/// An opaque file whose size and mtime match the manifest is not read on
3303
/// the next snapshot: its blob comes from the manifest's stat cache.
3304
#[cfg(unix)]
3305
#[test]
3306
fn stat_cache_skips_reading_unchanged_opaque_files() {
3307
    use std::os::unix::fs::PermissionsExt;
3308
    hermetic();
3309
    let dir = tempfile::tempdir().unwrap();
3310
    let root = dir.path();
3311
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3312
    let mut big = vec![0u8; 300 * 1024];
3313
    for (i, b) in big.iter_mut().enumerate() {
3314
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3315
    }
3316
    big[0] = 0;
3317
    write(root, "big.bin", &big);
3318
    write(root, "a.txt", b"text\n");
3319
    let h1 = repo.commit("base", &[]).unwrap();
3320
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3321
    assert!(
3322
        m.entries["big.bin"].blob.is_some(),
3323
        "opaque files record their blob"
3324
    );
3325
    assert!(m.entries["a.txt"].blob.is_none());
3326
    let blob = m.entries["big.bin"].blob.unwrap();
3327
    assert!(repo.store().has(&blob));
3328
3329
    // Files modified within two seconds of the manifest are racy and still
3330
    // read; age the file so the cache applies, then snapshot to record it.
3331
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3332
    fs::File::options()
3333
        .write(true)
3334
        .open(root.join("big.bin"))
3335
        .unwrap()
3336
        .set_modified(old)
3337
        .unwrap();
3338
    assert!(!repo.snapshot("status").unwrap().changed);
3339
    // Now the file cannot be read at all; the snapshot succeeds without it.
3340
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3341
    let snap = repo.snapshot("status").unwrap();
3342
    assert!(
3343
        !snap.changed && snap.statuses.is_empty(),
3344
        "{:?}",
3345
        snap.statuses
3346
    );
3347
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3348
    // A real change (new mtime, new content) is seen and committed correctly.
3349
    let mut big2 = big.clone();
3350
    big2[10] ^= 0xff;
3351
    write(root, "big.bin", &big2);
3352
    let snap = repo.snapshot("status").unwrap();
3353
    assert_eq!(
3354
        snap.statuses
3355
            .iter()
3356
            .map(|s| (s.path.as_str(), s.status))
3357
            .collect::<Vec<_>>(),
3358
        vec![("big.bin", ChangeStatus::Modified)]
3359
    );
3360
    let h2 = repo.commit("edit", &[]).unwrap();
3361
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3362
    assert_eq!(
3363
        files["big.bin"].content,
3364
        FileContent::Opaque {
3365
            blobs: vec![Repo::blob_ref(&big2)]
3366
        }
3367
    );
3368
    // Checkout writes a manifest with blobs too, so the next status is cached.
3369
    repo.checkout(&[h1], false, "checkout").unwrap();
3370
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3371
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3372
    assert!(!repo.snapshot("status").unwrap().changed);
3373
}
3374
3375
#[test]
3376
fn status_json_lists_conflicts_with_contributors() {
3377
    hermetic();
3378
    let dir = tempfile::tempdir().unwrap();
3379
    let root = dir.path();
3380
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3381
    write(root, "a.txt", b"one\n");
3382
    let h1 = repo.commit("base", &[]).unwrap();
3383
    write(root, "a.txt", b"one\nleft\n");
3384
    let ha = repo.commit("left", &[]).unwrap();
3385
    repo.checkout(&[h1], true, "checkout").unwrap();
3386
    write(root, "a.txt", b"one\nright\n");
3387
    let hb = repo.commit("right", &[]).unwrap();
3388
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3389
    let snap = repo.snapshot("status").unwrap();
3390
    assert!(snap.base_snapshot.is_conflicted());
3391
    let json = repo.status_json(&snap).unwrap();
3392
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3393
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3394
    assert!(json.contains("\"conflicted\":true"), "{json}");
3395
    assert!(
3396
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3397
        "{json}"
3398
    );
3399
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3400
    assert!(json.contains("\"resolved\":false"), "{json}");
3401
    assert!(json.starts_with('{') && json.ends_with('}'));
3402
    // Resolve and the report says so; a clean copy has no conflicts.
3403
    write(root, "a.txt", b"one\nleft\nright\n");
3404
    let snap = repo.snapshot("status").unwrap();
3405
    let json = repo.status_json(&snap).unwrap();
3406
    assert!(json.contains("\"resolved\":true"), "{json}");
3407
    repo.commit("resolve", &[]).unwrap();
3408
    let snap = repo.snapshot("status").unwrap();
3409
    let json = repo.status_json(&snap).unwrap();
3410
    assert!(
3411
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3412
        "{json}"
3413
    );
3414
}
3415
3416
#[test]
3417
fn ignore_rules_do_not_untrack_files() {
3418
    hermetic();
3419
    let dir = tempfile::tempdir().unwrap();
3420
    let root = dir.path();
3421
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3422
    write(root, "src.c", b"int x;\n");
3423
    write(root, "build/out.o", b"\0obj");
3424
    write(root, "sub/keep.log", b"keep\n");
3425
    write(root, "sub/junk.log", b"junk\n");
3426
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3427
    let snap = repo.snapshot("status").unwrap();
3428
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3429
    assert_eq!(
3430
        added,
3431
        vec![".oxyignore", "src.c", "sub/keep.log"],
3432
        "anchored, glob, and negated rules"
3433
    );
3434
    let h1 = repo.commit("base", &[]).unwrap();
3435
    // Ignoring a tracked file changes nothing about it.
3436
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3437
    let snap = repo.snapshot("status").unwrap();
3438
    assert_eq!(
3439
        snap.statuses
3440
            .iter()
3441
            .map(|s| s.path.as_str())
3442
            .collect::<Vec<_>>(),
3443
        vec![".oxyignore"]
3444
    );
3445
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3446
    assert!(repo
3447
        .load_state(&[h2])
3448
        .unwrap()
3449
        .materialize()
3450
        .files
3451
        .contains_key("src.c"));
3452
    // Its edits are still seen, by status and by the prompt.
3453
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3454
    write(root, "src.c", b"int x, y;\n");
3455
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3456
    let snap = repo.snapshot("status").unwrap();
3457
    assert_eq!(
3458
        snap.statuses
3459
            .iter()
3460
            .map(|s| (s.path.as_str(), s.status))
3461
            .collect::<Vec<_>>(),
3462
        vec![("src.c", ChangeStatus::Modified)]
3463
    );
3464
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3465
    assert!(
3466
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3467
    );
3468
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3469
    fs::remove_file(root.join("src.c")).unwrap();
3470
    let snap = repo.snapshot("status").unwrap();
3471
    assert_eq!(
3472
        snap.statuses
3473
            .iter()
3474
            .map(|s| (s.path.as_str(), s.status))
3475
            .collect::<Vec<_>>(),
3476
        vec![("src.c", ChangeStatus::Removed)]
3477
    );
3478
    repo.checkout(&[h3], true, "checkout").unwrap();
3479
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3480
    assert!(!repo.snapshot("status").unwrap().changed);
3481
    let _ = h1;
3482
}
3483
3484
#[test]
3485
fn split_works_on_non_heads_by_node() {
3486
    hermetic();
3487
    let dir = tempfile::tempdir().unwrap();
3488
    let root = dir.path();
3489
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3490
    write(root, "a.txt", b"one\n");
3491
    write(root, "junk/x.lock", b"lock\n");
3492
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3493
    write(root, "a.txt", b"one\ntwo\n");
3494
    let h2 = repo.commit("more work", &[]).unwrap();
3495
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3496
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3497
    // h1 is not a head: split it by node.
3498
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3499
    assert_ne!(h1b, h1);
3500
    assert_eq!(
3501
        repo.store().get_change(&h1b).unwrap().change_id,
3502
        id1,
3503
        "the rest keeps the ChangeId"
3504
    );
3505
    let junk = repo.store().get_change(&hj).unwrap();
3506
    assert!(junk.tree_ops.iter().all(
3507
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3508
    ));
3509
    let heads = repo.bookmark_heads().unwrap();
3510
    assert!(
3511
        heads.contains(&hj),
3512
        "the split-off part is a head of its own"
3513
    );
3514
    let snap = repo.load_state(&heads).unwrap().materialize();
3515
    assert!(
3516
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3517
        "the dependent was rewritten onto the new hash"
3518
    );
3519
    assert!(snap.files.contains_key("junk/x.lock"));
3520
    let h2b = heads
3521
        .iter()
3522
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3523
        .copied()
3524
        .unwrap();
3525
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3526
    assert!(!repo.snapshot("status").unwrap().changed);
3527
    // Abandoning the split-off head removes the junk from history.
3528
    repo.abandon(&hj).unwrap();
3529
    let heads = repo.bookmark_heads().unwrap();
3530
    let snap = repo.load_state(&heads).unwrap().materialize();
3531
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3532
    assert!(snap.files.contains_key("a.txt"));
3533
    // A dependent that touches the split-off paths blocks the split.
3534
    write(root, "junk/y.lock", b"y\n");
3535
    let hb = repo.commit("junk base", &[]).unwrap();
3536
    write(root, "junk/y.lock", b"yy\n");
3537
    write(root, "b.txt", b"b\n");
3538
    repo.commit("touches junk", &[]).unwrap();
3539
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3540
    assert!(err.contains("depends on the split-off paths"), "{err}");
3541
}
3542
3543
#[test]
3544
fn bookmarks_switch_merge_and_push() {
3545
    hermetic();
3546
    let dir = tempfile::tempdir().unwrap();
3547
    let root = dir.path();
3548
    let origin = Repo::init(&root.join("origin")).unwrap();
3549
    let url = root.join("origin").to_string_lossy().to_string();
3550
    let mut repo = Repo::clone(&url, &root.join("r"))
3551
        .unwrap()
3552
        .with_home(root.join("home"));
3553
    let r = root.join("r");
3554
    write(&r, "a.txt", b"a\n");
3555
    let h_a = repo.commit("a", &[]).unwrap();
3556
    assert!(repo.push("origin", false).unwrap()[0].ok);
3557
3558
    // A bookmark at the working copy's base, then work on it.
3559
    assert!(repo.bookmark_create("bad name..", None).is_err());
3560
    assert!(repo.bookmark_create("-x", None).is_err());
3561
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3562
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3563
    repo.bookmark_switch("feature", false).unwrap();
3564
    assert_eq!(repo.config.bookmark, "feature");
3565
    write(&r, "a.txt", b"a\nb\n");
3566
    write(&r, "b.txt", b"b\n");
3567
    let h_b = repo.commit("b on feature", &[]).unwrap();
3568
    assert_eq!(
3569
        repo.bookmark_heads().unwrap(),
3570
        vec![h_b],
3571
        "b edits a.txt, so it depends on a"
3572
    );
3573
    assert_eq!(
3574
        repo.resolve_heads("main").unwrap(),
3575
        vec![h_a],
3576
        "main is untouched"
3577
    );
3578
    assert_eq!(
3579
        repo.resolve_change("feature").unwrap(),
3580
        h_b,
3581
        "a one-head bookmark names its change"
3582
    );
3583
    // Reopening keeps the workspace's bookmark.
3584
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3585
    assert_eq!(reopened.config.bookmark, "feature");
3586
    // Back to main: b.txt goes away; work there.
3587
    repo.bookmark_switch("main", false).unwrap();
3588
    assert!(!r.join("b.txt").exists());
3589
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3590
    write(&r, "c.txt", b"c\n");
3591
    let h_c = repo.commit("c on main", &[]).unwrap();
3592
    let list = repo.bookmarks().unwrap();
3593
    assert_eq!(
3594
        list.iter()
3595
            .map(|b| (b.name.as_str(), b.current))
3596
            .collect::<Vec<_>>(),
3597
        vec![("feature", false), ("main", true)]
3598
    );
3599
    assert_eq!(
3600
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3601
        Some(1),
3602
        "c is not on origin yet"
3603
    );
3604
    // Merge feature into main: the union, both heads, no merge change.
3605
    let m = repo.merge("feature").unwrap();
3606
    assert!(m.changed && m.checked_out);
3607
    let mut want = vec![h_b, h_c];
3608
    want.sort();
3609
    assert_eq!(m.heads, want);
3610
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3611
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3612
    assert!(repo.merge("main").is_err());
3613
    // The other bookmark can be pushed by name and appears at origin.
3614
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3615
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3616
    assert!(repo.push("origin", false).unwrap()[0].ok);
3617
    assert_eq!(
3618
        repo.bookmarks()
3619
            .unwrap()
3620
            .iter()
3621
            .find(|b| b.name == "main")
3622
            .unwrap()
3623
            .ahead,
3624
        Some(0)
3625
    );
3626
    // A second workspace inherits the current bookmark and can switch independently.
3627
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3628
    assert_eq!(ws.config.bookmark, "main");
3629
    let mut ws = ws;
3630
    ws.bookmark_switch("feature", false).unwrap();
3631
    assert_eq!(
3632
        Repo::open(&r).unwrap().config.bookmark,
3633
        "main",
3634
        "the first workspace is unaffected"
3635
    );
3636
    assert!(
3637
        repo.bookmark_delete("feature").is_err(),
3638
        "current bookmark of another workspace"
3639
    );
3640
    ws.bookmark_switch("main", false).unwrap();
3641
    // Set and delete.
3642
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3643
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3644
    repo.bookmark_delete("feature").unwrap();
3645
    assert!(repo.resolve_heads("feature").is_err());
3646
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3647
    assert!(
3648
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3649
        "changes of a deleted bookmark remain"
3650
    );
3651
}
3652
3653
#[test]
3654
fn oxygen_subrepos_pin_follow_and_update() {
3655
    hermetic();
3656
    let dir = tempfile::tempdir().unwrap();
3657
    let root = dir.path();
3658
    // A library repository with two commits, and a bare-ish origin for it.
3659
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3660
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3661
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3662
        .unwrap()
3663
        .with_home(root.join("home"));
3664
    write(&root.join("lib"), "lib.txt", b"v1\n");
3665
    let l1 = lib.commit("lib v1", &[]).unwrap();
3666
    assert!(lib.push("origin", false).unwrap()[0].ok);
3667
    let _ = lib_origin;
3668
3669
    // The application (a clone of its own origin) adds it as a subrepo.
3670
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3671
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3672
    let _ = app_origin;
3673
    let app_dir = root.join("app");
3674
    let app = Repo::clone(&app_url, &app_dir)
3675
        .unwrap()
3676
        .with_home(root.join("home"));
3677
    write(&app_dir, "main.txt", b"app\n");
3678
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3679
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3680
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3681
    let snap = app.snapshot("status").unwrap();
3682
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3683
    assert_eq!(
3684
        paths,
3685
        vec![".oxymodules", "libs/lib", "main.txt"],
3686
        "the nested files are not walked"
3687
    );
3688
    let a1 = app.commit("app with lib", &[]).unwrap();
3689
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3690
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3691
    assert!(!files.contains_key("libs/lib/lib.txt"));
3692
    assert!(!app.snapshot("status").unwrap().changed);
3693
    let subs = app.subrepos().unwrap();
3694
    assert_eq!(subs.len(), 1);
3695
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3696
3697
    // Advance the nested repository: the parent sees a modified pin.
3698
    let nested = Repo::open(&app_dir.join("libs/lib"))
3699
        .unwrap()
3700
        .with_home(root.join("home"));
3701
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3702
    let l2 = nested.commit("lib v2", &[]).unwrap();
3703
    assert!(nested.push("origin", false).unwrap()[0].ok);
3704
    let snap = app.snapshot("status").unwrap();
3705
    assert_eq!(
3706
        snap.statuses
3707
            .iter()
3708
            .map(|s| (s.path.as_str(), s.status))
3709
            .collect::<Vec<_>>(),
3710
        vec![("libs/lib", ChangeStatus::Modified)]
3711
    );
3712
    let a2 = app.commit("bump lib", &[]).unwrap();
3713
    // Checking out the older app state brings the nested working copy back
3714
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3715
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3716
    assert!(
3717
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3718
        "{:?}",
3719
        r.notes
3720
    );
3721
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3722
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3723
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3724
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3725
    assert!(!app.snapshot("status").unwrap().changed);
3726
    // A dirty nested repository is left alone and reported.
3727
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3728
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3729
    assert!(
3730
        r.notes.iter().any(|n| n.contains("uncommitted")),
3731
        "{:?}",
3732
        r.notes
3733
    );
3734
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3735
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3736
    let r = app.submodule_update(false, &[]).unwrap();
3737
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3738
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3739
    let _ = l2;
3740
3741
    // A fresh clone of the app has the pin but no nested repository until update --init.
3742
    assert!(app.push("origin", false).unwrap()[0].ok);
3743
    let clone_dir = root.join("app-clone");
3744
    let clone = Repo::clone(&app_url, &clone_dir)
3745
        .unwrap()
3746
        .with_home(root.join("home"));
3747
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3748
    assert_eq!(
3749
        clone.submodule_update(false, &[]).unwrap(),
3750
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3751
    );
3752
    assert_eq!(
3753
        clone.submodule_update(true, &[]).unwrap(),
3754
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3755
    );
3756
    assert_eq!(
3757
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3758
        b"v2\n"
3759
    );
3760
    assert!(!clone.snapshot("status").unwrap().changed);
3761
    // Removing the subrepo leaves the directory and drops the node.
3762
    clone.submodule_remove("libs/lib").unwrap();
3763
    let snap = clone.snapshot("status").unwrap();
3764
    assert!(
3765
        snap.statuses
3766
            .iter()
3767
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3768
        "{:?}",
3769
        snap.statuses
3770
    );
3771
    let c = clone.commit("drop lib", &[]).unwrap();
3772
    assert!(!clone
3773
        .load_state(&[c])
3774
        .unwrap()
3775
        .materialize()
3776
        .files
3777
        .contains_key("libs/lib"));
3778
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3779
    assert!(
3780
        !clone.snapshot("status").unwrap().changed,
3781
        "an unregistered nested repository is ignored"
3782
    );
3783
}
3784
3785
#[test]
3786
fn git_submodules_import_and_export_as_gitlinks() {
3787
    hermetic();
3788
    if std::process::Command::new("git")
3789
        .arg("--version")
3790
        .output()
3791
        .is_err()
3792
    {
3793
        eprintln!("git not installed; skipping");
3794
        return;
3795
    }
3796
    let dir = tempfile::tempdir().unwrap();
3797
    let root = dir.path();
3798
    let git_in = |d: &Path, args: &[&str]| -> String {
3799
        let out = std::process::Command::new("git")
3800
            .arg("-C")
3801
            .arg(d)
3802
            .args([
3803
                "-c",
3804
                "user.name=Grace",
3805
                "-c",
3806
                "[email protected]",
3807
                "-c",
3808
                "commit.gpgsign=false",
3809
                "-c",
3810
                "protocol.file.allow=always",
3811
            ])
3812
            .args(args)
3813
            .output()
3814
            .unwrap();
3815
        assert!(
3816
            out.status.success(),
3817
            "git {args:?}: {}",
3818
            String::from_utf8_lossy(&out.stderr)
3819
        );
3820
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3821
    };
3822
    let sub = root.join("sub");
3823
    fs::create_dir_all(&sub).unwrap();
3824
    git_in(&sub, &["init", "-q", "-b", "main"]);
3825
    write(&sub, "s.txt", b"sub\n");
3826
    git_in(&sub, &["add", "."]);
3827
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3828
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3829
    let g = root.join("main.git");
3830
    fs::create_dir_all(&g).unwrap();
3831
    git_in(&g, &["init", "-q", "-b", "main"]);
3832
    write(&g, "README.md", b"# app\n");
3833
    git_in(&g, &["add", "."]);
3834
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3835
    git_in(
3836
        &g,
3837
        &[
3838
            "submodule",
3839
            "add",
3840
            "-q",
3841
            sub.to_str().unwrap(),
3842
            "vendor/sub",
3843
        ],
3844
    );
3845
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3846
3847
    let dest = root.join("oxy");
3848
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3849
    let rep = repo.import_git(&g, "main").unwrap();
3850
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3851
    let files = repo
3852
        .load_state(&repo.bookmark_heads().unwrap())
3853
        .unwrap()
3854
        .materialize()
3855
        .files;
3856
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3857
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3858
        panic!()
3859
    };
3860
    assert_eq!(
3861
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3862
        crate::subrepo::Pin::Git {
3863
            sha: sub_sha.clone(),
3864
            branch: "HEAD".into()
3865
        }
3866
    );
3867
    let modules =
3868
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3869
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3870
    assert!(modules.entries["vendor/sub"].git);
3871
    assert!(
3872
        files.contains_key(".gitmodules"),
3873
        "the Git file is kept for round trips"
3874
    );
3875
    assert!(
3876
        !dest.join("vendor/sub/.git").exists(),
3877
        "not cloned until update --init"
3878
    );
3879
    assert!(!repo.snapshot("status").unwrap().changed);
3880
    // update --init clones it at the pinned commit; status is unchanged.
3881
    assert_eq!(
3882
        repo.submodule_update(true, &[]).unwrap(),
3883
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3884
    );
3885
    assert_eq!(
3886
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3887
        sub_sha
3888
    );
3889
    assert!(!repo.snapshot("status").unwrap().changed);
3890
    // Export writes the gitlink and .gitmodules back.
3891
    let mirror = root.join("mirror.git");
3892
    let rep = repo.git_export(&mirror).unwrap();
3893
    assert_eq!(rep.skipped_subrepos, 0);
3894
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3895
    assert!(
3896
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3897
        "{ls}"
3898
    );
3899
    assert_eq!(
3900
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3901
        ".gitmodules\nREADME.md\nvendor"
3902
    );
3903
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3904
    assert_eq!(
3905
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3906
        orig_tree,
3907
        "tree round trip"
3908
    );
3909
}
3910
3911
#[test]
3912
fn partial_commits_by_path_and_by_hunk() {
3913
    hermetic();
3914
    let dir = tempfile::tempdir().unwrap();
3915
    let root = dir.path();
3916
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3917
    write(root, "a.txt", b"1\n2\n3\n");
3918
    write(root, "b.txt", b"b\n");
3919
    let h0 = repo.commit("base", &[]).unwrap();
3920
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3921
    write(root, "b.txt", b"b\nbb\n");
3922
    write(root, "c.txt", b"c\n");
3923
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3924
    let h1 = repo
3925
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3926
        .unwrap();
3927
    let c1 = repo.store().get_change(&h1).unwrap();
3928
    assert!(
3929
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3930
        "{:?}",
3931
        c1.tree_ops
3932
    );
3933
    assert_eq!(c1.deps, vec![h0]);
3934
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3935
    assert!(
3936
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3937
    );
3938
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3939
    assert!(!files.contains_key("c.txt"));
3940
    let snap = repo.snapshot("status").unwrap();
3941
    assert_eq!(
3942
        snap.statuses
3943
            .iter()
3944
            .map(|s| (s.path.as_str(), s.status))
3945
            .collect::<Vec<_>>(),
3946
        vec![
3947
            ("b.txt", ChangeStatus::Modified),
3948
            ("c.txt", ChangeStatus::Added)
3949
        ]
3950
    );
3951
    assert_eq!(
3952
        fs::read(root.join("b.txt")).unwrap(),
3953
        b"b\nbb\n",
3954
        "disk untouched"
3955
    );
3956
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3957
    let (_, hunks) = repo.hunks().unwrap();
3958
    let b_hunk = hunks
3959
        .iter()
3960
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3961
        .unwrap()
3962
        .index;
3963
    let h2 = repo
3964
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3965
        .unwrap();
3966
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3967
    assert!(
3968
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3969
    );
3970
    assert!(!files.contains_key("c.txt"));
3971
    let snap = repo.snapshot("status").unwrap();
3972
    assert_eq!(
3973
        snap.statuses
3974
            .iter()
3975
            .map(|s| s.path.as_str())
3976
            .collect::<Vec<_>>(),
3977
        vec!["c.txt"]
3978
    );
3979
    // Choosing only the content hunk of a file in a new directory pulls in
3980
    // the directory and file additions it needs.
3981
    write(root, "d/e.txt", b"e\n");
3982
    let (_, hunks) = repo.hunks().unwrap();
3983
    let e_insert = hunks
3984
        .iter()
3985
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3986
        .unwrap()
3987
        .index;
3988
    let h3 = repo
3989
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3990
        .unwrap();
3991
    let c3 = repo.store().get_change(&h3).unwrap();
3992
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3993
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3994
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3995
    // Choosing a new file's addition hunk brings its content along.
3996
    write(root, "f/g.txt", b"g\n");
3997
    let (_, hunks) = repo.hunks().unwrap();
3998
    let g_add = hunks
3999
        .iter()
4000
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4001
        .unwrap()
4002
        .index;
4003
    let h4 = repo
4004
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4005
        .unwrap();
4006
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
4007
    assert!(
4008
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4009
    );
4010
    assert!(!repo
4011
        .snapshot("status")
4012
        .unwrap()
4013
        .statuses
4014
        .iter()
4015
        .any(|s| s.path == "f/g.txt"));
4016
    // Everything left commits normally; the working copy is then clean.
4017
    repo.commit("the rest", &[]).unwrap();
4018
    assert!(!repo.snapshot("status").unwrap().changed);
4019
    let files = repo
4020
        .load_state(&repo.bookmark_heads().unwrap())
4021
        .unwrap()
4022
        .materialize()
4023
        .files;
4024
    assert!(files.contains_key("c.txt"));
4025
}
4026
4027
#[test]
4028
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4029
    hermetic();
4030
    let dir = tempfile::tempdir().unwrap();
4031
    let root = dir.path();
4032
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4033
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4034
        .unwrap();
4035
    write(root, "a.txt", b"one\n");
4036
    let h1 = repo.commit("first", &[]).unwrap();
4037
    write(root, "a.txt", b"one\ntwo\n");
4038
    let h2 = repo.commit("second", &[]).unwrap();
4039
    let b = repo.blame("a.txt").unwrap();
4040
    assert_eq!(
4041
        b.iter()
4042
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4043
            .collect::<Vec<_>>(),
4044
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4045
    );
4046
    assert!(b.iter().all(|l| l.author == "Ada"));
4047
    assert_eq!(
4048
        b[0].change_id,
4049
        repo.store().get_change(&h1).unwrap().change_id
4050
    );
4051
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4052
    repo.commit("rename", &[]).unwrap();
4053
    let b = repo.blame("b.txt").unwrap();
4054
    assert_eq!(
4055
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4056
        vec![h1, h2],
4057
        "the node survives the rename"
4058
    );
4059
    assert!(repo.blame("a.txt").is_err());
4060
}
4061
4062
#[test]
4063
fn bisect_finds_the_first_bad_change() {
4064
    hermetic();
4065
    let dir = tempfile::tempdir().unwrap();
4066
    let root = dir.path();
4067
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4068
    let mut content = String::new();
4069
    let mut hashes = Vec::new();
4070
    for i in 1..=8 {
4071
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4072
        write(root, "f.txt", content.as_bytes());
4073
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4074
    }
4075
    // Each step appends after the previous line, so the chain is linear.
4076
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4077
    repo.bisect_start().unwrap();
4078
    assert!(matches!(
4079
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4080
        BisectStep::NeedMarks { good: 1, bad: 0 }
4081
    ));
4082
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4083
    assert!(
4084
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4085
        "{step:?}"
4086
    );
4087
    // Automated: bad when the bug line is present.
4088
    let step = repo
4089
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4090
        .unwrap();
4091
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4092
    assert_eq!(
4093
        repo.bisect_status().unwrap(),
4094
        Some(BisectStep::Found { culprit: hashes[4] })
4095
    );
4096
    repo.bisect_reset().unwrap();
4097
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4098
    assert!(repo.bisect_status().unwrap().is_none());
4099
    assert!(!repo.snapshot("status").unwrap().changed);
4100
    // Manual marks and a skip.
4101
    repo.bisect_start().unwrap();
4102
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4103
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4104
    let mut skipped_once = false;
4105
    let mut guard = 0;
4106
    while let BisectStep::Testing { .. } = step {
4107
        guard += 1;
4108
        assert!(guard < 20);
4109
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4110
        if !skipped_once && text.contains("line 6") {
4111
            // An untestable state away from the boundary: the search routes around it.
4112
            skipped_once = true;
4113
            step = repo.bisect_mark(None, &[]).unwrap();
4114
            continue;
4115
        }
4116
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4117
    }
4118
    assert!(skipped_once);
4119
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4120
    repo.bisect_reset().unwrap();
4121
    // Skipping the culprit itself leaves it among the candidates reported.
4122
    repo.bisect_start().unwrap();
4123
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4124
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4125
    let mut guard = 0;
4126
    while let BisectStep::Testing { heads, .. } = &step {
4127
        guard += 1;
4128
        assert!(guard < 20);
4129
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4130
        let is_culprit_state =
4131
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4132
        step = if is_culprit_state {
4133
            repo.bisect_mark(None, &[]).unwrap()
4134
        } else {
4135
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4136
        };
4137
    }
4138
    match step {
4139
        BisectStep::Inconclusive { candidates } => assert!(
4140
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4141
            "{candidates:?}"
4142
        ),
4143
        other => panic!("{other:?}"),
4144
    }
4145
    repo.bisect_reset().unwrap();
4146
}
4147
4148
#[test]
4149
fn squash_folds_a_change_into_its_dependency() {
4150
    hermetic();
4151
    let dir = tempfile::tempdir().unwrap();
4152
    let root = dir.path();
4153
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4154
    write(root, "a.txt", b"1\n");
4155
    let a = repo.commit("A", &[]).unwrap();
4156
    write(root, "a.txt", b"1\n2\n");
4157
    let c = repo.commit("C", &[]).unwrap();
4158
    write(root, "a.txt", b"1\n2\n3\n");
4159
    let e = repo.commit("E", &[]).unwrap();
4160
    write(root, "b.txt", b"b\n");
4161
    let b = repo.commit("B", &[]).unwrap();
4162
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4163
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4164
    // E depends on C which A lacks: refused, naming it.
4165
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4166
    assert!(err.contains(&c.short(12)), "{err}");
4167
    // C into A: A' has both, C is gone, E follows and still reads the same.
4168
    let a2 = repo.squash(&c, &a).unwrap();
4169
    let a2c = repo.store().get_change(&a2).unwrap();
4170
    assert_eq!(a2c.change_id, id_a);
4171
    assert!(a2c.deps.is_empty());
4172
    let heads = repo.bookmark_heads().unwrap();
4173
    let st = repo.load_state(&heads).unwrap();
4174
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
4175
    let e2 = st
4176
        .changes()
4177
        .find(|(_, m)| m.change_id == id_e)
4178
        .map(|(h, _)| *h)
4179
        .unwrap();
4180
    assert_eq!(
4181
        repo.store().get_change(&e2).unwrap().deps,
4182
        vec![a2],
4183
        "E now depends on A' alone"
4184
    );
4185
    let files = st.materialize().files;
4186
    assert!(
4187
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4188
    );
4189
    assert!(files.contains_key("b.txt"));
4190
    assert!(st.contains(&b));
4191
    assert!(!repo.snapshot("status").unwrap().changed);
4192
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4193
    // Undo restores the three original changes.
4194
    repo.undo().unwrap();
4195
    repo.undo().unwrap();
4196
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4197
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4198
}
4199
4200
#[test]
4201
fn rebase_re_expresses_a_change_against_another_base() {
4202
    hermetic();
4203
    let dir = tempfile::tempdir().unwrap();
4204
    let root = dir.path();
4205
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4206
    write(root, "a.txt", b"1\n2\n");
4207
    let a = repo.commit("A", &[]).unwrap();
4208
    write(root, "a.txt", b"1\n2\n3\n");
4209
    let c = repo.commit("C: append 3", &[]).unwrap();
4210
    write(root, "a.txt", b"1\n2\n3\n4\n");
4211
    let e = repo.commit("E: append 4", &[]).unwrap();
4212
    // A different base: A plus a change that prepends a line.
4213
    repo.checkout(&[a], true, "checkout").unwrap();
4214
    write(root, "a.txt", b"0\n1\n2\n");
4215
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4216
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4217
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4218
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4219
    let c2 = repo.rebase(&c, &[d]).unwrap();
4220
    let c2c = repo.store().get_change(&c2).unwrap();
4221
    assert_eq!(c2c.change_id, id_c);
4222
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4223
    let heads = repo.bookmark_heads().unwrap();
4224
    let st = repo.load_state(&heads).unwrap();
4225
    assert!(!st.contains(&c) && st.contains(&d));
4226
    let e2 = st
4227
        .changes()
4228
        .find(|(_, m)| m.change_id == id_e)
4229
        .map(|(h, _)| *h)
4230
        .unwrap();
4231
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
4232
    assert!(
4233
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4234
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4235
    );
4236
    let files = st.materialize().files;
4237
    assert!(
4238
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4239
        "{:?}",
4240
        files["a.txt"].content
4241
    );
4242
    assert!(!files["a.txt"].is_conflicted());
4243
    // Rebasing onto a state that already contains the change is refused.
4244
    assert!(repo.rebase(&c2, &[c2]).is_err());
4245
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
4246
    assert!(
4247
        err.contains("lacks dependencies"),
4248
        "E needs C, which D's state does not have: {err}"
4249
    );
4250
}
4251
4252
#[test]
4253
fn unsigned_tags_keep_their_message() {
4254
    hermetic();
4255
    let dir = tempfile::tempdir().unwrap();
4256
    let root = dir.path();
4257
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4258
    write(root, "a.txt", b"a\n");
4259
    repo.commit("a", &[]).unwrap();
4260
    assert!(repo.secret_key().unwrap().is_none());
4261
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4262
        .unwrap();
4263
    let tags = repo.tags().unwrap();
4264
    assert_eq!(
4265
        (
4266
            tags[0].name.as_str(),
4267
            tags[0].message.as_str(),
4268
            tags[0].signer.as_deref()
4269
        ),
4270
        ("v1", "first release", None)
4271
    );
4272
    assert!(
4273
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4274
        "an unsigned attestation is not advertised"
4275
    );
4276
}
4277
4278
#[test]
4279
fn fsck_passes_a_sound_repository_and_names_each_fault() {
4280
    // Files on disk are what this tests: tampering with them, and the
4281
    // directory store's crash points.
4282
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4283
        return;
4284
    }
4285
    hermetic();
4286
    let dir = tempfile::tempdir().unwrap();
4287
    let root = dir.path();
4288
    let origin_path = root.join("origin");
4289
    let origin = Repo::init(&origin_path).unwrap();
4290
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4291
        .unwrap()
4292
        .with_home(root.join("home-a"));
4293
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4294
        .unwrap();
4295
    write(&root.join("a"), "f.txt", b"one\n");
4296
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4297
    let h1 = a.commit("first", &[]).unwrap();
4298
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4299
    let h2 = a.commit("second", &[]).unwrap();
4300
    a.tag_create("v1", &[h2], "first release").unwrap();
4301
    a.checkpoint().unwrap();
4302
    assert!(a.push("origin", false).unwrap()[0].ok);
4303
4304
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4305
    for repo in [&a, &origin] {
4306
        let rep = repo.fsck().unwrap();
4307
        assert_eq!(rep.problems, vec![], "{rep:?}");
4308
        // The two commits, plus the working copy's change in `a`.
4309
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4310
        assert!(rep.ops > 1 && rep.objects > 5);
4311
    }
4312
    assert!(origin.fsck().unwrap().attestations >= 1);
4313
4314
    // A flipped byte in a stored object is corruption, named by hash.
4315
    let c1 = a.store().path_for(&h1);
4316
    let pristine = fs::read(&c1).unwrap();
4317
    let mut bytes = pristine.clone();
4318
    *bytes.last_mut().unwrap() ^= 1;
4319
    fs::write(&c1, &bytes).unwrap();
4320
    let rep = a.fsck().unwrap();
4321
    assert!(rep.errors() >= 1);
4322
    assert!(
4323
        rep.problems
4324
            .iter()
4325
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4326
        "{rep:?}"
4327
    );
4328
    fs::write(&c1, &pristine).unwrap();
4329
    assert_eq!(a.fsck().unwrap().errors(), 0);
4330
4331
    // A missing change is named with what needed it.
4332
    fs::remove_file(&c1).unwrap();
4333
    let rep = a.fsck().unwrap();
4334
    assert!(
4335
        rep.problems.iter().any(|p| p.severity == Severity::Error
4336
            && p.object == Some(h1)
4337
            && p.what.contains("change missing, needed by change")),
4338
        "{rep:?}"
4339
    );
4340
    fs::write(&c1, &pristine).unwrap();
4341
4342
    // A missing blob is an error in a full clone.
4343
    let c2 = a.store().get_change(&h1).unwrap();
4344
    let blob = c2
4345
        .edits
4346
        .iter()
4347
        .find_map(|e| match e {
4348
            Edit::Replace { new: Some(b), .. } => Some(*b),
4349
            _ => None,
4350
        })
4351
        .expect("the binary file is a blob");
4352
    let bp = a.store().path_for(&blob);
4353
    let blob_bytes = fs::read(&bp).unwrap();
4354
    fs::remove_file(&bp).unwrap();
4355
    let rep = a.fsck().unwrap();
4356
    assert!(
4357
        rep.problems
4358
            .iter()
4359
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4360
        "{rep:?}"
4361
    );
4362
    fs::write(&bp, &blob_bytes).unwrap();
4363
4364
    // A broken op log head is reported, not a crash.
4365
    let head = root.join("a/.oxy/ops/head");
4366
    let saved = fs::read(&head).unwrap();
4367
    fs::write(&head, b"not a hash").unwrap();
4368
    let rep = a.fsck().unwrap();
4369
    assert!(
4370
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4371
        "{rep:?}"
4372
    );
4373
    fs::write(&head, saved).unwrap();
4374
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4375
}
4376
4377
/// Copy a directory tree (for restoring a pristine repository).
4378
fn copy_tree(from: &Path, to: &Path) {
4379
    fs::create_dir_all(to).unwrap();
4380
    for e in fs::read_dir(from).unwrap() {
4381
        let e = e.unwrap();
4382
        let target = to.join(e.file_name());
4383
        if e.file_type().unwrap().is_dir() {
4384
            copy_tree(&e.path(), &target);
4385
        } else {
4386
            fs::copy(e.path(), &target).unwrap();
4387
        }
4388
    }
4389
}
4390
4391
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4392
/// would, and check that both repositories still open, pass `fsck`, and
4393
/// accept the same operation again.
4394
#[test]
4395
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4396
    // Files on disk are what this tests: tampering with them, and the
4397
    // directory store's crash points.
4398
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4399
        return;
4400
    }
4401
    use crate::durable::failpoint;
4402
    hermetic();
4403
    let dir = tempfile::tempdir().unwrap();
4404
    let pristine = dir.path().join("pristine");
4405
    let origin_path = pristine.join("origin");
4406
    Repo::init(&origin_path).unwrap();
4407
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4408
        .unwrap()
4409
        .with_home(dir.path().join("home"));
4410
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4411
        .unwrap();
4412
    write(&pristine.join("a"), "f.txt", b"one\n");
4413
    a.commit("first", &[]).unwrap();
4414
    assert!(a.push("origin", false).unwrap()[0].ok);
4415
    drop(a);
4416
4417
    type Op = fn(&Repo) -> Result<()>;
4418
    let edit_and_commit: Op = |r| {
4419
        write(r.root(), "f.txt", b"one\ntwo\n");
4420
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4421
        r.commit("second", &[]).map(|_| ())
4422
    };
4423
    let push: Op = |r| {
4424
        let res = r.push("origin", false)?;
4425
        if res.iter().all(|x| x.ok) {
4426
            Ok(())
4427
        } else {
4428
            Err(RepoError::Msg(format!("{res:?}")))
4429
        }
4430
    };
4431
4432
    for (name, prepare, op) in [
4433
        ("commit", None, edit_and_commit),
4434
        ("push", Some(edit_and_commit), push),
4435
    ] {
4436
        let mut steps = 0;
4437
        for n in 1.. {
4438
            let run = dir.path().join(format!("{name}-{n}"));
4439
            copy_tree(&pristine, &run);
4440
            // Clones record their remote by path; point it at this copy.
4441
            let open = |p: &Path| {
4442
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4443
                r.config
4444
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4445
                    .unwrap();
4446
                r.save_config().unwrap();
4447
                r
4448
            };
4449
            let a = open(&run.join("a"));
4450
            if let Some(prep) = prepare {
4451
                prep(&a).unwrap();
4452
            }
4453
            failpoint::crash_after(n);
4454
            let outcome = op(&a);
4455
            let crashed = failpoint::disarm();
4456
            drop(a);
4457
            if !crashed {
4458
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4459
                steps = n - 1;
4460
                break;
4461
            }
4462
            assert!(
4463
                outcome.is_err(),
4464
                "{name}: a crash at step {n} was swallowed"
4465
            );
4466
            for repo in ["a", "origin"] {
4467
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4468
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4469
                });
4470
                let rep = r.fsck().unwrap();
4471
                assert_eq!(
4472
                    rep.errors(),
4473
                    0,
4474
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4475
                    rep.problems
4476
                );
4477
            }
4478
            // The interrupted operation can simply be run again.
4479
            let a = open(&run.join("a"));
4480
            // A crash after the commit point leaves the commit done.
4481
            let landed = a
4482
                .bookmark_heads()
4483
                .unwrap()
4484
                .iter()
4485
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4486
            let again = match (name, landed) {
4487
                ("commit", true) => Ok(()),
4488
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4489
                _ => op(&a),
4490
            };
4491
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4492
            assert_eq!(a.fsck().unwrap().errors(), 0);
4493
            fs::remove_dir_all(&run).unwrap();
4494
        }
4495
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4496
    }
4497
}
4498
4499
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4500
/// running at the same time lose nothing: every commit ends up on the
4501
/// bookmark, locally and on the remote, and the repository passes fsck.
4502
#[test]
4503
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4504
    hermetic();
4505
    let dir = tempfile::tempdir().unwrap();
4506
    let root = dir.path();
4507
    let origin = root.join("origin");
4508
    Repo::init_bare_unbound(&origin).unwrap();
4509
    let main = root.join("main");
4510
    let mut repo = Repo::init(&main).unwrap();
4511
    repo.config
4512
        .set("remote.origin.url", &origin.to_string_lossy())
4513
        .unwrap();
4514
    repo.save_config().unwrap();
4515
    write(&main, "seed.txt", b"seed\n");
4516
    repo.commit("seed", &[]).unwrap();
4517
    let second = root.join("second");
4518
    repo.workspace_add(&second, None).unwrap();
4519
    drop(repo);
4520
4521
    const EACH: usize = 15;
4522
    std::thread::scope(|s| {
4523
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4524
            s.spawn(move || {
4525
                let r = Repo::open(&dir).unwrap();
4526
                for i in 0..EACH {
4527
                    write(
4528
                        &dir,
4529
                        &format!("{tag}-{i}.txt"),
4530
                        format!("{tag} {i}\n").as_bytes(),
4531
                    );
4532
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4533
                    if push && i % 5 == 4 {
4534
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4535
                        let _ = r.push("origin", false);
4536
                    }
4537
                }
4538
            });
4539
        }
4540
    });
4541
4542
    let repo = Repo::open(&main).unwrap();
4543
    let heads = repo.bookmark_heads().unwrap();
4544
    let state = repo.load_state(&heads).unwrap();
4545
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4546
    for tag in ["a", "b"] {
4547
        for i in 0..EACH {
4548
            assert!(
4549
                messages.contains(&format!("{tag} {i}")),
4550
                "lost commit {tag} {i}; have {messages:?}"
4551
            );
4552
        }
4553
    }
4554
    let rep = repo.fsck().unwrap();
4555
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4556
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4557
    let hosted = Repo::open(&origin).unwrap();
4558
    let hosted_heads = hosted.bookmark_heads().unwrap();
4559
    assert_eq!(
4560
        hosted.load_state(&hosted_heads).unwrap().len(),
4561
        state.len(),
4562
        "the remote has every commit"
4563
    );
4564
}
4565
4566
/// Two operations recorded from the same parent (what two processes do
4567
/// when they race) are merged: both bookmarks' heads survive, and a
4568
/// change made on one side only is kept.
4569
#[test]
4570
fn operations_from_the_same_parent_are_merged() {
4571
    hermetic();
4572
    let dir = tempfile::tempdir().unwrap();
4573
    let root = dir.path();
4574
    let repo = Repo::init(root).unwrap();
4575
    write(root, "a.txt", b"a\n");
4576
    let a = repo.commit("a", &[]).unwrap();
4577
    write(root, "b.txt", b"b\n");
4578
    let b = repo.commit("b", &[]).unwrap();
4579
    let (x, op) = repo.head_op().unwrap();
4580
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4581
4582
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4583
    let mut one = op.view.clone();
4584
    one.bookmarks.insert("main".into(), state(vec![a]));
4585
    one.bookmarks.insert("topic".into(), state(vec![a]));
4586
    let mut two = op.view.clone();
4587
    two.bookmarks.insert("main".into(), state(vec![b]));
4588
    repo.record_op(&[x], "one", one).unwrap();
4589
    let merged = repo.record_op(&[x], "two", two).unwrap();
4590
4591
    let (head, op) = repo.head_op().unwrap();
4592
    assert_eq!(head, merged);
4593
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4594
    assert!(op.command.contains("merged with a concurrent operation"));
4595
    let mut main = repo
4596
        .store()
4597
        .get_state(&op.view.bookmarks["main"])
4598
        .unwrap()
4599
        .heads;
4600
    main.sort();
4601
    let mut want = vec![a, b];
4602
    want.sort();
4603
    assert_eq!(main, want, "both sides' heads are kept");
4604
    assert!(
4605
        op.view.bookmarks.contains_key("topic"),
4606
        "a one-sided change survives"
4607
    );
4608
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4609
}
4610
4611
#[test]
4612
fn failed_requests_come_with_a_next_step() {
4613
    use crate::protocol::hint_for;
4614
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4615
        .unwrap()
4616
        .contains("token"));
4617
    assert!(hint_for("…: HTTP 403: forbidden")
4618
        .unwrap()
4619
        .contains("repo:write"));
4620
    assert!(hint_for("…: HTTP 404: no such repository")
4621
        .unwrap()
4622
        .contains("owner and repository name"));
4623
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4624
        .unwrap()
4625
        .contains("oxyhub-ca.pem"));
4626
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4627
        .unwrap()
4628
        .contains("running"));
4629
    assert!(hint_for("Dns Failed: failed to lookup address information")
4630
        .unwrap()
4631
        .contains("resolve"));
4632
    assert_eq!(hint_for("something else entirely"), None);
4633
}
4634
4635
#[test]
4636
fn doctor_names_problems_and_what_to_do() {
4637
    hermetic();
4638
    let dir = tempfile::tempdir().unwrap();
4639
    let root = dir.path();
4640
    let origin = root.join("origin");
4641
    Repo::init_bare_unbound(&origin).unwrap();
4642
    let mut repo = Repo::init(&root.join("r"))
4643
        .unwrap()
4644
        .with_home(root.join("home"));
4645
    let find = |r: &DoctorReport, area: &str, h: Health| {
4646
        r.checks
4647
            .iter()
4648
            .find(|c| c.area == area && c.health == h)
4649
            .cloned()
4650
    };
4651
4652
    let r = repo.doctor(true);
4653
    assert!(find(&r, "identity", Health::Warn)
4654
        .unwrap()
4655
        .hint
4656
        .unwrap()
4657
        .contains("oxy identity create"));
4658
    assert!(find(&r, "repository", Health::Ok).is_some());
4659
4660
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4661
        .unwrap();
4662
    repo.config.set("author.name", "Ada").unwrap();
4663
    repo.config.set("author.email", "[email protected]").unwrap();
4664
    repo.config
4665
        .set("remote.origin.url", &origin.to_string_lossy())
4666
        .unwrap();
4667
    repo.config
4668
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4669
        .unwrap();
4670
    repo.config.set("remote.down.token", "t").unwrap();
4671
    repo.config
4672
        .set("remote.badca.url", "https://example.invalid/a/b")
4673
        .unwrap();
4674
    repo.config
4675
        .set(
4676
            "remote.badca.ca",
4677
            &root.join("missing.pem").to_string_lossy(),
4678
        )
4679
        .unwrap();
4680
    repo.save_config().unwrap();
4681
4682
    let r = repo.doctor(true);
4683
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4684
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4685
    assert!(find(&r, "remote origin", Health::Ok)
4686
        .unwrap()
4687
        .message
4688
        .contains("first push binds it"));
4689
    let down = find(&r, "remote down", Health::Fail).unwrap();
4690
    assert!(
4691
        down.hint.as_deref().unwrap_or("").contains("running"),
4692
        "{down:?}"
4693
    );
4694
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4695
    assert!(
4696
        badca.hint.unwrap().contains("remote.badca.ca"),
4697
        "the remote's own name is in the hint"
4698
    );
4699
    assert_eq!(r.worst(), Health::Fail);
4700
4701
    // Offline, nothing is contacted.
4702
    let r = repo.doctor(false);
4703
    assert!(find(&r, "remote down", Health::Fail).is_none());
4704
    assert!(find(&r, "remote down", Health::Ok)
4705
        .unwrap()
4706
        .message
4707
        .contains("not contacted"));
4708
}
4709
4710
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4711
/// after it. Inserting after `b` and then deleting `b`, one commit after
4712
/// the other, must not leave a delete/insert conflict.
4713
#[test]
4714
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4715
    hermetic();
4716
    let dir = tempfile::tempdir().unwrap();
4717
    let root = dir.path();
4718
    let repo = Repo::init(root).unwrap();
4719
    write(root, "f", b"a\nb\nc\n");
4720
    repo.commit("base", &[]).unwrap();
4721
    write(root, "f", b"a\nb\nx\nc\n");
4722
    let insert = repo.commit("insert x after b", &[]).unwrap();
4723
    write(root, "f", b"a\nx\nc\n");
4724
    let delete = repo.commit("delete b", &[]).unwrap();
4725
    assert!(
4726
        repo.store()
4727
            .get_change(&delete)
4728
            .unwrap()
4729
            .deps
4730
            .contains(&insert),
4731
        "the deletion depends on the insertion below the deleted line"
4732
    );
4733
    let heads = repo.bookmark_heads().unwrap();
4734
    assert_eq!(heads, vec![delete]);
4735
    let snap = repo.load_state(&heads).unwrap().materialize();
4736
    assert!(!snap.is_conflicted());
4737
    assert!(
4738
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4739
    );
4740
}
4741
4742
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4743
/// replacement depends on the change that set the blob it replaces.
4744
#[test]
4745
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4746
    hermetic();
4747
    let dir = tempfile::tempdir().unwrap();
4748
    let root = dir.path();
4749
    let repo = Repo::init(root).unwrap();
4750
    write(root, "bin", b"\0A");
4751
    let v1 = repo.commit("v1", &[]).unwrap();
4752
    write(root, "bin", b"\0B");
4753
    let v2 = repo.commit("v2", &[]).unwrap();
4754
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4755
    write(root, "bin", b"\0A");
4756
    let v3 = repo.commit("back to A", &[]).unwrap();
4757
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4758
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4759
    let state = repo.load_state(&[v3]).unwrap();
4760
    let snap = state.materialize();
4761
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4762
        panic!("opaque")
4763
    };
4764
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4765
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4766
}
4767
4768
/// Spec §23: a binary file changed on two branches and merged in Git to
4769
/// one side's version comes back as that version at the merge, and the
4770
/// import verifies commit by commit.
4771
#[test]
4772
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4773
    hermetic();
4774
    if std::process::Command::new("git")
4775
        .arg("--version")
4776
        .output()
4777
        .is_err()
4778
    {
4779
        eprintln!("git not installed; skipping");
4780
        return;
4781
    }
4782
    let dir = tempfile::tempdir().unwrap();
4783
    let root = dir.path();
4784
    let g = root.join("src.git");
4785
    fs::create_dir_all(&g).unwrap();
4786
    let git = |args: &[&str]| -> String {
4787
        let out = std::process::Command::new("git")
4788
            .arg("-C")
4789
            .arg(&g)
4790
            .args([
4791
                "-c",
4792
                "user.name=Grace",
4793
                "-c",
4794
                "[email protected]",
4795
                "-c",
4796
                "commit.gpgsign=false",
4797
            ])
4798
            .args(args)
4799
            .output()
4800
            .unwrap();
4801
        assert!(
4802
            out.status.success(),
4803
            "git {args:?}: {}",
4804
            String::from_utf8_lossy(&out.stderr)
4805
        );
4806
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4807
    };
4808
    git(&["init", "-q", "-b", "main"]);
4809
    write(&g, "logo.bin", b"\0base");
4810
    write(&g, "notes.txt", b"a\nb\nc\n");
4811
    git(&["add", "."]);
4812
    git(&["commit", "-qm", "base"]);
4813
    git(&["checkout", "-qb", "side"]);
4814
    write(&g, "logo.bin", b"\0side");
4815
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4816
    git(&["commit", "-qam", "side"]);
4817
    git(&["checkout", "-q", "main"]);
4818
    write(&g, "logo.bin", b"\0main");
4819
    git(&["commit", "-qam", "main"]);
4820
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4821
    let _ = std::process::Command::new("git")
4822
        .arg("-C")
4823
        .arg(&g)
4824
        .args([
4825
            "-c",
4826
            "user.name=G",
4827
            "-c",
4828
            "user.email=g@e",
4829
            "merge",
4830
            "-q",
4831
            "side",
4832
        ])
4833
        .output();
4834
    write(&g, "logo.bin", b"\0main");
4835
    git(&["add", "."]);
4836
    git(&["commit", "-qm", "merge side"]);
4837
    // Then a revert of the binary to its first version.
4838
    write(&g, "logo.bin", b"\0base");
4839
    git(&["commit", "-qam", "back to base"]);
4840
4841
    let repo = Repo::init(&root.join("o")).unwrap();
4842
    let rep = repo.import_git(&g, "main").unwrap();
4843
    assert_eq!(rep.merges, 1);
4844
    let v = repo.verify_git_import(&g, "main").unwrap();
4845
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4846
    assert_eq!(v.commits, 5);
4847
    let snap = repo
4848
        .load_state(&repo.bookmark_heads().unwrap())
4849
        .unwrap()
4850
        .materialize();
4851
    assert!(!snap.is_conflicted());
4852
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4853
        panic!("opaque")
4854
    };
4855
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4856
}
4857
4858
/// Spec §7.7 on a file system without executable bits or symlinks: the
4859
/// recorded bit is kept, and a symlink checked out as a plain file holding
4860
/// its target is still that symlink.
4861
#[cfg(unix)]
4862
#[test]
4863
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4864
    use crate::portable::Platform;
4865
    use std::os::unix::fs::PermissionsExt;
4866
    hermetic();
4867
    let dir = tempfile::tempdir().unwrap();
4868
    let root = dir.path();
4869
    let repo = Repo::init(root).unwrap();
4870
    write(root, "run.sh", b"#!/bin/sh\n");
4871
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4872
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4873
    repo.commit("script and link", &[]).unwrap();
4874
    drop(repo);
4875
4876
    // What checking out on Windows leaves: no exec bit, the link as a file.
4877
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4878
    fs::remove_file(root.join("link")).unwrap();
4879
    write(root, "link", b"run.sh");
4880
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4881
    let s = win.snapshot("oxy status").unwrap();
4882
    assert!(
4883
        s.statuses.is_empty(),
4884
        "nothing changed on Windows: {:?}",
4885
        statuses(&s)
4886
    );
4887
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4888
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4889
    write(root, "link", b"other");
4890
    let h = win.commit("edit on Windows", &[]).unwrap();
4891
    let snap = win.load_state(&[h]).unwrap().materialize();
4892
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4893
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4894
    // The same working copy read as Linux sees the lost bit and the plain file.
4895
    let linux = Repo::open(root).unwrap();
4896
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4897
}
4898
4899
/// Paths that collide on case-insensitive or Windows file systems are
4900
/// named at checkout there, and by doctor everywhere.
4901
#[test]
4902
fn paths_other_platforms_cannot_hold_are_reported() {
4903
    use crate::portable::Platform;
4904
    hermetic();
4905
    let dir = tempfile::tempdir().unwrap();
4906
    let root = dir.path();
4907
    let repo = Repo::init(root).unwrap();
4908
    write(root, "README.md", b"a\n");
4909
    write(root, "readme.md", b"b\n");
4910
    write(root, "src/aux.c", b"int x;\n");
4911
    let h = repo.commit("unportable", &[]).unwrap();
4912
    let r = repo.doctor(false);
4913
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4914
    assert_eq!(port.health, Health::Warn);
4915
    assert!(
4916
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4917
        "{}",
4918
        port.message
4919
    );
4920
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4921
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4922
    assert!(
4923
        rep.notes
4924
            .iter()
4925
            .any(|n| n.contains("README.md and readme.md")),
4926
        "{:?}",
4927
        rep.notes
4928
    );
4929
    assert!(
4930
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4931
        "macOS allows aux.c"
4932
    );
4933
}
4934
4935
#[test]
4936
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4937
    hermetic();
4938
    let dir = tempfile::tempdir().unwrap();
4939
    let repo = Repo::init(dir.path()).unwrap();
4940
    write(dir.path(), "a.txt", b"one\n");
4941
    write(dir.path(), "other.txt", b"x\n");
4942
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4943
    repo.snapshot("t").unwrap();
4944
    let c1 = repo.commit("first", &[]).unwrap();
4945
    write(dir.path(), "other.txt", b"y\n");
4946
    repo.snapshot("t").unwrap();
4947
    repo.commit("other only", &[]).unwrap();
4948
    write(dir.path(), "a.txt", b"one\ntwo\n");
4949
    repo.snapshot("t").unwrap();
4950
    let c3 = repo.commit("second line", &[]).unwrap();
4951
    write(dir.path(), "other.txt", b"z\n");
4952
    repo.snapshot("t").unwrap();
4953
    repo.commit("other again", &[]).unwrap();
4954
4955
    let heads = repo.bookmark_heads().unwrap();
4956
    let state = repo.load_state(&heads).unwrap();
4957
    let full: Vec<ChangeHash> = repo
4958
        .log_for_path_in("a.txt", &heads)
4959
        .unwrap()
4960
        .iter()
4961
        .map(|e| e.hash)
4962
        .collect();
4963
    assert_eq!(
4964
        full,
4965
        vec![c3, c1],
4966
        "newest first, only changes touching the path"
4967
    );
4968
    let newest: Vec<ChangeHash> = repo
4969
        .log_for_path_of(&state, "a.txt", Some(1))
4970
        .unwrap()
4971
        .iter()
4972
        .map(|e| e.hash)
4973
        .collect();
4974
    assert_eq!(newest, vec![c3], "stops at the first");
4975
    assert_eq!(
4976
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4977
        2
4978
    );
4979
    assert!(repo
4980
        .log_for_path_of(&state, "missing.txt", Some(1))
4981
        .is_err());
4982
    assert_eq!(
4983
        repo.log_state(&heads).unwrap().len(),
4984
        repo.log_of(&state).len()
4985
    );
4986
4987
    let tree = state.tree().view();
4988
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4989
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4990
    assert_eq!(
4991
        via_state
4992
            .iter()
4993
            .map(|l| (l.hash, l.text.clone()))
4994
            .collect::<Vec<_>>(),
4995
        via_heads
4996
            .iter()
4997
            .map(|l| (l.hash, l.text.clone()))
4998
            .collect::<Vec<_>>()
4999
    );
5000
    assert_eq!(
5001
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5002
        vec![c1, c3]
5003
    );
5004
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5005
}
5006
5007
/// A text file whose stat matches the manifest and whose recorded hash is
5008
/// the base's content is taken from the base without reading it; anything
5009
/// else is read, so no edit is missed (spec §12.3).
5010
#[cfg(unix)]
5011
#[test]
5012
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5013
    use std::os::unix::fs::PermissionsExt;
5014
    hermetic();
5015
    let dir = tempfile::tempdir().unwrap();
5016
    let root = dir.path();
5017
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5018
    write(root, "a.txt", b"one\ntwo\n");
5019
    write(root, "b.txt", b"bee\n");
5020
    repo.commit("base", &[]).unwrap();
5021
    let age = |p: &str| {
5022
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5023
        fs::File::options()
5024
            .write(true)
5025
            .open(root.join(p))
5026
            .unwrap()
5027
            .set_modified(old)
5028
            .unwrap();
5029
    };
5030
    age("a.txt");
5031
    age("b.txt");
5032
    assert!(
5033
        !repo.snapshot("status").unwrap().changed,
5034
        "records the aged stat"
5035
    );
5036
5037
    // Clean and equal to the base: not read at all.
5038
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5039
    let snap = repo.snapshot("status").unwrap();
5040
    assert!(
5041
        !snap.changed && snap.statuses.is_empty(),
5042
        "{:?}",
5043
        snap.statuses
5044
    );
5045
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5046
5047
    // An uncommitted edit that is older than the manifest: stat-clean, but
5048
    // its hash is not the base's, so it is read and stays visible.
5049
    write(root, "b.txt", b"bee edited\n");
5050
    age("b.txt");
5051
    let first = repo.snapshot("status").unwrap();
5052
    assert_eq!(
5053
        statuses(&first),
5054
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5055
    );
5056
    let again = repo.snapshot("status").unwrap();
5057
    assert_eq!(
5058
        statuses(&again),
5059
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5060
        "still seen once stat-clean"
5061
    );
5062
    assert!(!again.changed, "and the working copy hashes the same");
5063
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5064
    assert!(
5065
        repo.snapshot("status").is_err(),
5066
        "an edited file must be read, never taken from the base"
5067
    );
5068
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5069
5070
    // A same-size edit made just now is racy and read.
5071
    write(root, "a.txt", b"one\nTWO\n");
5072
    assert_eq!(
5073
        statuses(&repo.snapshot("status").unwrap()),
5074
        vec![
5075
            ("a.txt".to_string(), ChangeStatus::Modified),
5076
            ("b.txt".to_string(), ChangeStatus::Modified)
5077
        ]
5078
    );
5079
    // Committing makes the edits the base: both are clean and served from it again.
5080
    repo.commit("edits", &[]).unwrap();
5081
    age("a.txt");
5082
    age("b.txt");
5083
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5084
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5085
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5086
    let snap = repo.snapshot("status").unwrap();
5087
    assert!(!snap.changed && snap.statuses.is_empty());
5088
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5089
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5090
}
5091
5092
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5093
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5094
/// file is unchanged, and loading through the checkpoint equals a full load.
5095
#[test]
5096
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5097
    hermetic();
5098
    let dir = tempfile::tempdir().unwrap();
5099
    let root = dir.path();
5100
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5101
    let long: String = (0..300)
5102
        .map(|i| format!("line {i} of a long file\n"))
5103
        .collect();
5104
    write(root, "long.txt", long.as_bytes());
5105
    write(root, "short.txt", b"short\n");
5106
    repo.commit("base", &[]).unwrap();
5107
    let (r1, _, _) = repo.checkpoint().unwrap();
5108
    let cp1 = crate::objects::Checkpoint::decode(
5109
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5110
    )
5111
    .unwrap();
5112
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5113
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5114
5115
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5116
    repo.gc(true).unwrap();
5117
    assert!(repo.store().has(&graphs1[0]));
5118
    let report = repo.fsck().unwrap();
5119
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5120
5121
    // Loading through the checkpoint equals a full load.
5122
    write(root, "short.txt", b"short, edited\n");
5123
    repo.commit("edit the short file", &[]).unwrap();
5124
    let heads = repo.bookmark_heads().unwrap();
5125
    let fast = repo.load_state(&heads).unwrap();
5126
    let full = repo.load_state_full(&heads).unwrap();
5127
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5128
5129
    // The next checkpoint shares the unchanged long file's graph.
5130
    let (r2, _, _) = repo.checkpoint().unwrap();
5131
    let cp2 = crate::objects::Checkpoint::decode(
5132
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5133
    )
5134
    .unwrap();
5135
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5136
5137
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5138
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5139
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5140
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5141
5142
    // A version 1 checkpoint written by an older oxy still loads.
5143
    let state = repo.load_state_full(&heads).unwrap();
5144
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5145
    let cp_old = crate::objects::Checkpoint {
5146
        heads: cp2.heads.clone(),
5147
        count: cp2.count,
5148
        payload: old,
5149
    };
5150
    let r_old = repo
5151
        .store()
5152
        .put(ObjectType::Checkpoint, &cp_old.encode())
5153
        .unwrap();
5154
    repo.install_checkpoint("main", &r_old).unwrap();
5155
    assert_eq!(
5156
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5157
        full.checkpoint_payload()
5158
    );
5159
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5160
5161
    // A lost graph blob fails the load loudly rather than dropping the
5162
    // file, and fsck reports it (a fresh repository, objects still loose).
5163
    let dir2 = tempfile::tempdir().unwrap();
5164
    let root2 = dir2.path();
5165
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5166
    write(root2, "long.txt", long.as_bytes());
5167
    repo2.commit("base", &[]).unwrap();
5168
    let (r, _, _) = repo2.checkpoint().unwrap();
5169
    let cp = crate::objects::Checkpoint::decode(
5170
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5171
    )
5172
    .unwrap();
5173
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
5174
    repo2.store().remove_loose_for_test(&graph).unwrap();
5175
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5176
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5177
}
5178
5179
/// A new repository has not stored the user's identity yet (that happens
5180
/// at the first signed change); looking it up falls back to the key
5181
/// directory, and a file there that does not hash to the key is refused.
5182
#[test]
5183
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5184
    hermetic();
5185
    let dir = tempfile::tempdir().unwrap();
5186
    let home = dir.path().join("home");
5187
    let mut first = Repo::init(&dir.path().join("a"))
5188
        .unwrap()
5189
        .with_home(home.clone());
5190
    let (key, _) = first
5191
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5192
        .unwrap();
5193
    let fresh = Repo::init(&dir.path().join("b"))
5194
        .unwrap()
5195
        .with_home(home.clone());
5196
    assert!(!fresh.store().has(&key), "nothing stored yet");
5197
    let id = fresh.identity(&key).unwrap();
5198
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5199
    // A key file that is not this identity is an error, not a wrong answer.
5200
    let keys = fresh.keys_dir.clone();
5201
    let (other, _) = first
5202
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5203
        .unwrap();
5204
    fs::copy(
5205
        keys.join(format!("{}.identity", other.to_hex())),
5206
        keys.join(format!("{}.identity", key.to_hex())),
5207
    )
5208
    .unwrap();
5209
    assert!(fresh
5210
        .identity(&key)
5211
        .unwrap_err()
5212
        .to_string()
5213
        .contains("does not hold identity"));
5214
}
5215
5216
/// Status snapshots (spec §12.3): a text file whose stat matches the
5217
/// manifest, and whose base graph key is the one the manifest recorded it
5218
/// equal to, is neither read nor rendered; any edit, and any change to the
5219
/// file's graph in the base, brings it back.
5220
#[cfg(unix)]
5221
#[test]
5222
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5223
    use std::os::unix::fs::PermissionsExt;
5224
    hermetic();
5225
    let dir = tempfile::tempdir().unwrap();
5226
    let root = dir.path();
5227
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5228
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5229
        write(root, p, c.as_bytes());
5230
    }
5231
    repo.commit("base", &[]).unwrap();
5232
    let age = |p: &str| {
5233
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5234
        fs::File::options()
5235
            .write(true)
5236
            .open(root.join(p))
5237
            .unwrap()
5238
            .set_modified(old)
5239
            .unwrap();
5240
    };
5241
    let lock = |p: &str, mode: u32| {
5242
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5243
    };
5244
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5245
        age(p);
5246
    }
5247
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5248
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5249
    assert!(
5250
        m.entries.values().all(|e| e.graph.is_some()),
5251
        "keys recorded"
5252
    );
5253
5254
    // Unreadable files prove they are not read; the status snapshot does
5255
    // not render them either, and its base lacks their graphs.
5256
    lock("a.txt", 0o000);
5257
    lock("b.txt", 0o000);
5258
    let snap = repo.snapshot_status("status").unwrap();
5259
    assert!(!snap.changed && snap.statuses.is_empty());
5260
    assert_eq!(
5261
        snap.base_snapshot
5262
            .unrendered
5263
            .iter()
5264
            .cloned()
5265
            .collect::<Vec<_>>(),
5266
        vec!["a.txt", "b.txt", "d/c.txt"]
5267
    );
5268
    assert!(!snap.base.is_full());
5269
    assert!(!snap.base_snapshot.is_conflicted());
5270
    // A full snapshot does not read them either, but renders everything.
5271
    let full = repo.snapshot("status").unwrap();
5272
    assert!(full.statuses.is_empty() && full.base.is_full());
5273
    assert!(full.base_snapshot.unrendered.is_empty());
5274
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5275
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5276
5277
    // An edit is seen; the file is rendered, the others still are not.
5278
    write(root, "d/c.txt", b"sea edited\n");
5279
    let snap = repo.snapshot_status("status").unwrap();
5280
    assert_eq!(
5281
        statuses(&snap),
5282
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5283
    );
5284
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5285
    // So is a mode change of an unread file.
5286
    lock("b.txt", 0o100);
5287
    assert_eq!(
5288
        statuses(&repo.snapshot_status("status").unwrap()),
5289
        vec![
5290
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5291
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5292
        ]
5293
    );
5294
    lock("b.txt", 0o000);
5295
5296
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5297
    // stays unread, c.txt is read once and then skipped too.
5298
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5299
        .unwrap();
5300
    age("d/c.txt");
5301
    let snap = repo.snapshot_status("status").unwrap();
5302
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5303
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5304
    lock("d/c.txt", 0o000);
5305
    let snap = repo.snapshot_status("status").unwrap();
5306
    assert!(snap.statuses.is_empty());
5307
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5308
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5309
        lock(p, 0o644);
5310
    }
5311
}
5312
5313
/// Attributes decide how a file compares with the base, so a changed
5314
/// `.oxyattributes` makes every text file be compared again.
5315
#[cfg(unix)]
5316
#[test]
5317
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5318
    hermetic();
5319
    let dir = tempfile::tempdir().unwrap();
5320
    let root = dir.path();
5321
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5322
    write(root, "a.txt", b"crlf\r\n");
5323
    repo.commit("base", &[]).unwrap();
5324
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5325
    fs::File::options()
5326
        .write(true)
5327
        .open(root.join("a.txt"))
5328
        .unwrap()
5329
        .set_modified(old)
5330
        .unwrap();
5331
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5332
    assert!(repo
5333
        .snapshot_status("status")
5334
        .unwrap()
5335
        .base_snapshot
5336
        .unrendered
5337
        .contains("a.txt"));
5338
    // With eol=lf, a.txt as stored no longer equals the base.
5339
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5340
    let snap = repo.snapshot_status("status").unwrap();
5341
    assert_eq!(
5342
        statuses(&snap),
5343
        vec![
5344
            (".oxyattributes".to_string(), ChangeStatus::Added),
5345
            ("a.txt".to_string(), ChangeStatus::Modified)
5346
        ]
5347
    );
5348
}
5349
5350
/// Bookmarks with `/` in their names: pushing records their
5351
/// attestations, and checkpoints are kept for them, beside `feature`
5352
/// itself.
5353
#[test]
5354
fn bookmarks_with_slashes_push_and_checkpoint() {
5355
    hermetic();
5356
    let dir = tempfile::tempdir().unwrap();
5357
    let root = dir.path();
5358
    let origin = Repo::init(&root.join("origin")).unwrap();
5359
    let url = root.join("origin").to_string_lossy().to_string();
5360
    let mut repo = Repo::clone(&url, &root.join("r"))
5361
        .unwrap()
5362
        .with_home(root.join("home"));
5363
    // With an identity, pushes carry reference attestations: the case
5364
    // that failed, since the attestation is a file named after the bookmark.
5365
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5366
        .unwrap();
5367
    let r = root.join("r");
5368
    write(&r, "a.txt", b"a\n");
5369
    let h_a = repo.commit("a", &[]).unwrap();
5370
    assert!(repo.push("origin", false).unwrap()[0].ok);
5371
    repo.bookmark_create("feature", None).unwrap();
5372
    repo.bookmark_create("feature/x", None).unwrap();
5373
    repo.bookmark_switch("feature/x", false).unwrap();
5374
    write(&r, "b.txt", b"b\n");
5375
    let h_b = repo.commit("b", &[]).unwrap();
5376
    for name in ["feature", "feature/x"] {
5377
        let res = repo.push_bookmark("origin", name, false).unwrap();
5378
        assert!(res[0].ok, "{name}: {res:?}");
5379
    }
5380
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5381
    assert_eq!(
5382
        origin.resolve_heads("feature/x").unwrap(),
5383
        repo.resolve_heads("feature/x").unwrap()
5384
    );
5385
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5386
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5387
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5388
5389
    // A checkpoint of feature/x is found again when loading its state.
5390
    let (cp, _, _) = repo.checkpoint().unwrap();
5391
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5392
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5393
    let heads = repo.resolve_heads("feature/x").unwrap();
5394
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5395
}
5396
5397
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5398
/// never the remote's own bookmark, and a bookmark created again later is
5399
/// accepted although the deletion's attestation stays the latest.
5400
#[test]
5401
fn bookmarks_are_deleted_on_a_remote() {
5402
    hermetic();
5403
    let dir = tempfile::tempdir().unwrap();
5404
    let root = dir.path();
5405
    let origin = Repo::init(&root.join("origin")).unwrap();
5406
    let url = root.join("origin").to_string_lossy().to_string();
5407
    let mut repo = Repo::clone(&url, &root.join("r"))
5408
        .unwrap()
5409
        .with_home(root.join("home"));
5410
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5411
        .unwrap();
5412
    let r = root.join("r");
5413
    write(&r, "a.txt", b"a\n");
5414
    repo.commit("a", &[]).unwrap();
5415
    assert!(repo.push("origin", false).unwrap()[0].ok);
5416
    repo.bookmark_create("feature/x", None).unwrap();
5417
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5418
    assert!(origin.resolve_heads("feature/x").is_ok());
5419
5420
    let res = repo.push_delete("origin", "feature/x").unwrap();
5421
    assert!(res[0].ok, "{res:?}");
5422
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5423
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5424
    assert!(
5425
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5426
        "the deletion is attested"
5427
    );
5428
    assert!(
5429
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5430
        "the local bookmark stays"
5431
    );
5432
    assert!(!repo
5433
        .view()
5434
        .unwrap()
5435
        .remotes
5436
        .get("origin")
5437
        .is_some_and(|m| m.contains_key("feature/x")));
5438
5439
    // Pushing it again creates it again, past the deletion's serial.
5440
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5441
    assert!(res[0].ok, "{res:?}");
5442
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5443
5444
    // Nothing to delete, and never the remote's own bookmark.
5445
    assert!(repo.push_delete("origin", "nope").is_err());
5446
    let res = repo.push_delete("origin", "main").unwrap();
5447
    assert!(
5448
        !res[0].ok && res[0].reason.contains("default bookmark"),
5449
        "{res:?}"
5450
    );
5451
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5452
}
5453
5454
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5455
/// when the target has the same versions of the files it touches, and is
5456
/// refused, untouched, when it has others.
5457
#[test]
5458
fn switching_bookmarks_carries_uncommitted_work() {
5459
    hermetic();
5460
    let dir = tempfile::tempdir().unwrap();
5461
    let root = dir.path();
5462
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5463
    write(root, "a.txt", b"a\n");
5464
    write(root, "b.txt", b"b\n");
5465
    write(root, "gone.txt", b"gone\n");
5466
    repo.commit("base", &[]).unwrap();
5467
    repo.bookmark_create("feature", None).unwrap();
5468
    // Started on main, belongs on feature: edit, add, remove.
5469
    write(root, "a.txt", b"a\nmore\n");
5470
    write(root, "new.txt", b"new\n");
5471
    fs::remove_file(root.join("gone.txt")).unwrap();
5472
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5473
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5474
    assert_eq!(repo.config.bookmark, "feature");
5475
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5476
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5477
    assert!(!root.join("gone.txt").exists());
5478
    let snap = repo.snapshot("status").unwrap();
5479
    assert_eq!(
5480
        statuses(&snap),
5481
        vec![
5482
            ("a.txt".to_string(), ChangeStatus::Modified),
5483
            ("gone.txt".to_string(), ChangeStatus::Removed),
5484
            ("new.txt".to_string(), ChangeStatus::Added)
5485
        ]
5486
    );
5487
    repo.commit("the work", &[]).unwrap();
5488
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5489
5490
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5491
    repo.bookmark_switch("main", false).unwrap();
5492
    write(root, "b.txt", b"b on main\n");
5493
    repo.commit("b on main", &[]).unwrap();
5494
    repo.bookmark_switch("feature", false).unwrap();
5495
    write(root, "b.txt", b"b edited\n");
5496
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5497
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5498
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5499
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5500
}
5501
5502
/// Merging and checking out (feedback 3): a working copy without changes
5503
/// follows a merge whichever state it sat on; a refused checkout names
5504
/// what is in the way; `checkout --carry` takes the work along.
5505
#[test]
5506
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5507
    hermetic();
5508
    let dir = tempfile::tempdir().unwrap();
5509
    let root = dir.path();
5510
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5511
    write(root, "a.txt", b"a\n");
5512
    let h1 = repo.commit("a", &[]).unwrap();
5513
    write(root, "b.txt", b"b\n");
5514
    repo.commit("b", &[]).unwrap();
5515
    repo.bookmark_create("feature", None).unwrap();
5516
    repo.bookmark_switch("feature", false).unwrap();
5517
    write(root, "c.txt", b"c\n");
5518
    repo.commit("c on feature", &[]).unwrap();
5519
    repo.bookmark_switch("main", false).unwrap();
5520
    // The working copy sits on an older state than main's heads.
5521
    repo.checkout(&[h1], false, "checkout").unwrap();
5522
    assert!(!root.join("b.txt").exists());
5523
    let m = repo.merge("feature").unwrap();
5524
    assert!(m.checked_out, "a clean working copy follows the merge");
5525
    for f in ["a.txt", "b.txt", "c.txt"] {
5526
        assert!(root.join(f).exists(), "{f}");
5527
    }
5528
5529
    // A refusal says which paths are in the way and what to do.
5530
    fs::remove_file(root.join("b.txt")).unwrap();
5531
    write(root, "a.txt", b"a edited\n");
5532
    let err = repo
5533
        .checkout(&[h1], false, "checkout")
5534
        .unwrap_err()
5535
        .to_string();
5536
    assert!(
5537
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5538
        "{err}"
5539
    );
5540
    // --carry takes them along: h1 has a.txt as the base has it, and the
5541
    // removed b.txt is already as h1 has it (none), so that is no conflict
5542
    // either (oxygen#100).
5543
    let (_, carried) = repo
5544
        .checkout_carry(&[h1], "the first change", "checkout")
5545
        .unwrap();
5546
    assert_eq!(carried, vec!["a.txt"]);
5547
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5548
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5549
}
5550
5551
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5552
/// user identity not stored in a new repository yet is fine while its
5553
/// secret key is there; an added subrepo is listed as not committed yet.
5554
#[test]
5555
fn a_new_repository_is_healthy_before_its_first_commit() {
5556
    hermetic();
5557
    let dir = tempfile::tempdir().unwrap();
5558
    let root = dir.path();
5559
    let home = root.join("home");
5560
    let mut first = Repo::init(&root.join("first"))
5561
        .unwrap()
5562
        .with_home(home.clone());
5563
    let (key, _) = first
5564
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5565
        .unwrap();
5566
    let repo = Repo::init(&root.join("second"))
5567
        .unwrap()
5568
        .with_home(home.clone());
5569
    // Only the secret key: no identity object anywhere this repository sees.
5570
    let keys = repo.keys_dir.clone();
5571
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5572
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5573
    let r = repo.doctor(true);
5574
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5575
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5576
    assert!(id.message.contains("first signed change"), "{}", id.message);
5577
5578
    // A subrepo added and not committed yet is listed, pinned where it is.
5579
    let lib = root.join("lib");
5580
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5581
    write(&lib, "x.txt", b"x\n");
5582
    l.commit("x", &[]).unwrap();
5583
    let second = root.join("second");
5584
    write(&second, "a.txt", b"a\n");
5585
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5586
        .unwrap();
5587
    let subs = repo.subrepos().unwrap();
5588
    assert_eq!(subs.len(), 1);
5589
    assert_eq!(
5590
        (subs[0].path.as_str(), subs[0].committed),
5591
        ("deps/lib", false)
5592
    );
5593
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5594
    repo.commit("add lib", &[]).unwrap();
5595
    let subs = repo.subrepos().unwrap();
5596
    assert!(subs[0].committed, "committed now");
5597
}
5598
5599
/// Commit, diff, hunks and discard use the partial snapshot: a file
5600
/// unchanged since the manifest is neither read nor rendered, and showing
5601
/// a change renders only what it edits, the same as from a full base.
5602
#[cfg(unix)]
5603
#[test]
5604
fn commits_and_diffs_leave_unchanged_files_alone() {
5605
    use std::os::unix::fs::PermissionsExt;
5606
    hermetic();
5607
    let dir = tempfile::tempdir().unwrap();
5608
    let root = dir.path();
5609
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5610
    write(root, "big.txt", b"lots\nof\nlines\n");
5611
    write(root, "a.txt", b"one\ntwo\n");
5612
    repo.commit("base", &[]).unwrap();
5613
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5614
    for f in ["big.txt", "a.txt"] {
5615
        fs::File::options()
5616
            .write(true)
5617
            .open(root.join(f))
5618
            .unwrap()
5619
            .set_modified(old)
5620
            .unwrap();
5621
    }
5622
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5623
    // big.txt cannot be read at all from here on.
5624
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5625
5626
    write(root, "a.txt", b"one\nTWO\nthree\n");
5627
    let diff = repo.diff_files(None).unwrap();
5628
    assert_eq!(
5629
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5630
        ["a.txt"]
5631
    );
5632
    let (_, hunks) = repo.hunks().unwrap();
5633
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5634
    let h = repo.commit("edit a", &[]).unwrap();
5635
5636
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5637
    let c = repo.store().get_change(&h).unwrap();
5638
    let full = repo.load_state(&c.deps).unwrap();
5639
    let want = render_change(&c, &full, &full.materialize());
5640
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5641
    let (base, snap) = repo.change_base(&c).unwrap();
5642
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5643
5644
    // Discarding works the same way.
5645
    write(root, "a.txt", b"scratch\n");
5646
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5647
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5648
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5649
}
5650
5651
/// A replace conflict (spec §9.3) is settled by a change that writes one
5652
/// candidate, or new bytes, at the path when the caller names it; a plain
5653
/// snapshot of a checkout never settles it on its own.
5654
#[test]
5655
fn replace_conflicts_are_settled_when_asked() {
5656
    hermetic();
5657
    let dir = tempfile::tempdir().unwrap();
5658
    let root = dir.path();
5659
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5660
    let blob = |n: u8| {
5661
        let mut v = vec![0u8; 64];
5662
        v[1] = n;
5663
        v
5664
    };
5665
    write(root, "img.bin", &blob(1));
5666
    repo.commit("add img", &[]).unwrap();
5667
    repo.bookmark_create("other", None).unwrap();
5668
    write(root, "img.bin", &blob(2));
5669
    repo.commit("img two", &[]).unwrap();
5670
    repo.bookmark_switch("other", false).unwrap();
5671
    write(root, "img.bin", &blob(3));
5672
    repo.commit("img three", &[]).unwrap();
5673
    repo.bookmark_switch("main", false).unwrap();
5674
    repo.merge("other").unwrap();
5675
    let heads = repo.bookmark_heads().unwrap();
5676
    let merged = repo.load_state(&heads).unwrap().materialize();
5677
    assert!(
5678
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5679
        "a replace conflict"
5680
    );
5681
    // A snapshot of the checkout records nothing.
5682
    assert!(repo
5683
        .snapshot("status")
5684
        .unwrap()
5685
        .statuses
5686
        .iter()
5687
        .all(|s| s.path != "img.bin"));
5688
5689
    // Keeping candidate 3 settles it.
5690
    let author = repo.author();
5691
    let edits = [FileEdit {
5692
        path: "img.bin".into(),
5693
        content: Some(blob(3)),
5694
    }];
5695
    let c = repo
5696
        .build_change(&heads, &edits, "keep three", author)
5697
        .unwrap();
5698
    assert_eq!(c.kind, ChangeKind::Resolution);
5699
    let mut st = repo.load_state(&heads).unwrap();
5700
    for d in &c.deps {
5701
        assert!(st.contains(d));
5702
    }
5703
    assert!(
5704
        heads.iter().all(|h| c.deps.contains(h)),
5705
        "depends on both contributors"
5706
    );
5707
    st.add(c).unwrap();
5708
    let after = st.materialize();
5709
    assert!(!after.is_conflicted());
5710
    assert_eq!(
5711
        after.files["img.bin"].content,
5712
        FileContent::Opaque {
5713
            blobs: vec![Repo::blob_ref(&blob(3))]
5714
        }
5715
    );
5716
5717
    // New bytes settle it too.
5718
    let edits = [FileEdit {
5719
        path: "img.bin".into(),
5720
        content: Some(blob(9)),
5721
    }];
5722
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5723
    let mut st = repo.load_state(&heads).unwrap();
5724
    st.add(c).unwrap();
5725
    assert_eq!(
5726
        st.materialize().files["img.bin"].content,
5727
        FileContent::Opaque {
5728
            blobs: vec![Repo::blob_ref(&blob(9))]
5729
        }
5730
    );
5731
}
5732
5733
/// The history of a range of lines (spec §27): the changes that wrote
5734
/// or deleted its atoms, or deleted atoms from between them; edits outside
5735
/// the range and changes the range's lines survived are not in it.
5736
#[test]
5737
fn line_ranges_have_exact_histories() {
5738
    hermetic();
5739
    let dir = tempfile::tempdir().unwrap();
5740
    let root = dir.path();
5741
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5742
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5743
    let base = repo.commit("add f", &[]).unwrap();
5744
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5745
    let outside = repo.commit("change the import", &[]).unwrap();
5746
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5747
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5748
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5749
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5750
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5751
    let after = repo.commit("add b after a", &[]).unwrap();
5752
    let heads = repo.bookmark_heads().unwrap();
5753
5754
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5755
    let hist: Vec<ChangeHash> = repo
5756
        .line_history(&heads, "f.rs", 2, 4)
5757
        .unwrap()
5758
        .iter()
5759
        .map(|e| e.hash)
5760
        .collect();
5761
    for (h, what) in [
5762
        (base, "wrote it"),
5763
        (inside, "edited a line"),
5764
        (deleted, "deleted a line from inside"),
5765
    ] {
5766
        assert!(hist.contains(&h), "{what}");
5767
    }
5768
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5769
        assert!(!hist.contains(&h), "{what}");
5770
    }
5771
    assert_eq!(hist[0], deleted, "newest first");
5772
    // One line: only what touched it.
5773
    let one: Vec<ChangeHash> = repo
5774
        .line_history(&heads, "f.rs", 1, 1)
5775
        .unwrap()
5776
        .iter()
5777
        .map(|e| e.hash)
5778
        .collect();
5779
    assert!(one.contains(&outside) && !one.contains(&inside));
5780
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5781
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5782
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5783
}
5784
5785
#[test]
5786
fn receipts_are_kept_with_their_state_and_verified() {
5787
    use crate::receipt::{Receipt, SignedReceipt};
5788
    hermetic();
5789
    let dir = tempfile::tempdir().unwrap();
5790
    let root = dir.path();
5791
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5792
    write(root, "a.txt", b"1\n");
5793
    repo.commit("A", &[]).unwrap();
5794
    let heads = repo.bookmark_heads().unwrap();
5795
    let state = repo
5796
        .store()
5797
        .put_state(&StateObject::new(heads.clone()))
5798
        .unwrap();
5799
    let out = repo.store_blob(b"built\n").unwrap();
5800
    let receipt = Receipt {
5801
        job_name: "build".into(),
5802
        pipeline_hash: ObjectRef([1; 32]),
5803
        scope_tree_hash: ObjectRef([2; 32]),
5804
        inputs: vec![],
5805
        environment: ObjectRef([3; 32]),
5806
        outputs: vec![out],
5807
        exit_code: 0,
5808
        duration_ms: 42,
5809
    };
5810
    let sk = SecretKey::generate();
5811
    let runner = sk.identity("earth-1", "runner@earth", 1);
5812
    let sr = SignedReceipt::sign(
5813
        receipt.clone(),
5814
        repo.id().unwrap(),
5815
        state,
5816
        "demo#1",
5817
        &runner,
5818
        &sk,
5819
    );
5820
5821
    let r = repo.add_receipt(&sr).unwrap();
5822
    let found = repo.receipts(&heads).unwrap();
5823
    assert_eq!(found.len(), 1);
5824
    assert_eq!(found[0].attest, r);
5825
    assert_eq!(found[0].signed, sr);
5826
    assert!(found[0].problem.is_none() && !found[0].revoked);
5827
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5828
5829
    // Another repository's receipt, or a forged one, is refused.
5830
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5831
    assert!(repo
5832
        .add_receipt(&elsewhere)
5833
        .unwrap_err()
5834
        .to_string()
5835
        .contains("another repository"));
5836
    let mut forged = sr.clone();
5837
    forged.receipt.exit_code = 1;
5838
    assert!(repo
5839
        .add_receipt(&forged)
5840
        .unwrap_err()
5841
        .to_string()
5842
        .contains("does not verify"));
5843
5844
    // A receipt signed by a short-lived key keeps its certificate and the
5845
    // issuer's identity, and reads back with them (oxygenhub#241).
5846
    let hub_sk = SecretKey::generate();
5847
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
5848
    let job_sk = SecretKey::generate();
5849
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
5850
    let mut test_receipt = receipt.clone();
5851
    test_receipt.job_name = "test".into();
5852
    let plain = SignedReceipt::sign(
5853
        test_receipt,
5854
        repo.id().unwrap(),
5855
        state,
5856
        "demo#2",
5857
        &job,
5858
        &job_sk,
5859
    );
5860
    let now = plain.attest.hlc.wall_ms;
5861
    let cert = crate::cert::SignedCertificate::sign(
5862
        crate::cert::Certificate {
5863
            key: job.clone(),
5864
            issuer: hub.hash(),
5865
            subject: "repo:andy/demo:bookmark:main".into(),
5866
            claims: vec![],
5867
            scope: crate::identity::Scope::SEAL,
5868
            not_before: now - 1_000,
5869
            expires: now + 600_000,
5870
            grant: None,
5871
        },
5872
        &hub,
5873
        &hub_sk,
5874
    );
5875
    let certified = plain.with_certificate(cert, hub.clone());
5876
    repo.add_receipt(&certified).unwrap();
5877
    let found = repo.receipts(&heads).unwrap();
5878
    let got = found
5879
        .iter()
5880
        .find(|i| i.signed.receipt.job_name == "test")
5881
        .unwrap();
5882
    assert_eq!(got.signed, certified);
5883
    assert!(got.problem.is_none(), "{:?}", got.problem);
5884
5885
    // gc keeps the receipts, their runners, the certificate and its issuer,
5886
    // and the output while the state lives.
5887
    repo.gc(true).unwrap();
5888
    let found = repo.receipts(&heads).unwrap();
5889
    assert_eq!(found.len(), 2);
5890
    let got = found
5891
        .iter()
5892
        .find(|i| i.signed.receipt.job_name == "test")
5893
        .unwrap();
5894
    assert_eq!(got.signed, certified, "the certificate survives gc");
5895
    assert!(got.problem.is_none());
5896
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5897
    assert!(repo.fsck().unwrap().problems.is_empty());
5898
}
5899
5900
#[test]
5901
fn status_leaves_an_unchanged_manifest_alone() {
5902
    hermetic();
5903
    let dir = tempfile::tempdir().unwrap();
5904
    let root = dir.path();
5905
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5906
    write(root, "a.txt", b"1\n");
5907
    write(root, "b.txt", b"2\n");
5908
    repo.commit("A", &[]).unwrap();
5909
    // Files last touched well outside the racy window.
5910
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5911
    for f in ["a.txt", "b.txt"] {
5912
        fs::File::options()
5913
            .write(true)
5914
            .open(root.join(f))
5915
            .unwrap()
5916
            .set_modified(old)
5917
            .unwrap();
5918
    }
5919
    repo.snapshot_status("status").unwrap();
5920
    let path = repo.manifest_path();
5921
    let first = fs::read(&path).unwrap();
5922
    repo.snapshot_status("status").unwrap();
5923
    assert_eq!(
5924
        fs::read(&path).unwrap(),
5925
        first,
5926
        "an unchanged tree does not rewrite the manifest"
5927
    );
5928
    // A change rewrites it.
5929
    write(root, "a.txt", b"1\n2\n");
5930
    repo.snapshot_status("status").unwrap();
5931
    assert_ne!(fs::read(&path).unwrap(), first);
5932
}
5933
5934
#[test]
5935
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5936
    hermetic();
5937
    let dir = tempfile::tempdir().unwrap();
5938
    let root = dir.path();
5939
    let origin_path = root.join("origin");
5940
    Repo::init(&origin_path).unwrap();
5941
    let origin_url = origin_path.to_string_lossy().to_string();
5942
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5943
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5944
    write(&root.join("a"), "big.txt", big.as_bytes());
5945
    write(&root.join("a"), "small.txt", b"small\n");
5946
    let h1 = a.commit("large", &[]).unwrap();
5947
    let (_, body) = a.store().get(&h1).unwrap();
5948
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5949
    assert!(a.push("origin", false).unwrap()[0].ok);
5950
5951
    // A clone reads the text from the blobs that came with the change.
5952
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5953
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5954
    // An edit in the middle of the stored insert is an ordinary change.
5955
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5956
    write(&root.join("b"), "big.txt", edited.as_bytes());
5957
    let h2 = b.commit("edit", &[]).unwrap();
5958
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5959
    assert!(b.push("origin", false).unwrap()[0].ok);
5960
    assert!(a.pull("origin").unwrap().checked_out);
5961
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5962
    assert_eq!(
5963
        a.fsck().unwrap().errors(),
5964
        0,
5965
        "{:?}",
5966
        a.fsck().unwrap().problems
5967
    );
5968
5969
    // With zero retention gc keeps the text blobs of every kept change.
5970
    let mut a = Repo::open(&root.join("a")).unwrap();
5971
    a.config.set("core.op-retention", "0").unwrap();
5972
    a.save_config().unwrap();
5973
    let a = Repo::open(&root.join("a")).unwrap();
5974
    a.gc(true).unwrap();
5975
    let a = Repo::open(&root.join("a")).unwrap();
5976
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5977
    assert_eq!(
5978
        a.fsck().unwrap().errors(),
5979
        0,
5980
        "{:?}",
5981
        a.fsck().unwrap().problems
5982
    );
5983
    // And a clone of the packed repository reads them from its packs.
5984
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5985
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5986
    drop(c);
5987
}
5988
5989
#[test]
5990
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5991
    hermetic();
5992
    let dir = tempfile::tempdir().unwrap();
5993
    let root = dir.path();
5994
    let repo = Repo::init(root).unwrap();
5995
    write(root, "a.txt", b"a\n");
5996
    let a = repo.commit("a", &[]).unwrap();
5997
    write(root, "b.txt", b"b\n");
5998
    repo.commit("b", &[]).unwrap();
5999
    let (x, op) = repo.head_op().unwrap();
6000
    let ws = *op.view.workspaces.keys().next().unwrap();
6001
    let mut one = op.view.clone();
6002
    one.workspaces.insert(ws, a);
6003
    let mut two = op.view.clone();
6004
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6005
    let first = repo.record_op(&[x], "one", one).unwrap();
6006
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6007
    assert!(
6008
        e.to_string()
6009
            .contains("changed this working copy at the same time"),
6010
        "{e}"
6011
    );
6012
    assert_eq!(
6013
        repo.head_op().unwrap().0,
6014
        first,
6015
        "the second is not recorded"
6016
    );
6017
}
6018
6019
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6020
/// rewrote the working copy recorded the half-written files as edits, and
6021
/// its view replaced the switch's.
6022
#[test]
6023
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6024
    hermetic();
6025
    let dir = tempfile::tempdir().unwrap();
6026
    let root = dir.path().to_path_buf();
6027
    let mut repo = Repo::init(&root).unwrap();
6028
    write(&root, "keep.txt", b"keep\n");
6029
    repo.commit("base", &[]).unwrap();
6030
    repo.bookmark_create("small", None).unwrap();
6031
    for i in 0..300 {
6032
        write(
6033
            &root,
6034
            &format!("many/f{i}.txt"),
6035
            format!("file {i}\n").as_bytes(),
6036
        );
6037
    }
6038
    repo.commit("many", &[]).unwrap();
6039
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6040
    let watcher = {
6041
        let (root, stop) = (root.clone(), stop.clone());
6042
        std::thread::spawn(move || {
6043
            let r = Repo::open(&root).unwrap();
6044
            let mut ran = 0;
6045
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6046
                if r.snapshot_status("oxy status").is_ok() {
6047
                    ran += 1;
6048
                }
6049
            }
6050
            ran
6051
        })
6052
    };
6053
    for i in 0..20 {
6054
        let to = if i % 2 == 0 { "small" } else { "main" };
6055
        repo.bookmark_switch(to, false).unwrap();
6056
    }
6057
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6058
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6059
    // Back on main, clean, with every file where main has it.
6060
    let repo = Repo::open(&root).unwrap();
6061
    let s = repo.snapshot_status("oxy status").unwrap();
6062
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6063
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6064
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6065
    assert!(root.join("many/f299.txt").exists());
6066
}
6067
6068
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6069
/// put a subrepo that was ahead of its pin back at the pin and moved the
6070
/// subrepo's own bookmark backwards.
6071
#[test]
6072
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6073
    hermetic();
6074
    let dir = tempfile::tempdir().unwrap();
6075
    let root = dir.path();
6076
    Repo::init(&root.join("lib-origin")).unwrap();
6077
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6078
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6079
    write(&root.join("lib"), "lib.txt", b"v1\n");
6080
    lib.commit("lib v1", &[]).unwrap();
6081
    assert!(lib.push("origin", false).unwrap()[0].ok);
6082
6083
    let app_dir = root.join("app");
6084
    let mut app = Repo::init(&app_dir).unwrap();
6085
    write(&app_dir, "main.txt", b"app\n");
6086
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6087
    app.commit("app with lib", &[]).unwrap();
6088
    app.bookmark_create("feature", None).unwrap();
6089
6090
    // New work in the subrepo, not yet pinned by the parent.
6091
    let nested_dir = app_dir.join("libs/lib");
6092
    let nested = Repo::open(&nested_dir).unwrap();
6093
    write(&nested_dir, "new.txt", b"new\n");
6094
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6095
    drop(nested);
6096
6097
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6098
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6099
    let nested = Repo::open(&nested_dir).unwrap();
6100
    assert!(
6101
        nested.bookmark_heads().unwrap().contains(&l2),
6102
        "its bookmark kept its work"
6103
    );
6104
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6105
    let s = app.snapshot("status").unwrap();
6106
    assert_eq!(
6107
        statuses(&s),
6108
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6109
    );
6110
}
6111
6112
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6113
/// moving `main` to a change this clone had pushed on another bookmark,
6114
/// the first `pull` said "Already up to date" while `main` was behind.
6115
#[test]
6116
fn pull_takes_a_remote_move_to_changes_already_here() {
6117
    hermetic();
6118
    let dir = tempfile::tempdir().unwrap();
6119
    let root = dir.path();
6120
    let origin_path = root.join("origin");
6121
    let origin = Repo::init(&origin_path).unwrap();
6122
    let url = origin_path.to_string_lossy().to_string();
6123
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6124
    write(&root.join("b"), "base.txt", b"base\n");
6125
    b.commit("base", &[]).unwrap();
6126
    assert!(b.push("origin", false).unwrap()[0].ok);
6127
6128
    // A feature bookmark with one change, pushed.
6129
    b.bookmark_create("feat", None).unwrap();
6130
    b.bookmark_switch("feat", false).unwrap();
6131
    write(&root.join("b"), "x.txt", b"x\n");
6132
    let x = b.commit("x", &[]).unwrap();
6133
    assert!(b.push("origin", false).unwrap()[0].ok);
6134
    b.bookmark_switch("main", false).unwrap();
6135
6136
    // The remote lands it: its main moves to the feature's state.
6137
    let feat = origin
6138
        .store()
6139
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6140
        .unwrap()
6141
        .heads;
6142
    origin.bookmark_set("main", &feat).unwrap();
6143
6144
    let r = b.pull("origin").unwrap();
6145
    assert!(r.changed, "{r:?}");
6146
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6147
    let main = b
6148
        .bookmarks()
6149
        .unwrap()
6150
        .into_iter()
6151
        .find(|m| m.name == "main")
6152
        .unwrap();
6153
    assert_eq!(main.behind, Some(0), "{main:?}");
6154
}
6155
6156
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6157
/// to one only the remote has makes a local bookmark from it; a pull moves
6158
/// every local bookmark the remote has too; a clone checks out the remote's
6159
/// default bookmark.
6160
#[test]
6161
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6162
    hermetic();
6163
    let dir = tempfile::tempdir().unwrap();
6164
    let root = dir.path();
6165
    let origin_path = root.join("origin");
6166
    let mut origin = Repo::init(&origin_path).unwrap();
6167
    let url = origin_path.to_string_lossy().to_string();
6168
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6169
    write(&root.join("a"), "base.txt", b"base\n");
6170
    a.commit("base", &[]).unwrap();
6171
    assert!(a.push("origin", false).unwrap()[0].ok);
6172
    a.bookmark_create("develop", None).unwrap();
6173
    a.bookmark_switch("develop", false).unwrap();
6174
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6175
    let d1 = a.commit("d1", &[]).unwrap();
6176
    assert!(a.push("origin", false).unwrap()[0].ok);
6177
6178
    // A clone has main only; origin/develop is a name all the same.
6179
    let c_root = root.join("c");
6180
    let mut c = Repo::clone(&url, &c_root).unwrap();
6181
    assert_eq!(c.config.bookmark, "main");
6182
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6183
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6184
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6185
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6186
6187
    // Switching makes the local bookmark from origin's.
6188
    c.bookmark_switch("develop", false).unwrap();
6189
    assert_eq!(c.config.bookmark, "develop");
6190
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6191
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6192
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6193
    assert!(c.bookmark_switch("nowhere", false).is_err());
6194
6195
    // Both bookmarks move on the remote; one pull takes both.
6196
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6197
    let d2 = a.commit("d2", &[]).unwrap();
6198
    assert!(a.push("origin", false).unwrap()[0].ok);
6199
    a.bookmark_switch("main", false).unwrap();
6200
    write(&root.join("a"), "m.txt", b"m\n");
6201
    let m = a.commit("m", &[]).unwrap();
6202
    assert!(a.push("origin", false).unwrap()[0].ok);
6203
    let r = c.pull("origin").unwrap();
6204
    assert!(r.changed && r.checked_out, "{r:?}");
6205
    assert_eq!(r.heads, vec![d2]);
6206
    assert_eq!(r.others, vec!["main".to_string()]);
6207
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6208
    assert_eq!(
6209
        fs::read(c_root.join("base.txt")).unwrap(),
6210
        b"base\nd1\nd2\n"
6211
    );
6212
    let again = c.pull("origin").unwrap();
6213
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6214
6215
    // A clone checks out the remote's default bookmark.
6216
    origin.config.set("workspace.bookmark", "develop").unwrap();
6217
    origin.save_config().unwrap();
6218
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6219
    assert_eq!(e.config.bookmark, "develop");
6220
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6221
    let reopened = Repo::open(&root.join("e")).unwrap();
6222
    assert_eq!(reopened.config.bookmark, "develop");
6223
    // REMOTE/NAME names the remote's bookmark to switch to.
6224
    let mut e = reopened;
6225
    e.bookmark_switch("origin/main", false).unwrap();
6226
    assert_eq!(e.config.bookmark, "main");
6227
    assert!(e.bookmark_heads().unwrap().contains(&m));
6228
}
6229
6230
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6231
/// op restore goes back to an operation, files included, and undo takes
6232
/// the restore back whole; op revert undoes one operation alone; each
6233
/// operation's changes are described from the views.
6234
#[test]
6235
fn operations_can_be_read_restored_and_reverted() {
6236
    hermetic();
6237
    let dir = tempfile::tempdir().unwrap();
6238
    let root = dir.path();
6239
    let repo = Repo::init(root).unwrap();
6240
    write(root, "a.txt", b"a\n");
6241
    let first = repo.commit("first", &[]).unwrap();
6242
    write(root, "a.txt", b"a\nb\n");
6243
    let second = repo.commit("second", &[]).unwrap();
6244
    let at_second = repo.head_op().unwrap().0.to_hex();
6245
    repo.bookmark_create("keep", None).unwrap();
6246
    let created = repo.head_op().unwrap().0.to_hex();
6247
    write(root, "n.txt", b"n\n");
6248
    let third = repo.commit("third", &[]).unwrap();
6249
6250
    // What each operation changed.
6251
    let ops = repo.op_log().unwrap();
6252
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6253
    assert!(
6254
        changes
6255
            .iter()
6256
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6257
        "{changes:?}"
6258
    );
6259
    assert!(changes
6260
        .iter()
6261
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6262
6263
    // Reading at an earlier operation.
6264
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6265
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6266
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6267
    write(root, "z.txt", b"z\n");
6268
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6269
    fs::remove_file(root.join("z.txt")).unwrap();
6270
    assert!(repo.resolve_op("zz").is_err());
6271
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
6272
6273
    // Restore goes back, files and all; undo takes it back whole.
6274
    repo.op_restore(&at_second, false).unwrap();
6275
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
6276
    assert!(!root.join("n.txt").exists());
6277
    repo.undo().unwrap();
6278
    let mut heads = repo.bookmark_heads().unwrap();
6279
    heads.sort();
6280
    let mut want = vec![second, third];
6281
    want.sort();
6282
    assert_eq!(heads, want);
6283
    assert!(
6284
        root.join("n.txt").exists(),
6285
        "the files came back with the undo"
6286
    );
6287
6288
    // Revert the bookmark's creation alone: the commit after it stays.
6289
    let r = repo.op_revert(&created).unwrap();
6290
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6291
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6292
    assert!(repo
6293
        .load_state(&repo.bookmark_heads().unwrap())
6294
        .unwrap()
6295
        .contains(&third));
6296
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6297
    let _ = first;
6298
}
6299
6300
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6301
/// from the status cache while every file is as the snapshot left it, and
6302
/// from a snapshot again as soon as one is not.
6303
#[test]
6304
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6305
    hermetic();
6306
    let dir = tempfile::tempdir().unwrap();
6307
    let root = dir.path();
6308
    let repo = Repo::init(root).unwrap();
6309
    write(root, "a.txt", b"a\n");
6310
    write(root, "b.txt", b"b\n");
6311
    repo.commit("base", &[]).unwrap();
6312
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6313
6314
    write(root, "a.txt", b"a\nmore\n");
6315
    assert_eq!(
6316
        repo.status_by_manifest().unwrap(),
6317
        None,
6318
        "no snapshot of the edit yet"
6319
    );
6320
    let snap = repo.snapshot_status("oxy status").unwrap();
6321
    assert_eq!(snap.statuses.len(), 1);
6322
    let cached = repo
6323
        .status_by_manifest()
6324
        .unwrap()
6325
        .expect("answered from the cache");
6326
    assert_eq!(cached.len(), 1);
6327
    assert_eq!(
6328
        (cached[0].path.as_str(), cached[0].status),
6329
        ("a.txt", ChangeStatus::Modified)
6330
    );
6331
6332
    // Any further change sends status back to a snapshot.
6333
    write(root, "a.txt", b"a\nmore\nand more\n");
6334
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6335
    repo.snapshot_status("oxy status").unwrap();
6336
    assert!(repo.status_by_manifest().unwrap().is_some());
6337
    write(root, "new.txt", b"n\n");
6338
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6339
    fs::remove_file(root.join("new.txt")).unwrap();
6340
    assert!(
6341
        repo.status_by_manifest().unwrap().is_some(),
6342
        "back as it was"
6343
    );
6344
    fs::remove_file(root.join("b.txt")).unwrap();
6345
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6346
    write(root, "b.txt", b"b\n");
6347
6348
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6349
    repo.snapshot_status("oxy status").unwrap();
6350
    repo.commit("more", &[]).unwrap();
6351
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6352
}
6353
6354
/// oxygen#41: while the status cache holds, the working copy's diff is
6355
/// rendered from the stored working-copy change, and says exactly what a
6356
/// snapshot's diff says.
6357
#[test]
6358
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6359
    hermetic();
6360
    let dir = tempfile::tempdir().unwrap();
6361
    let root = dir.path();
6362
    let repo = Repo::init(root).unwrap();
6363
    write(root, "a.txt", b"one\ntwo\nthree\n");
6364
    write(root, "gone.txt", b"bye\n");
6365
    repo.commit("base", &[]).unwrap();
6366
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6367
    write(root, "new.txt", b"hello\n");
6368
    fs::remove_file(root.join("gone.txt")).unwrap();
6369
    let snap = repo.snapshot_status("oxy status").unwrap();
6370
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6371
    assert!(
6372
        repo.status_by_manifest().unwrap().is_some(),
6373
        "the cache holds"
6374
    );
6375
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6376
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6377
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6378
}
6379
6380
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6381
/// while none has moved, the check stats the tracked files without listing
6382
/// the tree, and a file added or removed anywhere moves its directory's
6383
/// time, so the tree is listed again.
6384
#[test]
6385
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6386
    hermetic();
6387
    let dir = tempfile::tempdir().unwrap();
6388
    let root = dir.path();
6389
    let repo = Repo::init(root).unwrap();
6390
    write(root, "a.txt", b"a\n");
6391
    write(root, "sub/deep/b.txt", b"b\n");
6392
    repo.commit("base", &[]).unwrap();
6393
    // Out of the racy window: every file and directory a minute old.
6394
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6395
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6396
        fs::File::open(root.join(p))
6397
            .unwrap()
6398
            .set_modified(old)
6399
            .unwrap();
6400
    }
6401
    repo.snapshot_status("oxy status").unwrap();
6402
    repo.write_manifest(false, false).unwrap();
6403
    let m = repo.read_manifest().unwrap().unwrap().2;
6404
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6405
    assert_eq!(
6406
        repo.disk_differs_by_dirs(&m),
6407
        Some(false),
6408
        "no listing needed"
6409
    );
6410
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6411
6412
    // A same-size edit with a new time: found by its stat.
6413
    write(root, "sub/deep/b.txt", b"c\n");
6414
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6415
    write(root, "sub/deep/b.txt", b"b\n");
6416
    fs::File::open(root.join("sub/deep/b.txt"))
6417
        .unwrap()
6418
        .set_modified(old)
6419
        .unwrap();
6420
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6421
6422
    // A new file moves its directory's time: the tree must be listed.
6423
    write(root, "sub/deep/new.txt", b"n\n");
6424
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6425
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6426
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6427
    // A removed one too.
6428
    fs::remove_file(root.join("a.txt")).unwrap();
6429
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6430
}
6431
6432
/// oxygen#41: a commit right after a status takes the snapshot the status
6433
/// left (the status cache holds) rather than walking again, and commits
6434
/// exactly what a snapshot would have.
6435
#[test]
6436
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6437
    hermetic();
6438
    let dir = tempfile::tempdir().unwrap();
6439
    let root = dir.path();
6440
    let repo = Repo::init(root).unwrap();
6441
    write(root, "a.txt", b"a\nb\n");
6442
    write(root, ".oxyattributes", b"*.bin binary\n");
6443
    repo.commit("base", &[]).unwrap();
6444
    write(root, "a.txt", b"a\nB\n");
6445
    write(root, "new.txt", b"new\n");
6446
    let snap = repo.snapshot_status("oxy status").unwrap();
6447
    let cached = repo
6448
        .snapshot_from_cache()
6449
        .unwrap()
6450
        .expect("the cache holds");
6451
    assert_eq!(cached.wc_hash, snap.wc_hash);
6452
    assert_eq!(cached.statuses, snap.statuses);
6453
    assert!(
6454
        !cached.attributes.is_empty(),
6455
        "the .oxyattributes file was read"
6456
    );
6457
    let h = repo.commit("edit", &[]).unwrap();
6458
    let c = repo.store().get_change(&h).unwrap();
6459
    assert_eq!(
6460
        c.tree_ops.len() + c.edits.len(),
6461
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6462
    );
6463
    assert_eq!(
6464
        repo.status_by_manifest().unwrap(),
6465
        Some(vec![]),
6466
        "clean after the commit"
6467
    );
6468
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6469
}
6470
6471
/// oxygen#41: a clean check that verified racy entries restamps the
6472
/// manifest, so later checks can trust them, and a same-size rewrite
6473
/// straight afterwards is still found: entries within two seconds of the
6474
/// new time stay racy.
6475
#[test]
6476
fn a_verified_clean_check_restamps_the_manifest_safely() {
6477
    hermetic();
6478
    let dir = tempfile::tempdir().unwrap();
6479
    let root = dir.path();
6480
    let repo = Repo::init(root).unwrap();
6481
    write(root, "a.txt", b"one\n");
6482
    repo.commit("one", &[]).unwrap();
6483
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6484
    assert!(repo.clean_by_manifest().unwrap());
6485
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6486
    assert!(after > before, "restamped");
6487
    write(root, "a.txt", b"two\n");
6488
    assert!(
6489
        !repo.clean_by_manifest().unwrap(),
6490
        "a same-size rewrite is still seen"
6491
    );
6492
}
6493
6494
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6495
/// stored insert's text blob only when it builds that file's graph, and
6496
/// builds the same graph a full load does.
6497
#[test]
6498
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6499
    hermetic();
6500
    let dir = tempfile::tempdir().unwrap();
6501
    let root = dir.path();
6502
    let repo = Repo::init(root).unwrap();
6503
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6504
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6505
    write(root, "big.txt", big.as_bytes());
6506
    write(root, "other.txt", other.as_bytes());
6507
    let h = repo.commit("two large files", &[]).unwrap();
6508
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6509
    let h2 = repo.commit("append", &[]).unwrap();
6510
6511
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6512
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6513
        FileContent::Text { bytes, .. } => bytes.clone(),
6514
        other => panic!("{other:?}"),
6515
    };
6516
    // Built on demand, every graph renders as the full load's.
6517
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6518
    let big_node = full.files["big.txt"].node;
6519
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6520
    repo.load_all_graphs(&mut hist).unwrap();
6521
    let rendered = hist.materialize();
6522
    for p in ["big.txt", "other.txt"] {
6523
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6524
    }
6525
6526
    // Without other.txt's text blob, history still loads and big.txt still
6527
    // builds: nothing read the other text.
6528
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6529
    assert_eq!(texts.len(), 2);
6530
    let content = |r: &ObjectRef| -> Vec<u8> {
6531
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6532
        blob.chunks
6533
            .iter()
6534
            .flat_map(|c| repo.store().get(c).unwrap().1)
6535
            .collect()
6536
    };
6537
    let other_text = texts
6538
        .iter()
6539
        .filter_map(|t| match t {
6540
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6541
            _ => None,
6542
        })
6543
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6544
        .unwrap();
6545
    repo.store().remove_loose_for_test(&other_text).unwrap();
6546
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6547
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6548
    assert!(repo
6549
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6550
        .is_err());
6551
}
6552
6553
/// oxygen#35: the first status after a commit read and rendered every
6554
/// file (79 s and more than 14 GB on the Linux tree), because the
6555
/// manifest had no graph keys for files the commit added.
6556
#[test]
6557
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6558
    use std::os::unix::fs::PermissionsExt;
6559
    hermetic();
6560
    let dir = tempfile::tempdir().unwrap();
6561
    let root = dir.path();
6562
    let repo = Repo::init(root).unwrap();
6563
    let files = ["a.txt", "b.txt", "d/c.txt"];
6564
    for p in files {
6565
        write(root, p, format!("{p}\n").as_bytes());
6566
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6567
        fs::File::options()
6568
            .write(true)
6569
            .open(root.join(p))
6570
            .unwrap()
6571
            .set_modified(old)
6572
            .unwrap();
6573
    }
6574
    repo.commit("added", &[]).unwrap();
6575
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6576
    assert!(
6577
        m.entries.values().all(|e| e.graph.is_some()),
6578
        "keys recorded at commit"
6579
    );
6580
    // Unreadable files prove the next status reads none of them.
6581
    for p in files {
6582
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6583
    }
6584
    let snap = repo.snapshot_status("status").unwrap();
6585
    for p in files {
6586
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6587
    }
6588
    assert!(!snap.changed && snap.statuses.is_empty());
6589
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6590
}
6591
6592
/// oxygen#35: a checkout reads, renders and writes only the files whose
6593
/// graphs differ, and renders the rest a batch at a time.
6594
#[test]
6595
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6596
    use std::os::unix::fs::PermissionsExt;
6597
    hermetic();
6598
    let dir = tempfile::tempdir().unwrap();
6599
    let root = dir.path();
6600
    let origin = root.join("origin");
6601
    let mut repo = Repo::init(&origin).unwrap();
6602
    // More files than one batch holds.
6603
    let n = 2100;
6604
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6605
    for i in 0..n {
6606
        let p = format!("f/{i:04}.txt");
6607
        write(&origin, &p, format!("file {i}\n").as_bytes());
6608
        fs::File::options()
6609
            .write(true)
6610
            .open(origin.join(&p))
6611
            .unwrap()
6612
            .set_modified(old)
6613
            .unwrap();
6614
    }
6615
    repo.commit("many", &[]).unwrap();
6616
    repo.bookmark_create("feature", None).unwrap();
6617
    repo.bookmark_switch("feature", false).unwrap();
6618
    write(&origin, "f/0007.txt", b"changed\n");
6619
    repo.commit("one change", &[]).unwrap();
6620
6621
    // Switching back to main must not read the unchanged files.
6622
    for i in 0..n {
6623
        if i != 7 {
6624
            let p = origin.join(format!("f/{i:04}.txt"));
6625
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6626
        }
6627
    }
6628
    let r = repo.bookmark_switch("main", false).unwrap();
6629
    for i in 0..n {
6630
        let p = origin.join(format!("f/{i:04}.txt"));
6631
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6632
    }
6633
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6634
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6635
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6636
6637
    // A clone renders every file, across batches.
6638
    let c = root.join("clone");
6639
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6640
    for i in [0, 2047, 2048, n - 1] {
6641
        assert_eq!(
6642
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6643
            format!("file {i}\n").as_bytes()
6644
        );
6645
    }
6646
    let cloned = Repo::open(&c).unwrap();
6647
    assert!(cloned
6648
        .snapshot_status("status")
6649
        .unwrap()
6650
        .statuses
6651
        .is_empty());
6652
}
6653
6654
/// A file written just before the manifest (inside the racy window) is
6655
/// checked by its hash: trusted when equal, caught when edited in place
6656
/// with the same size and time.
6657
#[test]
6658
fn a_racy_manifest_entry_is_checked_by_hash() {
6659
    hermetic();
6660
    let dir = tempfile::tempdir().unwrap();
6661
    let root = dir.path();
6662
    let repo = Repo::init(root).unwrap();
6663
    write(root, "a.txt", b"one\n");
6664
    repo.commit("fresh", &[]).unwrap();
6665
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6666
    let t = fs::metadata(root.join("a.txt"))
6667
        .unwrap()
6668
        .modified()
6669
        .unwrap();
6670
    write(root, "a.txt", b"two\n");
6671
    fs::File::options()
6672
        .write(true)
6673
        .open(root.join("a.txt"))
6674
        .unwrap()
6675
        .set_modified(t)
6676
        .unwrap();
6677
    assert!(
6678
        !repo.clean_by_manifest().unwrap(),
6679
        "same size and time, other bytes"
6680
    );
6681
    assert_eq!(
6682
        statuses(&repo.snapshot_status("status").unwrap()),
6683
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6684
    );
6685
}
6686
6687
/// A fetch on one machine moves changes as stored, text blobs among the
6688
/// objects; a change whose text blob did not come is refused, not stored.
6689
#[test]
6690
fn a_raw_bundle_without_a_changes_text_is_refused() {
6691
    hermetic();
6692
    let dir = tempfile::tempdir().unwrap();
6693
    let root = dir.path();
6694
    let a = Repo::init(&root.join("a")).unwrap();
6695
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6696
    write(&root.join("a"), "big.txt", big.as_bytes());
6697
    let h = a.commit("big", &[]).unwrap();
6698
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6699
    assert_eq!(bundle.raw_changes.len(), 1);
6700
    assert!(bundle.changes.is_empty());
6701
    let b = Repo::init(&root.join("b")).unwrap();
6702
    let mut without = bundle.clone();
6703
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6704
    let e = b.import_bundle(&without, false).unwrap_err();
6705
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6706
    assert!(!b.store().has(&h));
6707
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6708
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6709
}
6710
6711
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6712
/// again was a second node for one Git path, so a file moved into it on
6713
/// another line, where the first node still stood, ended up in two places.
6714
/// An import now brings the directory back rather than make a new one.
6715
#[test]
6716
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6717
    hermetic();
6718
    if std::process::Command::new("git")
6719
        .arg("--version")
6720
        .output()
6721
        .is_err()
6722
    {
6723
        eprintln!("git not installed; skipping");
6724
        return;
6725
    }
6726
    let dir = tempfile::tempdir().unwrap();
6727
    let root = dir.path();
6728
    let g = root.join("src.git");
6729
    fs::create_dir_all(&g).unwrap();
6730
    let git = |args: &[&str]| -> String {
6731
        let out = std::process::Command::new("git")
6732
            .arg("-C")
6733
            .arg(&g)
6734
            .args([
6735
                "-c",
6736
                "user.name=Grace",
6737
                "-c",
6738
                "[email protected]",
6739
                "-c",
6740
                "commit.gpgsign=false",
6741
            ])
6742
            .args(args)
6743
            .output()
6744
            .unwrap();
6745
        assert!(
6746
            out.status.success(),
6747
            "git {args:?}: {}",
6748
            String::from_utf8_lossy(&out.stderr)
6749
        );
6750
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6751
    };
6752
    git(&["init", "-q", "-b", "main"]);
6753
    write(&g, "d/a.txt", b"a\n");
6754
    write(&g, "c/x.txt", b"x\n");
6755
    git(&["add", "."]);
6756
    git(&["commit", "-qm", "base"]);
6757
    // One line: move x into d while d still stands.
6758
    git(&["checkout", "-qb", "side"]);
6759
    git(&["mv", "c/x.txt", "d/x.txt"]);
6760
    git(&["commit", "-qm", "x into d"]);
6761
    // The other: d goes, comes back, and x moves into it too.
6762
    git(&["checkout", "-q", "main"]);
6763
    git(&["rm", "-q", "d/a.txt"]);
6764
    git(&["commit", "-qm", "d goes"]);
6765
    write(&g, "d/b.txt", b"b\n");
6766
    git(&["add", "."]);
6767
    git(&["commit", "-qm", "d comes back"]);
6768
    git(&["mv", "c/x.txt", "d/x.txt"]);
6769
    git(&["commit", "-qm", "x into d again"]);
6770
    git(&["merge", "-q", "--no-edit", "side"]);
6771
6772
    let repo = Repo::init(&root.join("o")).unwrap();
6773
    repo.import_git(&g, "main").unwrap();
6774
    let v = repo.verify_git_import(&g, "main").unwrap();
6775
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6776
    let st = repo
6777
        .load_state_history(&repo.bookmark_heads().unwrap())
6778
        .unwrap();
6779
    let view = st.tree().view();
6780
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6781
    // The directory is the one the first commit made.
6782
    // Commits made in one second tie on time: find the first by its message.
6783
    let first = repo
6784
        .log()
6785
        .unwrap()
6786
        .into_iter()
6787
        .find(|e| e.change.message.starts_with("base"))
6788
        .unwrap();
6789
    let base = repo
6790
        .load_state_history(&[first.hash])
6791
        .unwrap()
6792
        .tree()
6793
        .view();
6794
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6795
}
6796
6797
/// oxygen#30, the rest: a placement left under a directory another line
6798
/// removed is out of sight, so no diff reaches it; the merge that settles
6799
/// where the file is retires it.
6800
#[test]
6801
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6802
    hermetic();
6803
    if std::process::Command::new("git")
6804
        .arg("--version")
6805
        .output()
6806
        .is_err()
6807
    {
6808
        eprintln!("git not installed; skipping");
6809
        return;
6810
    }
6811
    let dir = tempfile::tempdir().unwrap();
6812
    let root = dir.path();
6813
    let g = root.join("src.git");
6814
    fs::create_dir_all(&g).unwrap();
6815
    let run = |args: &[&str]| {
6816
        std::process::Command::new("git")
6817
            .arg("-C")
6818
            .arg(&g)
6819
            .args([
6820
                "-c",
6821
                "user.name=Grace",
6822
                "-c",
6823
                "[email protected]",
6824
                "-c",
6825
                "commit.gpgsign=false",
6826
            ])
6827
            .args(args)
6828
            .output()
6829
            .unwrap()
6830
    };
6831
    let git = |args: &[&str]| {
6832
        let out = run(args);
6833
        assert!(
6834
            out.status.success(),
6835
            "git {args:?}: {}",
6836
            String::from_utf8_lossy(&out.stderr)
6837
        );
6838
    };
6839
    git(&["init", "-q", "-b", "main"]);
6840
    write(&g, "c/x.txt", b"x\n");
6841
    write(&g, "keep.txt", b"k\n");
6842
    git(&["add", "."]);
6843
    git(&["commit", "-qm", "base"]);
6844
    // One line renames the file within c; the other moves it out of c,
6845
    // which goes.
6846
    git(&["checkout", "-qb", "side"]);
6847
    git(&["mv", "c/x.txt", "c/y.txt"]);
6848
    git(&["commit", "-qm", "rename within c"]);
6849
    git(&["checkout", "-q", "main"]);
6850
    fs::create_dir_all(g.join("n")).unwrap();
6851
    git(&["mv", "c/x.txt", "n/x.txt"]);
6852
    git(&["commit", "-qm", "move out of c"]);
6853
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6854
    let _ = run(&["merge", "-q", "side"]);
6855
    let _ = run(&[
6856
        "rm",
6857
        "-q",
6858
        "--cached",
6859
        "--ignore-unmatch",
6860
        "c/y.txt",
6861
        "c/x.txt",
6862
    ]);
6863
    let _ = std::fs::remove_dir_all(g.join("c"));
6864
    write(&g, "n/x.txt", b"x\n");
6865
    git(&["add", "-A"]);
6866
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6867
6868
    let repo = Repo::init(&root.join("o")).unwrap();
6869
    repo.import_git(&g, "main").unwrap();
6870
    let v = repo.verify_git_import(&g, "main").unwrap();
6871
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6872
    let st = repo
6873
        .load_state_history(&repo.bookmark_heads().unwrap())
6874
        .unwrap();
6875
    let view = st.tree().view();
6876
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6877
    assert!(view.entries.contains_key("n/x.txt"));
6878
}
6879
6880
/// oxygen#30, orphans: a file added on one line into a directory the other
6881
/// line removed is placed where the tree cannot show it; Git's merge keeps
6882
/// the file, and the import's merge leaves exactly one of it.
6883
#[test]
6884
fn git_import_merge_leaves_no_orphan_behind() {
6885
    hermetic();
6886
    if std::process::Command::new("git")
6887
        .arg("--version")
6888
        .output()
6889
        .is_err()
6890
    {
6891
        eprintln!("git not installed; skipping");
6892
        return;
6893
    }
6894
    let dir = tempfile::tempdir().unwrap();
6895
    let root = dir.path();
6896
    let g = root.join("src.git");
6897
    fs::create_dir_all(&g).unwrap();
6898
    let git = |args: &[&str]| {
6899
        let out = std::process::Command::new("git")
6900
            .arg("-C")
6901
            .arg(&g)
6902
            .args([
6903
                "-c",
6904
                "user.name=Grace",
6905
                "-c",
6906
                "[email protected]",
6907
                "-c",
6908
                "commit.gpgsign=false",
6909
            ])
6910
            .args(args)
6911
            .output()
6912
            .unwrap();
6913
        assert!(
6914
            out.status.success(),
6915
            "git {args:?}: {}",
6916
            String::from_utf8_lossy(&out.stderr)
6917
        );
6918
    };
6919
    git(&["init", "-q", "-b", "main"]);
6920
    write(&g, "d/f.txt", b"f\n");
6921
    write(&g, "keep.txt", b"k\n");
6922
    git(&["add", "."]);
6923
    git(&["commit", "-qm", "base"]);
6924
    git(&["checkout", "-qb", "side"]);
6925
    write(&g, "d/new.txt", b"new\n");
6926
    git(&["add", "."]);
6927
    git(&["commit", "-qm", "add into d"]);
6928
    git(&["checkout", "-q", "main"]);
6929
    git(&["rm", "-q", "d/f.txt"]);
6930
    git(&["commit", "-qm", "d goes"]);
6931
    git(&["merge", "-q", "--no-edit", "side"]);
6932
6933
    let repo = Repo::init(&root.join("o")).unwrap();
6934
    repo.import_git(&g, "main").unwrap();
6935
    let v = repo.verify_git_import(&g, "main").unwrap();
6936
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6937
    let st = repo
6938
        .load_state_history(&repo.bookmark_heads().unwrap())
6939
        .unwrap();
6940
    let view = st.tree().view();
6941
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6942
    assert!(view.entries.contains_key("d/new.txt"));
6943
}
6944
6945
/// fsck checks a change's text as the blobs it is stored in, without
6946
/// decoding it: a missing text blob is an error named for the change.
6947
#[test]
6948
fn fsck_names_a_missing_text_blob() {
6949
    hermetic();
6950
    let dir = tempfile::tempdir().unwrap();
6951
    let root = dir.path();
6952
    let repo = Repo::init(root).unwrap();
6953
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6954
    write(root, "big.txt", big.as_bytes());
6955
    let h = repo.commit("big", &[]).unwrap();
6956
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6957
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6958
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6959
        panic!("a stored text")
6960
    };
6961
    repo.store().remove_loose_for_test(&b).unwrap();
6962
    let rep = repo.fsck().unwrap();
6963
    assert!(rep.errors() > 0);
6964
    assert!(
6965
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6966
        "{:?}",
6967
        rep.problems
6968
    );
6969
}
6970
6971
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6972
/// reached with that remote's token and CA (a private subrepo then clones
6973
/// for anyone who can read the parent); another hub gets none of them.
6974
#[test]
6975
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6976
    hermetic();
6977
    let dir = tempfile::tempdir().unwrap();
6978
    let mut repo = Repo::init(dir.path()).unwrap();
6979
    repo.config
6980
        .set(
6981
            "remote.origin.url",
6982
            "https://Hub.example:7343/doomsdayone/metalgear",
6983
        )
6984
        .unwrap();
6985
    repo.config.set("remote.origin.token", "secret").unwrap();
6986
    repo.config
6987
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6988
        .unwrap();
6989
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6990
    assert_eq!(same.token.as_deref(), Some("secret"));
6991
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6992
    for other in [
6993
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6994
        "https://hub.example/doomsdayone/rstar-api",
6995
        "http://hub.example:7343/doomsdayone/rstar-api",
6996
    ] {
6997
        let o = repo.credentials_for(other);
6998
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6999
    }
7000
}
7001
7002
/// oxygen#47: a remote with no token of its own uses the user's credential
7003
/// store for its hub, and a nested checkout finds its parent's remote
7004
/// token there instead of keeping a copy.
7005
#[test]
7006
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7007
    hermetic();
7008
    let home = tempfile::tempdir().unwrap();
7009
    let dir = tempfile::tempdir().unwrap();
7010
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7011
    parent
7012
        .config
7013
        .set("remote.origin.url", "https://hub.example/o/parent")
7014
        .unwrap();
7015
    parent.save_config().unwrap();
7016
    assert_eq!(parent.remote_options("origin").token, None);
7017
    crate::credentials::Credentials::at(home.path())
7018
        .save("https://hub.example", "stored", Some("andy"), None)
7019
        .unwrap();
7020
    assert_eq!(
7021
        parent.remote_options("origin").token.as_deref(),
7022
        Some("stored")
7023
    );
7024
7025
    let empty_home = tempfile::tempdir().unwrap();
7026
    let nested = dir.path().join("deps").join("child");
7027
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7028
    child
7029
        .config
7030
        .set("remote.origin.url", "https://hub.example/o/child")
7031
        .unwrap();
7032
    child.save_config().unwrap();
7033
    assert_eq!(child.remote_options("origin").token, None);
7034
    parent
7035
        .config
7036
        .set("remote.origin.token", "checkout")
7037
        .unwrap();
7038
    parent.save_config().unwrap();
7039
    assert_eq!(
7040
        child.remote_options("origin").token.as_deref(),
7041
        Some("checkout")
7042
    );
7043
    // Another hub's checkout token is not borrowed.
7044
    child
7045
        .config
7046
        .set("remote.origin.url", "https://other.example/o/child")
7047
        .unwrap();
7048
    assert_eq!(child.remote_options("origin").token, None);
7049
}
7050
7051
#[test]
7052
fn the_metadata_cache_survives_a_torn_tail() {
7053
    hermetic();
7054
    let dir = tempfile::tempdir().unwrap();
7055
    let root = dir.path();
7056
    let repo = Repo::init(root).unwrap();
7057
    write(root, "a.txt", b"1\n");
7058
    let h = repo.commit("first", &[]).unwrap();
7059
    let meta = repo.store().get_change_meta(&h).unwrap();
7060
    let cache = repo.store().dir().join("metas");
7061
    let len = fs::metadata(&cache).unwrap().len();
7062
    assert!(len > 0, "a change read is cached");
7063
    // A torn record at the end: the cache reads up to it and cuts it off.
7064
    fs::OpenOptions::new()
7065
        .append(true)
7066
        .open(&cache)
7067
        .unwrap()
7068
        .write_all(&[7; 20])
7069
        .unwrap();
7070
    let again = Repo::open(root).unwrap();
7071
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7072
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7073
}
7074
7075
#[test]
7076
fn a_manifest_that_does_not_check_reads_as_none() {
7077
    hermetic();
7078
    let dir = tempfile::tempdir().unwrap();
7079
    let root = dir.path();
7080
    let repo = Repo::init(root).unwrap();
7081
    write(root, "a.txt", b"1\n");
7082
    repo.commit("first", &[]).unwrap();
7083
    let path = repo.manifest_path();
7084
    let mut bytes = fs::read(&path).unwrap();
7085
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7086
    let last = bytes.len() - 1;
7087
    bytes[last] ^= 1;
7088
    fs::write(&path, &bytes).unwrap();
7089
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7090
    // The next status reads the files and writes it again.
7091
    let again = Repo::open(root).unwrap();
7092
    assert!(!again.snapshot("status").unwrap().changed);
7093
    assert!(again.read_manifest().unwrap().is_some());
7094
}
7095
7096
#[test]
7097
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7098
    hermetic();
7099
    let dir = tempfile::tempdir().unwrap();
7100
    let root = dir.path();
7101
    let repo = Repo::init(root).unwrap();
7102
    write(root, "a.txt", b"1\n");
7103
    write(root, "b.txt", b"2\n");
7104
    // b.txt outside the racy window, so snapshots take it as unchanged.
7105
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7106
    fs::File::options()
7107
        .write(true)
7108
        .open(root.join("b.txt"))
7109
        .unwrap()
7110
        .set_modified(old)
7111
        .unwrap();
7112
    repo.commit("first", &[]).unwrap();
7113
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7114
    repo.snapshot_status("status").unwrap();
7115
    write(root, "a.txt", b"1\n2\n");
7116
    repo.commit("second", &[]).unwrap();
7117
    assert!(
7118
        repo.clean_by_manifest().unwrap(),
7119
        "after a commit of one file"
7120
    );
7121
    // Edited, seen by a status, edited again, then committed: the status
7122
    // left the first edit's stat, which the commit must not keep.
7123
    write(root, "a.txt", b"1\n2\n3\n");
7124
    repo.snapshot_status("status").unwrap();
7125
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7126
    repo.commit("third", &[]).unwrap();
7127
    assert!(
7128
        repo.clean_by_manifest().unwrap(),
7129
        "after an edit a status saw"
7130
    );
7131
}
7132
7133
#[test]
7134
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7135
    hermetic();
7136
    let dir = tempfile::tempdir().unwrap();
7137
    let root = dir.path();
7138
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7139
    write(root, "a.txt", b"1\n2\n");
7140
    let a = repo.commit("A", &[]).unwrap();
7141
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7142
    write(root, "a.txt", b"1\nX\n");
7143
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7144
    repo.bookmark_switch("develop", false).unwrap();
7145
    write(root, "a.txt", b"1\nY\n");
7146
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7147
    repo.bookmark_switch("main", false).unwrap();
7148
7149
    let err = repo.rebase(&c, &[d]).unwrap_err();
7150
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7151
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7152
    assert!(r.changed && r.checked_out);
7153
    let snap = repo.snapshot_status("status").unwrap();
7154
    assert!(
7155
        snap.base_snapshot.is_conflicted(),
7156
        "the conflict is in the working copy"
7157
    );
7158
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7159
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7160
7161
    write(root, "a.txt", b"1\nXY\n");
7162
    repo.commit("Resolve", &[]).unwrap();
7163
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7164
    assert!(st.contains(&c) && st.contains(&d));
7165
    let files = st.materialize().files;
7166
    assert!(!files["a.txt"].is_conflicted());
7167
    assert!(
7168
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7169
    );
7170
7171
    // A change the current bookmark does not hold is refused.
7172
    repo.bookmark_switch("develop", false).unwrap();
7173
    write(root, "b.txt", b"b\n");
7174
    let e = repo.commit("E", &[]).unwrap();
7175
    repo.bookmark_switch("main", false).unwrap();
7176
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7177
    assert!(
7178
        err.to_string().contains("not on the current bookmark"),
7179
        "{err}"
7180
    );
7181
}
7182
7183
#[test]
7184
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7185
    hermetic();
7186
    let dir = tempfile::tempdir().unwrap();
7187
    let root = dir.path();
7188
    let repo = Repo::init(root).unwrap();
7189
    write(root, "a.txt", b"a\n");
7190
    write(root, "kept.log", b"tracked\n");
7191
    repo.commit("first", &[]).unwrap();
7192
    write(root, "build.log", b"made\n");
7193
    let snap = repo.snapshot_status("status").unwrap();
7194
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7195
    // A rule written afterwards leaves the added file out again, while the
7196
    // committed one stays tracked.
7197
    write(root, ".gitignore", b"*.log\n");
7198
    let snap = repo.snapshot_status("status").unwrap();
7199
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7200
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7201
    write(root, "kept.log", b"tracked, edited\n");
7202
    let snap = repo.snapshot_status("status").unwrap();
7203
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7204
}
7205
7206
#[test]
7207
fn shed_graphs_come_back_the_same() {
7208
    hermetic();
7209
    let dir = tempfile::tempdir().unwrap();
7210
    let root = dir.path();
7211
    let repo = Repo::init(root).unwrap();
7212
    write(root, "a.txt", b"1\n2\n3\n");
7213
    write(root, "b.txt", b"x\n");
7214
    repo.commit("first", &[]).unwrap();
7215
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7216
    repo.commit("second", &[]).unwrap();
7217
    let heads = repo.bookmark_heads().unwrap();
7218
    let mut st = repo.load_state_history(&heads).unwrap();
7219
    let view = st.tree().view();
7220
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7221
        .iter()
7222
        .map(|p| view.entries[*p].node)
7223
        .collect();
7224
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7225
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7226
    assert_eq!(st.built_count(), 2);
7227
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7228
    assert_eq!((shed, st.built_count()), (2, 0));
7229
    // A later change applies on top of the shed history.
7230
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7231
    let h3 = repo.commit("third", &[]).unwrap();
7232
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7233
    st.add_known(h3, skeleton, texts);
7234
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7235
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7236
    assert_eq!(after[1], before[1]);
7237
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7238
}
7239
7240
#[test]
7241
fn many_edited_files_diff_in_parallel() {
7242
    // Enough edited files that the builder diffs them in parallel; the
7243
    // commit must hold exactly what is on disk, and a second snapshot
7244
    // must find nothing left to commit.
7245
    hermetic();
7246
    let dir = tempfile::tempdir().unwrap();
7247
    let root = dir.path();
7248
    let repo = Repo::init(root).unwrap();
7249
    let text = |i: usize, round: usize| {
7250
        let mut s = String::new();
7251
        for line in 0..50 {
7252
            if round > 0 && line % 7 == i % 7 {
7253
                s.push_str(&format!("edited {round} {i} {line}\n"));
7254
            } else {
7255
                s.push_str(&format!("file {i} line {line}\n"));
7256
            }
7257
        }
7258
        if round > 0 && i.is_multiple_of(3) {
7259
            s.push_str("appended\n");
7260
        }
7261
        s
7262
    };
7263
    for i in 0..40 {
7264
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7265
    }
7266
    repo.commit("first", &[]).unwrap();
7267
    for i in 0..40 {
7268
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7269
    }
7270
    let h = repo.commit("edit every file", &[]).unwrap();
7271
    let snap = repo.load_state(&[h]).unwrap().materialize();
7272
    for i in 0..40 {
7273
        let want = text(i, 1);
7274
        assert!(
7275
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
7276
            "d/f{i}.txt as committed"
7277
        );
7278
    }
7279
    assert!(
7280
        repo.commit("nothing", &[]).is_err(),
7281
        "nothing left to commit"
7282
    );
7283
}
7284
7285
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7286
/// is known (fetch printed "up to date" while main was behind), a change
7287
/// only fetched resolves and says where it is, and a checkout whose only
7288
/// remote is not `origin` uses that one.
7289
#[test]
7290
fn a_fetched_change_shows_as_behind_and_resolves() {
7291
    hermetic();
7292
    let dir = tempfile::tempdir().unwrap();
7293
    let root = dir.path();
7294
    let origin = Repo::init(&root.join("origin")).unwrap();
7295
    drop(origin);
7296
    let url = root.join("origin").to_string_lossy().to_string();
7297
    let a = Repo::clone(&url, &root.join("a"))
7298
        .unwrap()
7299
        .with_home(root.join("home-a"));
7300
    write(&root.join("a"), "f.txt", b"one\n");
7301
    a.commit("one", &[]).unwrap();
7302
    a.push("origin", false).unwrap();
7303
    let b = Repo::clone(&url, &root.join("b"))
7304
        .unwrap()
7305
        .with_home(root.join("home-b"));
7306
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7307
7308
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7309
    let h2 = a.commit("two", &[]).unwrap();
7310
    a.push("origin", false).unwrap();
7311
    b.fetch("origin").unwrap();
7312
    // Fetched, not pulled: one behind, the change found and placed.
7313
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7314
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7315
    assert_eq!(
7316
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7317
            .unwrap(),
7318
        h2
7319
    );
7320
    assert_eq!(
7321
        b.remote_only_location(&h2).unwrap().as_deref(),
7322
        Some("origin/main")
7323
    );
7324
    // Fetching again changes nothing: still behind, which is what the
7325
    // CLI now says rather than "up to date".
7326
    b.fetch("origin").unwrap();
7327
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7328
    b.pull("origin").unwrap();
7329
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7330
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7331
7332
    // One remote, not called origin: it is the default.
7333
    let mut c = Repo::init(&root.join("c")).unwrap();
7334
    assert_eq!(c.default_remote(), "origin");
7335
    c.config.set("remote.earth.url", &url).unwrap();
7336
    assert_eq!(c.default_remote(), "earth");
7337
    c.config.set("remote.origin.url", &url).unwrap();
7338
    assert_eq!(c.default_remote(), "origin");
7339
}
7340
7341
/// oxygen#57: a clone from a relative local path records the remote as an
7342
/// absolute path, so fetch still finds it from inside the clone.
7343
#[test]
7344
fn a_clone_from_a_relative_path_records_it_absolute() {
7345
    hermetic();
7346
    let dir = tempfile::tempdir().unwrap();
7347
    let root = dir.path();
7348
    Repo::init(&root.join("origin")).unwrap();
7349
    let rel = crate::protocol::stored_url("relative/repo");
7350
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7351
    assert_eq!(
7352
        crate::protocol::stored_url("https://hub.example/o/n"),
7353
        "https://hub.example/o/n"
7354
    );
7355
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7356
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7357
    // A bucket is kept as written: it is not a path.
7358
    assert_eq!(
7359
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7360
        "s3://bucket/prefix?profile=p"
7361
    );
7362
    let url = root.join("origin").to_string_lossy().to_string();
7363
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7364
    assert_eq!(b.config.remotes["origin"], url);
7365
    b.fetch("origin").unwrap();
7366
}
7367
7368
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7369
/// and gets its subrepos at their pins from this workspace's copies, with
7370
/// their remotes pointing where the subrepos come from.
7371
#[test]
7372
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7373
    hermetic();
7374
    let dir = tempfile::tempdir().unwrap();
7375
    let root = dir.path();
7376
    Repo::init(&root.join("lib-origin")).unwrap();
7377
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7378
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7379
        .unwrap()
7380
        .with_home(root.join("home"));
7381
    write(&root.join("lib"), "lib.txt", b"v1\n");
7382
    let l1 = lib.commit("lib v1", &[]).unwrap();
7383
    assert!(lib.push("origin", false).unwrap()[0].ok);
7384
7385
    let app_dir = root.join("app");
7386
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7387
    write(&app_dir, "main.txt", b"app\n");
7388
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7389
    app.commit("app with lib", &[]).unwrap();
7390
    // A second bookmark, and the main workspace on another.
7391
    app.bookmark_create("develop", None).unwrap();
7392
    app.bookmark_create("feature", None).unwrap();
7393
    let mut app = app;
7394
    app.bookmark_switch("feature", false).unwrap();
7395
    assert_eq!(app.config.bookmark, "feature");
7396
7397
    // The library's origin goes away: the subrepo must come from here.
7398
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7399
    let heads = app.resolve_heads("develop").unwrap();
7400
    let ws = app
7401
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7402
        .unwrap();
7403
    assert_eq!(
7404
        ws.config.bookmark, "develop",
7405
        "the new workspace is on develop"
7406
    );
7407
    assert_eq!(
7408
        app.config.bookmark, "feature",
7409
        "and this one stays on its own"
7410
    );
7411
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7412
    assert_eq!(
7413
        sub.config.remotes["origin"], lib_url,
7414
        "its origin is the subrepo's URL"
7415
    );
7416
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7417
    assert_eq!(
7418
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7419
        b"v1\n"
7420
    );
7421
}
7422
7423
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7424
/// operators and the predicates, over a small graph with two heads and
7425
/// a rename.
7426
#[test]
7427
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7428
    hermetic();
7429
    let dir = tempfile::tempdir().unwrap();
7430
    let root = dir.path();
7431
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7432
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7433
        .unwrap();
7434
    write(root, "src/a.rs", b"one\n");
7435
    let a = repo.commit("first: add a", &[]).unwrap();
7436
    write(root, "src/a.rs", b"one\ntwo\n");
7437
    let b = repo.commit("second: grow a", &[]).unwrap();
7438
    // A second head, independent of b: a new file on top of a.
7439
    repo.checkout(&[a], false, "checkout a").unwrap();
7440
    write(root, "docs/notes.md", b"notes\n");
7441
    let c = repo.commit("third: notes", &[]).unwrap();
7442
    // Back to both heads, then rename a.rs: the node keeps its identity.
7443
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7444
        .unwrap();
7445
    fs::remove_file(root.join("src/a.rs")).unwrap();
7446
    write(root, "src/z.rs", b"one\ntwo\n");
7447
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7448
    let wc = repo.working_copy().unwrap().0;
7449
    // A saved revset is checked when set.
7450
    repo.set_user_config("revset.mine", "author(me) & ::main")
7451
        .unwrap();
7452
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7453
    let set = |src: &str| -> Vec<ChangeHash> {
7454
        let mut v = repo.revset(src).unwrap().hashes;
7455
        v.sort();
7456
        v
7457
    };
7458
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7459
        let mut v = hs.to_vec();
7460
        v.sort();
7461
        v
7462
    };
7463
7464
    // Changes commute: a new file depends on nothing and the rename on the
7465
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7466
    // copy on the three heads b, c, d.
7467
    let heads = sorted(&repo.bookmark_heads().unwrap());
7468
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7469
    assert!(heads.contains(&d) && heads.contains(&c));
7470
    // Symbols and closures.
7471
    assert_eq!(set("main"), heads);
7472
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7473
    assert_eq!(set("@"), vec![wc]);
7474
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7475
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7476
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7477
    assert_eq!(
7478
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7479
        sorted(&[a, b])
7480
    );
7481
    // Ranges: what main has beyond b, and `..` forms.
7482
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7483
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7484
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7485
    // Operators and precedence: ~ binds tighter than &, & than |.
7486
    assert_eq!(
7487
        set(&format!("::main ~ #{}", d.short(12))),
7488
        sorted(&[a, b, c])
7489
    );
7490
    assert_eq!(
7491
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7492
        sorted(&[b, c])
7493
    );
7494
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7495
    // Relations.
7496
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7497
    head_deps.sort();
7498
    head_deps.dedup();
7499
    assert_eq!(set("deps(main)"), head_deps);
7500
    let on_a: Vec<ChangeHash> = [b, c, d]
7501
        .into_iter()
7502
        .filter(|h| meta(h).deps.contains(&a))
7503
        .collect();
7504
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7505
    assert_eq!(set("heads(::main)"), heads);
7506
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7507
    assert_eq!(
7508
        set(&format!(
7509
            "heads(#{} | #{} | #{})",
7510
            a.short(12),
7511
            b.short(12),
7512
            c.short(12)
7513
        )),
7514
        sorted(&[b, c])
7515
    );
7516
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7517
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7518
    assert_eq!(set("none()"), vec![]);
7519
    // Predicates: author by name, email, key prefix and `me`.
7520
    let key = repo.config.author_key.unwrap();
7521
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7522
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7523
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7524
    assert_eq!(set("author(me) & ::main").len(), 4);
7525
    assert_eq!(set("author(nobody)"), vec![]);
7526
    assert_eq!(set("description(notes)"), vec![c]);
7527
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7528
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7529
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7530
    // touches follows the node through the rename, in the current state.
7531
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7532
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7533
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7534
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7535
    // Newest first in the result order.
7536
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7537
    // The saved revset, and errors that say what is wrong.
7538
    assert_eq!(set("mine()").len(), 4);
7539
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7540
    assert!(e.contains("unknown function nosuch()"), "{e}");
7541
    let e = repo.revset("main &").unwrap_err().to_string();
7542
    assert!(e.contains("at character"), "{e}");
7543
    let e = repo.revset("zzzz").unwrap_err().to_string();
7544
    assert!(e.contains("no change matches"), "{e}");
7545
    let e = repo
7546
        .revset_with_budget("::main", std::time::Duration::ZERO)
7547
        .unwrap_err()
7548
        .to_string();
7549
    assert!(e.contains("budget"), "{e}");
7550
    // The log entries carry the bookmark's heads and the working copy.
7551
    let entries = repo.log_revset("::@").unwrap();
7552
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7553
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7554
    // push); then a signed change, a tag, and a revocation.
7555
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7556
    assert_eq!(set("signed_by(me)"), vec![]);
7557
    repo.sign_change(&d).unwrap();
7558
    assert_eq!(set("signed_by(me)"), vec![d]);
7559
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7560
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7561
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7562
    assert_eq!(set("delegated()"), vec![]);
7563
    assert_eq!(set("revoked()"), vec![]);
7564
    assert_eq!(set("attested(tag)"), vec![]);
7565
    repo.tag_create("v1", &[b], "first").unwrap();
7566
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7567
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7568
    assert_eq!(set("attested(receipt)"), vec![]);
7569
    assert_eq!(set("built(test)"), vec![]);
7570
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7571
    assert!(e.contains("tag, receipt or ref"), "{e}");
7572
    repo.revoke_identity(&key, "test").unwrap();
7573
    assert_eq!(set("revoked()"), vec![d]);
7574
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7575
}
7576
7577
#[test]
7578
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7579
    let dir = tempfile::tempdir().unwrap();
7580
    let root = dir.path();
7581
    let home = root.join("home");
7582
    // Ada's identity lives in the user file; repository `a` pins the same
7583
    // key in its own file, repository `b` names none.
7584
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7585
    let (key, _) = a
7586
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7587
        .unwrap();
7588
    a.config.set("author.key", &key.to_hex()).unwrap();
7589
    a.save_config().unwrap();
7590
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7591
    let r = a
7592
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7593
        .unwrap();
7594
    assert_eq!(
7595
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7596
        r.new.to_hex(),
7597
        "the user file follows"
7598
    );
7599
    assert_eq!(
7600
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7601
        r.new.to_hex(),
7602
        "the pinning repository follows"
7603
    );
7604
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7605
    assert_eq!(
7606
        b.config.author_key,
7607
        Some(r.new),
7608
        "a checkout without a pin follows the user file"
7609
    );
7610
    // A repository-scoped identity leaves the user file alone.
7611
    let other_home = root.join("home2");
7612
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7613
    let (ck, _) = c
7614
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7615
        .unwrap();
7616
    assert!(!other_home.join("config.toml").exists());
7617
    let r2 = c.rotate_identity().unwrap();
7618
    assert_ne!(r2.new, ck);
7619
    assert_eq!(
7620
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7621
        r2.new.to_hex()
7622
    );
7623
    assert!(
7624
        !other_home.join("config.toml").exists(),
7625
        "a repository-scoped identity stays repository-scoped"
7626
    );
7627
    // Several delegates in one rotation; a repeat is refused.
7628
    let (d1, d2) = (
7629
        SecretKey::generate().identity("D1", "d1@x", 1),
7630
        SecretKey::generate().identity("D2", "d2@x", 1),
7631
    );
7632
    let r3 = c
7633
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7634
        .unwrap();
7635
    assert_eq!(r3.identity.delegates.len(), 2);
7636
    assert!(c
7637
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7638
        .is_err());
7639
}
7640
7641
/// Two unrelated histories that both add the same file, joined by two
7642
/// independent merges on two branches, then those branches merged: Git
7643
/// merges identical additions cleanly, and the import must too (#71,
7644
/// found in VS Code's history).
7645
#[test]
7646
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7647
    // Batches of one: every merge renders apart from the state, where a
7648
    // file whose graph the state had built came out empty (#71).
7649
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7650
    hermetic();
7651
    if std::process::Command::new("git")
7652
        .arg("--version")
7653
        .output()
7654
        .is_err()
7655
    {
7656
        eprintln!("git not installed; skipping");
7657
        return;
7658
    }
7659
    let dir = tempfile::tempdir().unwrap();
7660
    let root = dir.path();
7661
    let g = root.join("src.git");
7662
    fs::create_dir_all(&g).unwrap();
7663
    let git = |args: &[&str]| -> String {
7664
        let out = std::process::Command::new("git")
7665
            .arg("-C")
7666
            .arg(&g)
7667
            .args([
7668
                "-c",
7669
                "user.name=Grace",
7670
                "-c",
7671
                "[email protected]",
7672
                "-c",
7673
                "commit.gpgsign=false",
7674
            ])
7675
            .args(args)
7676
            .output()
7677
            .unwrap();
7678
        assert!(
7679
            out.status.success(),
7680
            "git {args:?}: {}",
7681
            String::from_utf8_lossy(&out.stderr)
7682
        );
7683
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7684
    };
7685
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7686
    // History A: main.
7687
    git(&["init", "-q", "-b", "main"]);
7688
    write(&g, "gulpfile.js", text);
7689
    write(&g, "a.txt", b"a\n");
7690
    git(&["add", "."]);
7691
    git(&["commit", "-q", "-m", "A root"]);
7692
    // History B: an unrelated root adding the same file, identical.
7693
    git(&["checkout", "-q", "--orphan", "fork"]);
7694
    git(&["rm", "-q", "-r", "--cached", "."]);
7695
    for f in ["gulpfile.js", "a.txt"] {
7696
        let _ = fs::remove_file(g.join(f));
7697
    }
7698
    write(&g, "gulpfile.js", text);
7699
    write(&g, "b.txt", b"b\n");
7700
    git(&["add", "."]);
7701
    git(&["commit", "-q", "-m", "B root"]);
7702
    // Two branches from main, each joining B on its own.
7703
    git(&["checkout", "-q", "-b", "one", "main"]);
7704
    git(&[
7705
        "merge",
7706
        "-q",
7707
        "--no-ff",
7708
        "--allow-unrelated-histories",
7709
        "-m",
7710
        "join on one",
7711
        "fork",
7712
    ]);
7713
    git(&["checkout", "-q", "-b", "two", "main"]);
7714
    write(&g, "a.txt", b"a\ntwo\n");
7715
    git(&["commit", "-q", "-am", "work on two"]);
7716
    git(&[
7717
        "merge",
7718
        "-q",
7719
        "--no-ff",
7720
        "--allow-unrelated-histories",
7721
        "-m",
7722
        "join on two",
7723
        "fork",
7724
    ]);
7725
    // Then the two joins meet, and the file is reformatted after.
7726
    git(&["checkout", "-q", "main"]);
7727
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7728
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7729
    write(
7730
        &g,
7731
        "gulpfile.js",
7732
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7733
    );
7734
    git(&["commit", "-q", "-am", "after"]);
7735
7736
    let dest = root.join("dest");
7737
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7738
    repo.import_git(&g, "main").unwrap();
7739
    let v = repo.verify_git_import(&g, "main").unwrap();
7740
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7741
    assert_eq!(
7742
        fs::read(dest.join("gulpfile.js")).unwrap(),
7743
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7744
    );
7745
}
7746
7747
/// As above, but the two joins keep different copies (each branch had a
7748
/// different version when it joined), and later work edits each copy:
7749
/// the shape of VS Code's c67ef57cda90 (#71).
7750
#[test]
7751
fn git_import_joins_where_each_join_kept_a_different_copy() {
7752
    // Batches of one: every merge renders apart from the state, where a
7753
    // file whose graph the state had built came out empty (#71).
7754
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7755
    hermetic();
7756
    if std::process::Command::new("git")
7757
        .arg("--version")
7758
        .output()
7759
        .is_err()
7760
    {
7761
        eprintln!("git not installed; skipping");
7762
        return;
7763
    }
7764
    let dir = tempfile::tempdir().unwrap();
7765
    let root = dir.path();
7766
    let g = root.join("src.git");
7767
    fs::create_dir_all(&g).unwrap();
7768
    let run = |args: &[&str]| {
7769
        std::process::Command::new("git")
7770
            .arg("-C")
7771
            .arg(&g)
7772
            .args([
7773
                "-c",
7774
                "user.name=Grace",
7775
                "-c",
7776
                "[email protected]",
7777
                "-c",
7778
                "commit.gpgsign=false",
7779
            ])
7780
            .args(args)
7781
            .output()
7782
            .unwrap()
7783
    };
7784
    let git = |args: &[&str]| -> String {
7785
        let out = run(args);
7786
        assert!(
7787
            out.status.success(),
7788
            "git {args:?}: {}",
7789
            String::from_utf8_lossy(&out.stderr)
7790
        );
7791
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7792
    };
7793
    git(&["init", "-q", "-b", "main"]);
7794
    write(
7795
        &g,
7796
        "gulpfile.js",
7797
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7798
    );
7799
    git(&["add", "."]);
7800
    git(&["commit", "-q", "-m", "A root"]);
7801
    write(
7802
        &g,
7803
        "gulpfile.js",
7804
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7805
    );
7806
    git(&["commit", "-q", "-am", "whitespace"]);
7807
    git(&["checkout", "-q", "--orphan", "fork"]);
7808
    git(&["rm", "-q", "-r", "--cached", "."]);
7809
    let _ = fs::remove_file(g.join("gulpfile.js"));
7810
    write(
7811
        &g,
7812
        "gulpfile.js",
7813
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7814
    );
7815
    git(&["add", "."]);
7816
    git(&["commit", "-q", "-m", "B root"]);
7817
    // Branch one joins B keeping main's copy; branch two keeps B's.
7818
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7819
        git(&["checkout", "-q", "-b", branch, "main"]);
7820
        let _ = run(&[
7821
            "merge",
7822
            "-q",
7823
            "--no-ff",
7824
            "--allow-unrelated-histories",
7825
            "-m",
7826
            "join",
7827
            "fork",
7828
        ]);
7829
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7830
        git(&["add", "gulpfile.js"]);
7831
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7832
    }
7833
    // Each branch then edits its copy.
7834
    git(&["checkout", "-q", "one"]);
7835
    write(
7836
        &g,
7837
        "gulpfile.js",
7838
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7839
    );
7840
    git(&["commit", "-q", "-am", "tslint on one"]);
7841
    git(&["checkout", "-q", "two"]);
7842
    write(
7843
        &g,
7844
        "gulpfile.js",
7845
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7846
    );
7847
    write(&g, "extra.txt", b"x\n");
7848
    write(&g, "more.txt", b"m\n");
7849
    git(&["add", "."]);
7850
    git(&["commit", "-q", "-am", "fmt on two"]);
7851
    // They meet: resolved by hand.
7852
    git(&["checkout", "-q", "one"]);
7853
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7854
    write(
7855
        &g,
7856
        "gulpfile.js",
7857
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7858
    );
7859
    git(&["add", "gulpfile.js"]);
7860
    git(&["commit", "-q", "-m", "merge two into one"]);
7861
7862
    let dest = root.join("dest");
7863
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7864
    repo.import_git(&g, "one").unwrap();
7865
    let v = repo.verify_git_import(&g, "one").unwrap();
7866
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7867
}
7868
7869
/// oxygen#68: on a store that is not this disk's directory, the operation
7870
/// head is the store's reference record, moved by compare-and-swap. Two
7871
/// handles recording from the same head both get through, merged; a swap
7872
/// from a stale version is refused; a second repository cannot start on a
7873
/// store that already holds one.
7874
#[test]
7875
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
7876
    use crate::strata::{MemoryStore, Store as _};
7877
    let backend = std::sync::Arc::new(MemoryStore::new());
7878
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
7879
    let dir = tempfile::tempdir().unwrap();
7880
    let a = Repo::init(dir.path()).unwrap();
7881
    assert!(
7882
        !dir.path().join(".oxy/ops/head").exists(),
7883
        "the head is not a file"
7884
    );
7885
    let (h0, op0) = a.head_op().unwrap();
7886
    let record = backend
7887
        .read_ref(HEAD_RECORD)
7888
        .unwrap()
7889
        .expect("the head is the store's record");
7890
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
7891
7892
    let b = Repo::open(dir.path()).unwrap();
7893
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
7894
    let mut va = op0.view.clone();
7895
    va.bookmarks.insert("from-a".into(), state);
7896
    let mut vb = op0.view.clone();
7897
    vb.bookmarks.insert("from-b".into(), state);
7898
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
7899
    assert_eq!(b.head_ref().unwrap(), rb);
7900
    // a recorded from h0 too: the head moved, so the two are merged.
7901
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
7902
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
7903
    assert_eq!(head, ra);
7904
    assert!(
7905
        op.command.ends_with("(merged with a concurrent operation)"),
7906
        "{}",
7907
        op.command
7908
    );
7909
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
7910
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
7911
7912
    // A swap from a version that is no longer current moves nothing.
7913
    let (h, v) = a.read_head().unwrap();
7914
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
7915
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
7916
    assert_eq!(a.head_ref().unwrap(), rb);
7917
7918
    let other = tempfile::tempdir().unwrap();
7919
    let err = Repo::init(other.path())
7920
        .err()
7921
        .expect("the store already holds a log")
7922
        .to_string();
7923
    assert!(
7924
        err.contains("already holds a repository's operation log"),
7925
        "{err}"
7926
    );
7927
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
7928
}
7929
7930
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
7931
/// objects and operation head there, with `.oxy/cache` in front: it works
7932
/// as one on disk does, reopens, and survives losing its cache.
7933
#[test]
7934
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
7935
    hermetic();
7936
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
7937
        return;
7938
    }
7939
    let dir = tempfile::tempdir().unwrap();
7940
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
7941
    let url = format!("dir://{}", bucket.display());
7942
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
7943
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
7944
    write(&root, "a.txt", b"one\n");
7945
    let h1 = repo.commit("First", &[]).unwrap();
7946
    write(&root, "a.txt", b"one\ntwo\n");
7947
    let h2 = repo.commit("Second", &[]).unwrap();
7948
    assert!(
7949
        !root.join(".oxy/ops/head").exists(),
7950
        "the head is in the store"
7951
    );
7952
    assert!(bucket.join("ops/head").is_file());
7953
    assert!(root.join(".oxy/cache").is_dir());
7954
    drop(repo);
7955
7956
    // Reopened, and again with no cache at all: everything comes from the store.
7957
    for drop_cache in [false, true] {
7958
        if drop_cache {
7959
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
7960
        }
7961
        let repo = Repo::open(&root).unwrap();
7962
        let log: Vec<String> = repo
7963
            .op_log()
7964
            .unwrap()
7965
            .into_iter()
7966
            .map(|(_, op)| op.command)
7967
            .collect();
7968
        assert!(log.len() >= 3, "{log:?}");
7969
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
7970
        let heads = repo
7971
            .store()
7972
            .get_state(&repo.view().unwrap().bookmarks["main"])
7973
            .unwrap()
7974
            .heads;
7975
        assert_eq!(heads, vec![h2]);
7976
        assert_eq!(
7977
            repo.load_state(&heads).unwrap().materialize().files.len(),
7978
            1
7979
        );
7980
    }
7981
7982
    // A second repository cannot start on the same store.
7983
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
7984
        .err()
7985
        .unwrap()
7986
        .to_string();
7987
    assert!(
7988
        err.contains("already holds a repository's operation log"),
7989
        "{err}"
7990
    );
7991
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
7992
        .err()
7993
        .unwrap()
7994
        .to_string();
7995
    assert!(err.contains("cannot open that kind of store"), "{err}");
7996
}
7997
7998
/// oxygen#75: the prompt's quick check agrees with status in a repository
7999
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8000
/// another state, clean again once that pin is committed. (It compared the
8001
/// subrepo's directory as if it were a file, so it was always dirty.)
8002
#[test]
8003
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8004
    hermetic();
8005
    let dir = tempfile::tempdir().unwrap();
8006
    let root = dir.path();
8007
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8008
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8009
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8010
        .unwrap()
8011
        .with_home(root.join("home"));
8012
    write(&root.join("lib"), "lib.txt", b"v1\n");
8013
    lib.commit("lib v1", &[]).unwrap();
8014
    assert!(lib.push("origin", false).unwrap()[0].ok);
8015
    let app_dir = root.join("app");
8016
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8017
    write(&app_dir, "main.txt", b"app\n");
8018
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8019
    app.commit("app with lib", &[]).unwrap();
8020
    // Out of the racy window, so the stat-only path decides.
8021
    std::thread::sleep(std::time::Duration::from_millis(2100));
8022
    let reopen = || Repo::open(&app_dir).unwrap();
8023
    assert_eq!(
8024
        reopen().quick_dirty().unwrap(),
8025
        Some(false),
8026
        "clean, as status says"
8027
    );
8028
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8029
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8030
    nested.commit("lib v2", &[]).unwrap();
8031
    assert_eq!(
8032
        reopen().quick_dirty().unwrap(),
8033
        Some(true),
8034
        "the subrepo moved"
8035
    );
8036
    reopen().commit("pin lib v2", &[]).unwrap();
8037
    std::thread::sleep(std::time::Duration::from_millis(2100));
8038
    assert_eq!(
8039
        reopen().quick_dirty().unwrap(),
8040
        Some(false),
8041
        "the new pin is committed"
8042
    );
8043
}
8044
8045
#[test]
8046
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8047
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8048
    hermetic();
8049
    let dir = tempfile::tempdir().unwrap();
8050
    let root = dir.path();
8051
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8052
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8053
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8054
        .unwrap()
8055
        .with_home(root.join("home"));
8056
    write(&root.join("lib"), "lib.txt", b"v1\n");
8057
    lib.commit("lib v1", &[]).unwrap();
8058
    assert!(lib.push("origin", false).unwrap()[0].ok);
8059
    let app_dir = root.join("app");
8060
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8061
    write(
8062
        &app_dir,
8063
        ".oxymodules",
8064
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8065
    );
8066
    let unpinned = app.unpinned_modules().unwrap();
8067
    assert_eq!(unpinned.len(), 1);
8068
    assert_eq!(unpinned[0].0, "libs/lib");
8069
    assert_eq!(unpinned[0].1.url, lib_url);
8070
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8071
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8072
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8073
}
8074
8075
#[test]
8076
fn the_bookmark_revset_function_names_only_bookmarks() {
8077
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8078
    hermetic();
8079
    let dir = tempfile::tempdir().unwrap();
8080
    let repo = Repo::init(dir.path()).unwrap();
8081
    write(dir.path(), "a.txt", b"a\n");
8082
    let a = repo.commit("A", &[]).unwrap();
8083
    write(dir.path(), "b.txt", b"b\n");
8084
    let b = repo.commit("B", &[]).unwrap();
8085
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8086
    heads.sort();
8087
    let mut want = repo.bookmark_heads().unwrap();
8088
    want.sort();
8089
    assert_eq!(heads, want);
8090
    assert!(heads.contains(&b));
8091
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8092
    // A change prefix is a symbol, not a bookmark.
8093
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8094
    assert!(repo.revset(&prefix).is_ok());
8095
    let e = repo
8096
        .revset(&format!("bookmark({prefix})"))
8097
        .unwrap_err()
8098
        .to_string();
8099
    assert!(e.contains("no such bookmark"), "{e}");
8100
}
8101
8102
#[test]
8103
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8104
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8105
    // pinning the subrepo, and the nested repository on disk at that pin.
8106
    hermetic();
8107
    let dir = tempfile::tempdir().unwrap();
8108
    let root = dir.path();
8109
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8110
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8111
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8112
        .unwrap()
8113
        .with_home(root.join("home"));
8114
    write(&root.join("lib"), "lib.txt", b"v1\n");
8115
    lib.commit("lib v1", &[]).unwrap();
8116
    assert!(lib.push("origin", false).unwrap()[0].ok);
8117
    let app_dir = root.join("app");
8118
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8119
    write(&app_dir, "main.txt", b"app\n");
8120
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8121
    // The stale state: registered in .oxymodules, never pinned.
8122
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8123
    app.commit("initial", &[]).unwrap();
8124
    let stale = app.bookmark_heads().unwrap();
8125
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8126
    app.commit("pin lib", &[]).unwrap();
8127
    let newer = app.bookmark_heads().unwrap();
8128
    app.checkout(&stale, false, "test").unwrap();
8129
    write(&app_dir, "notes.txt", b"mine\n");
8130
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8131
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8132
    assert!(app_dir.join("notes.txt").exists());
8133
}
8134
8135
#[test]
8136
fn a_bookmark_only_behind_its_remote_catches_up() {
8137
    // oxygen#74: switch takes the remote's state rather than a stale one.
8138
    hermetic();
8139
    let dir = tempfile::tempdir().unwrap();
8140
    let root = dir.path();
8141
    let _origin = Repo::init(&root.join("origin")).unwrap();
8142
    let url = root.join("origin").to_string_lossy().to_string();
8143
    let one = Repo::clone(&url, &root.join("one"))
8144
        .unwrap()
8145
        .with_home(root.join("home"));
8146
    write(&root.join("one"), "a.txt", b"a\n");
8147
    one.commit("A", &[]).unwrap();
8148
    assert!(one.push("origin", false).unwrap()[0].ok);
8149
    let two = Repo::clone(&url, &root.join("two"))
8150
        .unwrap()
8151
        .with_home(root.join("home"));
8152
    write(&root.join("two"), "b.txt", b"b\n");
8153
    two.commit("B", &[]).unwrap();
8154
    assert!(two.push("origin", false).unwrap()[0].ok);
8155
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8156
    one.fetch("origin").unwrap();
8157
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8158
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8159
    // Local work the remote lacks: left alone.
8160
    write(&root.join("one"), "c.txt", b"c\n");
8161
    one.commit("C", &[]).unwrap();
8162
    write(&root.join("two"), "d.txt", b"d\n");
8163
    two.commit("D", &[]).unwrap();
8164
    assert!(two.push("origin", false).unwrap()[0].ok);
8165
    one.fetch("origin").unwrap();
8166
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8167
}
8168
8169
#[test]
8170
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8171
    // oxygen#83: remotes earth and gcs, origin removed.
8172
    hermetic();
8173
    let dir = tempfile::tempdir().unwrap();
8174
    let root = dir.path();
8175
    let _up = Repo::init(&root.join("up")).unwrap();
8176
    let url = root.join("up").to_string_lossy().to_string();
8177
    let other = Repo::clone(&url, &root.join("other"))
8178
        .unwrap()
8179
        .with_home(root.join("home"));
8180
    write(&root.join("other"), "a.txt", b"a\n");
8181
    other.commit("a", &[]).unwrap();
8182
    assert!(other.push("origin", false).unwrap()[0].ok);
8183
    let mut one = Repo::clone(&url, &root.join("one"))
8184
        .unwrap()
8185
        .with_home(root.join("home"));
8186
    one.config.set("remote.earth.url", &url).unwrap();
8187
    one.config.set("remote.gcs.url", &url).unwrap();
8188
    one.config.set("remote.origin.url", "").unwrap();
8189
    one.save_config().unwrap();
8190
    write(&root.join("other"), "b.txt", b"b\n");
8191
    other.commit("b", &[]).unwrap();
8192
    assert!(other.push("origin", false).unwrap()[0].ok);
8193
    one.fetch("earth").unwrap();
8194
    let b = one
8195
        .bookmarks()
8196
        .unwrap()
8197
        .into_iter()
8198
        .find(|b| b.name == "main")
8199
        .unwrap();
8200
    assert_eq!(
8201
        (b.remote.as_deref(), b.behind),
8202
        (Some("earth"), Some(1)),
8203
        "a stale origin copy is not used"
8204
    );
8205
    assert_eq!(
8206
        one.default_remote(),
8207
        "origin",
8208
        "no default chosen among several"
8209
    );
8210
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8211
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8212
    one.config.set("core.remote", "earth").unwrap();
8213
    assert_eq!(one.default_remote(), "earth");
8214
}
8215
8216
#[test]
8217
fn a_missing_author_identity_says_how_to_fix_it() {
8218
    // oxygen#82: an agent home's author.key naming an identity the
8219
    // repository does not hold.
8220
    hermetic();
8221
    let dir = tempfile::tempdir().unwrap();
8222
    let mut repo = Repo::init(dir.path()).unwrap();
8223
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8224
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8225
    let e = repo.identity(&missing).unwrap_err().to_string();
8226
    assert!(
8227
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8228
        "{e}"
8229
    );
8230
    assert!(e.contains("this repository's config"), "{e}");
8231
}
8232
8233
#[test]
8234
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8235
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8236
    // the working copy, a pull with nothing new left it there, and status
8237
    // said "clean".
8238
    hermetic();
8239
    let dir = tempfile::tempdir().unwrap();
8240
    let root = dir.path();
8241
    let _up = Repo::init(&root.join("up")).unwrap();
8242
    let url = root.join("up").to_string_lossy().to_string();
8243
    let other = Repo::clone(&url, &root.join("other"))
8244
        .unwrap()
8245
        .with_home(root.join("home"));
8246
    write(&root.join("other"), "a.txt", b"a\n");
8247
    other.commit("a", &[]).unwrap();
8248
    assert!(other.push("origin", false).unwrap()[0].ok);
8249
    let one = Repo::clone(&url, &root.join("one"))
8250
        .unwrap()
8251
        .with_home(root.join("home"));
8252
    write(&root.join("other"), "b.txt", b"b\n");
8253
    other.commit("b", &[]).unwrap();
8254
    assert!(other.push("origin", false).unwrap()[0].ok);
8255
    one.fetch("origin").unwrap();
8256
    // The bookmark moves; the working copy does not.
8257
    let theirs = one.resolve_heads("origin/main").unwrap();
8258
    one.bookmark_set("main", &theirs).unwrap();
8259
    assert!(!root.join("one/b.txt").exists());
8260
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8261
    let r = one.pull("origin").unwrap();
8262
    assert!(
8263
        !r.changed && r.checked_out,
8264
        "nothing new, but the working copy caught up"
8265
    );
8266
    assert!(root.join("one/b.txt").exists());
8267
    assert_eq!(one.working_copy_behind().unwrap(), None);
8268
}
8269
8270
#[test]
8271
fn touched_nodes_cache_answers_as_the_changes_do() {
8272
    hermetic();
8273
    let dir = tempfile::tempdir().unwrap();
8274
    let repo = Repo::init(dir.path()).unwrap();
8275
    write(dir.path(), "a.txt", b"one\n");
8276
    write(dir.path(), "b.txt", b"x\n");
8277
    repo.snapshot("t").unwrap();
8278
    let c1 = repo.commit("first", &[]).unwrap();
8279
    write(dir.path(), "b.txt", b"y\n");
8280
    repo.snapshot("t").unwrap();
8281
    repo.commit("b only", &[]).unwrap();
8282
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8283
    write(dir.path(), "c.txt", b"one\ntwo\n");
8284
    repo.snapshot("t").unwrap();
8285
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8286
    // Uncommitted work, so the working copy touches a file too.
8287
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8288
    repo.snapshot("t").unwrap();
8289
8290
    let path = dir.path().join(".oxy/index/touched");
8291
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8292
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8293
    assert!(path.exists(), "the first query writes the cache");
8294
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8295
    assert_eq!(cold, warm, "the cache answers as the changes do");
8296
    let (wc, _) = repo.working_copy().unwrap();
8297
    assert_eq!(
8298
        cold,
8299
        vec![wc, c3, c1],
8300
        "renames followed, the working copy included"
8301
    );
8302
8303
    // Working-copy changes are not kept: they are replaced by every snapshot.
8304
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8305
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8306
    assert!(cached.contains(&c1) && cached.contains(&c3));
8307
8308
    // A damaged cache is ignored, not trusted.
8309
    let mut bytes = fs::read(&path).unwrap();
8310
    let last = bytes.len() - 40;
8311
    bytes[last] ^= 1;
8312
    fs::write(&path, &bytes).unwrap();
8313
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8314
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8315
    assert_eq!(hashes(touches), vec![c3, c1]);
8316
}
8317
8318
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8319
/// file back where it was leave two placements at one place, which the
8320
/// tree shows as one file. Removing it, and then its directory, retires
8321
/// both, so no copy is left under a directory that is gone.
8322
#[test]
8323
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8324
    hermetic();
8325
    if std::process::Command::new("git")
8326
        .arg("--version")
8327
        .output()
8328
        .is_err()
8329
    {
8330
        eprintln!("git not installed; skipping");
8331
        return;
8332
    }
8333
    let dir = tempfile::tempdir().unwrap();
8334
    let root = dir.path();
8335
    let g = root.join("src.git");
8336
    fs::create_dir_all(&g).unwrap();
8337
    let git = |args: &[&str]| {
8338
        let out = std::process::Command::new("git")
8339
            .arg("-C")
8340
            .arg(&g)
8341
            .args([
8342
                "-c",
8343
                "user.name=Grace",
8344
                "-c",
8345
                "[email protected]",
8346
                "-c",
8347
                "commit.gpgsign=false",
8348
            ])
8349
            .args(args)
8350
            .output()
8351
            .unwrap();
8352
        assert!(
8353
            out.status.success(),
8354
            "git {args:?}: {}",
8355
            String::from_utf8_lossy(&out.stderr)
8356
        );
8357
    };
8358
    git(&["init", "-q", "-b", "main"]);
8359
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8360
    write(&g, "keep.txt", b"k\n");
8361
    git(&["add", "."]);
8362
    git(&["commit", "-qm", "base"]);
8363
    fs::create_dir_all(g.join("d/sub")).unwrap();
8364
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8365
    git(&["commit", "-qm", "into sub"]);
8366
    git(&["checkout", "-qb", "side"]);
8367
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8368
    git(&["commit", "-qm", "back, on side"]);
8369
    git(&["checkout", "-q", "main"]);
8370
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8371
    git(&["commit", "-qm", "back, on main"]);
8372
    git(&["merge", "-q", "--no-edit", "side"]);
8373
    git(&["rm", "-rq", "d"]);
8374
    git(&["commit", "-qm", "d goes"]);
8375
8376
    let repo = Repo::init(&root.join("o")).unwrap();
8377
    repo.import_git(&g, "main").unwrap();
8378
    let v = repo.verify_git_import(&g, "main").unwrap();
8379
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8380
    let st = repo
8381
        .load_state_history(&repo.bookmark_heads().unwrap())
8382
        .unwrap();
8383
    let view = st.tree().view();
8384
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8385
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8386
}
8387
8388
/// oxygen#94: a state index's file histories are read, and checked by
8389
/// their own hashes, only when a file is built. One found damaged is an
8390
/// error that says so, the index is removed, and the next read rebuilds it.
8391
#[test]
8392
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8393
    hermetic();
8394
    let dir = tempfile::tempdir().unwrap();
8395
    let repo = Repo::init(dir.path()).unwrap();
8396
    for i in 0..6 {
8397
        write(
8398
            dir.path(),
8399
            &format!("f{i}.txt"),
8400
            format!("one {i}\n").as_bytes(),
8401
        );
8402
    }
8403
    repo.snapshot("t").unwrap();
8404
    repo.commit("first", &[]).unwrap();
8405
    for i in 0..6 {
8406
        write(
8407
            dir.path(),
8408
            &format!("f{i}.txt"),
8409
            format!("one {i}\ntwo\n").as_bytes(),
8410
        );
8411
    }
8412
    repo.snapshot("t").unwrap();
8413
    repo.commit("second", &[]).unwrap();
8414
    let want: Vec<Vec<u8>> = (0..6)
8415
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8416
        .collect();
8417
    // The index of the working copy's base, holding every file's history
8418
    // (a few changes behind, an index is replayed onto, not rewritten).
8419
    let (_, wc) = repo.working_copy().unwrap();
8420
    let base = repo.load_state_history(&wc.deps).unwrap();
8421
    repo.write_state_index(&wc.deps, &base);
8422
    for (i, w) in want.iter().enumerate() {
8423
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8424
    }
8425
    let index = repo.state_indexes();
8426
    assert!(!index.is_empty(), "a state index was written");
8427
    // The histories are last in the file: damage the last of them.
8428
    let mut bytes = fs::read(&index[0]).unwrap();
8429
    let last = bytes.len() - 1;
8430
    bytes[last] ^= 0x40;
8431
    fs::write(&index[0], &bytes).unwrap();
8432
8433
    let reads: Vec<_> = (0..6)
8434
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8435
        .collect();
8436
    let damaged: Vec<String> = reads
8437
        .iter()
8438
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8439
        .collect();
8440
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8441
    assert!(
8442
        damaged[0].contains("state index was damaged")
8443
            && damaged[0].contains("run the command again"),
8444
        "{}",
8445
        damaged[0]
8446
    );
8447
    // Every file reads right again, from an index rebuilt from history.
8448
    for (i, w) in want.iter().enumerate() {
8449
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8450
    }
8451
}
8452
8453
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8454
/// objects alone and in dependency order, and the last moves the bookmark.
8455
/// The remote ends with every change and the same state, and says how each
8456
/// part went.
8457
#[test]
8458
fn a_long_push_goes_in_parts() {
8459
    hermetic();
8460
    let dir = tempfile::tempdir().unwrap();
8461
    let root = dir.path();
8462
    let origin = root.join("origin");
8463
    Repo::init_bare_unbound(&origin).unwrap();
8464
    let main = root.join("main");
8465
    let mut repo = Repo::init(&main).unwrap();
8466
    repo.config
8467
        .set("remote.origin.url", &origin.to_string_lossy())
8468
        .unwrap();
8469
    // One byte: every change is a part of its own.
8470
    repo.config.set("push.batch-bytes", "1").unwrap();
8471
    repo.save_config().unwrap();
8472
    for i in 0..6 {
8473
        write(
8474
            &main,
8475
            &format!("f{i}.txt"),
8476
            format!("file {i}\n").as_bytes(),
8477
        );
8478
        repo.commit(&format!("c{i}"), &[]).unwrap();
8479
    }
8480
    let mut parts = Vec::new();
8481
    let results = repo
8482
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8483
        .unwrap();
8484
    assert!(
8485
        results.iter().any(|r| r.ok && r.name == "main"),
8486
        "{results:?}"
8487
    );
8488
    assert_eq!(parts.len(), 6, "{parts:?}");
8489
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8490
8491
    let remote = Repo::open(&origin).unwrap();
8492
    let heads = repo.bookmark_heads().unwrap();
8493
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8494
    assert_eq!(
8495
        remote.log_state(&heads).unwrap().len(),
8496
        repo.log_state(&heads).unwrap().len()
8497
    );
8498
    // A push of objects alone reports how it went, as `objects`.
8499
    let got = remote
8500
        .receive_push(Bundle::default(), vec![], None, vec![])
8501
        .unwrap();
8502
    assert_eq!(got.len(), 1);
8503
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8504
}
8505
8506
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8507
/// own commits (Git author email = its email, any case) with its key, and
8508
/// leaves anyone else's with the zero key; the history verifies as before.
8509
#[test]
8510
fn git_import_claims_your_own_commits() {
8511
    hermetic();
8512
    if std::process::Command::new("git")
8513
        .arg("--version")
8514
        .output()
8515
        .is_err()
8516
    {
8517
        eprintln!("git not installed; skipping");
8518
        return;
8519
    }
8520
    let dir = tempfile::tempdir().unwrap();
8521
    let root = dir.path();
8522
    let g = root.join("src.git");
8523
    fs::create_dir_all(&g).unwrap();
8524
    let git = |who: &str, args: &[&str]| {
8525
        let (name, email) = who.split_once(' ').unwrap();
8526
        let out = std::process::Command::new("git")
8527
            .arg("-C")
8528
            .arg(&g)
8529
            .args([
8530
                "-c",
8531
                &format!("user.name={name}"),
8532
                "-c",
8533
                &format!("user.email={email}"),
8534
                "-c",
8535
                "commit.gpgsign=false",
8536
            ])
8537
            .args(args)
8538
            .output()
8539
            .unwrap();
8540
        assert!(
8541
            out.status.success(),
8542
            "git {args:?}: {}",
8543
            String::from_utf8_lossy(&out.stderr)
8544
        );
8545
    };
8546
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8547
    write(&g, "a.txt", b"a\n");
8548
    git("Grace [email protected]", &["add", "."]);
8549
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8550
    write(&g, "b.txt", b"b\n");
8551
    git("Ada [email protected]", &["add", "."]);
8552
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8553
8554
    let mut repo = Repo::init(&root.join("o")).unwrap();
8555
    let (key, _) = repo
8556
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8557
        .unwrap();
8558
    repo.config.set("git.claim", "true").unwrap();
8559
    repo.save_config().unwrap();
8560
    let repo = Repo::open(&root.join("o")).unwrap();
8561
    repo.import_git(&g, "main").unwrap();
8562
    let v = repo.verify_git_import(&g, "main").unwrap();
8563
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8564
    let heads = repo.bookmark_heads().unwrap();
8565
    let by_message: std::collections::HashMap<String, KeyId> = repo
8566
        .log_state(&heads)
8567
        .unwrap()
8568
        .into_iter()
8569
        .map(|e| {
8570
            (
8571
                e.change.message.lines().next().unwrap_or("").to_string(),
8572
                e.change.author,
8573
            )
8574
        })
8575
        .collect();
8576
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8577
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8578
}
8579
8580
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8581
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8582
#[test]
8583
fn removing_a_remote_leaves_nothing_of_it() {
8584
    hermetic();
8585
    let dir = tempfile::tempdir().unwrap();
8586
    let origin = dir.path().join("origin");
8587
    Repo::init_bare_unbound(&origin).unwrap();
8588
    let main = dir.path().join("main");
8589
    let mut repo = Repo::init(&main).unwrap();
8590
    repo.config
8591
        .set("remote.origin.url", &origin.to_string_lossy())
8592
        .unwrap();
8593
    repo.config
8594
        .set("remote.origin.token", "secret-ish")
8595
        .unwrap();
8596
    repo.config
8597
        .set("remote.keep.url", &origin.to_string_lossy())
8598
        .unwrap();
8599
    repo.save_config().unwrap();
8600
    write(&main, "a.txt", b"a\n");
8601
    repo.commit("a", &[]).unwrap();
8602
    assert!(repo.push("origin", false).unwrap()[0].ok);
8603
    assert!(
8604
        repo.view().unwrap().remotes.contains_key("origin"),
8605
        "a tracking bookmark"
8606
    );
8607
8608
    repo.remove_remote("origin").unwrap();
8609
    let again = Repo::open(&main).unwrap();
8610
    assert!(
8611
        !again
8612
            .config
8613
            .repo_layer()
8614
            .keys()
8615
            .any(|k| k.starts_with("remote.origin.")),
8616
        "{:?}",
8617
        again.config.repo_layer()
8618
    );
8619
    assert!(!again.config.remotes.contains_key("origin"));
8620
    assert!(
8621
        !again.view().unwrap().remotes.contains_key("origin"),
8622
        "its tracking bookmarks go"
8623
    );
8624
    assert!(
8625
        again.config.remotes.contains_key("keep"),
8626
        "another remote stays"
8627
    );
8628
    let mut again = again;
8629
    assert!(
8630
        again.remove_remote("origin").is_err(),
8631
        "a second removal is refused"
8632
    );
8633
}
8634
8635
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
8636
/// unreachable from history, so gc prunes it, unless the host names it:
8637
/// then it and its chunks stay, and it reads back whole.
8638
#[test]
8639
fn gc_keeps_the_blobs_a_host_names() {
8640
    hermetic();
8641
    let dir = tempfile::tempdir().unwrap();
8642
    let repo = Repo::init(dir.path()).unwrap();
8643
    write(dir.path(), "a.txt", b"a\n");
8644
    repo.commit("a", &[]).unwrap();
8645
    // Large enough to be several chunks.
8646
    let body: Vec<u8> = (0..400_000u32)
8647
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
8648
        .collect();
8649
    let kept = repo.store_blob(&body).unwrap();
8650
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
8651
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
8652
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
8653
    assert!(!repo.store().has(&lost), "not named: pruned");
8654
    repo.gc(true).unwrap();
8655
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
8656
}
8657
8658
/// oxygen#99: undo in one workspace undoes that workspace's last command,
8659
/// never another workspace's, says what it undid, and goes further back
8660
/// when run again.
8661
#[test]
8662
fn undo_is_scoped_to_its_workspace() {
8663
    hermetic();
8664
    let dir = tempfile::tempdir().unwrap();
8665
    let root = dir.path().join("main");
8666
    let a = Repo::init(&root).unwrap();
8667
    write(&root, "base.txt", b"base\n");
8668
    let base = a.commit("base", &[]).unwrap();
8669
    a.bookmark_create("feature", None).unwrap();
8670
    let ws_dir = dir.path().join("ws");
8671
    let heads = a.resolve_heads("feature").unwrap();
8672
    let b = a
8673
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
8674
        .unwrap();
8675
8676
    // A commits on main, then B commits on feature: B's is the newest.
8677
    write(&root, "a.txt", b"a\n");
8678
    let ca = a.commit("from a", &[]).unwrap();
8679
    write(&ws_dir, "b.txt", b"b\n");
8680
    let cb = b.commit("from b", &[]).unwrap();
8681
8682
    // A's undo undoes A's commit and leaves B's.
8683
    let u = a.undo().unwrap();
8684
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8685
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
8686
    assert!(!u.changes.is_empty());
8687
    let view = a.view().unwrap();
8688
    // (Independent changes commute, so a bookmark's heads may hold base too.)
8689
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
8690
    assert!(
8691
        a.heads_of(&view, "feature").unwrap().contains(&cb),
8692
        "B's commit stands"
8693
    );
8694
    assert!(
8695
        a.store().get_change(&ca).is_ok(),
8696
        "the change itself is still in the store"
8697
    );
8698
    // A's working copy was clean, so its files followed; B's are untouched.
8699
    assert!(!root.join("a.txt").exists());
8700
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
8701
    assert!(ws_dir.join("b.txt").exists());
8702
8703
    // B's undo still finds B's own commit, under A's undo.
8704
    let u = b.undo().unwrap();
8705
    assert_eq!(u.command, "oxy commit -m \"from b\"");
8706
    assert!(!b
8707
        .heads_of(&b.view().unwrap(), "feature")
8708
        .unwrap()
8709
        .contains(&cb));
8710
    assert_eq!(
8711
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
8712
        vec![base],
8713
        "A's undo stands"
8714
    );
8715
8716
    // A's next undo goes past the commit it already undid, to adding B's
8717
    // workspace: refused, since B has worked there since.
8718
    let e = a.undo().unwrap_err().to_string();
8719
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
8720
}
8721
8722
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
8723
/// own commit's head, and the other workspace's head stays.
8724
#[test]
8725
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
8726
    hermetic();
8727
    let dir = tempfile::tempdir().unwrap();
8728
    let root = dir.path().join("main");
8729
    let a = Repo::init(&root).unwrap();
8730
    write(&root, "base.txt", b"base\n");
8731
    a.commit("base", &[]).unwrap();
8732
    let ws_dir = dir.path().join("ws");
8733
    let b = a.workspace_add(&ws_dir, None).unwrap();
8734
    write(&root, "a.txt", b"a\n");
8735
    let ca = a.commit("from a", &[]).unwrap();
8736
    write(&ws_dir, "b.txt", b"b\n");
8737
    let cb = b.commit("from b", &[]).unwrap();
8738
    let u = a.undo().unwrap();
8739
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8740
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
8741
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
8742
}
8743
8744
/// oxygen#99: an undo that would also take back what another workspace
8745
/// did since to the same bookmark is refused, naming it.
8746
#[test]
8747
fn undo_refuses_to_take_back_another_workspaces_work() {
8748
    hermetic();
8749
    let dir = tempfile::tempdir().unwrap();
8750
    let root = dir.path().join("main");
8751
    let a = Repo::init(&root).unwrap();
8752
    write(&root, "base.txt", b"base\n");
8753
    a.commit("base", &[]).unwrap();
8754
    let ws_dir = dir.path().join("ws");
8755
    let b = a.workspace_add(&ws_dir, None).unwrap();
8756
    // Both on main: A commits, then B builds on it, editing A's file.
8757
    write(&root, "a.txt", b"a\n");
8758
    a.commit("from a", &[]).unwrap();
8759
    let heads = b.resolve_heads("main").unwrap();
8760
    b.checkout(&heads, false, "oxy checkout").unwrap();
8761
    write(&ws_dir, "a.txt", b"a, then b\n");
8762
    b.commit("from b", &[]).unwrap();
8763
    let e = a.undo().unwrap_err().to_string();
8764
    assert!(
8765
        e.contains("bookmark main") && e.contains("builds on"),
8766
        "{e}"
8767
    );
8768
    assert!(e.contains("oxy op restore"), "{e}");
8769
}
8770
8771
/// oxygen#99: undoing a commit that was already pushed says so: the remote
8772
/// still has it.
8773
#[test]
8774
fn undo_says_when_the_commit_was_pushed() {
8775
    hermetic();
8776
    let dir = tempfile::tempdir().unwrap();
8777
    let root = dir.path();
8778
    Repo::init(&root.join("origin")).unwrap();
8779
    let url = root.join("origin").to_string_lossy().to_string();
8780
    let repo = Repo::clone(&url, &root.join("work"))
8781
        .unwrap()
8782
        .with_home(root.join("home"));
8783
    write(&root.join("work"), "a.txt", b"a\n");
8784
    repo.commit("a", &[]).unwrap();
8785
    assert!(repo.push("origin", false).unwrap()[0].ok);
8786
    // The push itself is passed over: the remote keeps what it was sent.
8787
    let u = repo.undo().unwrap();
8788
    assert_eq!(u.command, "oxy commit -m \"a\"");
8789
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
8790
}
8791
8792
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
8793
/// out of the snapshot and named; tracked files and files already in the
8794
/// working copy are not.
8795
#[test]
8796
fn large_new_files_are_left_out_of_snapshots() {
8797
    hermetic();
8798
    let dir = tempfile::tempdir().unwrap();
8799
    let root = dir.path();
8800
    let mut repo = Repo::init(root).unwrap();
8801
    repo.config.max_new_file = 1024;
8802
    write(root, "small.txt", b"small\n");
8803
    write(root, "big.bin", &vec![0u8; 4096]);
8804
    let s = repo.snapshot("oxy status").unwrap();
8805
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8806
    assert_eq!(paths, ["small.txt"]);
8807
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
8808
    repo.commit("small", &[]).unwrap();
8809
8810
    // A tracked file may grow past the limit.
8811
    write(root, "small.txt", &vec![b'x'; 4096]);
8812
    let s = repo.snapshot("oxy status").unwrap();
8813
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
8814
    // With no limit the big file is taken in, and stays once it is.
8815
    repo.config.max_new_file = 0;
8816
    let s = repo.snapshot("oxy status").unwrap();
8817
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
8818
    repo.config.max_new_file = 1024;
8819
    let s = repo.snapshot("oxy status").unwrap();
8820
    assert!(
8821
        s.statuses.iter().any(|p| p.path == "big.bin"),
8822
        "already in the working copy"
8823
    );
8824
    assert!(repo.skipped_large().is_empty());
8825
}
8826
8827
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
8828
/// snapshots expire, and kept while they have not.
8829
#[test]
8830
fn gc_prunes_what_only_expired_snapshots_held() {
8831
    hermetic();
8832
    let dir = tempfile::tempdir().unwrap();
8833
    let root = dir.path();
8834
    let mut repo = Repo::init(root).unwrap();
8835
    repo.config.gc_grace_days = 0;
8836
    write(root, "a.txt", b"a\n");
8837
    repo.commit("a", &[]).unwrap();
8838
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
8839
    write(root, "image.tar", &image);
8840
    repo.snapshot("oxy status").unwrap();
8841
    std::fs::remove_file(root.join("image.tar")).unwrap();
8842
    repo.snapshot("oxy status").unwrap();
8843
    let blob = Repo::blob_ref(&image);
8844
    assert!(repo.store().has(&blob));
8845
    repo.gc(true).unwrap();
8846
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
8847
    repo.config.snapshot_retention_days = 0;
8848
    repo.gc(true).unwrap();
8849
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
8850
    assert_eq!(
8851
        repo.file_at("a.txt", None).unwrap(),
8852
        b"a\n",
8853
        "committed files stay"
8854
    );
8855
}
8856
8857
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
8858
/// already has is no conflict: the switch goes through, nothing is lost,
8859
/// and other carried work still comes along.
8860
#[test]
8861
fn carrying_work_the_target_already_has_is_no_conflict() {
8862
    hermetic();
8863
    let dir = tempfile::tempdir().unwrap();
8864
    let root = dir.path();
8865
    let mut repo = Repo::init(root).unwrap();
8866
    write(root, "a.txt", b"one\n");
8867
    write(root, "b.txt", b"b\n");
8868
    repo.commit("one", &[]).unwrap();
8869
    repo.bookmark_create("landed", None).unwrap();
8870
    // On landed, a.txt becomes "two" (as a proposal landing would).
8871
    repo.bookmark_switch("landed", false).unwrap();
8872
    write(root, "a.txt", b"two\n");
8873
    repo.commit("two", &[]).unwrap();
8874
    repo.bookmark_switch("main", false).unwrap();
8875
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
8876
    // The same edit, uncommitted, on main; and another edit besides.
8877
    write(root, "a.txt", b"two\n");
8878
    write(root, "b.txt", b"b, edited\n");
8879
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
8880
    assert_eq!(
8881
        carried,
8882
        vec!["b.txt".to_string()],
8883
        "only the work landed lacks is carried"
8884
    );
8885
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
8886
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
8887
    let s = repo.snapshot("oxy status").unwrap();
8888
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8889
    assert_eq!(paths, ["b.txt"]);
8890
8891
    // A real difference is still refused.
8892
    repo.bookmark_switch("main", true).unwrap();
8893
    write(root, "a.txt", b"three\n");
8894
    let e = repo
8895
        .bookmark_switch_carry("landed")
8896
        .unwrap_err()
8897
        .to_string();
8898
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
8899
}
8900
8901
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
8902
/// resolves, so JSON output feeds back into commands.
8903
#[test]
8904
fn a_full_hash_resolves_without_its_hash_sign() {
8905
    hermetic();
8906
    let dir = tempfile::tempdir().unwrap();
8907
    let root = dir.path();
8908
    let repo = Repo::init(root).unwrap();
8909
    write(root, "a.txt", b"a\n");
8910
    let h = repo.commit("a", &[]).unwrap();
8911
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
8912
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
8913
    assert!(repo
8914
        .resolve_change(&"0".repeat(64))
8915
        .unwrap_err()
8916
        .to_string()
8917
        .contains("no change matches"));
8918
}