OXYGENHUB
# f2f91ceb0e9f oxygen / crates / oxy-core / src / repo / tests.rs
318.1 KiB · Rust · last changed A hosted change can move a subrepo's pin 23 days ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
use crate::protocol::SignedPolicy;
5
use crate::repo::{BisectStep, Selection};
6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
137
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
138
    assert!(d.contains("-fn main() {}"), "{d}");
139
140
    // Resolution by prefix.
141
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
142
    assert_eq!(
143
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
144
        h1
145
    );
146
    assert!(repo.resolve_change("zzzz").is_err());
147
148
    // Undo the commit: bookmark and working copy go back.
149
    repo.undo().unwrap();
150
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
151
    let s = repo.snapshot("oxy status").unwrap();
152
    assert!(
153
        !s.changed,
154
        "files on disk still match the pre-commit working copy"
155
    );
156
    assert_eq!(s.statuses.len(), 3);
157
}
158
159
/// Make `main` conflicted: two commits on the same base that edit the same line.
160
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
161
    let dir = tempfile::tempdir().unwrap();
162
    let root = dir.path();
163
    let repo = Repo::init(root).unwrap();
164
    write(root, "f.txt", b"a\nb\nc\n");
165
    let h1 = repo.commit("base", &[]).unwrap();
166
    write(root, "f.txt", b"a\nB\nc\n");
167
    let h2 = repo.commit("upper", &[]).unwrap();
168
    repo.checkout(&[h1], false, "checkout").unwrap();
169
    write(root, "f.txt", b"a\nX\nc\n");
170
    let h3 = repo.commit("ex", &[]).unwrap();
171
    (dir, repo, h1, h2, h3)
172
}
173
174
#[test]
175
fn concurrent_edits_conflict_and_can_be_resolved() {
176
    hermetic();
177
    let (dir, repo, h1, h2, h3) = conflicted_repo();
178
    let root = dir.path();
179
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
180
    assert_eq!(heads, [h2, h3].into_iter().collect());
181
    let st = repo.load_state(&[h2, h3]).unwrap();
182
    assert!(st.materialize().is_conflicted());
183
184
    // Checking out main writes markers.
185
    let r = repo
186
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
187
        .unwrap();
188
    assert!(r.conflicted);
189
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
190
    assert!(
191
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
192
        "{marked}"
193
    );
194
    assert!(
195
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
196
        "{marked}"
197
    );
198
    assert!(has_conflict_markers(marked.as_bytes()));
199
    // Untouched markers: clean working copy; commit has nothing to do.
200
    let s = repo.snapshot("status").unwrap();
201
    assert!(s.statuses.is_empty());
202
    assert!(!s.resolves);
203
204
    // Partially edited file that still has markers cannot be committed.
205
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
206
    let s = repo.snapshot("status").unwrap();
207
    assert_eq!(
208
        statuses(&s),
209
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
210
    );
211
    assert!(repo.commit("no", &[]).is_err());
212
213
    // Resolve by keeping one side and adding a line elsewhere.
214
    write(root, "f.txt", b"a\nX\nc\nd\n");
215
    let s = repo.snapshot("status").unwrap();
216
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
217
    assert!(s.resolves);
218
    let h4 = repo.commit("resolve", &[]).unwrap();
219
    let c4 = repo.store().get_change(&h4).unwrap();
220
    assert_eq!(c4.kind, ChangeKind::Resolution);
221
    let mut want = vec![h1, h2, h3];
222
    want.sort();
223
    assert_eq!(
224
        c4.deps, want,
225
        "a resolution depends on exactly the contributors and what it references"
226
    );
227
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
228
    let snap = repo.load_state(&[h4]).unwrap().materialize();
229
    assert!(!snap.is_conflicted());
230
    assert!(
231
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
232
    );
233
    assert!(!repo.snapshot("status").unwrap().changed);
234
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
235
    // whatever order the changes arrive in.
236
    let mut st = State::new();
237
    for h in [h4, h3, h1, h2] {
238
        st.add_unchecked(repo.store().get_change(&h).unwrap());
239
    }
240
    st.validate().unwrap();
241
    assert!(
242
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
243
    );
244
}
245
246
#[test]
247
fn resolution_may_keep_both_sides_or_neither() {
248
    hermetic();
249
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
250
    let root = dir.path();
251
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
252
        .unwrap();
253
    // Keep both sides in a chosen order.
254
    write(root, "f.txt", b"a\nX\nB\nc\n");
255
    let h = repo.commit("both", &[]).unwrap();
256
    let snap = repo.load_state(&[h]).unwrap().materialize();
257
    assert!(!snap.is_conflicted());
258
    assert!(
259
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
260
    );
261
    // Undo and instead drop the whole region.
262
    repo.undo().unwrap();
263
    write(root, "f.txt", b"a\nc\n");
264
    let h = repo.commit("neither", &[]).unwrap();
265
    let snap = repo.load_state(&[h]).unwrap().materialize();
266
    assert!(!snap.is_conflicted());
267
    assert!(
268
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
269
    );
270
}
271
272
#[test]
273
fn name_conflict_resolved_by_removing_a_candidate() {
274
    hermetic();
275
    let dir = tempfile::tempdir().unwrap();
276
    let root = dir.path();
277
    let repo = Repo::init(root).unwrap();
278
    write(root, "keep.txt", b"k\n");
279
    let h1 = repo.commit("base", &[]).unwrap();
280
    write(root, "new.txt", b"one\n");
281
    repo.commit("one", &[]).unwrap();
282
    repo.checkout(&[h1], false, "checkout").unwrap();
283
    write(root, "new.txt", b"two\n");
284
    repo.commit("two", &[]).unwrap();
285
    let r = repo
286
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
287
        .unwrap();
288
    assert!(r.conflicted);
289
    assert!(
290
        root.join("new.txt.oxy-conflict-1").exists()
291
            && root.join("new.txt.oxy-conflict-2").exists()
292
    );
293
    assert!(!root.join("new.txt").exists());
294
    // Candidate numbering follows change-hash order, so pick by content:
295
    // keep the "two" candidate under the real name and drop the other.
296
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
297
        (1, 2)
298
    } else {
299
        (2, 1)
300
    };
301
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
302
    fs::rename(
303
        root.join(format!("new.txt.oxy-conflict-{keep}")),
304
        root.join("new.txt"),
305
    )
306
    .unwrap();
307
    let h = repo.commit("pick two", &[]).unwrap();
308
    assert_eq!(
309
        repo.store().get_change(&h).unwrap().kind,
310
        ChangeKind::Resolution
311
    );
312
    // The resolution does not touch keep.txt, so it does not depend on h1;
313
    // the bookmark keeps both as heads and their union is the state.
314
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
315
    assert_eq!(heads, [h1, h].into_iter().collect());
316
    let snap = repo
317
        .load_state(&repo.bookmark_heads().unwrap())
318
        .unwrap()
319
        .materialize();
320
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
321
    assert_eq!(
322
        snap.files.keys().cloned().collect::<Vec<_>>(),
323
        ["keep.txt", "new.txt"]
324
    );
325
    assert!(
326
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
327
    );
328
}
329
330
#[test]
331
fn identities_and_signed_commits() {
332
    hermetic();
333
    let dir = tempfile::tempdir().unwrap();
334
    let root = dir.path();
335
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
336
    write(root, "a.txt", b"a\n");
337
    let h0 = repo.commit("unsigned", &[]).unwrap();
338
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
339
    assert_eq!(
340
        repo.store().get_change(&h0).unwrap().author,
341
        ObjectRef::ZERO
342
    );
343
344
    let (key, id) = repo
345
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
346
        .unwrap();
347
    assert_eq!(id.hash(), key);
348
    assert_eq!(repo.config.author_key, Some(key));
349
    // Config survives reopen; the secret key is found again.
350
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
351
    assert_eq!(reopened.config.author_key, Some(key));
352
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
353
354
    // Default core.sign = seal: commits carry the author but no signature.
355
    write(root, "a.txt", b"a\nb\n");
356
    let h1 = repo.commit("authored", &[]).unwrap();
357
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
358
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
359
    // Signing later works too.
360
    repo.sign_change(&h1).unwrap();
361
    assert!(
362
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
363
    );
364
365
    repo.config.set("core.sign", "change").unwrap();
366
    repo.save_config().unwrap();
367
    write(root, "a.txt", b"a\nb\nc\n");
368
    let h2 = repo.commit("signed", &[]).unwrap();
369
    assert_eq!(
370
        repo.verify_change(&h2).unwrap(),
371
        SignatureStatus::Valid {
372
            key,
373
            name: "Ada".into(),
374
            email: "[email protected]".into(),
375
            sealed: false,
376
            revoked: false
377
        }
378
    );
379
380
    // A signature by a key that is not the author or a delegate is rejected
381
    // when the change names an author; an anonymous change (made before any
382
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
383
    let other = SecretKey::generate();
384
    let other_id = other.identity("Mallory", "[email protected]", 0);
385
    let other_key = repo.store().put_identity(&other_id).unwrap();
386
    write(root, "a.txt", b"a\nb\nc\nd\n");
387
    repo.config.set("core.sign", "seal").unwrap();
388
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
389
    let forged = other.sign(Domain::Change, &other_key, &h3);
390
    repo.store().put_signature(&h3, &forged).unwrap();
391
    assert!(
392
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
393
    );
394
    let adopted = other.sign(Domain::Change, &other_key, &h0);
395
    repo.store().put_signature(&h0, &adopted).unwrap();
396
    assert!(
397
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
398
    );
399
400
    // Tampering with the stored signature invalidates it.
401
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
402
    sig.ed[0] ^= 1;
403
    repo.store().put_signature(&h2, &sig).unwrap();
404
    assert!(matches!(
405
        repo.verify_change(&h2).unwrap(),
406
        SignatureStatus::Invalid(_)
407
    ));
408
409
    // Without the secret key, signing at commit fails cleanly.
410
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
411
    write(root, "a.txt", b"z\n");
412
    assert!(no_keys.commit("cannot sign", &[]).is_err());
413
}
414
415
#[test]
416
fn checkout_moves_the_working_copy() {
417
    hermetic();
418
    let dir = tempfile::tempdir().unwrap();
419
    let root = dir.path();
420
    let repo = Repo::init(root).unwrap();
421
    write(root, "a.txt", b"one\n");
422
    write(root, "sub/deep/b.txt", b"b\n");
423
    let h1 = repo.commit("first", &[]).unwrap();
424
    write(root, "a.txt", b"two\n");
425
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
426
    write(root, "bin.dat", &[0, 1, 2, 3]);
427
    let h2 = repo.commit("second", &[]).unwrap();
428
429
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
430
    assert_eq!(
431
        r,
432
        CheckoutReport {
433
            written: 2,
434
            removed: 1,
435
            conflicted: false,
436
            notes: vec![],
437
            lacks: 1,
438
        }
439
    );
440
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
441
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
442
    assert!(!root.join("bin.dat").exists());
443
    let (_, wc) = repo.working_copy().unwrap();
444
    assert_eq!(wc.deps, vec![h1]);
445
    assert!(
446
        !repo.snapshot("status").unwrap().changed,
447
        "checkout leaves a clean working copy"
448
    );
449
    // The bookmark still points at h2.
450
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
451
452
    // Dirty working copy refuses without --discard.
453
    write(root, "a.txt", b"dirty\n");
454
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
455
    let r = repo
456
        .checkout(&[h2], true, "oxy checkout --discard")
457
        .unwrap();
458
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
459
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
460
    assert!(!root.join("sub").exists(), "empty directories are pruned");
461
    assert_eq!(r.removed, 1);
462
    assert!(!repo.snapshot("status").unwrap().changed);
463
464
    // Refuses to write through a symlinked directory.
465
    #[cfg(unix)]
466
    {
467
        fs::remove_dir_all(root.join("sub")).ok();
468
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
469
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
470
    }
471
}
472
473
#[test]
474
fn large_files_are_chunked_and_read_back() {
475
    hermetic();
476
    let dir = tempfile::tempdir().unwrap();
477
    let repo = Repo::init(dir.path()).unwrap();
478
    let mut big = vec![0u8; 700 * 1024];
479
    for (i, b) in big.iter_mut().enumerate() {
480
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
481
    }
482
    let r = repo.store_blob(&big).unwrap();
483
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
484
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
485
    assert_eq!(repo.read_blob(&r).unwrap(), big);
486
    assert_eq!(Repo::blob_ref(&big), r);
487
}
488
489
#[test]
490
fn clone_push_pull_with_seals_and_attestations() {
491
    hermetic();
492
    let dir = tempfile::tempdir().unwrap();
493
    let root = dir.path();
494
    let origin_path = root.join("origin");
495
    let origin = Repo::init(&origin_path).unwrap();
496
    let origin_url = origin_path.to_string_lossy().to_string();
497
498
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
499
    let mut a = Repo::clone(&origin_url, &root.join("a"))
500
        .unwrap()
501
        .with_home(root.join("home-a"));
502
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
503
    let (key_a, _) = a
504
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
505
        .unwrap();
506
    write(&root.join("a"), "f.txt", b"a\n");
507
    let h1 = a.commit("first", &[]).unwrap();
508
    let results = a.push("origin", false).unwrap();
509
    assert!(results[0].ok, "{}", results[0].reason);
510
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
511
    // The change was sealed at push and the reference attested.
512
    assert!(
513
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
514
    );
515
    assert_eq!(
516
        origin.verify_change(&h1).unwrap(),
517
        SignatureStatus::Unsigned
518
    );
519
    let serial_of = |att: &SignedAttest| match att.attest.body {
520
        AttestBody::Ref { serial, .. } => serial,
521
        _ => unreachable!(),
522
    };
523
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
524
    // A bookmark new to the remote starts at the clock (past any deleted
525
    // namesake's serial); later updates count up from there.
526
    let first = serial_of(&att);
527
    assert!(first > 1_000_000_000_000, "{first}");
528
    let again = a.push("origin", false).unwrap();
529
    assert!(again[0].ok && again[0].reason.contains("up to date"));
530
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
531
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
532
533
    // B clones and sees the file and the seal.
534
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
535
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
536
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
537
    assert!(matches!(
538
        b.authenticate_change(&h1).unwrap(),
539
        SignatureStatus::Valid { sealed: true, .. }
540
    ));
541
542
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
543
    write(&root.join("b"), "f.txt", b"a\nb\n");
544
    let h2 = b.commit("second", &[]).unwrap();
545
    assert!(b.push("origin", false).unwrap()[0].ok);
546
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
547
548
    // A commits an independent change; push is refused until A pulls.
549
    write(&root.join("a"), "g.txt", b"g\n");
550
    let h3 = a.commit("third", &[]).unwrap();
551
    assert!(a.push("origin", false).is_err());
552
    let pr = a.pull("origin").unwrap();
553
    assert!(pr.changed && pr.checked_out);
554
    let mut want = vec![h2, h3];
555
    want.sort();
556
    assert_eq!(pr.heads, want);
557
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
558
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
559
    let results = a.push("origin", false).unwrap();
560
    assert!(results[0].ok, "{}", results[0].reason);
561
    let mut origin_heads = origin.bookmark_heads().unwrap();
562
    origin_heads.sort();
563
    assert_eq!(origin_heads, want);
564
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
565
    assert_eq!(serial_of(&att), first + 1);
566
567
    // B pulls and ends up identical.
568
    let pr = b.pull("origin").unwrap();
569
    assert_eq!(pr.heads, want);
570
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
571
    assert!(!b.snapshot("status").unwrap().changed);
572
573
    // Concurrent edits of the same line: the union is a reified conflict.
574
    write(&root.join("a"), "f.txt", b"a\nA\n");
575
    a.commit("a-edit", &[]).unwrap();
576
    a.push("origin", false).unwrap();
577
    write(&root.join("b"), "f.txt", b"a\nB\n");
578
    b.commit("b-edit", &[]).unwrap();
579
    let pr = b.pull("origin").unwrap();
580
    assert!(pr.changed && pr.checked_out);
581
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
582
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
583
    write(&root.join("b"), "f.txt", b"a\nAB\n");
584
    let hr = b.commit("resolve", &[]).unwrap();
585
    assert_eq!(
586
        b.store().get_change(&hr).unwrap().kind,
587
        ChangeKind::Resolution
588
    );
589
    assert!(b.push("origin", false).unwrap()[0].ok);
590
    a.pull("origin").unwrap();
591
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
592
    // The resolution depends on the conflicting edits, but nothing depends
593
    // on "third" (it only added g.txt), so it stays a head beside it.
594
    let mut want = vec![hr, h3];
595
    want.sort();
596
    assert_eq!(a.bookmark_heads().unwrap(), want);
597
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
598
}
599
600
#[test]
601
fn receive_push_rejects_bad_updates() {
602
    hermetic();
603
    let dir = tempfile::tempdir().unwrap();
604
    let root = dir.path();
605
    let origin = Repo::init(&root.join("origin")).unwrap();
606
    let url = root.join("origin").to_string_lossy().to_string();
607
    let mut a = Repo::clone(&url, &root.join("a"))
608
        .unwrap()
609
        .with_home(root.join("home"));
610
    let (key, _) = a
611
        .create_identity("Ada", "a@b", IdentityScope::Repo)
612
        .unwrap();
613
    write(&root.join("a"), "f.txt", b"x\n");
614
    let h1 = a.commit("one", &[]).unwrap();
615
    assert!(a.push("origin", false).unwrap()[0].ok);
616
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
617
    let s1 = origin
618
        .store()
619
        .put_state(&StateObject::new(vec![h1]))
620
        .unwrap();
621
622
    // Missing head.
623
    let ghost = origin
624
        .store()
625
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
626
        .unwrap();
627
    let r = origin
628
        .receive_push(
629
            Bundle::default(),
630
            vec![RefUpdate {
631
                name: "main".into(),
632
                old_state: s1,
633
                new_state: ghost,
634
                force: false,
635
                attestation: None,
636
            }],
637
            None,
638
            vec![],
639
        )
640
        .unwrap();
641
    assert!(
642
        !r[0].ok && r[0].reason.contains("missing"),
643
        "{}",
644
        r[0].reason
645
    );
646
647
    // Stale old_state.
648
    let r = origin
649
        .receive_push(
650
            Bundle::default(),
651
            vec![RefUpdate {
652
                name: "main".into(),
653
                old_state: empty,
654
                new_state: s1,
655
                force: false,
656
                attestation: None,
657
            }],
658
            None,
659
            vec![],
660
        )
661
        .unwrap();
662
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
663
664
    // Non-fast-forward without force is refused; with force it passes.
665
    let r = origin
666
        .receive_push(
667
            Bundle::default(),
668
            vec![RefUpdate {
669
                name: "main".into(),
670
                old_state: s1,
671
                new_state: empty,
672
                force: false,
673
                attestation: None,
674
            }],
675
            None,
676
            vec![],
677
        )
678
        .unwrap();
679
    assert!(
680
        !r[0].ok && r[0].reason.contains("fast-forward"),
681
        "{}",
682
        r[0].reason
683
    );
684
    let r = origin
685
        .receive_push(
686
            Bundle::default(),
687
            vec![RefUpdate {
688
                name: "main".into(),
689
                old_state: s1,
690
                new_state: empty,
691
                force: true,
692
                attestation: None,
693
            }],
694
            None,
695
            vec![],
696
        )
697
        .unwrap();
698
    assert!(r[0].ok);
699
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
700
701
    // Attestation with a stale serial is a rollback and is refused.
702
    let sa = a
703
        .sign_attest(&Attest {
704
            repo: a.id().unwrap(),
705
            hlc: Hlc::now(),
706
            body: AttestBody::Ref {
707
                name: "main".into(),
708
                old_state: empty,
709
                new_state: s1,
710
                serial: 1,
711
            },
712
        })
713
        .unwrap();
714
    let r = origin
715
        .receive_push(
716
            Bundle::default(),
717
            vec![RefUpdate {
718
                name: "main".into(),
719
                old_state: empty,
720
                new_state: s1,
721
                force: false,
722
                attestation: Some(sa.clone()),
723
            }],
724
            None,
725
            vec![],
726
        )
727
        .unwrap();
728
    assert!(
729
        !r[0].ok && r[0].reason.contains("serial"),
730
        "{}",
731
        r[0].reason
732
    );
733
    // An attestation for a different update is refused too.
734
    let sa2 = a
735
        .sign_attest(&Attest {
736
            repo: a.id().unwrap(),
737
            hlc: Hlc::now(),
738
            body: AttestBody::Ref {
739
                name: "main".into(),
740
                old_state: s1,
741
                new_state: empty,
742
                serial: 5,
743
            },
744
        })
745
        .unwrap();
746
    let r = origin
747
        .receive_push(
748
            Bundle::default(),
749
            vec![RefUpdate {
750
                name: "main".into(),
751
                old_state: empty,
752
                new_state: s1,
753
                force: false,
754
                attestation: Some(sa2),
755
            }],
756
            None,
757
            vec![],
758
        )
759
        .unwrap();
760
    assert!(
761
        !r[0].ok && r[0].reason.contains("describe"),
762
        "{}",
763
        r[0].reason
764
    );
765
    let _ = key;
766
}
767
768
#[test]
769
fn user_config_supplies_defaults_and_clones_sign() {
770
    hermetic();
771
    let dir = tempfile::tempdir().unwrap();
772
    let root = dir.path();
773
    let home = root.join("home");
774
    let origin = Repo::init(&root.join("origin")).unwrap();
775
    let url = root.join("origin").to_string_lossy().to_string();
776
777
    // Identity at user scope: the repository file stays free of author keys.
778
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
779
    let (key, _) = a
780
        .create_identity("Ada", "[email protected]", IdentityScope::User)
781
        .unwrap();
782
    assert!(!a.config.repo_layer().contains_key("author.key"));
783
    assert_eq!(a.config.author_key, Some(key));
784
    assert!(home.join("config.toml").exists());
785
    a.set_user_config("core.sign", "change").unwrap();
786
    assert!(a.config.sign_changes);
787
788
    // Repository settings override user settings and are the only ones saved.
789
    a.config.set("core.sign", "seal").unwrap();
790
    a.save_config().unwrap();
791
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
792
    assert!(!again.config.sign_changes);
793
    assert_eq!(again.config.author_key, Some(key));
794
    assert_eq!(
795
        read_config_file(&root.join("a/.oxy/config"))
796
            .unwrap()
797
            .get("core.sign")
798
            .map(String::as_str),
799
        Some("seal")
800
    );
801
802
    // A fresh clone made by this user signs with the user-level identity,
803
    // even though the clone's store has never seen the identity object.
804
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
805
    assert!(b.config.sign_changes);
806
    write(&root.join("b"), "f.txt", b"f\n");
807
    let h = b.commit("signed from a clone", &[]).unwrap();
808
    assert!(
809
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
810
    );
811
    assert!(b.push("origin", false).unwrap()[0].ok);
812
    assert!(matches!(
813
        origin.verify_change(&h).unwrap(),
814
        SignatureStatus::Valid { .. }
815
    ));
816
}
817
818
#[test]
819
fn format1_repositories_are_migrated_on_open() {
820
    hermetic();
821
    use crate::oplog::{Format1Op, Format1View};
822
    let dir = tempfile::tempdir().unwrap();
823
    let root = dir.path();
824
    let repo = Repo::init(root).unwrap();
825
    write(root, "a.txt", b"a\n");
826
    let h1 = repo.commit("one", &[]).unwrap();
827
    let (wc_hash, _) = repo.working_copy().unwrap();
828
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
829
    let mut v1 = Format1View::default();
830
    v1.bookmarks.insert("main".into(), vec![]);
831
    v1.workspaces.insert(repo.workspace(), wc_hash);
832
    let init = Format1Op {
833
        parents: vec![],
834
        hlc: Hlc::default(),
835
        command: "oxy init".into(),
836
        view: v1.clone(),
837
    };
838
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
839
    v1.bookmarks.insert("main".into(), vec![h1]);
840
    let commit = Format1Op {
841
        parents: vec![init_ref],
842
        hlc: Hlc::default(),
843
        command: "oxy commit".into(),
844
        view: v1,
845
    };
846
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
847
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
848
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
849
    drop(repo);
850
851
    let repo = Repo::open(root).unwrap();
852
    assert_eq!(
853
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
854
        FORMAT_LINE
855
    );
856
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
857
    let ops = repo.op_log().unwrap();
858
    assert_eq!(
859
        ops.iter()
860
            .map(|(_, o)| o.command.as_str())
861
            .collect::<Vec<_>>(),
862
        ["oxy commit", "oxy init"]
863
    );
864
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
865
    assert!(!repo.snapshot("status").unwrap().changed);
866
    // Reopening again is a no-op.
867
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
868
}
869
870
#[test]
871
fn undo_skips_snapshot_operations() {
872
    hermetic();
873
    let dir = tempfile::tempdir().unwrap();
874
    let root = dir.path();
875
    let repo = Repo::init(root).unwrap();
876
    write(root, "a.txt", b"a\n");
877
    let h1 = repo.commit("a", &[]).unwrap();
878
    // A later command snapshots new edits on top of the commit.
879
    write(root, "b.txt", b"b\n");
880
    let s = repo.snapshot("oxy status").unwrap();
881
    assert!(s.changed);
882
    assert!(repo.head_op().unwrap().1.is_snapshot());
883
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
884
    // Undo must undo the commit, not the snapshot.
885
    repo.undo().unwrap();
886
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
887
    let s = repo.snapshot("oxy status").unwrap();
888
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
889
    assert_eq!(
890
        paths,
891
        ["a.txt", "b.txt"],
892
        "both files are back in the working copy"
893
    );
894
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
895
    // Only snapshots remain above `init`, so there is nothing left to undo.
896
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
897
    assert!(repo.undo().is_err());
898
}
899
900
#[test]
901
fn independent_changes_commute_and_make_multiple_heads() {
902
    hermetic();
903
    let dir = tempfile::tempdir().unwrap();
904
    let root = dir.path();
905
    let repo = Repo::init(root).unwrap();
906
    write(root, "a.txt", b"a\n");
907
    let h1 = repo.commit("a", &[]).unwrap();
908
    write(root, "b.txt", b"b\n");
909
    let h2 = repo.commit("b", &[]).unwrap();
910
    let c2 = repo.store().get_change(&h2).unwrap();
911
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
912
    let mut heads = repo.bookmark_heads().unwrap();
913
    heads.sort();
914
    let mut want = vec![h1, h2];
915
    want.sort();
916
    assert_eq!(heads, want);
917
    // Editing a.txt depends on h1 only.
918
    write(root, "a.txt", b"a\na2\n");
919
    let h3 = repo.commit("a2", &[]).unwrap();
920
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
921
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
922
    assert_eq!(heads, [h2, h3].into_iter().collect());
923
    // Explicit dependency.
924
    write(root, "c.txt", b"c\n");
925
    let h4 = repo.commit("c", &[h2]).unwrap();
926
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
927
}
928
929
#[test]
930
fn mode_change_and_text_binary_switch() {
931
    hermetic();
932
    let dir = tempfile::tempdir().unwrap();
933
    let root = dir.path();
934
    let repo = Repo::init(root).unwrap();
935
    write(root, "run.sh", b"#!/bin/sh\n");
936
    repo.commit("add script", &[]).unwrap();
937
    #[cfg(unix)]
938
    {
939
        use std::os::unix::fs::PermissionsExt;
940
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
941
        let s = repo.snapshot("status").unwrap();
942
        assert_eq!(
943
            statuses(&s),
944
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
945
        );
946
        let h = repo.commit("exec", &[]).unwrap();
947
        let snap = repo.load_state(&[h]).unwrap().materialize();
948
        assert!(snap.files["run.sh"].mode.exec);
949
    }
950
    // Text → binary → text.
951
    write(root, "run.sh", b"\0binary");
952
    let h = repo.commit("binary", &[]).unwrap();
953
    let snap = repo.load_state(&[h]).unwrap().materialize();
954
    assert!(snap.files["run.sh"].mode.opaque);
955
    write(root, "run.sh", b"text again\n");
956
    let h = repo.commit("text", &[]).unwrap();
957
    let snap = repo.load_state(&[h]).unwrap().materialize();
958
    assert!(!snap.files["run.sh"].mode.opaque);
959
    assert!(
960
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
961
    );
962
    assert!(!snap.is_conflicted());
963
}
964
965
#[test]
966
fn trust_policy_governs_pushes_and_fetches() {
967
    hermetic();
968
    let dir = tempfile::tempdir().unwrap();
969
    let root = dir.path();
970
    let origin = Repo::init(&root.join("origin")).unwrap();
971
    let url = root.join("origin").to_string_lossy().to_string();
972
973
    // A is the root. Before the policy, an unsigned push from B is fine.
974
    let mut a = Repo::clone(&url, &root.join("a"))
975
        .unwrap()
976
        .with_home(root.join("home-a"));
977
    let (key_a, _) = a
978
        .create_identity("Ada", "[email protected]", IdentityScope::User)
979
        .unwrap();
980
    let mut b = Repo::clone(&url, &root.join("b"))
981
        .unwrap()
982
        .with_home(root.join("home-b"));
983
    write(&root.join("b"), "b.txt", b"b\n");
984
    b.commit("unsigned before policy", &[]).unwrap();
985
    assert!(b.push("origin", false).unwrap()[0].ok);
986
987
    // A creates the policy and pushes it; origin now enforces it.
988
    write(&root.join("a"), "a.txt", b"a\n");
989
    a.commit("a", &[]).unwrap();
990
    let sp = a.policy_init().unwrap();
991
    assert_eq!(sp.policy.serial, 1);
992
    a.pull("origin").unwrap();
993
    let results = a.push("origin", false).unwrap();
994
    assert!(results.iter().all(|r| r.ok), "{results:?}");
995
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
996
997
    // B pulls the policy. Without an identity B cannot push at all.
998
    b.pull("origin").unwrap();
999
    assert!(
1000
        b.current_policy().unwrap().is_some(),
1001
        "the policy arrived with the fetch"
1002
    );
1003
    assert!(b.push("origin", false).is_err());
1004
    // With an identity the policy does not list, the push is rejected by origin.
1005
    let (key_b, id_b) = b
1006
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1007
        .unwrap();
1008
    write(&root.join("b"), "b.txt", b"b2\n");
1009
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1010
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1011
    let r = b.push("origin", false).unwrap();
1012
    assert!(
1013
        !r[0].ok && r[0].reason.contains("may not update"),
1014
        "{:?}",
1015
        r
1016
    );
1017
1018
    // A grants B (identity handed over as a file) and publishes the policy.
1019
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1020
    assert_eq!(sp.policy.serial, 2);
1021
    let r = a.push("origin", false).unwrap();
1022
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1023
    // B must fetch the new policy before pushing.
1024
    assert!(b
1025
        .push("origin", false)
1026
        .unwrap_or_else(|e| vec![RefResult {
1027
            name: "main".into(),
1028
            ok: false,
1029
            reason: e.to_string()
1030
        }])
1031
        .iter()
1032
        .all(|x| !x.ok));
1033
    b.pull("origin").unwrap();
1034
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1035
    let r = b.push("origin", false).unwrap();
1036
    assert!(r[0].ok, "{:?}", r);
1037
    // Origin verified B's change under the policy.
1038
    let heads = origin.bookmark_heads().unwrap();
1039
    for h in &heads {
1040
        let c = origin.store().get_change(h).unwrap();
1041
        if c.author == key_b {
1042
            origin
1043
                .change_allowed(
1044
                    h,
1045
                    &origin.current_policy().unwrap().unwrap().1.policy,
1046
                    "main",
1047
                )
1048
                .unwrap();
1049
        }
1050
    }
1051
1052
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1053
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1054
    forged.serial = 3;
1055
    forged.roots = vec![key_b];
1056
    let fh = forged.hash();
1057
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1058
    let forged = SignedPolicy {
1059
        policy: forged,
1060
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1061
    };
1062
    let r = origin
1063
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1064
        .unwrap();
1065
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1066
    let stale = a.current_policy().unwrap().unwrap().1;
1067
    let mut old = stale.clone();
1068
    old.policy.serial = 1;
1069
    let r = origin
1070
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1071
        .unwrap();
1072
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1073
1074
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1075
    a.pull("origin").unwrap();
1076
    a.policy_revoke(&key_b).unwrap();
1077
    let r = a.push("origin", false).unwrap();
1078
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1079
    b.pull("origin").unwrap();
1080
    write(&root.join("b"), "b.txt", b"b3\n");
1081
    b.commit("b3", &[]).unwrap();
1082
    let r = b.push("origin", false).unwrap();
1083
    assert!(!r[0].ok, "{:?}", r);
1084
1085
    // A clone by a third party receives and verifies everything.
1086
    let c = Repo::clone(&url, &root.join("c"))
1087
        .unwrap()
1088
        .with_home(root.join("home-c"));
1089
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1090
    assert!(c
1091
        .current_policy()
1092
        .unwrap()
1093
        .unwrap()
1094
        .1
1095
        .policy
1096
        .roots
1097
        .contains(&key_a));
1098
    assert!(!c.snapshot("status").unwrap().changed);
1099
}
1100
1101
/// oxygen#66: a gc says what it is doing, phase by phase.
1102
#[test]
1103
fn gc_reports_its_phases() {
1104
    hermetic();
1105
    let dir = tempfile::tempdir().unwrap();
1106
    let repo = Repo::init(dir.path()).unwrap();
1107
    for i in 0..3 {
1108
        write(
1109
            dir.path(),
1110
            &format!("f{i}.txt"),
1111
            format!("{i}\n").as_bytes(),
1112
        );
1113
        repo.commit(&format!("c{i}"), &[]).unwrap();
1114
    }
1115
    let mut phases = Vec::new();
1116
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1117
        .unwrap();
1118
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1119
    assert!(
1120
        phases.iter().any(|p| p.starts_with("pruning")),
1121
        "{phases:?}"
1122
    );
1123
    assert!(
1124
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1125
        "{phases:?}"
1126
    );
1127
    assert!(
1128
        phases
1129
            .iter()
1130
            .any(|p| p.starts_with("writing the index of ")),
1131
        "{phases:?}"
1132
    );
1133
}
1134
1135
#[test]
1136
fn gc_packs_objects_and_history_still_works() {
1137
    hermetic();
1138
    let dir = tempfile::tempdir().unwrap();
1139
    let root = dir.path();
1140
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1141
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1142
        .unwrap();
1143
    repo.set_user_config("core.sign", "change").unwrap();
1144
    write(root, "a.txt", b"one\n");
1145
    let h1 = repo.commit("one", &[]).unwrap();
1146
    write(root, "a.txt", b"two\n");
1147
    write(root, "big.bin", &vec![0u8; 100_000]);
1148
    let h2 = repo.commit("two", &[]).unwrap();
1149
    // Several snapshots leave superseded working-copy versions behind.
1150
    for i in 0..5 {
1151
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1152
        repo.snapshot("status").unwrap();
1153
    }
1154
    write(root, "a.txt", b"two\n");
1155
    repo.snapshot("status").unwrap();
1156
    let before = repo.store().list().unwrap();
1157
    assert!(repo.store().loose_count().unwrap() > 0);
1158
1159
    // With the default retention every operation's view is a root: nothing prunes.
1160
    let r = repo.gc(true).unwrap();
1161
    assert_eq!(r.packed.objects, before.len());
1162
    assert_eq!(r.pruned.objects, 0);
1163
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1164
    assert_eq!(repo.store().list().unwrap(), before);
1165
1166
    // With zero retention only the current view is a root: superseded
1167
    // working copies go, everything reachable stays.
1168
    repo.config.set("core.op-retention", "0").unwrap();
1169
    repo.save_config().unwrap();
1170
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1171
    let r = repo.gc(true).unwrap();
1172
    assert!(r.pruned.objects >= 5, "{r:?}");
1173
    let after = repo.store().list().unwrap();
1174
    assert!(after.len() < before.len());
1175
    assert!(after.contains(&h1) && after.contains(&h2));
1176
    for (_, op) in repo.op_log().unwrap() {
1177
        assert!(!op.command.is_empty(), "operation objects are all kept");
1178
    }
1179
    // Everything still works from the pruned, packed store.
1180
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1181
    assert!(matches!(
1182
        repo.verify_change(&h2).unwrap(),
1183
        SignatureStatus::Valid { .. }
1184
    ));
1185
    assert_eq!(repo.log().unwrap().len(), 3);
1186
    repo.checkout(&[h1], false, "checkout").unwrap();
1187
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1188
    repo.checkout(&[h2], false, "checkout").unwrap();
1189
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1190
    assert!(!repo.snapshot("status").unwrap().changed);
1191
    // Grace period defers pruning of young garbage.
1192
    write(root, "a.txt", b"three\n");
1193
    repo.commit("three", &[]).unwrap();
1194
    let r = repo.gc(false).unwrap();
1195
    assert_eq!(r.pruned.objects, 0);
1196
    assert!(r.pruned.deferred > 0);
1197
    let r = repo.gc(true).unwrap();
1198
    assert!(r.pruned.objects > 0);
1199
    assert_eq!(repo.log().unwrap().len(), 4);
1200
    // Restoring the default retention makes the old views roots again; the
1201
    // working copies they name were pruned, which gc tolerates.
1202
    repo.config.set("core.op-retention", "90").unwrap();
1203
    repo.save_config().unwrap();
1204
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1205
    let r = repo.gc(false).unwrap();
1206
    assert_eq!(r.pruned.objects, 0);
1207
    assert_eq!(repo.log().unwrap().len(), 4);
1208
}
1209
1210
#[test]
1211
fn describe_amend_abandon_heads() {
1212
    hermetic();
1213
    let dir = tempfile::tempdir().unwrap();
1214
    let root = dir.path();
1215
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1216
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1217
        .unwrap();
1218
    repo.set_user_config("core.sign", "change").unwrap();
1219
    write(root, "a.txt", b"one\n");
1220
    let h1 = repo.commit("first", &[]).unwrap();
1221
    write(root, "a.txt", b"one\ntwo\n");
1222
    let h2 = repo.commit("secnod", &[]).unwrap();
1223
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1224
1225
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1226
    let h2b = repo.describe(&h2, "second").unwrap();
1227
    assert_ne!(h2b, h2);
1228
    let c = repo.store().get_change(&h2b).unwrap();
1229
    assert_eq!(
1230
        (c.change_id, c.message.as_str(), c.deps.clone()),
1231
        (id2, "second", vec![h1])
1232
    );
1233
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1234
    assert!(matches!(
1235
        repo.verify_change(&h2b).unwrap(),
1236
        SignatureStatus::Valid { .. }
1237
    ));
1238
    let s = repo.snapshot("status").unwrap();
1239
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1240
    assert_eq!(
1241
        repo.resolve_change(&id2.short(8)).unwrap(),
1242
        h2b,
1243
        "the old object is no longer reachable from the log"
1244
    );
1245
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1246
    let h1b = repo.describe(&h1, "first, described").unwrap();
1247
    assert_ne!(h1b, h1);
1248
    let heads = repo.bookmark_heads().unwrap();
1249
    assert_eq!(heads.len(), 1);
1250
    let top = repo.store().get_change(&heads[0]).unwrap();
1251
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1252
    assert!(
1253
        matches!(
1254
            repo.verify_change(&heads[0]).unwrap(),
1255
            SignatureStatus::Valid { .. }
1256
        ),
1257
        "rewritten own change is re-signed"
1258
    );
1259
    let (_, wc) = repo.working_copy().unwrap();
1260
    assert_eq!(
1261
        wc.deps,
1262
        vec![heads[0]],
1263
        "the working copy follows the rewrite"
1264
    );
1265
    assert!(!repo.snapshot("status").unwrap().changed);
1266
    let snap = repo.load_state(&heads).unwrap().materialize();
1267
    assert!(
1268
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1269
    );
1270
1271
    // amend: fold an edit into the head; the result is one change from h1.
1272
    write(root, "a.txt", b"one\ntwo\nthree\n");
1273
    write(root, "b.txt", b"b\n");
1274
    let h2c = repo.amend(None).unwrap();
1275
    let c = repo.store().get_change(&h2c).unwrap();
1276
    assert_eq!(c.change_id, id2);
1277
    assert_eq!(c.message, "second");
1278
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1279
    assert_eq!(
1280
        repo.log().unwrap().len(),
1281
        3,
1282
        "working copy, amended head, first"
1283
    );
1284
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1285
    assert!(
1286
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1287
    );
1288
    assert!(snap.files.contains_key("b.txt"));
1289
    assert!(!repo.snapshot("status").unwrap().changed);
1290
    assert!(
1291
        repo.amend(None).is_err(),
1292
        "clean working copy and no message"
1293
    );
1294
    let h2d = repo.amend(Some("second, amended")).unwrap();
1295
    assert_eq!(
1296
        repo.store().get_change(&h2d).unwrap().message,
1297
        "second, amended"
1298
    );
1299
1300
    // abandon: the head goes, its content stays as uncommitted work.
1301
    repo.abandon(&h2d).unwrap();
1302
    assert_eq!(
1303
        repo.bookmark_heads().unwrap(),
1304
        vec![h1b],
1305
        "the described first change is the head again"
1306
    );
1307
    let s = repo.snapshot("status").unwrap();
1308
    let paths: Vec<_> = s
1309
        .statuses
1310
        .iter()
1311
        .map(|p| (p.path.as_str(), p.status))
1312
        .collect();
1313
    assert_eq!(
1314
        paths,
1315
        vec![
1316
            ("a.txt", ChangeStatus::Modified),
1317
            ("b.txt", ChangeStatus::Added)
1318
        ]
1319
    );
1320
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1321
    let h3 = repo.commit("recommitted", &[]).unwrap();
1322
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1323
    // undo brings the abandoned head back.
1324
    repo.undo().unwrap();
1325
    repo.undo().unwrap();
1326
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1327
1328
    // Abandoning a non-head whose dependent references its atoms reifies
1329
    // the references (here: a.txt vanishes with it, so the dependent's edit
1330
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1331
    let base = repo.bookmark_heads().unwrap()[0];
1332
    let base_change = repo.store().get_change(&base).unwrap();
1333
    let h1_now = base_change.deps[0];
1334
    let notes = repo.abandon(&h1_now).unwrap();
1335
    assert!(
1336
        !notes.is_empty(),
1337
        "the dependent's edit of a.txt was reified"
1338
    );
1339
    let heads = repo.bookmark_heads().unwrap();
1340
    let after = repo.load_state(&heads).unwrap().materialize();
1341
    assert!(
1342
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1343
        "{:?}",
1344
        after.files.keys()
1345
    );
1346
    repo.undo().unwrap();
1347
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1348
    write(root, "c.txt", b"c\n");
1349
    let hc = repo.commit("c", &[]).unwrap();
1350
    write(root, "d.txt", b"d\n");
1351
    let hd = repo.commit("d", &[hc]).unwrap();
1352
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1353
    repo.abandon(&hc).unwrap();
1354
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1355
    assert!(!heads.contains(&hc));
1356
    let d_now = heads
1357
        .iter()
1358
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1359
        .copied()
1360
        .unwrap();
1361
    assert!(
1362
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1363
        "d inherited c's (empty) dependencies"
1364
    );
1365
    let s = repo.snapshot("status").unwrap();
1366
    assert_eq!(
1367
        s.statuses
1368
            .iter()
1369
            .map(|p| p.path.as_str())
1370
            .collect::<Vec<_>>(),
1371
        vec!["c.txt"],
1372
        "c's content is now uncommitted work"
1373
    );
1374
}
1375
1376
#[test]
1377
fn git_export_mirrors_history() {
1378
    hermetic();
1379
    if std::process::Command::new("git")
1380
        .arg("--version")
1381
        .output()
1382
        .is_err()
1383
    {
1384
        eprintln!("git not installed; skipping");
1385
        return;
1386
    }
1387
    let dir = tempfile::tempdir().unwrap();
1388
    let root = dir.path();
1389
    let mut repo = Repo::init(&root.join("r"))
1390
        .unwrap()
1391
        .with_home(root.join("home"));
1392
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1393
        .unwrap();
1394
    let r = root.join("r");
1395
    write(&r, "README.md", b"hello\n");
1396
    write(&r, "src/main.rs", b"fn main() {}\n");
1397
    let h1 = repo.commit("first", &[]).unwrap();
1398
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1399
    write(&r, "logo.png", b"\x89PNG\0\0");
1400
    let h2 = repo.commit("second", &[]).unwrap();
1401
1402
    let git_dir = root.join("mirror.git");
1403
    let rep = repo.git_export(&git_dir).unwrap();
1404
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1405
    let git = |args: &[&str]| -> String {
1406
        let out = std::process::Command::new("git")
1407
            .arg("-C")
1408
            .arg(&git_dir)
1409
            .args(args)
1410
            .output()
1411
            .unwrap();
1412
        assert!(
1413
            out.status.success(),
1414
            "{}",
1415
            String::from_utf8_lossy(&out.stderr)
1416
        );
1417
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1418
    };
1419
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1420
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1421
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1422
    let body = git(&["log", "-1", "--format=%B", "main"]);
1423
    assert!(
1424
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1425
        "{body}"
1426
    );
1427
    assert!(body.contains("Change-Id: "), "{body}");
1428
    assert_eq!(
1429
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1430
        "Ada Lovelace <[email protected]>"
1431
    );
1432
    assert_eq!(
1433
        git(&["ls-tree", "--name-only", "main"]),
1434
        "README.md\nlogo.png\nsrc"
1435
    );
1436
1437
    // Re-export is incremental.
1438
    let rep = repo.git_export(&git_dir).unwrap();
1439
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1440
1441
    // An independent change makes two heads; the next state is one more
1442
    // commit on the linear branch whose tree is the union.
1443
    repo.checkout(&[h1], false, "checkout").unwrap();
1444
    write(&r, "other.txt", b"o\n");
1445
    let h3 = repo.commit("third", &[]).unwrap();
1446
    let rep = repo.git_export(&git_dir).unwrap();
1447
    assert_eq!((rep.exported, rep.heads), (1, 2));
1448
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1449
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1450
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1451
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1452
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1453
    assert_eq!(
1454
        git(&["ls-tree", "--name-only", "main"]),
1455
        "README.md\nlogo.png\nother.txt\nsrc"
1456
    );
1457
    let body = git(&["log", "-1", "--format=%B", "main"]);
1458
    assert!(
1459
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1460
        "{body}"
1461
    );
1462
    // A rewrite is a new state whose one new change is the rewritten one.
1463
    repo.describe(&h3, "third, described").unwrap();
1464
    let rep = repo.git_export(&git_dir).unwrap();
1465
    assert_eq!(rep.exported, 1);
1466
    assert_eq!(
1467
        git(&["log", "-1", "--format=%s", "main"]),
1468
        "third, described"
1469
    );
1470
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1471
    let _ = h2;
1472
}
1473
1474
#[test]
1475
fn git_import_reproduces_trees() {
1476
    git_import_reproduces_trees_with(None);
1477
}
1478
1479
/// The same import with every merge rendered in batches of one file
1480
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1481
#[test]
1482
fn git_import_reproduces_trees_in_batches() {
1483
    git_import_reproduces_trees_with(Some(1));
1484
}
1485
1486
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1487
    crate::repo::git::set_merge_batch_for_tests(batch);
1488
    hermetic();
1489
    if std::process::Command::new("git")
1490
        .arg("--version")
1491
        .output()
1492
        .is_err()
1493
    {
1494
        eprintln!("git not installed; skipping");
1495
        return;
1496
    }
1497
    let dir = tempfile::tempdir().unwrap();
1498
    let root = dir.path();
1499
    let g = root.join("src.git");
1500
    fs::create_dir_all(&g).unwrap();
1501
    let git = |args: &[&str]| -> String {
1502
        let out = std::process::Command::new("git")
1503
            .arg("-C")
1504
            .arg(&g)
1505
            .args([
1506
                "-c",
1507
                "user.name=Grace",
1508
                "-c",
1509
                "[email protected]",
1510
                "-c",
1511
                "commit.gpgsign=false",
1512
            ])
1513
            .args(args)
1514
            .output()
1515
            .unwrap();
1516
        assert!(
1517
            out.status.success(),
1518
            "git {args:?}: {}",
1519
            String::from_utf8_lossy(&out.stderr)
1520
        );
1521
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1522
    };
1523
    git(&["init", "-q", "-b", "main"]);
1524
    write(&g, "README.md", b"# Hi\n");
1525
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1526
    git(&["add", "."]);
1527
    git(&["commit", "-q", "-m", "initial"]);
1528
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1529
    write(&g, "run.sh", b"#!/bin/sh\n");
1530
    #[cfg(unix)]
1531
    {
1532
        use std::os::unix::fs::PermissionsExt;
1533
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1534
    }
1535
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1536
    git(&["add", "."]);
1537
    git(&[
1538
        "commit",
1539
        "-q",
1540
        "-m",
1541
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1542
    ]);
1543
    // A branch that edits README, merged back with a conflict-free merge.
1544
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1545
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1546
    git(&["commit", "-q", "-am", "readme"]);
1547
    git(&["checkout", "-q", "main"]);
1548
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1549
    // A branch from the initial commit inserting at the same place as
1550
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1551
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1552
    git(&["checkout", "-q", "-b", "clash", &initial]);
1553
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1554
    git(&["commit", "-q", "-am", "clash"]);
1555
    git(&["checkout", "-q", "main"]);
1556
    let _ = std::process::Command::new("git")
1557
        .arg("-C")
1558
        .arg(&g)
1559
        .args(["merge", "-q", "clash"])
1560
        .output();
1561
    write(
1562
        &g,
1563
        "src/lib.rs",
1564
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1565
    );
1566
    git(&["add", "."]);
1567
    git(&["commit", "-q", "-m", "resolve clash"]);
1568
    git(&["rm", "-q", "logo.png"]);
1569
    git(&["commit", "-q", "-m", "drop logo"]);
1570
    // A rename with a small edit is imported as a move of the same node.
1571
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1572
    write(
1573
        &g,
1574
        "src/lib2.rs",
1575
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1576
    );
1577
    git(&["add", "."]);
1578
    git(&["commit", "-q", "-m", "rename lib"]);
1579
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1580
    // run.sh is the same as in the first parent's tree, but the merged
1581
    // change touched it, so the importer must compare it, not skip it.
1582
    git(&["checkout", "-q", "-b", "discarded"]);
1583
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1584
    git(&["commit", "-q", "-am", "discarded edit"]);
1585
    git(&["checkout", "-q", "main"]);
1586
    git(&[
1587
        "merge",
1588
        "-q",
1589
        "-s",
1590
        "ours",
1591
        "-m",
1592
        "merge discarded, keeping ours",
1593
        "discarded",
1594
    ]);
1595
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1596
1597
    let dest = root.join("oxy");
1598
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1599
    let rep = repo.import_git(&g, "main").unwrap();
1600
    assert_eq!(rep.commits, expected_count);
1601
    assert_eq!(rep.merges, 3);
1602
    assert_eq!(
1603
        fs::read(dest.join("run.sh")).unwrap(),
1604
        b"#!/bin/sh\n",
1605
        "the ours merge kept main's run.sh"
1606
    );
1607
    let v = repo.verify_git_import(&g, "main").unwrap();
1608
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1609
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1610
    // The working copy equals the Git tree at main.
1611
    assert_eq!(
1612
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1613
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1614
    );
1615
    assert!(!dest.join("src/lib.rs").exists());
1616
    assert_eq!(
1617
        fs::read(dest.join("README.md")).unwrap(),
1618
        b"# Hi\n\nMore.\n"
1619
    );
1620
    assert!(!dest.join("logo.png").exists());
1621
    #[cfg(unix)]
1622
    {
1623
        use std::os::unix::fs::PermissionsExt;
1624
        assert!(
1625
            fs::metadata(dest.join("run.sh"))
1626
                .unwrap()
1627
                .permissions()
1628
                .mode()
1629
                & 0o111
1630
                != 0
1631
        );
1632
    }
1633
    assert!(
1634
        !repo.snapshot("status").unwrap().changed,
1635
        "clean after import"
1636
    );
1637
    let heads = repo.bookmark_heads().unwrap();
1638
    let st = repo.load_state(&heads).unwrap();
1639
    assert!(!st.materialize().is_conflicted());
1640
    assert_eq!(st.len(), expected_count);
1641
    let tip = repo
1642
        .log()
1643
        .unwrap()
1644
        .into_iter()
1645
        .find(|e| e.change.message.starts_with("rename lib"))
1646
        .unwrap();
1647
    let c = repo.store().get_change(&tip.hash).unwrap();
1648
    assert!(
1649
        c.tree_ops
1650
            .iter()
1651
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1652
        "{:?}",
1653
        c.tree_ops
1654
    );
1655
    assert!(!c
1656
        .tree_ops
1657
        .iter()
1658
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1659
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1660
    let log = repo.log().unwrap();
1661
    let second = log
1662
        .iter()
1663
        .find(|e| e.change.message.starts_with("second"))
1664
        .unwrap();
1665
    assert_eq!(
1666
        second.change.change_id,
1667
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1668
    );
1669
    assert!(second
1670
        .change
1671
        .message
1672
        .contains("Git-Author: Grace <[email protected]>"));
1673
    let resolve = log
1674
        .iter()
1675
        .find(|e| e.change.message.starts_with("resolve clash"))
1676
        .unwrap();
1677
    assert_eq!(
1678
        resolve.change.kind,
1679
        ChangeKind::Resolution,
1680
        "a conflicting Git merge becomes a resolution"
1681
    );
1682
    // Re-importing into another fresh repository gives the same ChangeIds.
1683
    let repo2 = Repo::init(&root.join("oxy2"))
1684
        .unwrap()
1685
        .with_home(root.join("home"));
1686
    repo2.import_git(&g, "main").unwrap();
1687
    // New nodes' identifiers derive from the commit (spec §23), so the
1688
    // re-import is not just the same ChangeIds but the same changes.
1689
    assert_eq!(
1690
        repo2.bookmark_heads().unwrap(),
1691
        repo.bookmark_heads().unwrap()
1692
    );
1693
    let ids: BTreeSet<ChangeId> = repo
1694
        .log()
1695
        .unwrap()
1696
        .iter()
1697
        .filter(|e| !e.is_working_copy)
1698
        .map(|e| e.change.change_id)
1699
        .collect();
1700
    let ids2: BTreeSet<ChangeId> = repo2
1701
        .log()
1702
        .unwrap()
1703
        .iter()
1704
        .filter(|e| !e.is_working_copy)
1705
        .map(|e| e.change.change_id)
1706
        .collect();
1707
    assert_eq!(ids, ids2);
1708
    // Round trip back out to Git reproduces the tip tree.
1709
    let mirror = root.join("mirror.git");
1710
    repo.git_export(&mirror).unwrap();
1711
    let out = std::process::Command::new("git")
1712
        .arg("-C")
1713
        .arg(&mirror)
1714
        .args(["show", "main:src/lib2.rs"])
1715
        .output()
1716
        .unwrap();
1717
    assert_eq!(
1718
        String::from_utf8_lossy(&out.stdout),
1719
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1720
    );
1721
    let out = std::process::Command::new("git")
1722
        .arg("-C")
1723
        .arg(&mirror)
1724
        .args(["show", "main:src/lib.rs"])
1725
        .output()
1726
        .unwrap();
1727
    assert!(
1728
        !out.status.success(),
1729
        "the old path is gone from the export"
1730
    );
1731
}
1732
1733
#[test]
1734
fn checkpoints_accelerate_loading_and_stay_correct() {
1735
    hermetic();
1736
    let dir = tempfile::tempdir().unwrap();
1737
    let root = dir.path();
1738
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1739
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1740
    repo.save_config().unwrap();
1741
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1742
    let mut hashes = Vec::new();
1743
    for i in 0..12 {
1744
        write(
1745
            root,
1746
            "a.txt",
1747
            format!(
1748
                "{}\n",
1749
                (0..=i)
1750
                    .map(|k| k.to_string())
1751
                    .collect::<Vec<_>>()
1752
                    .join("\n")
1753
            )
1754
            .as_bytes(),
1755
        );
1756
        write(root, &format!("f{i}.txt"), b"x\n");
1757
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1758
    }
1759
    let (_, cp) = repo
1760
        .latest_checkpoint("main")
1761
        .unwrap()
1762
        .expect("automatic checkpoint");
1763
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1764
    // Loading through the checkpoint equals loading everything.
1765
    let heads = repo.bookmark_heads().unwrap();
1766
    let fast = repo.load_state(&heads).unwrap();
1767
    let full = repo.load_state_full(&heads).unwrap();
1768
    assert_eq!(fast.len(), full.len());
1769
    assert_eq!(fast.heads(), full.heads());
1770
    let (a, b) = (fast.materialize(), full.materialize());
1771
    assert_eq!(
1772
        a.files.keys().collect::<Vec<_>>(),
1773
        b.files.keys().collect::<Vec<_>>()
1774
    );
1775
    for (p, f) in &a.files {
1776
        assert_eq!(f.content, b.files[p].content, "{p}");
1777
    }
1778
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1779
    // A head set that does not contain the checkpoint's heads falls back.
1780
    assert!(repo
1781
        .load_state_checkpointed(&[hashes[0]])
1782
        .unwrap()
1783
        .is_none());
1784
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1785
    // Everything else keeps working on top of the checkpoint.
1786
    assert!(!repo.snapshot("status").unwrap().changed);
1787
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1788
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1789
    let (r, n, bytes) = repo.checkpoint().unwrap();
1790
    assert!(n >= 12 && bytes > 0);
1791
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1792
    write(root, "a.txt", b"after\n");
1793
    let h_after = repo.commit("after", &[]).unwrap();
1794
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1795
    assert!(st.contains(&h_after));
1796
    assert!(
1797
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1798
    );
1799
    assert_eq!(repo.log().unwrap().len(), 14);
1800
    // Checkpoints survive gc.
1801
    repo.gc(true).unwrap();
1802
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1803
    assert!(repo
1804
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1805
        .unwrap()
1806
        .is_some());
1807
}
1808
1809
#[test]
1810
fn quick_status_for_prompts() {
1811
    hermetic();
1812
    let dir = tempfile::tempdir().unwrap();
1813
    let root = dir.path();
1814
    let origin = Repo::init(&root.join("origin")).unwrap();
1815
    let url = root.join("origin").to_string_lossy().to_string();
1816
    let a = Repo::clone(&url, &root.join("a"))
1817
        .unwrap()
1818
        .with_home(root.join("home"));
1819
    let ops_before = a.op_log().unwrap().len();
1820
    let info = a.quick_status().unwrap();
1821
    assert_eq!(
1822
        (
1823
            info.bookmark.as_str(),
1824
            info.heads,
1825
            info.dirty,
1826
            info.conflicted,
1827
            info.ahead,
1828
            info.behind
1829
        ),
1830
        ("main", 0, false, false, Some(0), Some(0))
1831
    );
1832
    write(&root.join("a"), "f.txt", b"f\n");
1833
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1834
    assert_eq!(
1835
        a.op_log().unwrap().len(),
1836
        ops_before,
1837
        "quick_status records nothing"
1838
    );
1839
    // A snapshotted but uncommitted change is still dirty.
1840
    a.snapshot("status").unwrap();
1841
    assert!(a.quick_status().unwrap().dirty);
1842
    a.commit("f", &[]).unwrap();
1843
    let info = a.quick_status().unwrap();
1844
    assert!(!info.dirty, "clean right after a commit");
1845
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
1846
    assert_eq!(
1847
        info.format("%b %c%d%x%A%D"),
1848
        format!("main {}+1", info.change_id)
1849
    );
1850
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1851
    // Touching a file without changing it is not dirty; changing content of
1852
    // the same size is.
1853
    let p = root.join("a/f.txt");
1854
    let content = fs::read(&p).unwrap();
1855
    fs::write(&p, &content).unwrap();
1856
    assert!(!a.quick_status().unwrap().dirty);
1857
    fs::write(&p, b"g\n").unwrap();
1858
    assert!(a.quick_status().unwrap().dirty);
1859
    fs::write(&p, b"f\n").unwrap();
1860
    // Push, then a second clone commits and pushes: we are behind.
1861
    assert!(a.push("origin", false).unwrap()[0].ok);
1862
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
1863
    let b = Repo::clone(&url, &root.join("b"))
1864
        .unwrap()
1865
        .with_home(root.join("home-b"));
1866
    write(&root.join("b"), "g.txt", b"g\n");
1867
    b.commit("g", &[]).unwrap();
1868
    b.push("origin", false).unwrap();
1869
    a.fetch("origin").unwrap();
1870
    let info = a.quick_status().unwrap();
1871
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1872
    assert_eq!(info.format("%A%D"), "-1");
1873
    let _ = origin;
1874
}
1875
1876
#[test]
1877
fn lazy_blobs_are_fetched_on_first_read() {
1878
    hermetic();
1879
    let dir = tempfile::tempdir().unwrap();
1880
    let root = dir.path();
1881
    let origin_dir = root.join("origin");
1882
    let origin = Repo::init(&origin_dir)
1883
        .unwrap()
1884
        .with_home(root.join("home"));
1885
    let url = origin_dir.to_string_lossy().to_string();
1886
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1887
    write(&origin_dir, "big.bin", &big);
1888
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1889
    write(&origin_dir, "t.txt", b"t\n");
1890
    let h = origin.commit("blobs", &[]).unwrap();
1891
    let big_ref = Repo::blob_ref(&big);
1892
1893
    // Fetch only (no checkout) with a filter: the big blob stays absent.
1894
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1895
        .unwrap()
1896
        .with_home(root.join("home"));
1897
    let a = {
1898
        let mut a = a;
1899
        a.config.set("remote.origin.url", &url).unwrap();
1900
        a.config.set("filter.max-blob", "100K").unwrap();
1901
        a.save_config().unwrap();
1902
        a
1903
    };
1904
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1905
    a.fetch("origin").unwrap();
1906
    assert!(a.store().has(&h));
1907
    assert!(!a.store().has(&big_ref), "withheld");
1908
    assert!(
1909
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1910
        "small blob came along"
1911
    );
1912
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1913
1914
    // status and commit do not need it: adopt the state, edit a text file, commit.
1915
    let (op_ref, op) = a.head_op().unwrap();
1916
    let mut view = op.view.clone();
1917
    view.bookmarks.insert(
1918
        "main".into(),
1919
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1920
    );
1921
    a.record_op(&[op_ref], "adopt", view).unwrap();
1922
    // Checkout reads the blob lazily, which fetches it.
1923
    a.checkout(&[h], true, "checkout").unwrap();
1924
    assert!(a.store().has(&big_ref), "fetched on first read");
1925
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1926
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1927
    write(&root.join("a"), "t.txt", b"t2\n");
1928
    a.commit("text edit", &[]).unwrap();
1929
1930
    // clone --max-blob records the filter; the checkout fetches lazily.
1931
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
1932
    assert_eq!(b.config.max_blob, Some(1024));
1933
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1934
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1935
    assert!(parse_size("lots").is_err());
1936
}
1937
1938
#[test]
1939
fn sparse_checkout_materializes_only_chosen_paths() {
1940
    hermetic();
1941
    let dir = tempfile::tempdir().unwrap();
1942
    let root = dir.path();
1943
    let origin_dir = root.join("origin");
1944
    let origin = Repo::init(&origin_dir)
1945
        .unwrap()
1946
        .with_home(root.join("home"));
1947
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1948
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1949
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1950
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1951
    write(&origin_dir, "docs/logo.png", &logo);
1952
    write(&origin_dir, "README.md", b"# top\n");
1953
    let h1 = origin.commit("tree", &[]).unwrap();
1954
    let url = origin_dir.to_string_lossy().to_string();
1955
1956
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
1957
        .unwrap()
1958
        .with_home(root.join("home"));
1959
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1960
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1961
    assert!(root.join("a/src/main.rs").exists());
1962
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
1963
    assert!(
1964
        !a.store().has(&Repo::blob_ref(&logo)),
1965
        "out-of-scope blob never fetched"
1966
    );
1967
    assert!(
1968
        !a.snapshot("status").unwrap().changed,
1969
        "out-of-scope files are not removals"
1970
    );
1971
    assert!(!a.quick_status().unwrap().dirty);
1972
1973
    // Edits in scope commit normally and keep the rest of the tree intact.
1974
    write(
1975
        &root.join("a"),
1976
        "src/lib.rs",
1977
        b"pub fn a() {}\npub fn b() {}\n",
1978
    );
1979
    let h2 = a.commit("edit lib", &[]).unwrap();
1980
    let st = a.load_state(&[h2]).unwrap().materialize();
1981
    assert!(
1982
        st.files.contains_key("docs/guide.md"),
1983
        "the state still has everything"
1984
    );
1985
    assert!(a.push("origin", false).unwrap()[0].ok);
1986
    // Files created outside the scope are ignored by status.
1987
    write(&root.join("a"), "docs/new.md", b"ignored\n");
1988
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
1989
1990
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
1991
    let mut a = a;
1992
    a.config.set("filter.paths", "src,docs").unwrap();
1993
    a.save_config().unwrap();
1994
    let r = a
1995
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
1996
        .unwrap();
1997
    assert!(r.written >= 2);
1998
    assert_eq!(
1999
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2000
        logo,
2001
        "now fetched lazily"
2002
    );
2003
    assert!(!root.join("a/README.md").exists());
2004
    // Origin sees the change made under a sparse checkout with the full tree intact.
2005
    origin.pull("origin").err();
2006
    let full = origin
2007
        .load_state(&origin.bookmark_heads().unwrap())
2008
        .unwrap()
2009
        .materialize();
2010
    assert!(
2011
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2012
    );
2013
    assert!(full.files.contains_key("README.md"));
2014
    let _ = h1;
2015
}
2016
2017
#[test]
2018
fn shallow_clone_and_deepen() {
2019
    hermetic();
2020
    let dir = tempfile::tempdir().unwrap();
2021
    let root = dir.path();
2022
    let origin_dir = root.join("origin");
2023
    let origin = Repo::init(&origin_dir)
2024
        .unwrap()
2025
        .with_home(root.join("home"));
2026
    let mut hashes = Vec::new();
2027
    for i in 0..8 {
2028
        write(
2029
            &origin_dir,
2030
            "a.txt",
2031
            format!(
2032
                "{}\n",
2033
                (0..=i)
2034
                    .map(|k| k.to_string())
2035
                    .collect::<Vec<_>>()
2036
                    .join("\n")
2037
            )
2038
            .as_bytes(),
2039
        );
2040
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2041
    }
2042
    let url = origin_dir.to_string_lossy().to_string();
2043
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2044
        .unwrap()
2045
        .with_home(root.join("home"));
2046
    assert!(a.is_shallow());
2047
    assert_eq!(
2048
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2049
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2050
    );
2051
    assert!(
2052
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2053
        "three levels present"
2054
    );
2055
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2056
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2057
    assert_eq!(
2058
        a.log().unwrap().len(),
2059
        9,
2060
        "the log shows every change from the checkpoint's metadata"
2061
    );
2062
    assert!(!a.snapshot("status").unwrap().changed);
2063
    assert_eq!(a.quick_status().unwrap().heads, 1);
2064
2065
    // Work continues on top of the shallow history and pushes back.
2066
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2067
    let h_new = a.commit("c8", &[]).unwrap();
2068
    assert!(a.push("origin", false).unwrap()[0].ok);
2069
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2070
    // Fetching new work from origin into the shallow clone works too.
2071
    write(&origin_dir, "b.txt", b"b\n");
2072
    origin.pull("origin").err();
2073
    let (_, wc) = origin.working_copy().unwrap();
2074
    let _ = wc;
2075
    origin
2076
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2077
        .unwrap();
2078
    write(&origin_dir, "b.txt", b"b\n");
2079
    let h_b = origin.commit("b", &[]).unwrap();
2080
    let pr = a.pull("origin").unwrap();
2081
    assert!(pr.changed);
2082
    assert!(a.store().has(&h_b));
2083
    assert!(root.join("a/b.txt").exists());
2084
2085
    // Deepening fetches older history until the boundary is gone.
2086
    // Every commit also depends on the change that created the file, so two
2087
    // levels below the boundary hold h4, h3, and the root.
2088
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2089
    assert!(a.store().has(&hashes[3]));
2090
    assert!(a.is_shallow());
2091
    a.deepen("origin", 100).unwrap();
2092
    assert!(!a.is_shallow(), "boundary reached the root");
2093
    assert!(a.store().has(&hashes[0]));
2094
    assert_eq!(
2095
        a.load_state_full(&a.bookmark_heads().unwrap())
2096
            .unwrap()
2097
            .len(),
2098
        10
2099
    );
2100
}
2101
2102
#[test]
2103
fn tags_are_immutable_named_states_and_travel() {
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 mut a = Repo::clone(&url, &root.join("a"))
2110
        .unwrap()
2111
        .with_home(root.join("home-a"));
2112
    let (key_a, _) = a
2113
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2114
        .unwrap();
2115
    write(&root.join("a"), "f.txt", b"1\n");
2116
    let h1 = a.commit("one", &[]).unwrap();
2117
    write(&root.join("a"), "f.txt", b"1\n2\n");
2118
    let h2 = a.commit("two", &[]).unwrap();
2119
2120
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2121
    assert_eq!(
2122
        (t.heads.clone(), t.signer.as_deref()),
2123
        (vec![h1], Some("Ada"))
2124
    );
2125
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2126
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2127
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2128
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2129
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2130
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2131
    assert_eq!(sa.sigs[0].key, key_a);
2132
    // Checkout by tag.
2133
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2134
        .unwrap();
2135
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2136
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2137
        .unwrap();
2138
2139
    // Push carries the tag; a second attestation for the name is refused.
2140
    let r = a.push("origin", false).unwrap();
2141
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2142
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2143
    let mut forged = a
2144
        .tag_refs()
2145
        .unwrap()
2146
        .into_iter()
2147
        .find(|t| t.name == "v1")
2148
        .unwrap();
2149
    forged.state = origin
2150
        .store()
2151
        .put_state(&StateObject::new(vec![h2]))
2152
        .unwrap();
2153
    forged.heads = vec![h2];
2154
    forged.attestation = None;
2155
    let r = origin
2156
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2157
        .unwrap();
2158
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2159
2160
    // A clone gets the tag; a later tag arrives on fetch.
2161
    let b = Repo::clone(&url, &root.join("b"))
2162
        .unwrap()
2163
        .with_home(root.join("home-b"));
2164
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2165
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2166
    a.tag_create("v2", &[h2], "second").unwrap();
2167
    a.push("origin", false).unwrap();
2168
    let rep = b.fetch("origin").unwrap();
2169
    assert_eq!(rep.new_tags, 1);
2170
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2171
2172
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2173
    a.policy_init().unwrap();
2174
    a.push("origin", false).unwrap();
2175
    let unattested = crate::protocol::TagRef {
2176
        name: "v3".into(),
2177
        state: origin
2178
            .store()
2179
            .put_state(&StateObject::new(vec![h2]))
2180
            .unwrap(),
2181
        heads: vec![h2],
2182
        attestation: None,
2183
    };
2184
    let r = origin
2185
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2186
        .unwrap();
2187
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2188
    a.tag_create("v3", &[h2], "").unwrap();
2189
    let r = a.push("origin", false).unwrap();
2190
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2191
    assert!(a.gc(true).is_ok());
2192
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2193
}
2194
2195
#[test]
2196
fn multiple_workspaces_share_a_repository() {
2197
    hermetic();
2198
    let dir = tempfile::tempdir().unwrap();
2199
    let root = dir.path();
2200
    let main_dir = root.join("main");
2201
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2202
    write(&main_dir, "a.txt", b"a\n");
2203
    let h1 = repo.commit("a", &[]).unwrap();
2204
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2205
2206
    // A second workspace elsewhere, checked out on the bookmark.
2207
    let ws_dir = root.join("ws2");
2208
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2209
    assert!(ws_dir.join(".oxy").is_file());
2210
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2211
    assert_ne!(ws.workspace(), repo.workspace());
2212
    let list = repo.workspaces().unwrap();
2213
    assert_eq!(list.len(), 2);
2214
    assert!(list
2215
        .iter()
2216
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2217
    assert!(!ws.snapshot("status").unwrap().changed);
2218
2219
    // Work in the second workspace: its own working copy, shared bookmark.
2220
    write(&ws_dir, "b.txt", b"b\n");
2221
    let s = ws.snapshot("status").unwrap();
2222
    assert_eq!(s.statuses.len(), 1);
2223
    assert!(
2224
        !repo.snapshot("status").unwrap().changed,
2225
        "the first workspace is untouched"
2226
    );
2227
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2228
    let mut heads = repo.bookmark_heads().unwrap();
2229
    heads.sort();
2230
    let mut want = vec![h1, h2];
2231
    want.sort();
2232
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2233
    assert!(!main_dir.join("b.txt").exists());
2234
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2235
        .unwrap();
2236
    assert!(main_dir.join("b.txt").exists());
2237
2238
    // Reopening from inside the second workspace finds the shared repository.
2239
    let reopened = Repo::open(&ws_dir).unwrap();
2240
    assert_eq!(reopened.workspace(), ws.workspace());
2241
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2242
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2243
2244
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2245
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2246
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2247
    repo.workspace_forget(&ws.workspace()).unwrap();
2248
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2249
    assert!(ws_dir.join("b.txt").exists());
2250
    assert!(
2251
        ws.snapshot("status").is_err(),
2252
        "a forgotten workspace is no longer in the view"
2253
    );
2254
2255
    // The working-copy lock: re-entrant in a thread; a lock whose process
2256
    // is gone is taken over, and a live process's is not, however old.
2257
    let lock = repo.lock_snapshot().unwrap();
2258
    let again = repo.lock_working_copy().unwrap();
2259
    drop(again);
2260
    drop(lock);
2261
    let lock_path = main_dir
2262
        .join(".oxy/workspaces")
2263
        .join(repo.workspace().to_hex())
2264
        .join("lock");
2265
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2266
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2267
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2268
    age(&lock_path);
2269
    assert!(
2270
        !super::workspace::lock_is_stale(&lock_path),
2271
        "a live process keeps its lock"
2272
    );
2273
    fs::write(&lock_path, "4294967295").unwrap();
2274
    age(&lock_path);
2275
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2276
}
2277
2278
#[test]
2279
fn attributes_binary_eol_nocompress_lockable() {
2280
    hermetic();
2281
    let dir = tempfile::tempdir().unwrap();
2282
    let root = dir.path();
2283
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2284
    write(
2285
        root,
2286
        ".oxyattributes",
2287
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2288
    );
2289
    write(root, "plain.dat", b"no nul bytes here\n");
2290
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2291
    write(root, "assets/model.bin", b"\0model");
2292
    let h = repo.commit("attrs", &[]).unwrap();
2293
    let snap = repo.load_state(&[h]).unwrap().materialize();
2294
    assert!(
2295
        snap.files["plain.dat"].mode.opaque,
2296
        "binary attribute forces opaque without NUL bytes"
2297
    );
2298
    assert!(
2299
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2300
        "stored with LF"
2301
    );
2302
    assert!(
2303
        !repo.snapshot("status").unwrap().changed,
2304
        "CRLF on disk equals LF in the state"
2305
    );
2306
    // nocompress chunks pack raw.
2307
    let r = repo.gc(true).unwrap();
2308
    assert!(r.packed.objects > 0);
2309
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2310
    fs::remove_file(root.join("notes.txt")).unwrap();
2311
    repo.checkout(&[h], true, "co").unwrap();
2312
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2313
    assert!(fs::metadata(root.join("assets/model.bin"))
2314
        .unwrap()
2315
        .permissions()
2316
        .readonly());
2317
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2318
    repo.lock_path("assets/model.bin").unwrap();
2319
    assert!(!fs::metadata(root.join("assets/model.bin"))
2320
        .unwrap()
2321
        .permissions()
2322
        .readonly());
2323
    assert!(repo.is_locked("assets/model.bin"));
2324
    write(root, "assets/model.bin", b"\0model2");
2325
    repo.commit("edit model", &[]).unwrap();
2326
    repo.unlock_path("assets/model.bin").unwrap();
2327
    assert!(fs::metadata(root.join("assets/model.bin"))
2328
        .unwrap()
2329
        .permissions()
2330
        .readonly());
2331
    // A later checkout can still overwrite a read-only lockable file.
2332
    repo.checkout(&[h], true, "co").unwrap();
2333
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2334
}
2335
2336
#[cfg(unix)]
2337
#[test]
2338
fn hooks_can_veto_observe_and_add_dependencies() {
2339
    use std::os::unix::fs::PermissionsExt;
2340
    hermetic();
2341
    let dir = tempfile::tempdir().unwrap();
2342
    let root = dir.path();
2343
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2344
    let hooks = root.join(".oxy/hooks");
2345
    fs::create_dir_all(&hooks).unwrap();
2346
    let hook = |name: &str, body: &str| {
2347
        let p = hooks.join(name);
2348
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2349
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2350
    };
2351
    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");
2352
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2353
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2354
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2355
    write(root, ".oxyignore", b".last-*\n");
2356
    write(root, "a.txt", b"a\n");
2357
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2358
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2359
    let h1 = repo.commit("first", &[]).unwrap();
2360
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2361
    assert!(
2362
        pre.contains("\"event\":\"pre-commit\"")
2363
            && pre.contains("\"path\":\"a.txt\"")
2364
            && pre.contains("\"message\":\"first\""),
2365
        "{pre}"
2366
    );
2367
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2368
    assert!(post.contains(&h1.to_hex()), "{post}");
2369
    repo.checkout(&[h1], false, "co").unwrap();
2370
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2371
        .unwrap()
2372
        .contains("post-checkout"));
2373
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2374
    repo.save_config().unwrap();
2375
    let err = repo.push("origin", false).unwrap_err().to_string();
2376
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2377
2378
    // semantic-deps: only when enabled; adds an explicit dependency.
2379
    write(root, "b.txt", b"b\n");
2380
    hook(
2381
        "semantic-deps",
2382
        &format!(
2383
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2384
            h1.to_hex()
2385
        ),
2386
    );
2387
    let h2 = repo.commit("b without hook", &[]).unwrap();
2388
    assert!(
2389
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2390
        "hook disabled by default"
2391
    );
2392
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2393
    repo.save_config().unwrap();
2394
    write(root, "c.txt", b"c\n");
2395
    let h3 = repo.commit("c with hook", &[]).unwrap();
2396
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2397
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2398
    assert!(
2399
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2400
        "{sem}"
2401
    );
2402
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2403
}
2404
2405
#[test]
2406
fn amend_into_older_change_and_split() {
2407
    hermetic();
2408
    let dir = tempfile::tempdir().unwrap();
2409
    let root = dir.path();
2410
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2411
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2412
        .unwrap();
2413
    repo.set_user_config("core.sign", "change").unwrap();
2414
    write(root, "a.txt", b"one\ntwo\n");
2415
    let h0 = repo.commit("base", &[]).unwrap();
2416
    write(root, "a.txt", b"one\nTWO\n");
2417
    let h1 = repo.commit("edit two", &[]).unwrap();
2418
    write(root, "a.txt", b"one\nTWO\nthree\n");
2419
    let h2 = repo.commit("add three", &[]).unwrap();
2420
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2421
2422
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2423
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2424
    let h1b = repo.amend_into(&h1, None).unwrap();
2425
    assert_ne!(h1b, h1);
2426
    let c1b = repo.store().get_change(&h1b).unwrap();
2427
    assert_eq!(c1b.change_id, id1);
2428
    assert_eq!(c1b.deps, vec![h0]);
2429
    assert!(matches!(
2430
        repo.verify_change(&h1b).unwrap(),
2431
        SignatureStatus::Valid { .. }
2432
    ));
2433
    let heads = repo.bookmark_heads().unwrap();
2434
    assert_eq!(heads.len(), 1);
2435
    let top = repo.store().get_change(&heads[0]).unwrap();
2436
    assert_eq!(top.message, "add three");
2437
    assert_eq!(
2438
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2439
        [h0, h1b].into_iter().collect(),
2440
        "depends on the file's creator and the rewritten line"
2441
    );
2442
    let snap = repo.load_state(&heads).unwrap().materialize();
2443
    assert!(
2444
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2445
    );
2446
    assert!(
2447
        !repo.snapshot("status").unwrap().changed,
2448
        "the working copy is clean after folding"
2449
    );
2450
    // Only h1b's own state shows the fix without "three".
2451
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2452
    assert!(
2453
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2454
    );
2455
    assert_eq!(repo.log().unwrap().len(), 4);
2456
2457
    // An edit to a line introduced by h2 cannot fold into h1.
2458
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2459
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2460
    assert!(err.contains("introduced after"), "{err}");
2461
    assert!(
2462
        repo.snapshot("status").unwrap().statuses.len() == 1,
2463
        "nothing was changed by the refusal"
2464
    );
2465
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2466
2467
    // Split the head that touches two files.
2468
    write(root, "b.txt", b"b\n");
2469
    write(root, "c.txt", b"c\n");
2470
    let h3 = repo.commit("b and c", &[]).unwrap();
2471
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2472
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2473
    let c_1 = repo.store().get_change(&p1).unwrap();
2474
    let c_2 = repo.store().get_change(&p2).unwrap();
2475
    assert!(c_1.message.contains("part 1: b.txt"));
2476
    assert_eq!(c_2.change_id, id3);
2477
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2478
    assert!(
2479
        heads.contains(&p1) && heads.contains(&p2),
2480
        "independent parts are both heads"
2481
    );
2482
    let snap = repo
2483
        .load_state(&repo.bookmark_heads().unwrap())
2484
        .unwrap()
2485
        .materialize();
2486
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2487
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2488
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2489
    assert!(!repo.snapshot("status").unwrap().changed);
2490
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2491
    let _ = h2;
2492
}
2493
2494
#[test]
2495
fn identity_lifecycle() {
2496
    hermetic();
2497
    let dir = tempfile::tempdir().unwrap();
2498
    let root = dir.path();
2499
    let origin = Repo::init(&root.join("origin")).unwrap();
2500
    let url = root.join("origin").to_string_lossy().to_string();
2501
    let mut a = Repo::clone(&url, &root.join("a"))
2502
        .unwrap()
2503
        .with_home(root.join("home-a"));
2504
    a.set_user_config("core.sign", "change").unwrap();
2505
    let (key_a, _) = a
2506
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2507
        .unwrap();
2508
    write(&root.join("a"), "a.txt", b"a\n");
2509
    let h1 = a.commit("one", &[]).unwrap();
2510
    assert!(a.policy_init().unwrap().applied);
2511
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2512
2513
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2514
    let mut e = Repo::init(&root.join("e"))
2515
        .unwrap()
2516
        .with_home(root.join("home-e"));
2517
    e.set_user_config("core.sign", "change").unwrap();
2518
    e.create_identity_with(
2519
        "Eve",
2520
        "[email protected]",
2521
        IdentityScope::User,
2522
        Some(Hlc::now().wall_ms - 1),
2523
    )
2524
    .unwrap();
2525
    write(&root.join("e"), "e.txt", b"e\n");
2526
    let he = e.commit("late", &[]).unwrap();
2527
    assert!(
2528
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2529
    );
2530
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2531
    let r = e
2532
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2533
        .unwrap();
2534
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2535
    write(&root.join("e"), "e.txt", b"e2\n");
2536
    let he2 = e.commit("in time", &[]).unwrap();
2537
    assert!(
2538
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2539
    );
2540
2541
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2542
    let r = a.rotate_identity().unwrap();
2543
    assert_eq!(r.old, key_a);
2544
    assert_eq!(a.config.author_key, Some(r.new));
2545
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2546
    assert!(r.policy.as_ref().unwrap().applied);
2547
    let (_, sp) = a.current_policy().unwrap().unwrap();
2548
    assert_eq!(
2549
        (sp.policy.serial, sp.policy.roots.clone()),
2550
        (2, vec![r.new])
2551
    );
2552
    assert!(
2553
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2554
        "superseded, not revoked"
2555
    );
2556
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2557
    assert!(
2558
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2559
    );
2560
    write(&root.join("a"), "a.txt", b"a2\n");
2561
    let h2 = a.commit("two", &[]).unwrap();
2562
    assert!(
2563
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2564
    );
2565
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2566
    let res = a.push("origin", false).unwrap();
2567
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2568
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2569
    let key_a = r.new;
2570
2571
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2572
    // identity object, so Ada's KeyId changes while her keys stay the same.
2573
    let mut b = Repo::clone(&url, &root.join("b"))
2574
        .unwrap()
2575
        .with_home(root.join("home-b"));
2576
    let (key_b, id_b) = b
2577
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2578
        .unwrap();
2579
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
2580
    assert_eq!(r.old, key_a);
2581
    let key_a2 = r.new;
2582
    assert_eq!(
2583
        a.identity(&key_a2).unwrap().delegates,
2584
        vec![Delegate::full(key_b)]
2585
    );
2586
    assert_eq!(
2587
        a.identity(&key_a2).unwrap().ed25519_pk,
2588
        a.identity(&key_a).unwrap().ed25519_pk
2589
    );
2590
    assert!(
2591
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2592
        "already a delegate"
2593
    );
2594
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2595
    write(&root.join("a"), "a.txt", b"a3\n");
2596
    let h3 = a.commit("three", &[]).unwrap();
2597
    assert!(
2598
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2599
        "the same secret signs under the new KeyId"
2600
    );
2601
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2602
    a.set_user_config("core.sign", "seal").unwrap();
2603
    write(&root.join("a"), "a.txt", b"a4\n");
2604
    let h4 = a.commit("four", &[]).unwrap();
2605
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2606
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2607
    a.store()
2608
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2609
        .unwrap();
2610
    assert!(
2611
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2612
    );
2613
    a.set_user_config("core.sign", "change").unwrap();
2614
    // Withdrawing the delegation re-issues the identity again.
2615
    let r = a.delegate_remove(&key_b).unwrap();
2616
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2617
    assert!(a.delegate_remove(&key_b).is_err());
2618
    let key_a3 = r.new;
2619
    let res = a.push("origin", false).unwrap();
2620
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2621
2622
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2623
    // both applied under the old threshold of 1. A grant then needs Bob too.
2624
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2625
    assert!(a.policy_root_add(id_b.clone()).is_err());
2626
    assert!(a.policy_set_threshold(3).is_err());
2627
    assert!(a.policy_set_threshold(2).unwrap().applied);
2628
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2629
    b.pull("origin").unwrap();
2630
    assert_eq!(
2631
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2632
        2
2633
    );
2634
    let mut c = Repo::init(&root.join("c"))
2635
        .unwrap()
2636
        .with_home(root.join("home-c"));
2637
    let (key_c, id_c) = c
2638
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2639
        .unwrap();
2640
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2641
    let proposal = a.policy_grant(id_c, None).unwrap();
2642
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2643
    assert_eq!(proposal.policy.serial, serial_before + 1);
2644
    assert_eq!(
2645
        a.current_policy().unwrap().unwrap().1.policy.serial,
2646
        serial_before,
2647
        "a proposal changes nothing yet"
2648
    );
2649
    // Bob signs the proposal, handed over as a file, and it applies for him.
2650
    let bytes = proposal.signed().encode();
2651
    let signed = b
2652
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2653
        .unwrap();
2654
    assert!(signed.applied && signed.sigs.len() == 2);
2655
    assert!(b
2656
        .current_policy()
2657
        .unwrap()
2658
        .unwrap()
2659
        .1
2660
        .policy
2661
        .authorizes(&key_c, "main"));
2662
    assert!(
2663
        b.policy_sign(signed.signed()).is_err(),
2664
        "a stale proposal is refused"
2665
    );
2666
    // Bob publishes it and Ada picks it up.
2667
    assert!(b
2668
        .push("origin", false)
2669
        .unwrap()
2670
        .iter()
2671
        .any(|x| x.name == "policy" && x.ok));
2672
    a.pull("origin").unwrap();
2673
    assert_eq!(
2674
        a.current_policy().unwrap().unwrap().1.policy.serial,
2675
        serial_before + 1
2676
    );
2677
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2678
    assert!(a.policy_revoke(&key_a3).is_err());
2679
    let u = a
2680
        .revoke_identity(&key_c, "left the project")
2681
        .unwrap()
2682
        .unwrap();
2683
    assert!(!u.applied);
2684
    assert!(a.is_revoked(&key_c).unwrap());
2685
    assert!(!b.is_revoked(&key_c).unwrap());
2686
    let u = b.policy_sign(u.signed()).unwrap();
2687
    assert!(u.applied && u.policy.is_revoked(&key_c));
2688
    assert!(b.is_revoked(&key_c).unwrap());
2689
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2690
    assert!(
2691
        b.policy_revoke(&key_a3).is_err(),
2692
        "would leave one root for a threshold of 2"
2693
    );
2694
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2695
    let key_c_own = c.config.author_key.unwrap();
2696
    assert!(c
2697
        .revoke_identity(&key_c_own, "lost laptop")
2698
        .unwrap()
2699
        .is_none());
2700
    assert!(c.is_revoked(&key_c_own).unwrap());
2701
    assert_eq!(key_c_own, key_c);
2702
}
2703
2704
#[test]
2705
fn renames_are_detected_and_tracked_as_moves() {
2706
    hermetic();
2707
    let dir = tempfile::tempdir().unwrap();
2708
    let root = dir.path();
2709
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2710
    write(
2711
        root,
2712
        "src/old.rs",
2713
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2714
    );
2715
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2716
    write(root, "tiny.txt", b"x\n");
2717
    let h1 = repo.commit("base", &[]).unwrap();
2718
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2719
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2720
2721
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2722
    // that shares nothing with the removed file.
2723
    fs::remove_file(root.join("src/old.rs")).unwrap();
2724
    write(
2725
        root,
2726
        "lib/new.rs",
2727
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2728
    );
2729
    fs::remove_file(root.join("img.bin")).unwrap();
2730
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2731
    fs::remove_file(root.join("tiny.txt")).unwrap();
2732
    write(root, "other.txt", b"completely different\n");
2733
    let snap = repo.snapshot("status").unwrap();
2734
    let statuses: Vec<(&str, ChangeStatus)> = snap
2735
        .statuses
2736
        .iter()
2737
        .map(|s| (s.path.as_str(), s.status))
2738
        .collect();
2739
    assert_eq!(
2740
        statuses,
2741
        vec![
2742
            ("assets/img.bin", ChangeStatus::Renamed),
2743
            ("lib/new.rs", ChangeStatus::Renamed),
2744
            ("other.txt", ChangeStatus::Added),
2745
            ("src", ChangeStatus::Removed),
2746
            ("tiny.txt", ChangeStatus::Removed)
2747
        ]
2748
    );
2749
    let h2 = repo.commit("move things", &[]).unwrap();
2750
    let c = repo.store().get_change(&h2).unwrap();
2751
    let moves: Vec<_> = c
2752
        .tree_ops
2753
        .iter()
2754
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2755
        .collect();
2756
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
2757
    assert!(c.tree_ops.iter().any(
2758
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2759
    ));
2760
    assert!(c.tree_ops.iter().any(
2761
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2762
    ));
2763
    let snap = repo.load_state(&[h2]).unwrap().materialize();
2764
    assert_eq!(
2765
        snap.files["lib/new.rs"].node, node_old,
2766
        "the node survives the rename"
2767
    );
2768
    assert!(
2769
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2770
    );
2771
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
2772
    assert!(render_change(
2773
        &c,
2774
        &repo.load_state(&[h1]).unwrap(),
2775
        &repo.load_state(&[h1]).unwrap().materialize()
2776
    )
2777
    .contains("R "));
2778
    // A fresh checkout reproduces the tree.
2779
    let other = tempfile::tempdir().unwrap();
2780
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
2781
    assert_eq!(
2782
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2783
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2784
    );
2785
    assert!(!other.path().join("src").exists());
2786
    assert!(!clone.snapshot("status").unwrap().changed);
2787
    // Similarity is line based, byte weighted.
2788
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2789
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2790
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2791
    assert_eq!(similarity(b"", b"x\n"), 0);
2792
}
2793
2794
#[test]
2795
fn git_fetch_and_push_round_trip() {
2796
    hermetic();
2797
    if std::process::Command::new("git")
2798
        .arg("--version")
2799
        .output()
2800
        .is_err()
2801
    {
2802
        eprintln!("git not installed; skipping");
2803
        return;
2804
    }
2805
    let dir = tempfile::tempdir().unwrap();
2806
    let root = dir.path();
2807
    let git_in = |d: &Path, args: &[&str]| -> String {
2808
        let out = std::process::Command::new("git")
2809
            .arg("-C")
2810
            .arg(d)
2811
            .args([
2812
                "-c",
2813
                "user.name=Grace",
2814
                "-c",
2815
                "[email protected]",
2816
                "-c",
2817
                "commit.gpgsign=false",
2818
            ])
2819
            .args(args)
2820
            .output()
2821
            .unwrap();
2822
        assert!(
2823
            out.status.success(),
2824
            "git {args:?}: {}",
2825
            String::from_utf8_lossy(&out.stderr)
2826
        );
2827
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2828
    };
2829
    // A bare "remote" and a work tree that pushes to it.
2830
    let remote = root.join("remote.git");
2831
    fs::create_dir_all(&remote).unwrap();
2832
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2833
    let work = root.join("work");
2834
    git_in(
2835
        root,
2836
        &[
2837
            "clone",
2838
            "-q",
2839
            remote.to_str().unwrap(),
2840
            work.to_str().unwrap(),
2841
        ],
2842
    );
2843
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2844
    write(&work, "README.md", b"# Project\n");
2845
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2846
    git_in(&work, &["add", "."]);
2847
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2848
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2849
    git_in(&work, &["commit", "-q", "-am", "second"]);
2850
    git_in(&work, &["push", "-q", "origin", "main"]);
2851
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2852
2853
    // Fetch into a fresh oxy repository.
2854
    let o = root.join("oxy");
2855
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
2856
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2857
        .unwrap();
2858
    let url = remote.to_string_lossy().to_string();
2859
    let r = repo.git_fetch(&url, "main").unwrap();
2860
    assert_eq!((r.commits, r.heads), (2, 1));
2861
    assert_eq!(
2862
        fs::read(o.join("src/lib.rs")).unwrap(),
2863
        b"pub fn a() {}\npub fn b() {}\n"
2864
    );
2865
    assert!(!repo.snapshot("status").unwrap().changed);
2866
    assert_eq!(
2867
        repo.git_fetch(&url, "main").unwrap().commits,
2868
        0,
2869
        "nothing new"
2870
    );
2871
2872
    // An oxy change, pushed back: one commit on top of the Git tip.
2873
    write(
2874
        &o,
2875
        "src/lib.rs",
2876
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2877
    );
2878
    write(&o, "NOTES.md", b"from oxy\n");
2879
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2880
    let r = repo.git_push(&url, "main").unwrap();
2881
    assert_eq!(r.exported, 1, "{r:?}");
2882
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2883
    assert_eq!(
2884
        git_in(&work, &["log", "--format=%s", "main"]),
2885
        "add c and notes\nsecond\ninitial"
2886
    );
2887
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2888
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2889
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
2890
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2891
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2892
    assert_eq!(
2893
        repo.git_push(&url, "main").unwrap().exported,
2894
        0,
2895
        "already pushed"
2896
    );
2897
2898
    // Git moves on; pushing without fetching is refused, fetching brings
2899
    // the commit in and the working copy follows.
2900
    write(&work, "README.md", b"# Project\n\nMore.\n");
2901
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2902
    git_in(&work, &["push", "-q", "origin", "main"]);
2903
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
2904
    assert!(repo
2905
        .git_push(&url, "main")
2906
        .unwrap_err()
2907
        .to_string()
2908
        .contains("fetch"));
2909
    let r = repo.git_fetch(&url, "main").unwrap();
2910
    assert_eq!(
2911
        (r.commits, r.heads),
2912
        (1, 2),
2913
        "the Git change and the oxy change commute"
2914
    );
2915
    assert_eq!(
2916
        fs::read(o.join("README.md")).unwrap(),
2917
        b"# Project\n\nMore.\n"
2918
    );
2919
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2920
    assert!(!repo.snapshot("status").unwrap().changed);
2921
    // Another oxy change pushes on top of Git's newest commit.
2922
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2923
    repo.commit("notes again", &[]).unwrap();
2924
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2925
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2926
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
2927
    assert_eq!(
2928
        fs::read(work.join("NOTES.md")).unwrap(),
2929
        b"from oxy\nagain\n"
2930
    );
2931
    assert_eq!(
2932
        git_in(&work, &["log", "--format=%s", "main"])
2933
            .lines()
2934
            .count(),
2935
        5
2936
    );
2937
}
2938
2939
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2940
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2941
#[test]
2942
#[ignore]
2943
fn bench_one_gibibyte_file() {
2944
    hermetic();
2945
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2946
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2947
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2948
        None => tempfile::tempdir().unwrap(),
2949
    };
2950
    let root = dir.path();
2951
    let repo = Repo::init(&root.join("r"))
2952
        .unwrap()
2953
        .with_home(root.join("home"));
2954
    let size = 1usize << 30;
2955
    let mut data = vec![0u8; size];
2956
    let mut x = 0x9e3779b97f4a7c15u64;
2957
    for chunk in data.chunks_mut(8) {
2958
        x ^= x << 13;
2959
        x ^= x >> 7;
2960
        x ^= x << 17;
2961
        let b = x.to_le_bytes();
2962
        chunk.copy_from_slice(&b[..chunk.len()]);
2963
    }
2964
    let t = std::time::Instant::now();
2965
    write(&root.join("r"), "big.bin", &data);
2966
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
2967
    let t = std::time::Instant::now();
2968
    let h = repo.commit("big", &[]).unwrap();
2969
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
2970
    let t = std::time::Instant::now();
2971
    assert!(!repo.snapshot("status").unwrap().changed);
2972
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
2973
    let t = std::time::Instant::now();
2974
    let objects = repo.store().list().unwrap().len();
2975
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
2976
    let t = std::time::Instant::now();
2977
    let g = repo.gc(true).unwrap();
2978
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
2979
    let t = std::time::Instant::now();
2980
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
2981
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
2982
    let t = std::time::Instant::now();
2983
    let back = fs::read(root.join("c/big.bin")).unwrap();
2984
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
2985
    eprintln!("read back and verify: {:.2?}", t.elapsed());
2986
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
2987
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
2988
    eprintln!(
2989
        "store size: {:.1} MiB for 1 GiB of data",
2990
        store_bytes as f64 / (1024.0 * 1024.0)
2991
    );
2992
}
2993
2994
fn walkdir_size(p: &Path) -> u64 {
2995
    let mut total = 0;
2996
    if let Ok(rd) = fs::read_dir(p) {
2997
        for e in rd.flatten() {
2998
            let path = e.path();
2999
            if path.is_dir() {
3000
                total += walkdir_size(&path);
3001
            } else if let Ok(m) = fs::metadata(&path) {
3002
                total += m.len();
3003
            }
3004
        }
3005
    }
3006
    total
3007
}
3008
3009
/// An opaque file whose size and mtime match the manifest is not read on
3010
/// the next snapshot: its blob comes from the manifest's stat cache.
3011
#[cfg(unix)]
3012
#[test]
3013
fn stat_cache_skips_reading_unchanged_opaque_files() {
3014
    use std::os::unix::fs::PermissionsExt;
3015
    hermetic();
3016
    let dir = tempfile::tempdir().unwrap();
3017
    let root = dir.path();
3018
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3019
    let mut big = vec![0u8; 300 * 1024];
3020
    for (i, b) in big.iter_mut().enumerate() {
3021
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3022
    }
3023
    big[0] = 0;
3024
    write(root, "big.bin", &big);
3025
    write(root, "a.txt", b"text\n");
3026
    let h1 = repo.commit("base", &[]).unwrap();
3027
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3028
    assert!(
3029
        m.entries["big.bin"].blob.is_some(),
3030
        "opaque files record their blob"
3031
    );
3032
    assert!(m.entries["a.txt"].blob.is_none());
3033
    let blob = m.entries["big.bin"].blob.unwrap();
3034
    assert!(repo.store().has(&blob));
3035
3036
    // Files modified within two seconds of the manifest are racy and still
3037
    // read; age the file so the cache applies, then snapshot to record it.
3038
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3039
    fs::File::options()
3040
        .write(true)
3041
        .open(root.join("big.bin"))
3042
        .unwrap()
3043
        .set_modified(old)
3044
        .unwrap();
3045
    assert!(!repo.snapshot("status").unwrap().changed);
3046
    // Now the file cannot be read at all; the snapshot succeeds without it.
3047
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3048
    let snap = repo.snapshot("status").unwrap();
3049
    assert!(
3050
        !snap.changed && snap.statuses.is_empty(),
3051
        "{:?}",
3052
        snap.statuses
3053
    );
3054
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3055
    // A real change (new mtime, new content) is seen and committed correctly.
3056
    let mut big2 = big.clone();
3057
    big2[10] ^= 0xff;
3058
    write(root, "big.bin", &big2);
3059
    let snap = repo.snapshot("status").unwrap();
3060
    assert_eq!(
3061
        snap.statuses
3062
            .iter()
3063
            .map(|s| (s.path.as_str(), s.status))
3064
            .collect::<Vec<_>>(),
3065
        vec![("big.bin", ChangeStatus::Modified)]
3066
    );
3067
    let h2 = repo.commit("edit", &[]).unwrap();
3068
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3069
    assert_eq!(
3070
        files["big.bin"].content,
3071
        FileContent::Opaque {
3072
            blobs: vec![Repo::blob_ref(&big2)]
3073
        }
3074
    );
3075
    // Checkout writes a manifest with blobs too, so the next status is cached.
3076
    repo.checkout(&[h1], false, "checkout").unwrap();
3077
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3078
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3079
    assert!(!repo.snapshot("status").unwrap().changed);
3080
}
3081
3082
#[test]
3083
fn status_json_lists_conflicts_with_contributors() {
3084
    hermetic();
3085
    let dir = tempfile::tempdir().unwrap();
3086
    let root = dir.path();
3087
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3088
    write(root, "a.txt", b"one\n");
3089
    let h1 = repo.commit("base", &[]).unwrap();
3090
    write(root, "a.txt", b"one\nleft\n");
3091
    let ha = repo.commit("left", &[]).unwrap();
3092
    repo.checkout(&[h1], true, "checkout").unwrap();
3093
    write(root, "a.txt", b"one\nright\n");
3094
    let hb = repo.commit("right", &[]).unwrap();
3095
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3096
    let snap = repo.snapshot("status").unwrap();
3097
    assert!(snap.base_snapshot.is_conflicted());
3098
    let json = repo.status_json(&snap).unwrap();
3099
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3100
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3101
    assert!(json.contains("\"conflicted\":true"), "{json}");
3102
    assert!(
3103
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3104
        "{json}"
3105
    );
3106
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3107
    assert!(json.contains("\"resolved\":false"), "{json}");
3108
    assert!(json.starts_with('{') && json.ends_with('}'));
3109
    // Resolve and the report says so; a clean copy has no conflicts.
3110
    write(root, "a.txt", b"one\nleft\nright\n");
3111
    let snap = repo.snapshot("status").unwrap();
3112
    let json = repo.status_json(&snap).unwrap();
3113
    assert!(json.contains("\"resolved\":true"), "{json}");
3114
    repo.commit("resolve", &[]).unwrap();
3115
    let snap = repo.snapshot("status").unwrap();
3116
    let json = repo.status_json(&snap).unwrap();
3117
    assert!(
3118
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3119
        "{json}"
3120
    );
3121
}
3122
3123
#[test]
3124
fn ignore_rules_do_not_untrack_files() {
3125
    hermetic();
3126
    let dir = tempfile::tempdir().unwrap();
3127
    let root = dir.path();
3128
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3129
    write(root, "src.c", b"int x;\n");
3130
    write(root, "build/out.o", b"\0obj");
3131
    write(root, "sub/keep.log", b"keep\n");
3132
    write(root, "sub/junk.log", b"junk\n");
3133
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3134
    let snap = repo.snapshot("status").unwrap();
3135
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3136
    assert_eq!(
3137
        added,
3138
        vec![".oxyignore", "src.c", "sub/keep.log"],
3139
        "anchored, glob, and negated rules"
3140
    );
3141
    let h1 = repo.commit("base", &[]).unwrap();
3142
    // Ignoring a tracked file changes nothing about it.
3143
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3144
    let snap = repo.snapshot("status").unwrap();
3145
    assert_eq!(
3146
        snap.statuses
3147
            .iter()
3148
            .map(|s| s.path.as_str())
3149
            .collect::<Vec<_>>(),
3150
        vec![".oxyignore"]
3151
    );
3152
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3153
    assert!(repo
3154
        .load_state(&[h2])
3155
        .unwrap()
3156
        .materialize()
3157
        .files
3158
        .contains_key("src.c"));
3159
    // Its edits are still seen, by status and by the prompt.
3160
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3161
    write(root, "src.c", b"int x, y;\n");
3162
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3163
    let snap = repo.snapshot("status").unwrap();
3164
    assert_eq!(
3165
        snap.statuses
3166
            .iter()
3167
            .map(|s| (s.path.as_str(), s.status))
3168
            .collect::<Vec<_>>(),
3169
        vec![("src.c", ChangeStatus::Modified)]
3170
    );
3171
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3172
    assert!(
3173
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3174
    );
3175
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3176
    fs::remove_file(root.join("src.c")).unwrap();
3177
    let snap = repo.snapshot("status").unwrap();
3178
    assert_eq!(
3179
        snap.statuses
3180
            .iter()
3181
            .map(|s| (s.path.as_str(), s.status))
3182
            .collect::<Vec<_>>(),
3183
        vec![("src.c", ChangeStatus::Removed)]
3184
    );
3185
    repo.checkout(&[h3], true, "checkout").unwrap();
3186
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3187
    assert!(!repo.snapshot("status").unwrap().changed);
3188
    let _ = h1;
3189
}
3190
3191
#[test]
3192
fn split_works_on_non_heads_by_node() {
3193
    hermetic();
3194
    let dir = tempfile::tempdir().unwrap();
3195
    let root = dir.path();
3196
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3197
    write(root, "a.txt", b"one\n");
3198
    write(root, "junk/x.lock", b"lock\n");
3199
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3200
    write(root, "a.txt", b"one\ntwo\n");
3201
    let h2 = repo.commit("more work", &[]).unwrap();
3202
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3203
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3204
    // h1 is not a head: split it by node.
3205
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3206
    assert_ne!(h1b, h1);
3207
    assert_eq!(
3208
        repo.store().get_change(&h1b).unwrap().change_id,
3209
        id1,
3210
        "the rest keeps the ChangeId"
3211
    );
3212
    let junk = repo.store().get_change(&hj).unwrap();
3213
    assert!(junk.tree_ops.iter().all(
3214
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3215
    ));
3216
    let heads = repo.bookmark_heads().unwrap();
3217
    assert!(
3218
        heads.contains(&hj),
3219
        "the split-off part is a head of its own"
3220
    );
3221
    let snap = repo.load_state(&heads).unwrap().materialize();
3222
    assert!(
3223
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3224
        "the dependent was rewritten onto the new hash"
3225
    );
3226
    assert!(snap.files.contains_key("junk/x.lock"));
3227
    let h2b = heads
3228
        .iter()
3229
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3230
        .copied()
3231
        .unwrap();
3232
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3233
    assert!(!repo.snapshot("status").unwrap().changed);
3234
    // Abandoning the split-off head removes the junk from history.
3235
    repo.abandon(&hj).unwrap();
3236
    let heads = repo.bookmark_heads().unwrap();
3237
    let snap = repo.load_state(&heads).unwrap().materialize();
3238
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3239
    assert!(snap.files.contains_key("a.txt"));
3240
    // A dependent that touches the split-off paths blocks the split.
3241
    write(root, "junk/y.lock", b"y\n");
3242
    let hb = repo.commit("junk base", &[]).unwrap();
3243
    write(root, "junk/y.lock", b"yy\n");
3244
    write(root, "b.txt", b"b\n");
3245
    repo.commit("touches junk", &[]).unwrap();
3246
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3247
    assert!(err.contains("depends on the split-off paths"), "{err}");
3248
}
3249
3250
#[test]
3251
fn bookmarks_switch_merge_and_push() {
3252
    hermetic();
3253
    let dir = tempfile::tempdir().unwrap();
3254
    let root = dir.path();
3255
    let origin = Repo::init(&root.join("origin")).unwrap();
3256
    let url = root.join("origin").to_string_lossy().to_string();
3257
    let mut repo = Repo::clone(&url, &root.join("r"))
3258
        .unwrap()
3259
        .with_home(root.join("home"));
3260
    let r = root.join("r");
3261
    write(&r, "a.txt", b"a\n");
3262
    let h_a = repo.commit("a", &[]).unwrap();
3263
    assert!(repo.push("origin", false).unwrap()[0].ok);
3264
3265
    // A bookmark at the working copy's base, then work on it.
3266
    assert!(repo.bookmark_create("bad name..", None).is_err());
3267
    assert!(repo.bookmark_create("-x", None).is_err());
3268
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3269
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3270
    repo.bookmark_switch("feature", false).unwrap();
3271
    assert_eq!(repo.config.bookmark, "feature");
3272
    write(&r, "a.txt", b"a\nb\n");
3273
    write(&r, "b.txt", b"b\n");
3274
    let h_b = repo.commit("b on feature", &[]).unwrap();
3275
    assert_eq!(
3276
        repo.bookmark_heads().unwrap(),
3277
        vec![h_b],
3278
        "b edits a.txt, so it depends on a"
3279
    );
3280
    assert_eq!(
3281
        repo.resolve_heads("main").unwrap(),
3282
        vec![h_a],
3283
        "main is untouched"
3284
    );
3285
    assert_eq!(
3286
        repo.resolve_change("feature").unwrap(),
3287
        h_b,
3288
        "a one-head bookmark names its change"
3289
    );
3290
    // Reopening keeps the workspace's bookmark.
3291
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3292
    assert_eq!(reopened.config.bookmark, "feature");
3293
    // Back to main: b.txt goes away; work there.
3294
    repo.bookmark_switch("main", false).unwrap();
3295
    assert!(!r.join("b.txt").exists());
3296
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3297
    write(&r, "c.txt", b"c\n");
3298
    let h_c = repo.commit("c on main", &[]).unwrap();
3299
    let list = repo.bookmarks().unwrap();
3300
    assert_eq!(
3301
        list.iter()
3302
            .map(|b| (b.name.as_str(), b.current))
3303
            .collect::<Vec<_>>(),
3304
        vec![("feature", false), ("main", true)]
3305
    );
3306
    assert_eq!(
3307
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3308
        Some(1),
3309
        "c is not on origin yet"
3310
    );
3311
    // Merge feature into main: the union, both heads, no merge change.
3312
    let m = repo.merge("feature").unwrap();
3313
    assert!(m.changed && m.checked_out);
3314
    let mut want = vec![h_b, h_c];
3315
    want.sort();
3316
    assert_eq!(m.heads, want);
3317
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3318
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3319
    assert!(repo.merge("main").is_err());
3320
    // The other bookmark can be pushed by name and appears at origin.
3321
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3322
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3323
    assert!(repo.push("origin", false).unwrap()[0].ok);
3324
    assert_eq!(
3325
        repo.bookmarks()
3326
            .unwrap()
3327
            .iter()
3328
            .find(|b| b.name == "main")
3329
            .unwrap()
3330
            .ahead,
3331
        Some(0)
3332
    );
3333
    // A second workspace inherits the current bookmark and can switch independently.
3334
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3335
    assert_eq!(ws.config.bookmark, "main");
3336
    let mut ws = ws;
3337
    ws.bookmark_switch("feature", false).unwrap();
3338
    assert_eq!(
3339
        Repo::open(&r).unwrap().config.bookmark,
3340
        "main",
3341
        "the first workspace is unaffected"
3342
    );
3343
    assert!(
3344
        repo.bookmark_delete("feature").is_err(),
3345
        "current bookmark of another workspace"
3346
    );
3347
    ws.bookmark_switch("main", false).unwrap();
3348
    // Set and delete.
3349
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3350
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3351
    repo.bookmark_delete("feature").unwrap();
3352
    assert!(repo.resolve_heads("feature").is_err());
3353
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3354
    assert!(
3355
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3356
        "changes of a deleted bookmark remain"
3357
    );
3358
}
3359
3360
#[test]
3361
fn oxygen_subrepos_pin_follow_and_update() {
3362
    hermetic();
3363
    let dir = tempfile::tempdir().unwrap();
3364
    let root = dir.path();
3365
    // A library repository with two commits, and a bare-ish origin for it.
3366
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3367
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3368
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3369
        .unwrap()
3370
        .with_home(root.join("home"));
3371
    write(&root.join("lib"), "lib.txt", b"v1\n");
3372
    let l1 = lib.commit("lib v1", &[]).unwrap();
3373
    assert!(lib.push("origin", false).unwrap()[0].ok);
3374
    let _ = lib_origin;
3375
3376
    // The application (a clone of its own origin) adds it as a subrepo.
3377
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3378
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3379
    let _ = app_origin;
3380
    let app_dir = root.join("app");
3381
    let app = Repo::clone(&app_url, &app_dir)
3382
        .unwrap()
3383
        .with_home(root.join("home"));
3384
    write(&app_dir, "main.txt", b"app\n");
3385
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3386
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3387
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3388
    let snap = app.snapshot("status").unwrap();
3389
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3390
    assert_eq!(
3391
        paths,
3392
        vec![".oxymodules", "libs/lib", "main.txt"],
3393
        "the nested files are not walked"
3394
    );
3395
    let a1 = app.commit("app with lib", &[]).unwrap();
3396
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3397
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3398
    assert!(!files.contains_key("libs/lib/lib.txt"));
3399
    assert!(!app.snapshot("status").unwrap().changed);
3400
    let subs = app.subrepos().unwrap();
3401
    assert_eq!(subs.len(), 1);
3402
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3403
3404
    // Advance the nested repository: the parent sees a modified pin.
3405
    let nested = Repo::open(&app_dir.join("libs/lib"))
3406
        .unwrap()
3407
        .with_home(root.join("home"));
3408
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3409
    let l2 = nested.commit("lib v2", &[]).unwrap();
3410
    assert!(nested.push("origin", false).unwrap()[0].ok);
3411
    let snap = app.snapshot("status").unwrap();
3412
    assert_eq!(
3413
        snap.statuses
3414
            .iter()
3415
            .map(|s| (s.path.as_str(), s.status))
3416
            .collect::<Vec<_>>(),
3417
        vec![("libs/lib", ChangeStatus::Modified)]
3418
    );
3419
    let a2 = app.commit("bump lib", &[]).unwrap();
3420
    // Checking out the older app state brings the nested working copy back
3421
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3422
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3423
    assert!(
3424
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3425
        "{:?}",
3426
        r.notes
3427
    );
3428
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3429
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3430
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3431
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3432
    assert!(!app.snapshot("status").unwrap().changed);
3433
    // A dirty nested repository is left alone and reported.
3434
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3435
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3436
    assert!(
3437
        r.notes.iter().any(|n| n.contains("uncommitted")),
3438
        "{:?}",
3439
        r.notes
3440
    );
3441
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3442
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3443
    let r = app.submodule_update(false, &[]).unwrap();
3444
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3445
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3446
    let _ = l2;
3447
3448
    // A fresh clone of the app has the pin but no nested repository until update --init.
3449
    assert!(app.push("origin", false).unwrap()[0].ok);
3450
    let clone_dir = root.join("app-clone");
3451
    let clone = Repo::clone(&app_url, &clone_dir)
3452
        .unwrap()
3453
        .with_home(root.join("home"));
3454
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3455
    assert_eq!(
3456
        clone.submodule_update(false, &[]).unwrap(),
3457
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3458
    );
3459
    assert_eq!(
3460
        clone.submodule_update(true, &[]).unwrap(),
3461
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3462
    );
3463
    assert_eq!(
3464
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3465
        b"v2\n"
3466
    );
3467
    assert!(!clone.snapshot("status").unwrap().changed);
3468
    // Removing the subrepo leaves the directory and drops the node.
3469
    clone.submodule_remove("libs/lib").unwrap();
3470
    let snap = clone.snapshot("status").unwrap();
3471
    assert!(
3472
        snap.statuses
3473
            .iter()
3474
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3475
        "{:?}",
3476
        snap.statuses
3477
    );
3478
    let c = clone.commit("drop lib", &[]).unwrap();
3479
    assert!(!clone
3480
        .load_state(&[c])
3481
        .unwrap()
3482
        .materialize()
3483
        .files
3484
        .contains_key("libs/lib"));
3485
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3486
    assert!(
3487
        !clone.snapshot("status").unwrap().changed,
3488
        "an unregistered nested repository is ignored"
3489
    );
3490
}
3491
3492
#[test]
3493
fn git_submodules_import_and_export_as_gitlinks() {
3494
    hermetic();
3495
    if std::process::Command::new("git")
3496
        .arg("--version")
3497
        .output()
3498
        .is_err()
3499
    {
3500
        eprintln!("git not installed; skipping");
3501
        return;
3502
    }
3503
    let dir = tempfile::tempdir().unwrap();
3504
    let root = dir.path();
3505
    let git_in = |d: &Path, args: &[&str]| -> String {
3506
        let out = std::process::Command::new("git")
3507
            .arg("-C")
3508
            .arg(d)
3509
            .args([
3510
                "-c",
3511
                "user.name=Grace",
3512
                "-c",
3513
                "[email protected]",
3514
                "-c",
3515
                "commit.gpgsign=false",
3516
                "-c",
3517
                "protocol.file.allow=always",
3518
            ])
3519
            .args(args)
3520
            .output()
3521
            .unwrap();
3522
        assert!(
3523
            out.status.success(),
3524
            "git {args:?}: {}",
3525
            String::from_utf8_lossy(&out.stderr)
3526
        );
3527
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3528
    };
3529
    let sub = root.join("sub");
3530
    fs::create_dir_all(&sub).unwrap();
3531
    git_in(&sub, &["init", "-q", "-b", "main"]);
3532
    write(&sub, "s.txt", b"sub\n");
3533
    git_in(&sub, &["add", "."]);
3534
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3535
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3536
    let g = root.join("main.git");
3537
    fs::create_dir_all(&g).unwrap();
3538
    git_in(&g, &["init", "-q", "-b", "main"]);
3539
    write(&g, "README.md", b"# app\n");
3540
    git_in(&g, &["add", "."]);
3541
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3542
    git_in(
3543
        &g,
3544
        &[
3545
            "submodule",
3546
            "add",
3547
            "-q",
3548
            sub.to_str().unwrap(),
3549
            "vendor/sub",
3550
        ],
3551
    );
3552
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3553
3554
    let dest = root.join("oxy");
3555
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3556
    let rep = repo.import_git(&g, "main").unwrap();
3557
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3558
    let files = repo
3559
        .load_state(&repo.bookmark_heads().unwrap())
3560
        .unwrap()
3561
        .materialize()
3562
        .files;
3563
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3564
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3565
        panic!()
3566
    };
3567
    assert_eq!(
3568
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3569
        crate::subrepo::Pin::Git {
3570
            sha: sub_sha.clone(),
3571
            branch: "HEAD".into()
3572
        }
3573
    );
3574
    let modules =
3575
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3576
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3577
    assert!(modules.entries["vendor/sub"].git);
3578
    assert!(
3579
        files.contains_key(".gitmodules"),
3580
        "the Git file is kept for round trips"
3581
    );
3582
    assert!(
3583
        !dest.join("vendor/sub/.git").exists(),
3584
        "not cloned until update --init"
3585
    );
3586
    assert!(!repo.snapshot("status").unwrap().changed);
3587
    // update --init clones it at the pinned commit; status is unchanged.
3588
    assert_eq!(
3589
        repo.submodule_update(true, &[]).unwrap(),
3590
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3591
    );
3592
    assert_eq!(
3593
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3594
        sub_sha
3595
    );
3596
    assert!(!repo.snapshot("status").unwrap().changed);
3597
    // Export writes the gitlink and .gitmodules back.
3598
    let mirror = root.join("mirror.git");
3599
    let rep = repo.git_export(&mirror).unwrap();
3600
    assert_eq!(rep.skipped_subrepos, 0);
3601
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3602
    assert!(
3603
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3604
        "{ls}"
3605
    );
3606
    assert_eq!(
3607
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3608
        ".gitmodules\nREADME.md\nvendor"
3609
    );
3610
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3611
    assert_eq!(
3612
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3613
        orig_tree,
3614
        "tree round trip"
3615
    );
3616
}
3617
3618
#[test]
3619
fn partial_commits_by_path_and_by_hunk() {
3620
    hermetic();
3621
    let dir = tempfile::tempdir().unwrap();
3622
    let root = dir.path();
3623
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3624
    write(root, "a.txt", b"1\n2\n3\n");
3625
    write(root, "b.txt", b"b\n");
3626
    let h0 = repo.commit("base", &[]).unwrap();
3627
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3628
    write(root, "b.txt", b"b\nbb\n");
3629
    write(root, "c.txt", b"c\n");
3630
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3631
    let h1 = repo
3632
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3633
        .unwrap();
3634
    let c1 = repo.store().get_change(&h1).unwrap();
3635
    assert!(
3636
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3637
        "{:?}",
3638
        c1.tree_ops
3639
    );
3640
    assert_eq!(c1.deps, vec![h0]);
3641
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3642
    assert!(
3643
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3644
    );
3645
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3646
    assert!(!files.contains_key("c.txt"));
3647
    let snap = repo.snapshot("status").unwrap();
3648
    assert_eq!(
3649
        snap.statuses
3650
            .iter()
3651
            .map(|s| (s.path.as_str(), s.status))
3652
            .collect::<Vec<_>>(),
3653
        vec![
3654
            ("b.txt", ChangeStatus::Modified),
3655
            ("c.txt", ChangeStatus::Added)
3656
        ]
3657
    );
3658
    assert_eq!(
3659
        fs::read(root.join("b.txt")).unwrap(),
3660
        b"b\nbb\n",
3661
        "disk untouched"
3662
    );
3663
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3664
    let (_, hunks) = repo.hunks().unwrap();
3665
    let b_hunk = hunks
3666
        .iter()
3667
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3668
        .unwrap()
3669
        .index;
3670
    let h2 = repo
3671
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3672
        .unwrap();
3673
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3674
    assert!(
3675
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3676
    );
3677
    assert!(!files.contains_key("c.txt"));
3678
    let snap = repo.snapshot("status").unwrap();
3679
    assert_eq!(
3680
        snap.statuses
3681
            .iter()
3682
            .map(|s| s.path.as_str())
3683
            .collect::<Vec<_>>(),
3684
        vec!["c.txt"]
3685
    );
3686
    // Choosing only the content hunk of a file in a new directory pulls in
3687
    // the directory and file additions it needs.
3688
    write(root, "d/e.txt", b"e\n");
3689
    let (_, hunks) = repo.hunks().unwrap();
3690
    let e_insert = hunks
3691
        .iter()
3692
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3693
        .unwrap()
3694
        .index;
3695
    let h3 = repo
3696
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3697
        .unwrap();
3698
    let c3 = repo.store().get_change(&h3).unwrap();
3699
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3700
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3701
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3702
    // Choosing a new file's addition hunk brings its content along.
3703
    write(root, "f/g.txt", b"g\n");
3704
    let (_, hunks) = repo.hunks().unwrap();
3705
    let g_add = hunks
3706
        .iter()
3707
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3708
        .unwrap()
3709
        .index;
3710
    let h4 = repo
3711
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3712
        .unwrap();
3713
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
3714
    assert!(
3715
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3716
    );
3717
    assert!(!repo
3718
        .snapshot("status")
3719
        .unwrap()
3720
        .statuses
3721
        .iter()
3722
        .any(|s| s.path == "f/g.txt"));
3723
    // Everything left commits normally; the working copy is then clean.
3724
    repo.commit("the rest", &[]).unwrap();
3725
    assert!(!repo.snapshot("status").unwrap().changed);
3726
    let files = repo
3727
        .load_state(&repo.bookmark_heads().unwrap())
3728
        .unwrap()
3729
        .materialize()
3730
        .files;
3731
    assert!(files.contains_key("c.txt"));
3732
}
3733
3734
#[test]
3735
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3736
    hermetic();
3737
    let dir = tempfile::tempdir().unwrap();
3738
    let root = dir.path();
3739
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3740
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3741
        .unwrap();
3742
    write(root, "a.txt", b"one\n");
3743
    let h1 = repo.commit("first", &[]).unwrap();
3744
    write(root, "a.txt", b"one\ntwo\n");
3745
    let h2 = repo.commit("second", &[]).unwrap();
3746
    let b = repo.blame("a.txt").unwrap();
3747
    assert_eq!(
3748
        b.iter()
3749
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3750
            .collect::<Vec<_>>(),
3751
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3752
    );
3753
    assert!(b.iter().all(|l| l.author == "Ada"));
3754
    assert_eq!(
3755
        b[0].change_id,
3756
        repo.store().get_change(&h1).unwrap().change_id
3757
    );
3758
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3759
    repo.commit("rename", &[]).unwrap();
3760
    let b = repo.blame("b.txt").unwrap();
3761
    assert_eq!(
3762
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3763
        vec![h1, h2],
3764
        "the node survives the rename"
3765
    );
3766
    assert!(repo.blame("a.txt").is_err());
3767
}
3768
3769
#[test]
3770
fn bisect_finds_the_first_bad_change() {
3771
    hermetic();
3772
    let dir = tempfile::tempdir().unwrap();
3773
    let root = dir.path();
3774
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3775
    let mut content = String::new();
3776
    let mut hashes = Vec::new();
3777
    for i in 1..=8 {
3778
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3779
        write(root, "f.txt", content.as_bytes());
3780
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3781
    }
3782
    // Each step appends after the previous line, so the chain is linear.
3783
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3784
    repo.bisect_start().unwrap();
3785
    assert!(matches!(
3786
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3787
        BisectStep::NeedMarks { good: 1, bad: 0 }
3788
    ));
3789
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3790
    assert!(
3791
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3792
        "{step:?}"
3793
    );
3794
    // Automated: bad when the bug line is present.
3795
    let step = repo
3796
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3797
        .unwrap();
3798
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3799
    assert_eq!(
3800
        repo.bisect_status().unwrap(),
3801
        Some(BisectStep::Found { culprit: hashes[4] })
3802
    );
3803
    repo.bisect_reset().unwrap();
3804
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3805
    assert!(repo.bisect_status().unwrap().is_none());
3806
    assert!(!repo.snapshot("status").unwrap().changed);
3807
    // Manual marks and a skip.
3808
    repo.bisect_start().unwrap();
3809
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3810
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3811
    let mut skipped_once = false;
3812
    let mut guard = 0;
3813
    while let BisectStep::Testing { .. } = step {
3814
        guard += 1;
3815
        assert!(guard < 20);
3816
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3817
        if !skipped_once && text.contains("line 6") {
3818
            // An untestable state away from the boundary: the search routes around it.
3819
            skipped_once = true;
3820
            step = repo.bisect_mark(None, &[]).unwrap();
3821
            continue;
3822
        }
3823
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3824
    }
3825
    assert!(skipped_once);
3826
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3827
    repo.bisect_reset().unwrap();
3828
    // Skipping the culprit itself leaves it among the candidates reported.
3829
    repo.bisect_start().unwrap();
3830
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3831
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3832
    let mut guard = 0;
3833
    while let BisectStep::Testing { heads, .. } = &step {
3834
        guard += 1;
3835
        assert!(guard < 20);
3836
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3837
        let is_culprit_state =
3838
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3839
        step = if is_culprit_state {
3840
            repo.bisect_mark(None, &[]).unwrap()
3841
        } else {
3842
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3843
        };
3844
    }
3845
    match step {
3846
        BisectStep::Inconclusive { candidates } => assert!(
3847
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3848
            "{candidates:?}"
3849
        ),
3850
        other => panic!("{other:?}"),
3851
    }
3852
    repo.bisect_reset().unwrap();
3853
}
3854
3855
#[test]
3856
fn squash_folds_a_change_into_its_dependency() {
3857
    hermetic();
3858
    let dir = tempfile::tempdir().unwrap();
3859
    let root = dir.path();
3860
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3861
    write(root, "a.txt", b"1\n");
3862
    let a = repo.commit("A", &[]).unwrap();
3863
    write(root, "a.txt", b"1\n2\n");
3864
    let c = repo.commit("C", &[]).unwrap();
3865
    write(root, "a.txt", b"1\n2\n3\n");
3866
    let e = repo.commit("E", &[]).unwrap();
3867
    write(root, "b.txt", b"b\n");
3868
    let b = repo.commit("B", &[]).unwrap();
3869
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3870
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3871
    // E depends on C which A lacks: refused, naming it.
3872
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3873
    assert!(err.contains(&c.short(12)), "{err}");
3874
    // C into A: A' has both, C is gone, E follows and still reads the same.
3875
    let a2 = repo.squash(&c, &a).unwrap();
3876
    let a2c = repo.store().get_change(&a2).unwrap();
3877
    assert_eq!(a2c.change_id, id_a);
3878
    assert!(a2c.deps.is_empty());
3879
    let heads = repo.bookmark_heads().unwrap();
3880
    let st = repo.load_state(&heads).unwrap();
3881
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
3882
    let e2 = st
3883
        .changes()
3884
        .find(|(_, m)| m.change_id == id_e)
3885
        .map(|(h, _)| *h)
3886
        .unwrap();
3887
    assert_eq!(
3888
        repo.store().get_change(&e2).unwrap().deps,
3889
        vec![a2],
3890
        "E now depends on A' alone"
3891
    );
3892
    let files = st.materialize().files;
3893
    assert!(
3894
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3895
    );
3896
    assert!(files.contains_key("b.txt"));
3897
    assert!(st.contains(&b));
3898
    assert!(!repo.snapshot("status").unwrap().changed);
3899
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3900
    // Undo restores the three original changes.
3901
    repo.undo().unwrap();
3902
    repo.undo().unwrap();
3903
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3904
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3905
}
3906
3907
#[test]
3908
fn rebase_re_expresses_a_change_against_another_base() {
3909
    hermetic();
3910
    let dir = tempfile::tempdir().unwrap();
3911
    let root = dir.path();
3912
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3913
    write(root, "a.txt", b"1\n2\n");
3914
    let a = repo.commit("A", &[]).unwrap();
3915
    write(root, "a.txt", b"1\n2\n3\n");
3916
    let c = repo.commit("C: append 3", &[]).unwrap();
3917
    write(root, "a.txt", b"1\n2\n3\n4\n");
3918
    let e = repo.commit("E: append 4", &[]).unwrap();
3919
    // A different base: A plus a change that prepends a line.
3920
    repo.checkout(&[a], true, "checkout").unwrap();
3921
    write(root, "a.txt", b"0\n1\n2\n");
3922
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3923
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3924
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3925
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3926
    let c2 = repo.rebase(&c, &[d]).unwrap();
3927
    let c2c = repo.store().get_change(&c2).unwrap();
3928
    assert_eq!(c2c.change_id, id_c);
3929
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3930
    let heads = repo.bookmark_heads().unwrap();
3931
    let st = repo.load_state(&heads).unwrap();
3932
    assert!(!st.contains(&c) && st.contains(&d));
3933
    let e2 = st
3934
        .changes()
3935
        .find(|(_, m)| m.change_id == id_e)
3936
        .map(|(h, _)| *h)
3937
        .unwrap();
3938
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
3939
    assert!(
3940
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3941
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3942
    );
3943
    let files = st.materialize().files;
3944
    assert!(
3945
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3946
        "{:?}",
3947
        files["a.txt"].content
3948
    );
3949
    assert!(!files["a.txt"].is_conflicted());
3950
    // Rebasing onto a state that already contains the change is refused.
3951
    assert!(repo.rebase(&c2, &[c2]).is_err());
3952
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
3953
    assert!(
3954
        err.contains("lacks dependencies"),
3955
        "E needs C, which D's state does not have: {err}"
3956
    );
3957
}
3958
3959
#[test]
3960
fn unsigned_tags_keep_their_message() {
3961
    hermetic();
3962
    let dir = tempfile::tempdir().unwrap();
3963
    let root = dir.path();
3964
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3965
    write(root, "a.txt", b"a\n");
3966
    repo.commit("a", &[]).unwrap();
3967
    assert!(repo.secret_key().unwrap().is_none());
3968
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
3969
        .unwrap();
3970
    let tags = repo.tags().unwrap();
3971
    assert_eq!(
3972
        (
3973
            tags[0].name.as_str(),
3974
            tags[0].message.as_str(),
3975
            tags[0].signer.as_deref()
3976
        ),
3977
        ("v1", "first release", None)
3978
    );
3979
    assert!(
3980
        repo.tag_refs().unwrap()[0].attestation.is_none(),
3981
        "an unsigned attestation is not advertised"
3982
    );
3983
}
3984
3985
#[test]
3986
fn fsck_passes_a_sound_repository_and_names_each_fault() {
3987
    // Files on disk are what this tests: tampering with them, and the
3988
    // directory store's crash points.
3989
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
3990
        return;
3991
    }
3992
    hermetic();
3993
    let dir = tempfile::tempdir().unwrap();
3994
    let root = dir.path();
3995
    let origin_path = root.join("origin");
3996
    let origin = Repo::init(&origin_path).unwrap();
3997
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
3998
        .unwrap()
3999
        .with_home(root.join("home-a"));
4000
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4001
        .unwrap();
4002
    write(&root.join("a"), "f.txt", b"one\n");
4003
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4004
    let h1 = a.commit("first", &[]).unwrap();
4005
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4006
    let h2 = a.commit("second", &[]).unwrap();
4007
    a.tag_create("v1", &[h2], "first release").unwrap();
4008
    a.checkpoint().unwrap();
4009
    assert!(a.push("origin", false).unwrap()[0].ok);
4010
4011
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4012
    for repo in [&a, &origin] {
4013
        let rep = repo.fsck().unwrap();
4014
        assert_eq!(rep.problems, vec![], "{rep:?}");
4015
        // The two commits, plus the working copy's change in `a`.
4016
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4017
        assert!(rep.ops > 1 && rep.objects > 5);
4018
    }
4019
    assert!(origin.fsck().unwrap().attestations >= 1);
4020
4021
    // A flipped byte in a stored object is corruption, named by hash.
4022
    let c1 = a.store().path_for(&h1);
4023
    let pristine = fs::read(&c1).unwrap();
4024
    let mut bytes = pristine.clone();
4025
    *bytes.last_mut().unwrap() ^= 1;
4026
    fs::write(&c1, &bytes).unwrap();
4027
    let rep = a.fsck().unwrap();
4028
    assert!(rep.errors() >= 1);
4029
    assert!(
4030
        rep.problems
4031
            .iter()
4032
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4033
        "{rep:?}"
4034
    );
4035
    fs::write(&c1, &pristine).unwrap();
4036
    assert_eq!(a.fsck().unwrap().errors(), 0);
4037
4038
    // A missing change is named with what needed it.
4039
    fs::remove_file(&c1).unwrap();
4040
    let rep = a.fsck().unwrap();
4041
    assert!(
4042
        rep.problems.iter().any(|p| p.severity == Severity::Error
4043
            && p.object == Some(h1)
4044
            && p.what.contains("change missing, needed by change")),
4045
        "{rep:?}"
4046
    );
4047
    fs::write(&c1, &pristine).unwrap();
4048
4049
    // A missing blob is an error in a full clone.
4050
    let c2 = a.store().get_change(&h1).unwrap();
4051
    let blob = c2
4052
        .edits
4053
        .iter()
4054
        .find_map(|e| match e {
4055
            Edit::Replace { new: Some(b), .. } => Some(*b),
4056
            _ => None,
4057
        })
4058
        .expect("the binary file is a blob");
4059
    let bp = a.store().path_for(&blob);
4060
    let blob_bytes = fs::read(&bp).unwrap();
4061
    fs::remove_file(&bp).unwrap();
4062
    let rep = a.fsck().unwrap();
4063
    assert!(
4064
        rep.problems
4065
            .iter()
4066
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4067
        "{rep:?}"
4068
    );
4069
    fs::write(&bp, &blob_bytes).unwrap();
4070
4071
    // A broken op log head is reported, not a crash.
4072
    let head = root.join("a/.oxy/ops/head");
4073
    let saved = fs::read(&head).unwrap();
4074
    fs::write(&head, b"not a hash").unwrap();
4075
    let rep = a.fsck().unwrap();
4076
    assert!(
4077
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4078
        "{rep:?}"
4079
    );
4080
    fs::write(&head, saved).unwrap();
4081
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4082
}
4083
4084
/// Copy a directory tree (for restoring a pristine repository).
4085
fn copy_tree(from: &Path, to: &Path) {
4086
    fs::create_dir_all(to).unwrap();
4087
    for e in fs::read_dir(from).unwrap() {
4088
        let e = e.unwrap();
4089
        let target = to.join(e.file_name());
4090
        if e.file_type().unwrap().is_dir() {
4091
            copy_tree(&e.path(), &target);
4092
        } else {
4093
            fs::copy(e.path(), &target).unwrap();
4094
        }
4095
    }
4096
}
4097
4098
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4099
/// would, and check that both repositories still open, pass `fsck`, and
4100
/// accept the same operation again.
4101
#[test]
4102
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4103
    // Files on disk are what this tests: tampering with them, and the
4104
    // directory store's crash points.
4105
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4106
        return;
4107
    }
4108
    use crate::durable::failpoint;
4109
    hermetic();
4110
    let dir = tempfile::tempdir().unwrap();
4111
    let pristine = dir.path().join("pristine");
4112
    let origin_path = pristine.join("origin");
4113
    Repo::init(&origin_path).unwrap();
4114
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4115
        .unwrap()
4116
        .with_home(dir.path().join("home"));
4117
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4118
        .unwrap();
4119
    write(&pristine.join("a"), "f.txt", b"one\n");
4120
    a.commit("first", &[]).unwrap();
4121
    assert!(a.push("origin", false).unwrap()[0].ok);
4122
    drop(a);
4123
4124
    type Op = fn(&Repo) -> Result<()>;
4125
    let edit_and_commit: Op = |r| {
4126
        write(r.root(), "f.txt", b"one\ntwo\n");
4127
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4128
        r.commit("second", &[]).map(|_| ())
4129
    };
4130
    let push: Op = |r| {
4131
        let res = r.push("origin", false)?;
4132
        if res.iter().all(|x| x.ok) {
4133
            Ok(())
4134
        } else {
4135
            Err(RepoError::Msg(format!("{res:?}")))
4136
        }
4137
    };
4138
4139
    for (name, prepare, op) in [
4140
        ("commit", None, edit_and_commit),
4141
        ("push", Some(edit_and_commit), push),
4142
    ] {
4143
        let mut steps = 0;
4144
        for n in 1.. {
4145
            let run = dir.path().join(format!("{name}-{n}"));
4146
            copy_tree(&pristine, &run);
4147
            // Clones record their remote by path; point it at this copy.
4148
            let open = |p: &Path| {
4149
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4150
                r.config
4151
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4152
                    .unwrap();
4153
                r.save_config().unwrap();
4154
                r
4155
            };
4156
            let a = open(&run.join("a"));
4157
            if let Some(prep) = prepare {
4158
                prep(&a).unwrap();
4159
            }
4160
            failpoint::crash_after(n);
4161
            let outcome = op(&a);
4162
            let crashed = failpoint::disarm();
4163
            drop(a);
4164
            if !crashed {
4165
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4166
                steps = n - 1;
4167
                break;
4168
            }
4169
            assert!(
4170
                outcome.is_err(),
4171
                "{name}: a crash at step {n} was swallowed"
4172
            );
4173
            for repo in ["a", "origin"] {
4174
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4175
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4176
                });
4177
                let rep = r.fsck().unwrap();
4178
                assert_eq!(
4179
                    rep.errors(),
4180
                    0,
4181
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4182
                    rep.problems
4183
                );
4184
            }
4185
            // The interrupted operation can simply be run again.
4186
            let a = open(&run.join("a"));
4187
            // A crash after the commit point leaves the commit done.
4188
            let landed = a
4189
                .bookmark_heads()
4190
                .unwrap()
4191
                .iter()
4192
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4193
            let again = match (name, landed) {
4194
                ("commit", true) => Ok(()),
4195
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4196
                _ => op(&a),
4197
            };
4198
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4199
            assert_eq!(a.fsck().unwrap().errors(), 0);
4200
            fs::remove_dir_all(&run).unwrap();
4201
        }
4202
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4203
    }
4204
}
4205
4206
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4207
/// running at the same time lose nothing: every commit ends up on the
4208
/// bookmark, locally and on the remote, and the repository passes fsck.
4209
#[test]
4210
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4211
    hermetic();
4212
    let dir = tempfile::tempdir().unwrap();
4213
    let root = dir.path();
4214
    let origin = root.join("origin");
4215
    Repo::init_bare_unbound(&origin).unwrap();
4216
    let main = root.join("main");
4217
    let mut repo = Repo::init(&main).unwrap();
4218
    repo.config
4219
        .set("remote.origin.url", &origin.to_string_lossy())
4220
        .unwrap();
4221
    repo.save_config().unwrap();
4222
    write(&main, "seed.txt", b"seed\n");
4223
    repo.commit("seed", &[]).unwrap();
4224
    let second = root.join("second");
4225
    repo.workspace_add(&second, None).unwrap();
4226
    drop(repo);
4227
4228
    const EACH: usize = 15;
4229
    std::thread::scope(|s| {
4230
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4231
            s.spawn(move || {
4232
                let r = Repo::open(&dir).unwrap();
4233
                for i in 0..EACH {
4234
                    write(
4235
                        &dir,
4236
                        &format!("{tag}-{i}.txt"),
4237
                        format!("{tag} {i}\n").as_bytes(),
4238
                    );
4239
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4240
                    if push && i % 5 == 4 {
4241
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4242
                        let _ = r.push("origin", false);
4243
                    }
4244
                }
4245
            });
4246
        }
4247
    });
4248
4249
    let repo = Repo::open(&main).unwrap();
4250
    let heads = repo.bookmark_heads().unwrap();
4251
    let state = repo.load_state(&heads).unwrap();
4252
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4253
    for tag in ["a", "b"] {
4254
        for i in 0..EACH {
4255
            assert!(
4256
                messages.contains(&format!("{tag} {i}")),
4257
                "lost commit {tag} {i}; have {messages:?}"
4258
            );
4259
        }
4260
    }
4261
    let rep = repo.fsck().unwrap();
4262
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4263
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4264
    let hosted = Repo::open(&origin).unwrap();
4265
    let hosted_heads = hosted.bookmark_heads().unwrap();
4266
    assert_eq!(
4267
        hosted.load_state(&hosted_heads).unwrap().len(),
4268
        state.len(),
4269
        "the remote has every commit"
4270
    );
4271
}
4272
4273
/// Two operations recorded from the same parent (what two processes do
4274
/// when they race) are merged: both bookmarks' heads survive, and a
4275
/// change made on one side only is kept.
4276
#[test]
4277
fn operations_from_the_same_parent_are_merged() {
4278
    hermetic();
4279
    let dir = tempfile::tempdir().unwrap();
4280
    let root = dir.path();
4281
    let repo = Repo::init(root).unwrap();
4282
    write(root, "a.txt", b"a\n");
4283
    let a = repo.commit("a", &[]).unwrap();
4284
    write(root, "b.txt", b"b\n");
4285
    let b = repo.commit("b", &[]).unwrap();
4286
    let (x, op) = repo.head_op().unwrap();
4287
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4288
4289
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4290
    let mut one = op.view.clone();
4291
    one.bookmarks.insert("main".into(), state(vec![a]));
4292
    one.bookmarks.insert("topic".into(), state(vec![a]));
4293
    let mut two = op.view.clone();
4294
    two.bookmarks.insert("main".into(), state(vec![b]));
4295
    repo.record_op(&[x], "one", one).unwrap();
4296
    let merged = repo.record_op(&[x], "two", two).unwrap();
4297
4298
    let (head, op) = repo.head_op().unwrap();
4299
    assert_eq!(head, merged);
4300
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4301
    assert!(op.command.contains("merged with a concurrent operation"));
4302
    let mut main = repo
4303
        .store()
4304
        .get_state(&op.view.bookmarks["main"])
4305
        .unwrap()
4306
        .heads;
4307
    main.sort();
4308
    let mut want = vec![a, b];
4309
    want.sort();
4310
    assert_eq!(main, want, "both sides' heads are kept");
4311
    assert!(
4312
        op.view.bookmarks.contains_key("topic"),
4313
        "a one-sided change survives"
4314
    );
4315
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4316
}
4317
4318
#[test]
4319
fn failed_requests_come_with_a_next_step() {
4320
    use crate::protocol::hint_for;
4321
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4322
        .unwrap()
4323
        .contains("token"));
4324
    assert!(hint_for("…: HTTP 403: forbidden")
4325
        .unwrap()
4326
        .contains("repo:write"));
4327
    assert!(hint_for("…: HTTP 404: no such repository")
4328
        .unwrap()
4329
        .contains("owner and repository name"));
4330
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4331
        .unwrap()
4332
        .contains("oxyhub-ca.pem"));
4333
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4334
        .unwrap()
4335
        .contains("running"));
4336
    assert!(hint_for("Dns Failed: failed to lookup address information")
4337
        .unwrap()
4338
        .contains("resolve"));
4339
    assert_eq!(hint_for("something else entirely"), None);
4340
}
4341
4342
#[test]
4343
fn doctor_names_problems_and_what_to_do() {
4344
    hermetic();
4345
    let dir = tempfile::tempdir().unwrap();
4346
    let root = dir.path();
4347
    let origin = root.join("origin");
4348
    Repo::init_bare_unbound(&origin).unwrap();
4349
    let mut repo = Repo::init(&root.join("r"))
4350
        .unwrap()
4351
        .with_home(root.join("home"));
4352
    let find = |r: &DoctorReport, area: &str, h: Health| {
4353
        r.checks
4354
            .iter()
4355
            .find(|c| c.area == area && c.health == h)
4356
            .cloned()
4357
    };
4358
4359
    let r = repo.doctor(true);
4360
    assert!(find(&r, "identity", Health::Warn)
4361
        .unwrap()
4362
        .hint
4363
        .unwrap()
4364
        .contains("oxy identity create"));
4365
    assert!(find(&r, "repository", Health::Ok).is_some());
4366
4367
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4368
        .unwrap();
4369
    repo.config.set("author.name", "Ada").unwrap();
4370
    repo.config.set("author.email", "[email protected]").unwrap();
4371
    repo.config
4372
        .set("remote.origin.url", &origin.to_string_lossy())
4373
        .unwrap();
4374
    repo.config
4375
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4376
        .unwrap();
4377
    repo.config.set("remote.down.token", "t").unwrap();
4378
    repo.config
4379
        .set("remote.badca.url", "https://example.invalid/a/b")
4380
        .unwrap();
4381
    repo.config
4382
        .set(
4383
            "remote.badca.ca",
4384
            &root.join("missing.pem").to_string_lossy(),
4385
        )
4386
        .unwrap();
4387
    repo.save_config().unwrap();
4388
4389
    let r = repo.doctor(true);
4390
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4391
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4392
    assert!(find(&r, "remote origin", Health::Ok)
4393
        .unwrap()
4394
        .message
4395
        .contains("first push binds it"));
4396
    let down = find(&r, "remote down", Health::Fail).unwrap();
4397
    assert!(
4398
        down.hint.as_deref().unwrap_or("").contains("running"),
4399
        "{down:?}"
4400
    );
4401
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4402
    assert!(
4403
        badca.hint.unwrap().contains("remote.badca.ca"),
4404
        "the remote's own name is in the hint"
4405
    );
4406
    assert_eq!(r.worst(), Health::Fail);
4407
4408
    // Offline, nothing is contacted.
4409
    let r = repo.doctor(false);
4410
    assert!(find(&r, "remote down", Health::Fail).is_none());
4411
    assert!(find(&r, "remote down", Health::Ok)
4412
        .unwrap()
4413
        .message
4414
        .contains("not contacted"));
4415
}
4416
4417
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4418
/// after it. Inserting after `b` and then deleting `b`, one commit after
4419
/// the other, must not leave a delete/insert conflict.
4420
#[test]
4421
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4422
    hermetic();
4423
    let dir = tempfile::tempdir().unwrap();
4424
    let root = dir.path();
4425
    let repo = Repo::init(root).unwrap();
4426
    write(root, "f", b"a\nb\nc\n");
4427
    repo.commit("base", &[]).unwrap();
4428
    write(root, "f", b"a\nb\nx\nc\n");
4429
    let insert = repo.commit("insert x after b", &[]).unwrap();
4430
    write(root, "f", b"a\nx\nc\n");
4431
    let delete = repo.commit("delete b", &[]).unwrap();
4432
    assert!(
4433
        repo.store()
4434
            .get_change(&delete)
4435
            .unwrap()
4436
            .deps
4437
            .contains(&insert),
4438
        "the deletion depends on the insertion below the deleted line"
4439
    );
4440
    let heads = repo.bookmark_heads().unwrap();
4441
    assert_eq!(heads, vec![delete]);
4442
    let snap = repo.load_state(&heads).unwrap().materialize();
4443
    assert!(!snap.is_conflicted());
4444
    assert!(
4445
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4446
    );
4447
}
4448
4449
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4450
/// replacement depends on the change that set the blob it replaces.
4451
#[test]
4452
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4453
    hermetic();
4454
    let dir = tempfile::tempdir().unwrap();
4455
    let root = dir.path();
4456
    let repo = Repo::init(root).unwrap();
4457
    write(root, "bin", b"\0A");
4458
    let v1 = repo.commit("v1", &[]).unwrap();
4459
    write(root, "bin", b"\0B");
4460
    let v2 = repo.commit("v2", &[]).unwrap();
4461
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4462
    write(root, "bin", b"\0A");
4463
    let v3 = repo.commit("back to A", &[]).unwrap();
4464
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4465
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4466
    let state = repo.load_state(&[v3]).unwrap();
4467
    let snap = state.materialize();
4468
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4469
        panic!("opaque")
4470
    };
4471
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4472
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4473
}
4474
4475
/// Spec §23: a binary file changed on two branches and merged in Git to
4476
/// one side's version comes back as that version at the merge, and the
4477
/// import verifies commit by commit.
4478
#[test]
4479
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4480
    hermetic();
4481
    if std::process::Command::new("git")
4482
        .arg("--version")
4483
        .output()
4484
        .is_err()
4485
    {
4486
        eprintln!("git not installed; skipping");
4487
        return;
4488
    }
4489
    let dir = tempfile::tempdir().unwrap();
4490
    let root = dir.path();
4491
    let g = root.join("src.git");
4492
    fs::create_dir_all(&g).unwrap();
4493
    let git = |args: &[&str]| -> String {
4494
        let out = std::process::Command::new("git")
4495
            .arg("-C")
4496
            .arg(&g)
4497
            .args([
4498
                "-c",
4499
                "user.name=Grace",
4500
                "-c",
4501
                "[email protected]",
4502
                "-c",
4503
                "commit.gpgsign=false",
4504
            ])
4505
            .args(args)
4506
            .output()
4507
            .unwrap();
4508
        assert!(
4509
            out.status.success(),
4510
            "git {args:?}: {}",
4511
            String::from_utf8_lossy(&out.stderr)
4512
        );
4513
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4514
    };
4515
    git(&["init", "-q", "-b", "main"]);
4516
    write(&g, "logo.bin", b"\0base");
4517
    write(&g, "notes.txt", b"a\nb\nc\n");
4518
    git(&["add", "."]);
4519
    git(&["commit", "-qm", "base"]);
4520
    git(&["checkout", "-qb", "side"]);
4521
    write(&g, "logo.bin", b"\0side");
4522
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4523
    git(&["commit", "-qam", "side"]);
4524
    git(&["checkout", "-q", "main"]);
4525
    write(&g, "logo.bin", b"\0main");
4526
    git(&["commit", "-qam", "main"]);
4527
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4528
    let _ = std::process::Command::new("git")
4529
        .arg("-C")
4530
        .arg(&g)
4531
        .args([
4532
            "-c",
4533
            "user.name=G",
4534
            "-c",
4535
            "user.email=g@e",
4536
            "merge",
4537
            "-q",
4538
            "side",
4539
        ])
4540
        .output();
4541
    write(&g, "logo.bin", b"\0main");
4542
    git(&["add", "."]);
4543
    git(&["commit", "-qm", "merge side"]);
4544
    // Then a revert of the binary to its first version.
4545
    write(&g, "logo.bin", b"\0base");
4546
    git(&["commit", "-qam", "back to base"]);
4547
4548
    let repo = Repo::init(&root.join("o")).unwrap();
4549
    let rep = repo.import_git(&g, "main").unwrap();
4550
    assert_eq!(rep.merges, 1);
4551
    let v = repo.verify_git_import(&g, "main").unwrap();
4552
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4553
    assert_eq!(v.commits, 5);
4554
    let snap = repo
4555
        .load_state(&repo.bookmark_heads().unwrap())
4556
        .unwrap()
4557
        .materialize();
4558
    assert!(!snap.is_conflicted());
4559
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4560
        panic!("opaque")
4561
    };
4562
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4563
}
4564
4565
/// Spec §7.7 on a file system without executable bits or symlinks: the
4566
/// recorded bit is kept, and a symlink checked out as a plain file holding
4567
/// its target is still that symlink.
4568
#[cfg(unix)]
4569
#[test]
4570
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4571
    use crate::portable::Platform;
4572
    use std::os::unix::fs::PermissionsExt;
4573
    hermetic();
4574
    let dir = tempfile::tempdir().unwrap();
4575
    let root = dir.path();
4576
    let repo = Repo::init(root).unwrap();
4577
    write(root, "run.sh", b"#!/bin/sh\n");
4578
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4579
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4580
    repo.commit("script and link", &[]).unwrap();
4581
    drop(repo);
4582
4583
    // What checking out on Windows leaves: no exec bit, the link as a file.
4584
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4585
    fs::remove_file(root.join("link")).unwrap();
4586
    write(root, "link", b"run.sh");
4587
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4588
    let s = win.snapshot("oxy status").unwrap();
4589
    assert!(
4590
        s.statuses.is_empty(),
4591
        "nothing changed on Windows: {:?}",
4592
        statuses(&s)
4593
    );
4594
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4595
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4596
    write(root, "link", b"other");
4597
    let h = win.commit("edit on Windows", &[]).unwrap();
4598
    let snap = win.load_state(&[h]).unwrap().materialize();
4599
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4600
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4601
    // The same working copy read as Linux sees the lost bit and the plain file.
4602
    let linux = Repo::open(root).unwrap();
4603
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4604
}
4605
4606
/// Paths that collide on case-insensitive or Windows file systems are
4607
/// named at checkout there, and by doctor everywhere.
4608
#[test]
4609
fn paths_other_platforms_cannot_hold_are_reported() {
4610
    use crate::portable::Platform;
4611
    hermetic();
4612
    let dir = tempfile::tempdir().unwrap();
4613
    let root = dir.path();
4614
    let repo = Repo::init(root).unwrap();
4615
    write(root, "README.md", b"a\n");
4616
    write(root, "readme.md", b"b\n");
4617
    write(root, "src/aux.c", b"int x;\n");
4618
    let h = repo.commit("unportable", &[]).unwrap();
4619
    let r = repo.doctor(false);
4620
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4621
    assert_eq!(port.health, Health::Warn);
4622
    assert!(
4623
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4624
        "{}",
4625
        port.message
4626
    );
4627
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4628
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4629
    assert!(
4630
        rep.notes
4631
            .iter()
4632
            .any(|n| n.contains("README.md and readme.md")),
4633
        "{:?}",
4634
        rep.notes
4635
    );
4636
    assert!(
4637
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4638
        "macOS allows aux.c"
4639
    );
4640
}
4641
4642
#[test]
4643
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4644
    hermetic();
4645
    let dir = tempfile::tempdir().unwrap();
4646
    let repo = Repo::init(dir.path()).unwrap();
4647
    write(dir.path(), "a.txt", b"one\n");
4648
    write(dir.path(), "other.txt", b"x\n");
4649
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4650
    repo.snapshot("t").unwrap();
4651
    let c1 = repo.commit("first", &[]).unwrap();
4652
    write(dir.path(), "other.txt", b"y\n");
4653
    repo.snapshot("t").unwrap();
4654
    repo.commit("other only", &[]).unwrap();
4655
    write(dir.path(), "a.txt", b"one\ntwo\n");
4656
    repo.snapshot("t").unwrap();
4657
    let c3 = repo.commit("second line", &[]).unwrap();
4658
    write(dir.path(), "other.txt", b"z\n");
4659
    repo.snapshot("t").unwrap();
4660
    repo.commit("other again", &[]).unwrap();
4661
4662
    let heads = repo.bookmark_heads().unwrap();
4663
    let state = repo.load_state(&heads).unwrap();
4664
    let full: Vec<ChangeHash> = repo
4665
        .log_for_path_in("a.txt", &heads)
4666
        .unwrap()
4667
        .iter()
4668
        .map(|e| e.hash)
4669
        .collect();
4670
    assert_eq!(
4671
        full,
4672
        vec![c3, c1],
4673
        "newest first, only changes touching the path"
4674
    );
4675
    let newest: Vec<ChangeHash> = repo
4676
        .log_for_path_of(&state, "a.txt", Some(1))
4677
        .unwrap()
4678
        .iter()
4679
        .map(|e| e.hash)
4680
        .collect();
4681
    assert_eq!(newest, vec![c3], "stops at the first");
4682
    assert_eq!(
4683
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4684
        2
4685
    );
4686
    assert!(repo
4687
        .log_for_path_of(&state, "missing.txt", Some(1))
4688
        .is_err());
4689
    assert_eq!(
4690
        repo.log_state(&heads).unwrap().len(),
4691
        repo.log_of(&state).len()
4692
    );
4693
4694
    let tree = state.tree().view();
4695
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4696
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4697
    assert_eq!(
4698
        via_state
4699
            .iter()
4700
            .map(|l| (l.hash, l.text.clone()))
4701
            .collect::<Vec<_>>(),
4702
        via_heads
4703
            .iter()
4704
            .map(|l| (l.hash, l.text.clone()))
4705
            .collect::<Vec<_>>()
4706
    );
4707
    assert_eq!(
4708
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4709
        vec![c1, c3]
4710
    );
4711
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4712
}
4713
4714
/// A text file whose stat matches the manifest and whose recorded hash is
4715
/// the base's content is taken from the base without reading it; anything
4716
/// else is read, so no edit is missed (spec §12.3).
4717
#[cfg(unix)]
4718
#[test]
4719
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4720
    use std::os::unix::fs::PermissionsExt;
4721
    hermetic();
4722
    let dir = tempfile::tempdir().unwrap();
4723
    let root = dir.path();
4724
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4725
    write(root, "a.txt", b"one\ntwo\n");
4726
    write(root, "b.txt", b"bee\n");
4727
    repo.commit("base", &[]).unwrap();
4728
    let age = |p: &str| {
4729
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4730
        fs::File::options()
4731
            .write(true)
4732
            .open(root.join(p))
4733
            .unwrap()
4734
            .set_modified(old)
4735
            .unwrap();
4736
    };
4737
    age("a.txt");
4738
    age("b.txt");
4739
    assert!(
4740
        !repo.snapshot("status").unwrap().changed,
4741
        "records the aged stat"
4742
    );
4743
4744
    // Clean and equal to the base: not read at all.
4745
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4746
    let snap = repo.snapshot("status").unwrap();
4747
    assert!(
4748
        !snap.changed && snap.statuses.is_empty(),
4749
        "{:?}",
4750
        snap.statuses
4751
    );
4752
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4753
4754
    // An uncommitted edit that is older than the manifest: stat-clean, but
4755
    // its hash is not the base's, so it is read and stays visible.
4756
    write(root, "b.txt", b"bee edited\n");
4757
    age("b.txt");
4758
    let first = repo.snapshot("status").unwrap();
4759
    assert_eq!(
4760
        statuses(&first),
4761
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4762
    );
4763
    let again = repo.snapshot("status").unwrap();
4764
    assert_eq!(
4765
        statuses(&again),
4766
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4767
        "still seen once stat-clean"
4768
    );
4769
    assert!(!again.changed, "and the working copy hashes the same");
4770
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4771
    assert!(
4772
        repo.snapshot("status").is_err(),
4773
        "an edited file must be read, never taken from the base"
4774
    );
4775
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4776
4777
    // A same-size edit made just now is racy and read.
4778
    write(root, "a.txt", b"one\nTWO\n");
4779
    assert_eq!(
4780
        statuses(&repo.snapshot("status").unwrap()),
4781
        vec![
4782
            ("a.txt".to_string(), ChangeStatus::Modified),
4783
            ("b.txt".to_string(), ChangeStatus::Modified)
4784
        ]
4785
    );
4786
    // Committing makes the edits the base: both are clean and served from it again.
4787
    repo.commit("edits", &[]).unwrap();
4788
    age("a.txt");
4789
    age("b.txt");
4790
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4791
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4792
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4793
    let snap = repo.snapshot("status").unwrap();
4794
    assert!(!snap.changed && snap.statuses.is_empty());
4795
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4796
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4797
}
4798
4799
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4800
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4801
/// file is unchanged, and loading through the checkpoint equals a full load.
4802
#[test]
4803
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4804
    hermetic();
4805
    let dir = tempfile::tempdir().unwrap();
4806
    let root = dir.path();
4807
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4808
    let long: String = (0..300)
4809
        .map(|i| format!("line {i} of a long file\n"))
4810
        .collect();
4811
    write(root, "long.txt", long.as_bytes());
4812
    write(root, "short.txt", b"short\n");
4813
    repo.commit("base", &[]).unwrap();
4814
    let (r1, _, _) = repo.checkpoint().unwrap();
4815
    let cp1 = crate::objects::Checkpoint::decode(
4816
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4817
    )
4818
    .unwrap();
4819
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4820
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4821
4822
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4823
    repo.gc(true).unwrap();
4824
    assert!(repo.store().has(&graphs1[0]));
4825
    let report = repo.fsck().unwrap();
4826
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4827
4828
    // Loading through the checkpoint equals a full load.
4829
    write(root, "short.txt", b"short, edited\n");
4830
    repo.commit("edit the short file", &[]).unwrap();
4831
    let heads = repo.bookmark_heads().unwrap();
4832
    let fast = repo.load_state(&heads).unwrap();
4833
    let full = repo.load_state_full(&heads).unwrap();
4834
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4835
4836
    // The next checkpoint shares the unchanged long file's graph.
4837
    let (r2, _, _) = repo.checkpoint().unwrap();
4838
    let cp2 = crate::objects::Checkpoint::decode(
4839
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
4840
    )
4841
    .unwrap();
4842
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
4843
4844
    // A shallow clone's bundle carries the graph blob with the checkpoint.
4845
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
4846
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
4847
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
4848
4849
    // A version 1 checkpoint written by an older oxy still loads.
4850
    let state = repo.load_state_full(&heads).unwrap();
4851
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
4852
    let cp_old = crate::objects::Checkpoint {
4853
        heads: cp2.heads.clone(),
4854
        count: cp2.count,
4855
        payload: old,
4856
    };
4857
    let r_old = repo
4858
        .store()
4859
        .put(ObjectType::Checkpoint, &cp_old.encode())
4860
        .unwrap();
4861
    repo.install_checkpoint("main", &r_old).unwrap();
4862
    assert_eq!(
4863
        repo.load_state(&heads).unwrap().checkpoint_payload(),
4864
        full.checkpoint_payload()
4865
    );
4866
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4867
4868
    // A lost graph blob fails the load loudly rather than dropping the
4869
    // file, and fsck reports it (a fresh repository, objects still loose).
4870
    let dir2 = tempfile::tempdir().unwrap();
4871
    let root2 = dir2.path();
4872
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
4873
    write(root2, "long.txt", long.as_bytes());
4874
    repo2.commit("base", &[]).unwrap();
4875
    let (r, _, _) = repo2.checkpoint().unwrap();
4876
    let cp = crate::objects::Checkpoint::decode(
4877
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
4878
    )
4879
    .unwrap();
4880
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
4881
    repo2.store().remove_loose_for_test(&graph).unwrap();
4882
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
4883
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
4884
}
4885
4886
/// A new repository has not stored the user's identity yet (that happens
4887
/// at the first signed change); looking it up falls back to the key
4888
/// directory, and a file there that does not hash to the key is refused.
4889
#[test]
4890
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
4891
    hermetic();
4892
    let dir = tempfile::tempdir().unwrap();
4893
    let home = dir.path().join("home");
4894
    let mut first = Repo::init(&dir.path().join("a"))
4895
        .unwrap()
4896
        .with_home(home.clone());
4897
    let (key, _) = first
4898
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4899
        .unwrap();
4900
    let fresh = Repo::init(&dir.path().join("b"))
4901
        .unwrap()
4902
        .with_home(home.clone());
4903
    assert!(!fresh.store().has(&key), "nothing stored yet");
4904
    let id = fresh.identity(&key).unwrap();
4905
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
4906
    // A key file that is not this identity is an error, not a wrong answer.
4907
    let keys = fresh.keys_dir.clone();
4908
    let (other, _) = first
4909
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4910
        .unwrap();
4911
    fs::copy(
4912
        keys.join(format!("{}.identity", other.to_hex())),
4913
        keys.join(format!("{}.identity", key.to_hex())),
4914
    )
4915
    .unwrap();
4916
    assert!(fresh
4917
        .identity(&key)
4918
        .unwrap_err()
4919
        .to_string()
4920
        .contains("does not hold identity"));
4921
}
4922
4923
/// Status snapshots (spec §12.3): a text file whose stat matches the
4924
/// manifest, and whose base graph key is the one the manifest recorded it
4925
/// equal to, is neither read nor rendered; any edit, and any change to the
4926
/// file's graph in the base, brings it back.
4927
#[cfg(unix)]
4928
#[test]
4929
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
4930
    use std::os::unix::fs::PermissionsExt;
4931
    hermetic();
4932
    let dir = tempfile::tempdir().unwrap();
4933
    let root = dir.path();
4934
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4935
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
4936
        write(root, p, c.as_bytes());
4937
    }
4938
    repo.commit("base", &[]).unwrap();
4939
    let age = |p: &str| {
4940
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4941
        fs::File::options()
4942
            .write(true)
4943
            .open(root.join(p))
4944
            .unwrap()
4945
            .set_modified(old)
4946
            .unwrap();
4947
    };
4948
    let lock = |p: &str, mode: u32| {
4949
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
4950
    };
4951
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4952
        age(p);
4953
    }
4954
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4955
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4956
    assert!(
4957
        m.entries.values().all(|e| e.graph.is_some()),
4958
        "keys recorded"
4959
    );
4960
4961
    // Unreadable files prove they are not read; the status snapshot does
4962
    // not render them either, and its base lacks their graphs.
4963
    lock("a.txt", 0o000);
4964
    lock("b.txt", 0o000);
4965
    let snap = repo.snapshot_status("status").unwrap();
4966
    assert!(!snap.changed && snap.statuses.is_empty());
4967
    assert_eq!(
4968
        snap.base_snapshot
4969
            .unrendered
4970
            .iter()
4971
            .cloned()
4972
            .collect::<Vec<_>>(),
4973
        vec!["a.txt", "b.txt", "d/c.txt"]
4974
    );
4975
    assert!(!snap.base.is_full());
4976
    assert!(!snap.base_snapshot.is_conflicted());
4977
    // A full snapshot does not read them either, but renders everything.
4978
    let full = repo.snapshot("status").unwrap();
4979
    assert!(full.statuses.is_empty() && full.base.is_full());
4980
    assert!(full.base_snapshot.unrendered.is_empty());
4981
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
4982
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
4983
4984
    // An edit is seen; the file is rendered, the others still are not.
4985
    write(root, "d/c.txt", b"sea edited\n");
4986
    let snap = repo.snapshot_status("status").unwrap();
4987
    assert_eq!(
4988
        statuses(&snap),
4989
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
4990
    );
4991
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
4992
    // So is a mode change of an unread file.
4993
    lock("b.txt", 0o100);
4994
    assert_eq!(
4995
        statuses(&repo.snapshot_status("status").unwrap()),
4996
        vec![
4997
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
4998
            ("d/c.txt".to_string(), ChangeStatus::Modified)
4999
        ]
5000
    );
5001
    lock("b.txt", 0o000);
5002
5003
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5004
    // stays unread, c.txt is read once and then skipped too.
5005
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5006
        .unwrap();
5007
    age("d/c.txt");
5008
    let snap = repo.snapshot_status("status").unwrap();
5009
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5010
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5011
    lock("d/c.txt", 0o000);
5012
    let snap = repo.snapshot_status("status").unwrap();
5013
    assert!(snap.statuses.is_empty());
5014
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5015
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5016
        lock(p, 0o644);
5017
    }
5018
}
5019
5020
/// Attributes decide how a file compares with the base, so a changed
5021
/// `.oxyattributes` makes every text file be compared again.
5022
#[cfg(unix)]
5023
#[test]
5024
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5025
    hermetic();
5026
    let dir = tempfile::tempdir().unwrap();
5027
    let root = dir.path();
5028
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5029
    write(root, "a.txt", b"crlf\r\n");
5030
    repo.commit("base", &[]).unwrap();
5031
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5032
    fs::File::options()
5033
        .write(true)
5034
        .open(root.join("a.txt"))
5035
        .unwrap()
5036
        .set_modified(old)
5037
        .unwrap();
5038
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5039
    assert!(repo
5040
        .snapshot_status("status")
5041
        .unwrap()
5042
        .base_snapshot
5043
        .unrendered
5044
        .contains("a.txt"));
5045
    // With eol=lf, a.txt as stored no longer equals the base.
5046
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5047
    let snap = repo.snapshot_status("status").unwrap();
5048
    assert_eq!(
5049
        statuses(&snap),
5050
        vec![
5051
            (".oxyattributes".to_string(), ChangeStatus::Added),
5052
            ("a.txt".to_string(), ChangeStatus::Modified)
5053
        ]
5054
    );
5055
}
5056
5057
/// Bookmarks with `/` in their names: pushing records their
5058
/// attestations, and checkpoints are kept for them, beside `feature`
5059
/// itself.
5060
#[test]
5061
fn bookmarks_with_slashes_push_and_checkpoint() {
5062
    hermetic();
5063
    let dir = tempfile::tempdir().unwrap();
5064
    let root = dir.path();
5065
    let origin = Repo::init(&root.join("origin")).unwrap();
5066
    let url = root.join("origin").to_string_lossy().to_string();
5067
    let mut repo = Repo::clone(&url, &root.join("r"))
5068
        .unwrap()
5069
        .with_home(root.join("home"));
5070
    // With an identity, pushes carry reference attestations: the case
5071
    // that failed, since the attestation is a file named after the bookmark.
5072
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5073
        .unwrap();
5074
    let r = root.join("r");
5075
    write(&r, "a.txt", b"a\n");
5076
    let h_a = repo.commit("a", &[]).unwrap();
5077
    assert!(repo.push("origin", false).unwrap()[0].ok);
5078
    repo.bookmark_create("feature", None).unwrap();
5079
    repo.bookmark_create("feature/x", None).unwrap();
5080
    repo.bookmark_switch("feature/x", false).unwrap();
5081
    write(&r, "b.txt", b"b\n");
5082
    let h_b = repo.commit("b", &[]).unwrap();
5083
    for name in ["feature", "feature/x"] {
5084
        let res = repo.push_bookmark("origin", name, false).unwrap();
5085
        assert!(res[0].ok, "{name}: {res:?}");
5086
    }
5087
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5088
    assert_eq!(
5089
        origin.resolve_heads("feature/x").unwrap(),
5090
        repo.resolve_heads("feature/x").unwrap()
5091
    );
5092
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5093
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5094
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5095
5096
    // A checkpoint of feature/x is found again when loading its state.
5097
    let (cp, _, _) = repo.checkpoint().unwrap();
5098
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5099
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5100
    let heads = repo.resolve_heads("feature/x").unwrap();
5101
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5102
}
5103
5104
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5105
/// never the remote's own bookmark, and a bookmark created again later is
5106
/// accepted although the deletion's attestation stays the latest.
5107
#[test]
5108
fn bookmarks_are_deleted_on_a_remote() {
5109
    hermetic();
5110
    let dir = tempfile::tempdir().unwrap();
5111
    let root = dir.path();
5112
    let origin = Repo::init(&root.join("origin")).unwrap();
5113
    let url = root.join("origin").to_string_lossy().to_string();
5114
    let mut repo = Repo::clone(&url, &root.join("r"))
5115
        .unwrap()
5116
        .with_home(root.join("home"));
5117
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5118
        .unwrap();
5119
    let r = root.join("r");
5120
    write(&r, "a.txt", b"a\n");
5121
    repo.commit("a", &[]).unwrap();
5122
    assert!(repo.push("origin", false).unwrap()[0].ok);
5123
    repo.bookmark_create("feature/x", None).unwrap();
5124
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5125
    assert!(origin.resolve_heads("feature/x").is_ok());
5126
5127
    let res = repo.push_delete("origin", "feature/x").unwrap();
5128
    assert!(res[0].ok, "{res:?}");
5129
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5130
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5131
    assert!(
5132
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5133
        "the deletion is attested"
5134
    );
5135
    assert!(
5136
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5137
        "the local bookmark stays"
5138
    );
5139
    assert!(!repo
5140
        .view()
5141
        .unwrap()
5142
        .remotes
5143
        .get("origin")
5144
        .is_some_and(|m| m.contains_key("feature/x")));
5145
5146
    // Pushing it again creates it again, past the deletion's serial.
5147
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5148
    assert!(res[0].ok, "{res:?}");
5149
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5150
5151
    // Nothing to delete, and never the remote's own bookmark.
5152
    assert!(repo.push_delete("origin", "nope").is_err());
5153
    let res = repo.push_delete("origin", "main").unwrap();
5154
    assert!(
5155
        !res[0].ok && res[0].reason.contains("default bookmark"),
5156
        "{res:?}"
5157
    );
5158
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5159
}
5160
5161
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5162
/// when the target has the same versions of the files it touches, and is
5163
/// refused, untouched, when it has others.
5164
#[test]
5165
fn switching_bookmarks_carries_uncommitted_work() {
5166
    hermetic();
5167
    let dir = tempfile::tempdir().unwrap();
5168
    let root = dir.path();
5169
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5170
    write(root, "a.txt", b"a\n");
5171
    write(root, "b.txt", b"b\n");
5172
    write(root, "gone.txt", b"gone\n");
5173
    repo.commit("base", &[]).unwrap();
5174
    repo.bookmark_create("feature", None).unwrap();
5175
    // Started on main, belongs on feature: edit, add, remove.
5176
    write(root, "a.txt", b"a\nmore\n");
5177
    write(root, "new.txt", b"new\n");
5178
    fs::remove_file(root.join("gone.txt")).unwrap();
5179
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5180
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5181
    assert_eq!(repo.config.bookmark, "feature");
5182
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5183
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5184
    assert!(!root.join("gone.txt").exists());
5185
    let snap = repo.snapshot("status").unwrap();
5186
    assert_eq!(
5187
        statuses(&snap),
5188
        vec![
5189
            ("a.txt".to_string(), ChangeStatus::Modified),
5190
            ("gone.txt".to_string(), ChangeStatus::Removed),
5191
            ("new.txt".to_string(), ChangeStatus::Added)
5192
        ]
5193
    );
5194
    repo.commit("the work", &[]).unwrap();
5195
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5196
5197
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5198
    repo.bookmark_switch("main", false).unwrap();
5199
    write(root, "b.txt", b"b on main\n");
5200
    repo.commit("b on main", &[]).unwrap();
5201
    repo.bookmark_switch("feature", false).unwrap();
5202
    write(root, "b.txt", b"b edited\n");
5203
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5204
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5205
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5206
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5207
}
5208
5209
/// Merging and checking out (feedback 3): a working copy without changes
5210
/// follows a merge whichever state it sat on; a refused checkout names
5211
/// what is in the way; `checkout --carry` takes the work along.
5212
#[test]
5213
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5214
    hermetic();
5215
    let dir = tempfile::tempdir().unwrap();
5216
    let root = dir.path();
5217
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5218
    write(root, "a.txt", b"a\n");
5219
    let h1 = repo.commit("a", &[]).unwrap();
5220
    write(root, "b.txt", b"b\n");
5221
    repo.commit("b", &[]).unwrap();
5222
    repo.bookmark_create("feature", None).unwrap();
5223
    repo.bookmark_switch("feature", false).unwrap();
5224
    write(root, "c.txt", b"c\n");
5225
    repo.commit("c on feature", &[]).unwrap();
5226
    repo.bookmark_switch("main", false).unwrap();
5227
    // The working copy sits on an older state than main's heads.
5228
    repo.checkout(&[h1], false, "checkout").unwrap();
5229
    assert!(!root.join("b.txt").exists());
5230
    let m = repo.merge("feature").unwrap();
5231
    assert!(m.checked_out, "a clean working copy follows the merge");
5232
    for f in ["a.txt", "b.txt", "c.txt"] {
5233
        assert!(root.join(f).exists(), "{f}");
5234
    }
5235
5236
    // A refusal says which paths are in the way and what to do.
5237
    fs::remove_file(root.join("b.txt")).unwrap();
5238
    write(root, "a.txt", b"a edited\n");
5239
    let err = repo
5240
        .checkout(&[h1], false, "checkout")
5241
        .unwrap_err()
5242
        .to_string();
5243
    assert!(
5244
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5245
        "{err}"
5246
    );
5247
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5248
    // is carried as absent (h1 has none either, so that is refused).
5249
    let err = repo
5250
        .checkout_carry(&[h1], "the first change", "checkout")
5251
        .unwrap_err()
5252
        .to_string();
5253
    assert!(
5254
        err.contains("b.txt") && err.contains("the first change"),
5255
        "{err}"
5256
    );
5257
    write(root, "b.txt", b"b\n");
5258
    let (_, carried) = repo
5259
        .checkout_carry(&[h1], "the first change", "checkout")
5260
        .unwrap();
5261
    assert_eq!(carried, vec!["a.txt"]);
5262
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5263
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5264
}
5265
5266
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5267
/// user identity not stored in a new repository yet is fine while its
5268
/// secret key is there; an added subrepo is listed as not committed yet.
5269
#[test]
5270
fn a_new_repository_is_healthy_before_its_first_commit() {
5271
    hermetic();
5272
    let dir = tempfile::tempdir().unwrap();
5273
    let root = dir.path();
5274
    let home = root.join("home");
5275
    let mut first = Repo::init(&root.join("first"))
5276
        .unwrap()
5277
        .with_home(home.clone());
5278
    let (key, _) = first
5279
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5280
        .unwrap();
5281
    let repo = Repo::init(&root.join("second"))
5282
        .unwrap()
5283
        .with_home(home.clone());
5284
    // Only the secret key: no identity object anywhere this repository sees.
5285
    let keys = repo.keys_dir.clone();
5286
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5287
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5288
    let r = repo.doctor(true);
5289
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5290
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5291
    assert!(id.message.contains("first signed change"), "{}", id.message);
5292
5293
    // A subrepo added and not committed yet is listed, pinned where it is.
5294
    let lib = root.join("lib");
5295
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5296
    write(&lib, "x.txt", b"x\n");
5297
    l.commit("x", &[]).unwrap();
5298
    let second = root.join("second");
5299
    write(&second, "a.txt", b"a\n");
5300
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5301
        .unwrap();
5302
    let subs = repo.subrepos().unwrap();
5303
    assert_eq!(subs.len(), 1);
5304
    assert_eq!(
5305
        (subs[0].path.as_str(), subs[0].committed),
5306
        ("deps/lib", false)
5307
    );
5308
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5309
    repo.commit("add lib", &[]).unwrap();
5310
    let subs = repo.subrepos().unwrap();
5311
    assert!(subs[0].committed, "committed now");
5312
}
5313
5314
/// Commit, diff, hunks and discard use the partial snapshot: a file
5315
/// unchanged since the manifest is neither read nor rendered, and showing
5316
/// a change renders only what it edits, the same as from a full base.
5317
#[cfg(unix)]
5318
#[test]
5319
fn commits_and_diffs_leave_unchanged_files_alone() {
5320
    use std::os::unix::fs::PermissionsExt;
5321
    hermetic();
5322
    let dir = tempfile::tempdir().unwrap();
5323
    let root = dir.path();
5324
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5325
    write(root, "big.txt", b"lots\nof\nlines\n");
5326
    write(root, "a.txt", b"one\ntwo\n");
5327
    repo.commit("base", &[]).unwrap();
5328
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5329
    for f in ["big.txt", "a.txt"] {
5330
        fs::File::options()
5331
            .write(true)
5332
            .open(root.join(f))
5333
            .unwrap()
5334
            .set_modified(old)
5335
            .unwrap();
5336
    }
5337
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5338
    // big.txt cannot be read at all from here on.
5339
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5340
5341
    write(root, "a.txt", b"one\nTWO\nthree\n");
5342
    let diff = repo.diff_files(None).unwrap();
5343
    assert_eq!(
5344
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5345
        ["a.txt"]
5346
    );
5347
    let (_, hunks) = repo.hunks().unwrap();
5348
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5349
    let h = repo.commit("edit a", &[]).unwrap();
5350
5351
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5352
    let c = repo.store().get_change(&h).unwrap();
5353
    let full = repo.load_state(&c.deps).unwrap();
5354
    let want = render_change(&c, &full, &full.materialize());
5355
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5356
    let (base, snap) = repo.change_base(&c).unwrap();
5357
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5358
5359
    // Discarding works the same way.
5360
    write(root, "a.txt", b"scratch\n");
5361
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5362
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5363
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5364
}
5365
5366
/// A replace conflict (spec §9.3) is settled by a change that writes one
5367
/// candidate, or new bytes, at the path when the caller names it; a plain
5368
/// snapshot of a checkout never settles it on its own.
5369
#[test]
5370
fn replace_conflicts_are_settled_when_asked() {
5371
    hermetic();
5372
    let dir = tempfile::tempdir().unwrap();
5373
    let root = dir.path();
5374
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5375
    let blob = |n: u8| {
5376
        let mut v = vec![0u8; 64];
5377
        v[1] = n;
5378
        v
5379
    };
5380
    write(root, "img.bin", &blob(1));
5381
    repo.commit("add img", &[]).unwrap();
5382
    repo.bookmark_create("other", None).unwrap();
5383
    write(root, "img.bin", &blob(2));
5384
    repo.commit("img two", &[]).unwrap();
5385
    repo.bookmark_switch("other", false).unwrap();
5386
    write(root, "img.bin", &blob(3));
5387
    repo.commit("img three", &[]).unwrap();
5388
    repo.bookmark_switch("main", false).unwrap();
5389
    repo.merge("other").unwrap();
5390
    let heads = repo.bookmark_heads().unwrap();
5391
    let merged = repo.load_state(&heads).unwrap().materialize();
5392
    assert!(
5393
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5394
        "a replace conflict"
5395
    );
5396
    // A snapshot of the checkout records nothing.
5397
    assert!(repo
5398
        .snapshot("status")
5399
        .unwrap()
5400
        .statuses
5401
        .iter()
5402
        .all(|s| s.path != "img.bin"));
5403
5404
    // Keeping candidate 3 settles it.
5405
    let author = repo.author();
5406
    let edits = [FileEdit {
5407
        path: "img.bin".into(),
5408
        content: Some(blob(3)),
5409
    }];
5410
    let c = repo
5411
        .build_change(&heads, &edits, "keep three", author)
5412
        .unwrap();
5413
    assert_eq!(c.kind, ChangeKind::Resolution);
5414
    let mut st = repo.load_state(&heads).unwrap();
5415
    for d in &c.deps {
5416
        assert!(st.contains(d));
5417
    }
5418
    assert!(
5419
        heads.iter().all(|h| c.deps.contains(h)),
5420
        "depends on both contributors"
5421
    );
5422
    st.add(c).unwrap();
5423
    let after = st.materialize();
5424
    assert!(!after.is_conflicted());
5425
    assert_eq!(
5426
        after.files["img.bin"].content,
5427
        FileContent::Opaque {
5428
            blobs: vec![Repo::blob_ref(&blob(3))]
5429
        }
5430
    );
5431
5432
    // New bytes settle it too.
5433
    let edits = [FileEdit {
5434
        path: "img.bin".into(),
5435
        content: Some(blob(9)),
5436
    }];
5437
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5438
    let mut st = repo.load_state(&heads).unwrap();
5439
    st.add(c).unwrap();
5440
    assert_eq!(
5441
        st.materialize().files["img.bin"].content,
5442
        FileContent::Opaque {
5443
            blobs: vec![Repo::blob_ref(&blob(9))]
5444
        }
5445
    );
5446
}
5447
5448
/// The history of a range of lines (spec §27): the changes that wrote
5449
/// or deleted its atoms, or deleted atoms from between them; edits outside
5450
/// the range and changes the range's lines survived are not in it.
5451
#[test]
5452
fn line_ranges_have_exact_histories() {
5453
    hermetic();
5454
    let dir = tempfile::tempdir().unwrap();
5455
    let root = dir.path();
5456
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5457
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5458
    let base = repo.commit("add f", &[]).unwrap();
5459
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5460
    let outside = repo.commit("change the import", &[]).unwrap();
5461
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5462
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5463
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5464
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5465
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5466
    let after = repo.commit("add b after a", &[]).unwrap();
5467
    let heads = repo.bookmark_heads().unwrap();
5468
5469
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5470
    let hist: Vec<ChangeHash> = repo
5471
        .line_history(&heads, "f.rs", 2, 4)
5472
        .unwrap()
5473
        .iter()
5474
        .map(|e| e.hash)
5475
        .collect();
5476
    for (h, what) in [
5477
        (base, "wrote it"),
5478
        (inside, "edited a line"),
5479
        (deleted, "deleted a line from inside"),
5480
    ] {
5481
        assert!(hist.contains(&h), "{what}");
5482
    }
5483
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5484
        assert!(!hist.contains(&h), "{what}");
5485
    }
5486
    assert_eq!(hist[0], deleted, "newest first");
5487
    // One line: only what touched it.
5488
    let one: Vec<ChangeHash> = repo
5489
        .line_history(&heads, "f.rs", 1, 1)
5490
        .unwrap()
5491
        .iter()
5492
        .map(|e| e.hash)
5493
        .collect();
5494
    assert!(one.contains(&outside) && !one.contains(&inside));
5495
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5496
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5497
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5498
}
5499
5500
#[test]
5501
fn receipts_are_kept_with_their_state_and_verified() {
5502
    use crate::receipt::{Receipt, SignedReceipt};
5503
    hermetic();
5504
    let dir = tempfile::tempdir().unwrap();
5505
    let root = dir.path();
5506
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5507
    write(root, "a.txt", b"1\n");
5508
    repo.commit("A", &[]).unwrap();
5509
    let heads = repo.bookmark_heads().unwrap();
5510
    let state = repo
5511
        .store()
5512
        .put_state(&StateObject::new(heads.clone()))
5513
        .unwrap();
5514
    let out = repo.store_blob(b"built\n").unwrap();
5515
    let receipt = Receipt {
5516
        job_name: "build".into(),
5517
        pipeline_hash: ObjectRef([1; 32]),
5518
        scope_tree_hash: ObjectRef([2; 32]),
5519
        inputs: vec![],
5520
        environment: ObjectRef([3; 32]),
5521
        outputs: vec![out],
5522
        exit_code: 0,
5523
        duration_ms: 42,
5524
    };
5525
    let sk = SecretKey::generate();
5526
    let runner = sk.identity("earth-1", "runner@earth", 1);
5527
    let sr = SignedReceipt::sign(
5528
        receipt.clone(),
5529
        repo.id().unwrap(),
5530
        state,
5531
        "demo#1",
5532
        &runner,
5533
        &sk,
5534
    );
5535
5536
    let r = repo.add_receipt(&sr).unwrap();
5537
    let found = repo.receipts(&heads).unwrap();
5538
    assert_eq!(found.len(), 1);
5539
    assert_eq!(found[0].attest, r);
5540
    assert_eq!(found[0].signed, sr);
5541
    assert!(found[0].problem.is_none() && !found[0].revoked);
5542
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5543
5544
    // Another repository's receipt, or a forged one, is refused.
5545
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5546
    assert!(repo
5547
        .add_receipt(&elsewhere)
5548
        .unwrap_err()
5549
        .to_string()
5550
        .contains("another repository"));
5551
    let mut forged = sr.clone();
5552
    forged.receipt.exit_code = 1;
5553
    assert!(repo
5554
        .add_receipt(&forged)
5555
        .unwrap_err()
5556
        .to_string()
5557
        .contains("does not verify"));
5558
5559
    // gc keeps the receipt, its runner and its output while the state lives.
5560
    repo.gc(true).unwrap();
5561
    assert_eq!(repo.receipts(&heads).unwrap().len(), 1);
5562
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5563
    assert!(repo.fsck().unwrap().problems.is_empty());
5564
}
5565
5566
#[test]
5567
fn status_leaves_an_unchanged_manifest_alone() {
5568
    hermetic();
5569
    let dir = tempfile::tempdir().unwrap();
5570
    let root = dir.path();
5571
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5572
    write(root, "a.txt", b"1\n");
5573
    write(root, "b.txt", b"2\n");
5574
    repo.commit("A", &[]).unwrap();
5575
    // Files last touched well outside the racy window.
5576
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5577
    for f in ["a.txt", "b.txt"] {
5578
        fs::File::options()
5579
            .write(true)
5580
            .open(root.join(f))
5581
            .unwrap()
5582
            .set_modified(old)
5583
            .unwrap();
5584
    }
5585
    repo.snapshot_status("status").unwrap();
5586
    let path = repo.manifest_path();
5587
    let first = fs::read(&path).unwrap();
5588
    repo.snapshot_status("status").unwrap();
5589
    assert_eq!(
5590
        fs::read(&path).unwrap(),
5591
        first,
5592
        "an unchanged tree does not rewrite the manifest"
5593
    );
5594
    // A change rewrites it.
5595
    write(root, "a.txt", b"1\n2\n");
5596
    repo.snapshot_status("status").unwrap();
5597
    assert_ne!(fs::read(&path).unwrap(), first);
5598
}
5599
5600
#[test]
5601
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5602
    hermetic();
5603
    let dir = tempfile::tempdir().unwrap();
5604
    let root = dir.path();
5605
    let origin_path = root.join("origin");
5606
    Repo::init(&origin_path).unwrap();
5607
    let origin_url = origin_path.to_string_lossy().to_string();
5608
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5609
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5610
    write(&root.join("a"), "big.txt", big.as_bytes());
5611
    write(&root.join("a"), "small.txt", b"small\n");
5612
    let h1 = a.commit("large", &[]).unwrap();
5613
    let (_, body) = a.store().get(&h1).unwrap();
5614
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5615
    assert!(a.push("origin", false).unwrap()[0].ok);
5616
5617
    // A clone reads the text from the blobs that came with the change.
5618
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5619
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5620
    // An edit in the middle of the stored insert is an ordinary change.
5621
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5622
    write(&root.join("b"), "big.txt", edited.as_bytes());
5623
    let h2 = b.commit("edit", &[]).unwrap();
5624
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5625
    assert!(b.push("origin", false).unwrap()[0].ok);
5626
    assert!(a.pull("origin").unwrap().checked_out);
5627
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5628
    assert_eq!(
5629
        a.fsck().unwrap().errors(),
5630
        0,
5631
        "{:?}",
5632
        a.fsck().unwrap().problems
5633
    );
5634
5635
    // With zero retention gc keeps the text blobs of every kept change.
5636
    let mut a = Repo::open(&root.join("a")).unwrap();
5637
    a.config.set("core.op-retention", "0").unwrap();
5638
    a.save_config().unwrap();
5639
    let a = Repo::open(&root.join("a")).unwrap();
5640
    a.gc(true).unwrap();
5641
    let a = Repo::open(&root.join("a")).unwrap();
5642
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5643
    assert_eq!(
5644
        a.fsck().unwrap().errors(),
5645
        0,
5646
        "{:?}",
5647
        a.fsck().unwrap().problems
5648
    );
5649
    // And a clone of the packed repository reads them from its packs.
5650
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5651
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5652
    drop(c);
5653
}
5654
5655
#[test]
5656
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5657
    hermetic();
5658
    let dir = tempfile::tempdir().unwrap();
5659
    let root = dir.path();
5660
    let repo = Repo::init(root).unwrap();
5661
    write(root, "a.txt", b"a\n");
5662
    let a = repo.commit("a", &[]).unwrap();
5663
    write(root, "b.txt", b"b\n");
5664
    repo.commit("b", &[]).unwrap();
5665
    let (x, op) = repo.head_op().unwrap();
5666
    let ws = *op.view.workspaces.keys().next().unwrap();
5667
    let mut one = op.view.clone();
5668
    one.workspaces.insert(ws, a);
5669
    let mut two = op.view.clone();
5670
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5671
    let first = repo.record_op(&[x], "one", one).unwrap();
5672
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5673
    assert!(
5674
        e.to_string()
5675
            .contains("changed this working copy at the same time"),
5676
        "{e}"
5677
    );
5678
    assert_eq!(
5679
        repo.head_op().unwrap().0,
5680
        first,
5681
        "the second is not recorded"
5682
    );
5683
}
5684
5685
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5686
/// rewrote the working copy recorded the half-written files as edits, and
5687
/// its view replaced the switch's.
5688
#[test]
5689
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5690
    hermetic();
5691
    let dir = tempfile::tempdir().unwrap();
5692
    let root = dir.path().to_path_buf();
5693
    let mut repo = Repo::init(&root).unwrap();
5694
    write(&root, "keep.txt", b"keep\n");
5695
    repo.commit("base", &[]).unwrap();
5696
    repo.bookmark_create("small", None).unwrap();
5697
    for i in 0..300 {
5698
        write(
5699
            &root,
5700
            &format!("many/f{i}.txt"),
5701
            format!("file {i}\n").as_bytes(),
5702
        );
5703
    }
5704
    repo.commit("many", &[]).unwrap();
5705
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5706
    let watcher = {
5707
        let (root, stop) = (root.clone(), stop.clone());
5708
        std::thread::spawn(move || {
5709
            let r = Repo::open(&root).unwrap();
5710
            let mut ran = 0;
5711
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
5712
                if r.snapshot_status("oxy status").is_ok() {
5713
                    ran += 1;
5714
                }
5715
            }
5716
            ran
5717
        })
5718
    };
5719
    for i in 0..20 {
5720
        let to = if i % 2 == 0 { "small" } else { "main" };
5721
        repo.bookmark_switch(to, false).unwrap();
5722
    }
5723
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
5724
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
5725
    // Back on main, clean, with every file where main has it.
5726
    let repo = Repo::open(&root).unwrap();
5727
    let s = repo.snapshot_status("oxy status").unwrap();
5728
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
5729
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
5730
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
5731
    assert!(root.join("many/f299.txt").exists());
5732
}
5733
5734
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
5735
/// put a subrepo that was ahead of its pin back at the pin and moved the
5736
/// subrepo's own bookmark backwards.
5737
#[test]
5738
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
5739
    hermetic();
5740
    let dir = tempfile::tempdir().unwrap();
5741
    let root = dir.path();
5742
    Repo::init(&root.join("lib-origin")).unwrap();
5743
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5744
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
5745
    write(&root.join("lib"), "lib.txt", b"v1\n");
5746
    lib.commit("lib v1", &[]).unwrap();
5747
    assert!(lib.push("origin", false).unwrap()[0].ok);
5748
5749
    let app_dir = root.join("app");
5750
    let mut app = Repo::init(&app_dir).unwrap();
5751
    write(&app_dir, "main.txt", b"app\n");
5752
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5753
    app.commit("app with lib", &[]).unwrap();
5754
    app.bookmark_create("feature", None).unwrap();
5755
5756
    // New work in the subrepo, not yet pinned by the parent.
5757
    let nested_dir = app_dir.join("libs/lib");
5758
    let nested = Repo::open(&nested_dir).unwrap();
5759
    write(&nested_dir, "new.txt", b"new\n");
5760
    let l2 = nested.commit("lib: new file", &[]).unwrap();
5761
    drop(nested);
5762
5763
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
5764
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
5765
    let nested = Repo::open(&nested_dir).unwrap();
5766
    assert!(
5767
        nested.bookmark_heads().unwrap().contains(&l2),
5768
        "its bookmark kept its work"
5769
    );
5770
    assert!(nested_dir.join("new.txt").exists(), "and its files");
5771
    let s = app.snapshot("status").unwrap();
5772
    assert_eq!(
5773
        statuses(&s),
5774
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
5775
    );
5776
}
5777
5778
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
5779
/// moving `main` to a change this clone had pushed on another bookmark,
5780
/// the first `pull` said "Already up to date" while `main` was behind.
5781
#[test]
5782
fn pull_takes_a_remote_move_to_changes_already_here() {
5783
    hermetic();
5784
    let dir = tempfile::tempdir().unwrap();
5785
    let root = dir.path();
5786
    let origin_path = root.join("origin");
5787
    let origin = Repo::init(&origin_path).unwrap();
5788
    let url = origin_path.to_string_lossy().to_string();
5789
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
5790
    write(&root.join("b"), "base.txt", b"base\n");
5791
    b.commit("base", &[]).unwrap();
5792
    assert!(b.push("origin", false).unwrap()[0].ok);
5793
5794
    // A feature bookmark with one change, pushed.
5795
    b.bookmark_create("feat", None).unwrap();
5796
    b.bookmark_switch("feat", false).unwrap();
5797
    write(&root.join("b"), "x.txt", b"x\n");
5798
    let x = b.commit("x", &[]).unwrap();
5799
    assert!(b.push("origin", false).unwrap()[0].ok);
5800
    b.bookmark_switch("main", false).unwrap();
5801
5802
    // The remote lands it: its main moves to the feature's state.
5803
    let feat = origin
5804
        .store()
5805
        .get_state(&origin.view().unwrap().bookmarks["feat"])
5806
        .unwrap()
5807
        .heads;
5808
    origin.bookmark_set("main", &feat).unwrap();
5809
5810
    let r = b.pull("origin").unwrap();
5811
    assert!(r.changed, "{r:?}");
5812
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
5813
    let main = b
5814
        .bookmarks()
5815
        .unwrap()
5816
        .into_iter()
5817
        .find(|m| m.name == "main")
5818
        .unwrap();
5819
    assert_eq!(main.behind, Some(0), "{main:?}");
5820
}
5821
5822
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
5823
/// to one only the remote has makes a local bookmark from it; a pull moves
5824
/// every local bookmark the remote has too; a clone checks out the remote's
5825
/// default bookmark.
5826
#[test]
5827
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
5828
    hermetic();
5829
    let dir = tempfile::tempdir().unwrap();
5830
    let root = dir.path();
5831
    let origin_path = root.join("origin");
5832
    let mut origin = Repo::init(&origin_path).unwrap();
5833
    let url = origin_path.to_string_lossy().to_string();
5834
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
5835
    write(&root.join("a"), "base.txt", b"base\n");
5836
    a.commit("base", &[]).unwrap();
5837
    assert!(a.push("origin", false).unwrap()[0].ok);
5838
    a.bookmark_create("develop", None).unwrap();
5839
    a.bookmark_switch("develop", false).unwrap();
5840
    write(&root.join("a"), "base.txt", b"base\nd1\n");
5841
    let d1 = a.commit("d1", &[]).unwrap();
5842
    assert!(a.push("origin", false).unwrap()[0].ok);
5843
5844
    // A clone has main only; origin/develop is a name all the same.
5845
    let c_root = root.join("c");
5846
    let mut c = Repo::clone(&url, &c_root).unwrap();
5847
    assert_eq!(c.config.bookmark, "main");
5848
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
5849
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
5850
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
5851
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
5852
5853
    // Switching makes the local bookmark from origin's.
5854
    c.bookmark_switch("develop", false).unwrap();
5855
    assert_eq!(c.config.bookmark, "develop");
5856
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
5857
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
5858
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
5859
    assert!(c.bookmark_switch("nowhere", false).is_err());
5860
5861
    // Both bookmarks move on the remote; one pull takes both.
5862
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
5863
    let d2 = a.commit("d2", &[]).unwrap();
5864
    assert!(a.push("origin", false).unwrap()[0].ok);
5865
    a.bookmark_switch("main", false).unwrap();
5866
    write(&root.join("a"), "m.txt", b"m\n");
5867
    let m = a.commit("m", &[]).unwrap();
5868
    assert!(a.push("origin", false).unwrap()[0].ok);
5869
    let r = c.pull("origin").unwrap();
5870
    assert!(r.changed && r.checked_out, "{r:?}");
5871
    assert_eq!(r.heads, vec![d2]);
5872
    assert_eq!(r.others, vec!["main".to_string()]);
5873
    assert!(c.resolve_heads("main").unwrap().contains(&m));
5874
    assert_eq!(
5875
        fs::read(c_root.join("base.txt")).unwrap(),
5876
        b"base\nd1\nd2\n"
5877
    );
5878
    let again = c.pull("origin").unwrap();
5879
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
5880
5881
    // A clone checks out the remote's default bookmark.
5882
    origin.config.set("workspace.bookmark", "develop").unwrap();
5883
    origin.save_config().unwrap();
5884
    let e = Repo::clone(&url, &root.join("e")).unwrap();
5885
    assert_eq!(e.config.bookmark, "develop");
5886
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
5887
    let reopened = Repo::open(&root.join("e")).unwrap();
5888
    assert_eq!(reopened.config.bookmark, "develop");
5889
    // REMOTE/NAME names the remote's bookmark to switch to.
5890
    let mut e = reopened;
5891
    e.bookmark_switch("origin/main", false).unwrap();
5892
    assert_eq!(e.config.bookmark, "main");
5893
    assert!(e.bookmark_heads().unwrap().contains(&m));
5894
}
5895
5896
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
5897
/// op restore goes back to an operation, files included, and undo takes
5898
/// the restore back whole; op revert undoes one operation alone; each
5899
/// operation's changes are described from the views.
5900
#[test]
5901
fn operations_can_be_read_restored_and_reverted() {
5902
    hermetic();
5903
    let dir = tempfile::tempdir().unwrap();
5904
    let root = dir.path();
5905
    let repo = Repo::init(root).unwrap();
5906
    write(root, "a.txt", b"a\n");
5907
    let first = repo.commit("first", &[]).unwrap();
5908
    write(root, "a.txt", b"a\nb\n");
5909
    let second = repo.commit("second", &[]).unwrap();
5910
    let at_second = repo.head_op().unwrap().0.to_hex();
5911
    repo.bookmark_create("keep", None).unwrap();
5912
    let created = repo.head_op().unwrap().0.to_hex();
5913
    write(root, "n.txt", b"n\n");
5914
    let third = repo.commit("third", &[]).unwrap();
5915
5916
    // What each operation changed.
5917
    let ops = repo.op_log().unwrap();
5918
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
5919
    assert!(
5920
        changes
5921
            .iter()
5922
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
5923
        "{changes:?}"
5924
    );
5925
    assert!(changes
5926
        .iter()
5927
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
5928
5929
    // Reading at an earlier operation.
5930
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
5931
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
5932
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
5933
    write(root, "z.txt", b"z\n");
5934
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
5935
    fs::remove_file(root.join("z.txt")).unwrap();
5936
    assert!(repo.resolve_op("zz").is_err());
5937
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
5938
5939
    // Restore goes back, files and all; undo takes it back whole.
5940
    repo.op_restore(&at_second, false).unwrap();
5941
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
5942
    assert!(!root.join("n.txt").exists());
5943
    repo.undo().unwrap();
5944
    let mut heads = repo.bookmark_heads().unwrap();
5945
    heads.sort();
5946
    let mut want = vec![second, third];
5947
    want.sort();
5948
    assert_eq!(heads, want);
5949
    assert!(
5950
        root.join("n.txt").exists(),
5951
        "the files came back with the undo"
5952
    );
5953
5954
    // Revert the bookmark's creation alone: the commit after it stays.
5955
    let r = repo.op_revert(&created).unwrap();
5956
    assert_eq!(r.reverted, vec!["keep".to_string()]);
5957
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
5958
    assert!(repo
5959
        .load_state(&repo.bookmark_heads().unwrap())
5960
        .unwrap()
5961
        .contains(&third));
5962
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
5963
    let _ = first;
5964
}
5965
5966
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
5967
/// from the status cache while every file is as the snapshot left it, and
5968
/// from a snapshot again as soon as one is not.
5969
#[test]
5970
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
5971
    hermetic();
5972
    let dir = tempfile::tempdir().unwrap();
5973
    let root = dir.path();
5974
    let repo = Repo::init(root).unwrap();
5975
    write(root, "a.txt", b"a\n");
5976
    write(root, "b.txt", b"b\n");
5977
    repo.commit("base", &[]).unwrap();
5978
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
5979
5980
    write(root, "a.txt", b"a\nmore\n");
5981
    assert_eq!(
5982
        repo.status_by_manifest().unwrap(),
5983
        None,
5984
        "no snapshot of the edit yet"
5985
    );
5986
    let snap = repo.snapshot_status("oxy status").unwrap();
5987
    assert_eq!(snap.statuses.len(), 1);
5988
    let cached = repo
5989
        .status_by_manifest()
5990
        .unwrap()
5991
        .expect("answered from the cache");
5992
    assert_eq!(cached.len(), 1);
5993
    assert_eq!(
5994
        (cached[0].path.as_str(), cached[0].status),
5995
        ("a.txt", ChangeStatus::Modified)
5996
    );
5997
5998
    // Any further change sends status back to a snapshot.
5999
    write(root, "a.txt", b"a\nmore\nand more\n");
6000
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6001
    repo.snapshot_status("oxy status").unwrap();
6002
    assert!(repo.status_by_manifest().unwrap().is_some());
6003
    write(root, "new.txt", b"n\n");
6004
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6005
    fs::remove_file(root.join("new.txt")).unwrap();
6006
    assert!(
6007
        repo.status_by_manifest().unwrap().is_some(),
6008
        "back as it was"
6009
    );
6010
    fs::remove_file(root.join("b.txt")).unwrap();
6011
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6012
    write(root, "b.txt", b"b\n");
6013
6014
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6015
    repo.snapshot_status("oxy status").unwrap();
6016
    repo.commit("more", &[]).unwrap();
6017
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6018
}
6019
6020
/// oxygen#41: while the status cache holds, the working copy's diff is
6021
/// rendered from the stored working-copy change, and says exactly what a
6022
/// snapshot's diff says.
6023
#[test]
6024
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6025
    hermetic();
6026
    let dir = tempfile::tempdir().unwrap();
6027
    let root = dir.path();
6028
    let repo = Repo::init(root).unwrap();
6029
    write(root, "a.txt", b"one\ntwo\nthree\n");
6030
    write(root, "gone.txt", b"bye\n");
6031
    repo.commit("base", &[]).unwrap();
6032
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6033
    write(root, "new.txt", b"hello\n");
6034
    fs::remove_file(root.join("gone.txt")).unwrap();
6035
    let snap = repo.snapshot_status("oxy status").unwrap();
6036
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6037
    assert!(
6038
        repo.status_by_manifest().unwrap().is_some(),
6039
        "the cache holds"
6040
    );
6041
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6042
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6043
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6044
}
6045
6046
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6047
/// while none has moved, the check stats the tracked files without listing
6048
/// the tree, and a file added or removed anywhere moves its directory's
6049
/// time, so the tree is listed again.
6050
#[test]
6051
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6052
    hermetic();
6053
    let dir = tempfile::tempdir().unwrap();
6054
    let root = dir.path();
6055
    let repo = Repo::init(root).unwrap();
6056
    write(root, "a.txt", b"a\n");
6057
    write(root, "sub/deep/b.txt", b"b\n");
6058
    repo.commit("base", &[]).unwrap();
6059
    // Out of the racy window: every file and directory a minute old.
6060
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6061
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6062
        fs::File::open(root.join(p))
6063
            .unwrap()
6064
            .set_modified(old)
6065
            .unwrap();
6066
    }
6067
    repo.snapshot_status("oxy status").unwrap();
6068
    repo.write_manifest(false, false).unwrap();
6069
    let m = repo.read_manifest().unwrap().unwrap().2;
6070
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6071
    assert_eq!(
6072
        repo.disk_differs_by_dirs(&m),
6073
        Some(false),
6074
        "no listing needed"
6075
    );
6076
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6077
6078
    // A same-size edit with a new time: found by its stat.
6079
    write(root, "sub/deep/b.txt", b"c\n");
6080
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6081
    write(root, "sub/deep/b.txt", b"b\n");
6082
    fs::File::open(root.join("sub/deep/b.txt"))
6083
        .unwrap()
6084
        .set_modified(old)
6085
        .unwrap();
6086
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6087
6088
    // A new file moves its directory's time: the tree must be listed.
6089
    write(root, "sub/deep/new.txt", b"n\n");
6090
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6091
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6092
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6093
    // A removed one too.
6094
    fs::remove_file(root.join("a.txt")).unwrap();
6095
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6096
}
6097
6098
/// oxygen#41: a commit right after a status takes the snapshot the status
6099
/// left (the status cache holds) rather than walking again, and commits
6100
/// exactly what a snapshot would have.
6101
#[test]
6102
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6103
    hermetic();
6104
    let dir = tempfile::tempdir().unwrap();
6105
    let root = dir.path();
6106
    let repo = Repo::init(root).unwrap();
6107
    write(root, "a.txt", b"a\nb\n");
6108
    write(root, ".oxyattributes", b"*.bin binary\n");
6109
    repo.commit("base", &[]).unwrap();
6110
    write(root, "a.txt", b"a\nB\n");
6111
    write(root, "new.txt", b"new\n");
6112
    let snap = repo.snapshot_status("oxy status").unwrap();
6113
    let cached = repo
6114
        .snapshot_from_cache()
6115
        .unwrap()
6116
        .expect("the cache holds");
6117
    assert_eq!(cached.wc_hash, snap.wc_hash);
6118
    assert_eq!(cached.statuses, snap.statuses);
6119
    assert!(
6120
        !cached.attributes.is_empty(),
6121
        "the .oxyattributes file was read"
6122
    );
6123
    let h = repo.commit("edit", &[]).unwrap();
6124
    let c = repo.store().get_change(&h).unwrap();
6125
    assert_eq!(
6126
        c.tree_ops.len() + c.edits.len(),
6127
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6128
    );
6129
    assert_eq!(
6130
        repo.status_by_manifest().unwrap(),
6131
        Some(vec![]),
6132
        "clean after the commit"
6133
    );
6134
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6135
}
6136
6137
/// oxygen#41: a clean check that verified racy entries restamps the
6138
/// manifest, so later checks can trust them, and a same-size rewrite
6139
/// straight afterwards is still found: entries within two seconds of the
6140
/// new time stay racy.
6141
#[test]
6142
fn a_verified_clean_check_restamps_the_manifest_safely() {
6143
    hermetic();
6144
    let dir = tempfile::tempdir().unwrap();
6145
    let root = dir.path();
6146
    let repo = Repo::init(root).unwrap();
6147
    write(root, "a.txt", b"one\n");
6148
    repo.commit("one", &[]).unwrap();
6149
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6150
    assert!(repo.clean_by_manifest().unwrap());
6151
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6152
    assert!(after > before, "restamped");
6153
    write(root, "a.txt", b"two\n");
6154
    assert!(
6155
        !repo.clean_by_manifest().unwrap(),
6156
        "a same-size rewrite is still seen"
6157
    );
6158
}
6159
6160
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6161
/// stored insert's text blob only when it builds that file's graph, and
6162
/// builds the same graph a full load does.
6163
#[test]
6164
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6165
    hermetic();
6166
    let dir = tempfile::tempdir().unwrap();
6167
    let root = dir.path();
6168
    let repo = Repo::init(root).unwrap();
6169
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6170
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6171
    write(root, "big.txt", big.as_bytes());
6172
    write(root, "other.txt", other.as_bytes());
6173
    let h = repo.commit("two large files", &[]).unwrap();
6174
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6175
    let h2 = repo.commit("append", &[]).unwrap();
6176
6177
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6178
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6179
        FileContent::Text { bytes, .. } => bytes.clone(),
6180
        other => panic!("{other:?}"),
6181
    };
6182
    // Built on demand, every graph renders as the full load's.
6183
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6184
    let big_node = full.files["big.txt"].node;
6185
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6186
    repo.load_all_graphs(&mut hist).unwrap();
6187
    let rendered = hist.materialize();
6188
    for p in ["big.txt", "other.txt"] {
6189
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6190
    }
6191
6192
    // Without other.txt's text blob, history still loads and big.txt still
6193
    // builds: nothing read the other text.
6194
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6195
    assert_eq!(texts.len(), 2);
6196
    let content = |r: &ObjectRef| -> Vec<u8> {
6197
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6198
        blob.chunks
6199
            .iter()
6200
            .flat_map(|c| repo.store().get(c).unwrap().1)
6201
            .collect()
6202
    };
6203
    let other_text = texts
6204
        .iter()
6205
        .filter_map(|t| match t {
6206
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6207
            _ => None,
6208
        })
6209
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6210
        .unwrap();
6211
    repo.store().remove_loose_for_test(&other_text).unwrap();
6212
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6213
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6214
    assert!(repo
6215
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6216
        .is_err());
6217
}
6218
6219
/// oxygen#35: the first status after a commit read and rendered every
6220
/// file (79 s and more than 14 GB on the Linux tree), because the
6221
/// manifest had no graph keys for files the commit added.
6222
#[test]
6223
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6224
    use std::os::unix::fs::PermissionsExt;
6225
    hermetic();
6226
    let dir = tempfile::tempdir().unwrap();
6227
    let root = dir.path();
6228
    let repo = Repo::init(root).unwrap();
6229
    let files = ["a.txt", "b.txt", "d/c.txt"];
6230
    for p in files {
6231
        write(root, p, format!("{p}\n").as_bytes());
6232
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6233
        fs::File::options()
6234
            .write(true)
6235
            .open(root.join(p))
6236
            .unwrap()
6237
            .set_modified(old)
6238
            .unwrap();
6239
    }
6240
    repo.commit("added", &[]).unwrap();
6241
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6242
    assert!(
6243
        m.entries.values().all(|e| e.graph.is_some()),
6244
        "keys recorded at commit"
6245
    );
6246
    // Unreadable files prove the next status reads none of them.
6247
    for p in files {
6248
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6249
    }
6250
    let snap = repo.snapshot_status("status").unwrap();
6251
    for p in files {
6252
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6253
    }
6254
    assert!(!snap.changed && snap.statuses.is_empty());
6255
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6256
}
6257
6258
/// oxygen#35: a checkout reads, renders and writes only the files whose
6259
/// graphs differ, and renders the rest a batch at a time.
6260
#[test]
6261
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6262
    use std::os::unix::fs::PermissionsExt;
6263
    hermetic();
6264
    let dir = tempfile::tempdir().unwrap();
6265
    let root = dir.path();
6266
    let origin = root.join("origin");
6267
    let mut repo = Repo::init(&origin).unwrap();
6268
    // More files than one batch holds.
6269
    let n = 2100;
6270
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6271
    for i in 0..n {
6272
        let p = format!("f/{i:04}.txt");
6273
        write(&origin, &p, format!("file {i}\n").as_bytes());
6274
        fs::File::options()
6275
            .write(true)
6276
            .open(origin.join(&p))
6277
            .unwrap()
6278
            .set_modified(old)
6279
            .unwrap();
6280
    }
6281
    repo.commit("many", &[]).unwrap();
6282
    repo.bookmark_create("feature", None).unwrap();
6283
    repo.bookmark_switch("feature", false).unwrap();
6284
    write(&origin, "f/0007.txt", b"changed\n");
6285
    repo.commit("one change", &[]).unwrap();
6286
6287
    // Switching back to main must not read the unchanged files.
6288
    for i in 0..n {
6289
        if i != 7 {
6290
            let p = origin.join(format!("f/{i:04}.txt"));
6291
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6292
        }
6293
    }
6294
    let r = repo.bookmark_switch("main", false).unwrap();
6295
    for i in 0..n {
6296
        let p = origin.join(format!("f/{i:04}.txt"));
6297
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6298
    }
6299
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6300
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6301
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6302
6303
    // A clone renders every file, across batches.
6304
    let c = root.join("clone");
6305
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6306
    for i in [0, 2047, 2048, n - 1] {
6307
        assert_eq!(
6308
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6309
            format!("file {i}\n").as_bytes()
6310
        );
6311
    }
6312
    let cloned = Repo::open(&c).unwrap();
6313
    assert!(cloned
6314
        .snapshot_status("status")
6315
        .unwrap()
6316
        .statuses
6317
        .is_empty());
6318
}
6319
6320
/// A file written just before the manifest (inside the racy window) is
6321
/// checked by its hash: trusted when equal, caught when edited in place
6322
/// with the same size and time.
6323
#[test]
6324
fn a_racy_manifest_entry_is_checked_by_hash() {
6325
    hermetic();
6326
    let dir = tempfile::tempdir().unwrap();
6327
    let root = dir.path();
6328
    let repo = Repo::init(root).unwrap();
6329
    write(root, "a.txt", b"one\n");
6330
    repo.commit("fresh", &[]).unwrap();
6331
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6332
    let t = fs::metadata(root.join("a.txt"))
6333
        .unwrap()
6334
        .modified()
6335
        .unwrap();
6336
    write(root, "a.txt", b"two\n");
6337
    fs::File::options()
6338
        .write(true)
6339
        .open(root.join("a.txt"))
6340
        .unwrap()
6341
        .set_modified(t)
6342
        .unwrap();
6343
    assert!(
6344
        !repo.clean_by_manifest().unwrap(),
6345
        "same size and time, other bytes"
6346
    );
6347
    assert_eq!(
6348
        statuses(&repo.snapshot_status("status").unwrap()),
6349
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6350
    );
6351
}
6352
6353
/// A fetch on one machine moves changes as stored, text blobs among the
6354
/// objects; a change whose text blob did not come is refused, not stored.
6355
#[test]
6356
fn a_raw_bundle_without_a_changes_text_is_refused() {
6357
    hermetic();
6358
    let dir = tempfile::tempdir().unwrap();
6359
    let root = dir.path();
6360
    let a = Repo::init(&root.join("a")).unwrap();
6361
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6362
    write(&root.join("a"), "big.txt", big.as_bytes());
6363
    let h = a.commit("big", &[]).unwrap();
6364
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6365
    assert_eq!(bundle.raw_changes.len(), 1);
6366
    assert!(bundle.changes.is_empty());
6367
    let b = Repo::init(&root.join("b")).unwrap();
6368
    let mut without = bundle.clone();
6369
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6370
    let e = b.import_bundle(&without, false).unwrap_err();
6371
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6372
    assert!(!b.store().has(&h));
6373
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6374
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6375
}
6376
6377
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6378
/// again was a second node for one Git path, so a file moved into it on
6379
/// another line, where the first node still stood, ended up in two places.
6380
/// An import now brings the directory back rather than make a new one.
6381
#[test]
6382
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6383
    hermetic();
6384
    if std::process::Command::new("git")
6385
        .arg("--version")
6386
        .output()
6387
        .is_err()
6388
    {
6389
        eprintln!("git not installed; skipping");
6390
        return;
6391
    }
6392
    let dir = tempfile::tempdir().unwrap();
6393
    let root = dir.path();
6394
    let g = root.join("src.git");
6395
    fs::create_dir_all(&g).unwrap();
6396
    let git = |args: &[&str]| -> String {
6397
        let out = std::process::Command::new("git")
6398
            .arg("-C")
6399
            .arg(&g)
6400
            .args([
6401
                "-c",
6402
                "user.name=Grace",
6403
                "-c",
6404
                "[email protected]",
6405
                "-c",
6406
                "commit.gpgsign=false",
6407
            ])
6408
            .args(args)
6409
            .output()
6410
            .unwrap();
6411
        assert!(
6412
            out.status.success(),
6413
            "git {args:?}: {}",
6414
            String::from_utf8_lossy(&out.stderr)
6415
        );
6416
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6417
    };
6418
    git(&["init", "-q", "-b", "main"]);
6419
    write(&g, "d/a.txt", b"a\n");
6420
    write(&g, "c/x.txt", b"x\n");
6421
    git(&["add", "."]);
6422
    git(&["commit", "-qm", "base"]);
6423
    // One line: move x into d while d still stands.
6424
    git(&["checkout", "-qb", "side"]);
6425
    git(&["mv", "c/x.txt", "d/x.txt"]);
6426
    git(&["commit", "-qm", "x into d"]);
6427
    // The other: d goes, comes back, and x moves into it too.
6428
    git(&["checkout", "-q", "main"]);
6429
    git(&["rm", "-q", "d/a.txt"]);
6430
    git(&["commit", "-qm", "d goes"]);
6431
    write(&g, "d/b.txt", b"b\n");
6432
    git(&["add", "."]);
6433
    git(&["commit", "-qm", "d comes back"]);
6434
    git(&["mv", "c/x.txt", "d/x.txt"]);
6435
    git(&["commit", "-qm", "x into d again"]);
6436
    git(&["merge", "-q", "--no-edit", "side"]);
6437
6438
    let repo = Repo::init(&root.join("o")).unwrap();
6439
    repo.import_git(&g, "main").unwrap();
6440
    let v = repo.verify_git_import(&g, "main").unwrap();
6441
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6442
    let st = repo
6443
        .load_state_history(&repo.bookmark_heads().unwrap())
6444
        .unwrap();
6445
    let view = st.tree().view();
6446
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6447
    // The directory is the one the first commit made.
6448
    // Commits made in one second tie on time: find the first by its message.
6449
    let first = repo
6450
        .log()
6451
        .unwrap()
6452
        .into_iter()
6453
        .find(|e| e.change.message.starts_with("base"))
6454
        .unwrap();
6455
    let base = repo
6456
        .load_state_history(&[first.hash])
6457
        .unwrap()
6458
        .tree()
6459
        .view();
6460
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6461
}
6462
6463
/// oxygen#30, the rest: a placement left under a directory another line
6464
/// removed is out of sight, so no diff reaches it; the merge that settles
6465
/// where the file is retires it.
6466
#[test]
6467
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6468
    hermetic();
6469
    if std::process::Command::new("git")
6470
        .arg("--version")
6471
        .output()
6472
        .is_err()
6473
    {
6474
        eprintln!("git not installed; skipping");
6475
        return;
6476
    }
6477
    let dir = tempfile::tempdir().unwrap();
6478
    let root = dir.path();
6479
    let g = root.join("src.git");
6480
    fs::create_dir_all(&g).unwrap();
6481
    let run = |args: &[&str]| {
6482
        std::process::Command::new("git")
6483
            .arg("-C")
6484
            .arg(&g)
6485
            .args([
6486
                "-c",
6487
                "user.name=Grace",
6488
                "-c",
6489
                "[email protected]",
6490
                "-c",
6491
                "commit.gpgsign=false",
6492
            ])
6493
            .args(args)
6494
            .output()
6495
            .unwrap()
6496
    };
6497
    let git = |args: &[&str]| {
6498
        let out = run(args);
6499
        assert!(
6500
            out.status.success(),
6501
            "git {args:?}: {}",
6502
            String::from_utf8_lossy(&out.stderr)
6503
        );
6504
    };
6505
    git(&["init", "-q", "-b", "main"]);
6506
    write(&g, "c/x.txt", b"x\n");
6507
    write(&g, "keep.txt", b"k\n");
6508
    git(&["add", "."]);
6509
    git(&["commit", "-qm", "base"]);
6510
    // One line renames the file within c; the other moves it out of c,
6511
    // which goes.
6512
    git(&["checkout", "-qb", "side"]);
6513
    git(&["mv", "c/x.txt", "c/y.txt"]);
6514
    git(&["commit", "-qm", "rename within c"]);
6515
    git(&["checkout", "-q", "main"]);
6516
    fs::create_dir_all(g.join("n")).unwrap();
6517
    git(&["mv", "c/x.txt", "n/x.txt"]);
6518
    git(&["commit", "-qm", "move out of c"]);
6519
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6520
    let _ = run(&["merge", "-q", "side"]);
6521
    let _ = run(&[
6522
        "rm",
6523
        "-q",
6524
        "--cached",
6525
        "--ignore-unmatch",
6526
        "c/y.txt",
6527
        "c/x.txt",
6528
    ]);
6529
    let _ = std::fs::remove_dir_all(g.join("c"));
6530
    write(&g, "n/x.txt", b"x\n");
6531
    git(&["add", "-A"]);
6532
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6533
6534
    let repo = Repo::init(&root.join("o")).unwrap();
6535
    repo.import_git(&g, "main").unwrap();
6536
    let v = repo.verify_git_import(&g, "main").unwrap();
6537
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6538
    let st = repo
6539
        .load_state_history(&repo.bookmark_heads().unwrap())
6540
        .unwrap();
6541
    let view = st.tree().view();
6542
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6543
    assert!(view.entries.contains_key("n/x.txt"));
6544
}
6545
6546
/// oxygen#30, orphans: a file added on one line into a directory the other
6547
/// line removed is placed where the tree cannot show it; Git's merge keeps
6548
/// the file, and the import's merge leaves exactly one of it.
6549
#[test]
6550
fn git_import_merge_leaves_no_orphan_behind() {
6551
    hermetic();
6552
    if std::process::Command::new("git")
6553
        .arg("--version")
6554
        .output()
6555
        .is_err()
6556
    {
6557
        eprintln!("git not installed; skipping");
6558
        return;
6559
    }
6560
    let dir = tempfile::tempdir().unwrap();
6561
    let root = dir.path();
6562
    let g = root.join("src.git");
6563
    fs::create_dir_all(&g).unwrap();
6564
    let git = |args: &[&str]| {
6565
        let out = std::process::Command::new("git")
6566
            .arg("-C")
6567
            .arg(&g)
6568
            .args([
6569
                "-c",
6570
                "user.name=Grace",
6571
                "-c",
6572
                "[email protected]",
6573
                "-c",
6574
                "commit.gpgsign=false",
6575
            ])
6576
            .args(args)
6577
            .output()
6578
            .unwrap();
6579
        assert!(
6580
            out.status.success(),
6581
            "git {args:?}: {}",
6582
            String::from_utf8_lossy(&out.stderr)
6583
        );
6584
    };
6585
    git(&["init", "-q", "-b", "main"]);
6586
    write(&g, "d/f.txt", b"f\n");
6587
    write(&g, "keep.txt", b"k\n");
6588
    git(&["add", "."]);
6589
    git(&["commit", "-qm", "base"]);
6590
    git(&["checkout", "-qb", "side"]);
6591
    write(&g, "d/new.txt", b"new\n");
6592
    git(&["add", "."]);
6593
    git(&["commit", "-qm", "add into d"]);
6594
    git(&["checkout", "-q", "main"]);
6595
    git(&["rm", "-q", "d/f.txt"]);
6596
    git(&["commit", "-qm", "d goes"]);
6597
    git(&["merge", "-q", "--no-edit", "side"]);
6598
6599
    let repo = Repo::init(&root.join("o")).unwrap();
6600
    repo.import_git(&g, "main").unwrap();
6601
    let v = repo.verify_git_import(&g, "main").unwrap();
6602
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6603
    let st = repo
6604
        .load_state_history(&repo.bookmark_heads().unwrap())
6605
        .unwrap();
6606
    let view = st.tree().view();
6607
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6608
    assert!(view.entries.contains_key("d/new.txt"));
6609
}
6610
6611
/// fsck checks a change's text as the blobs it is stored in, without
6612
/// decoding it: a missing text blob is an error named for the change.
6613
#[test]
6614
fn fsck_names_a_missing_text_blob() {
6615
    hermetic();
6616
    let dir = tempfile::tempdir().unwrap();
6617
    let root = dir.path();
6618
    let repo = Repo::init(root).unwrap();
6619
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6620
    write(root, "big.txt", big.as_bytes());
6621
    let h = repo.commit("big", &[]).unwrap();
6622
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6623
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6624
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6625
        panic!("a stored text")
6626
    };
6627
    repo.store().remove_loose_for_test(&b).unwrap();
6628
    let rep = repo.fsck().unwrap();
6629
    assert!(rep.errors() > 0);
6630
    assert!(
6631
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6632
        "{:?}",
6633
        rep.problems
6634
    );
6635
}
6636
6637
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6638
/// reached with that remote's token and CA (a private subrepo then clones
6639
/// for anyone who can read the parent); another hub gets none of them.
6640
#[test]
6641
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6642
    hermetic();
6643
    let dir = tempfile::tempdir().unwrap();
6644
    let mut repo = Repo::init(dir.path()).unwrap();
6645
    repo.config
6646
        .set(
6647
            "remote.origin.url",
6648
            "https://Hub.example:7343/doomsdayone/metalgear",
6649
        )
6650
        .unwrap();
6651
    repo.config.set("remote.origin.token", "secret").unwrap();
6652
    repo.config
6653
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6654
        .unwrap();
6655
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6656
    assert_eq!(same.token.as_deref(), Some("secret"));
6657
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6658
    for other in [
6659
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6660
        "https://hub.example/doomsdayone/rstar-api",
6661
        "http://hub.example:7343/doomsdayone/rstar-api",
6662
    ] {
6663
        let o = repo.credentials_for(other);
6664
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6665
    }
6666
}
6667
6668
/// oxygen#47: a remote with no token of its own uses the user's credential
6669
/// store for its hub, and a nested checkout finds its parent's remote
6670
/// token there instead of keeping a copy.
6671
#[test]
6672
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
6673
    hermetic();
6674
    let home = tempfile::tempdir().unwrap();
6675
    let dir = tempfile::tempdir().unwrap();
6676
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
6677
    parent
6678
        .config
6679
        .set("remote.origin.url", "https://hub.example/o/parent")
6680
        .unwrap();
6681
    parent.save_config().unwrap();
6682
    assert_eq!(parent.remote_options("origin").token, None);
6683
    crate::credentials::Credentials::at(home.path())
6684
        .save("https://hub.example", "stored", Some("andy"), None)
6685
        .unwrap();
6686
    assert_eq!(
6687
        parent.remote_options("origin").token.as_deref(),
6688
        Some("stored")
6689
    );
6690
6691
    let empty_home = tempfile::tempdir().unwrap();
6692
    let nested = dir.path().join("deps").join("child");
6693
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
6694
    child
6695
        .config
6696
        .set("remote.origin.url", "https://hub.example/o/child")
6697
        .unwrap();
6698
    child.save_config().unwrap();
6699
    assert_eq!(child.remote_options("origin").token, None);
6700
    parent
6701
        .config
6702
        .set("remote.origin.token", "checkout")
6703
        .unwrap();
6704
    parent.save_config().unwrap();
6705
    assert_eq!(
6706
        child.remote_options("origin").token.as_deref(),
6707
        Some("checkout")
6708
    );
6709
    // Another hub's checkout token is not borrowed.
6710
    child
6711
        .config
6712
        .set("remote.origin.url", "https://other.example/o/child")
6713
        .unwrap();
6714
    assert_eq!(child.remote_options("origin").token, None);
6715
}
6716
6717
#[test]
6718
fn the_metadata_cache_survives_a_torn_tail() {
6719
    hermetic();
6720
    let dir = tempfile::tempdir().unwrap();
6721
    let root = dir.path();
6722
    let repo = Repo::init(root).unwrap();
6723
    write(root, "a.txt", b"1\n");
6724
    let h = repo.commit("first", &[]).unwrap();
6725
    let meta = repo.store().get_change_meta(&h).unwrap();
6726
    let cache = repo.store().dir().join("metas");
6727
    let len = fs::metadata(&cache).unwrap().len();
6728
    assert!(len > 0, "a change read is cached");
6729
    // A torn record at the end: the cache reads up to it and cuts it off.
6730
    fs::OpenOptions::new()
6731
        .append(true)
6732
        .open(&cache)
6733
        .unwrap()
6734
        .write_all(&[7; 20])
6735
        .unwrap();
6736
    let again = Repo::open(root).unwrap();
6737
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
6738
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
6739
}
6740
6741
#[test]
6742
fn a_manifest_that_does_not_check_reads_as_none() {
6743
    hermetic();
6744
    let dir = tempfile::tempdir().unwrap();
6745
    let root = dir.path();
6746
    let repo = Repo::init(root).unwrap();
6747
    write(root, "a.txt", b"1\n");
6748
    repo.commit("first", &[]).unwrap();
6749
    let path = repo.manifest_path();
6750
    let mut bytes = fs::read(&path).unwrap();
6751
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
6752
    let last = bytes.len() - 1;
6753
    bytes[last] ^= 1;
6754
    fs::write(&path, &bytes).unwrap();
6755
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
6756
    // The next status reads the files and writes it again.
6757
    let again = Repo::open(root).unwrap();
6758
    assert!(!again.snapshot("status").unwrap().changed);
6759
    assert!(again.read_manifest().unwrap().is_some());
6760
}
6761
6762
#[test]
6763
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
6764
    hermetic();
6765
    let dir = tempfile::tempdir().unwrap();
6766
    let root = dir.path();
6767
    let repo = Repo::init(root).unwrap();
6768
    write(root, "a.txt", b"1\n");
6769
    write(root, "b.txt", b"2\n");
6770
    // b.txt outside the racy window, so snapshots take it as unchanged.
6771
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6772
    fs::File::options()
6773
        .write(true)
6774
        .open(root.join("b.txt"))
6775
        .unwrap()
6776
        .set_modified(old)
6777
        .unwrap();
6778
    repo.commit("first", &[]).unwrap();
6779
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
6780
    repo.snapshot_status("status").unwrap();
6781
    write(root, "a.txt", b"1\n2\n");
6782
    repo.commit("second", &[]).unwrap();
6783
    assert!(
6784
        repo.clean_by_manifest().unwrap(),
6785
        "after a commit of one file"
6786
    );
6787
    // Edited, seen by a status, edited again, then committed: the status
6788
    // left the first edit's stat, which the commit must not keep.
6789
    write(root, "a.txt", b"1\n2\n3\n");
6790
    repo.snapshot_status("status").unwrap();
6791
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
6792
    repo.commit("third", &[]).unwrap();
6793
    assert!(
6794
        repo.clean_by_manifest().unwrap(),
6795
        "after an edit a status saw"
6796
    );
6797
}
6798
6799
#[test]
6800
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
6801
    hermetic();
6802
    let dir = tempfile::tempdir().unwrap();
6803
    let root = dir.path();
6804
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6805
    write(root, "a.txt", b"1\n2\n");
6806
    let a = repo.commit("A", &[]).unwrap();
6807
    repo.bookmark_create("develop", Some(&[a])).unwrap();
6808
    write(root, "a.txt", b"1\nX\n");
6809
    let c = repo.commit("C: 2 to X", &[]).unwrap();
6810
    repo.bookmark_switch("develop", false).unwrap();
6811
    write(root, "a.txt", b"1\nY\n");
6812
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
6813
    repo.bookmark_switch("main", false).unwrap();
6814
6815
    let err = repo.rebase(&c, &[d]).unwrap_err();
6816
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
6817
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
6818
    assert!(r.changed && r.checked_out);
6819
    let snap = repo.snapshot_status("status").unwrap();
6820
    assert!(
6821
        snap.base_snapshot.is_conflicted(),
6822
        "the conflict is in the working copy"
6823
    );
6824
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
6825
    assert!(text.contains('X') && text.contains('Y'), "{text}");
6826
6827
    write(root, "a.txt", b"1\nXY\n");
6828
    repo.commit("Resolve", &[]).unwrap();
6829
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
6830
    assert!(st.contains(&c) && st.contains(&d));
6831
    let files = st.materialize().files;
6832
    assert!(!files["a.txt"].is_conflicted());
6833
    assert!(
6834
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
6835
    );
6836
6837
    // A change the current bookmark does not hold is refused.
6838
    repo.bookmark_switch("develop", false).unwrap();
6839
    write(root, "b.txt", b"b\n");
6840
    let e = repo.commit("E", &[]).unwrap();
6841
    repo.bookmark_switch("main", false).unwrap();
6842
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
6843
    assert!(
6844
        err.to_string().contains("not on the current bookmark"),
6845
        "{err}"
6846
    );
6847
}
6848
6849
#[test]
6850
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
6851
    hermetic();
6852
    let dir = tempfile::tempdir().unwrap();
6853
    let root = dir.path();
6854
    let repo = Repo::init(root).unwrap();
6855
    write(root, "a.txt", b"a\n");
6856
    write(root, "kept.log", b"tracked\n");
6857
    repo.commit("first", &[]).unwrap();
6858
    write(root, "build.log", b"made\n");
6859
    let snap = repo.snapshot_status("status").unwrap();
6860
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
6861
    // A rule written afterwards leaves the added file out again, while the
6862
    // committed one stays tracked.
6863
    write(root, ".gitignore", b"*.log\n");
6864
    let snap = repo.snapshot_status("status").unwrap();
6865
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
6866
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
6867
    write(root, "kept.log", b"tracked, edited\n");
6868
    let snap = repo.snapshot_status("status").unwrap();
6869
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
6870
}
6871
6872
#[test]
6873
fn shed_graphs_come_back_the_same() {
6874
    hermetic();
6875
    let dir = tempfile::tempdir().unwrap();
6876
    let root = dir.path();
6877
    let repo = Repo::init(root).unwrap();
6878
    write(root, "a.txt", b"1\n2\n3\n");
6879
    write(root, "b.txt", b"x\n");
6880
    repo.commit("first", &[]).unwrap();
6881
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
6882
    repo.commit("second", &[]).unwrap();
6883
    let heads = repo.bookmark_heads().unwrap();
6884
    let mut st = repo.load_state_history(&heads).unwrap();
6885
    let view = st.tree().view();
6886
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
6887
        .iter()
6888
        .map(|p| view.entries[*p].node)
6889
        .collect();
6890
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6891
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6892
    assert_eq!(st.built_count(), 2);
6893
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
6894
    assert_eq!((shed, st.built_count()), (2, 0));
6895
    // A later change applies on top of the shed history.
6896
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
6897
    let h3 = repo.commit("third", &[]).unwrap();
6898
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
6899
    st.add_known(h3, skeleton, texts);
6900
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6901
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6902
    assert_eq!(after[1], before[1]);
6903
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
6904
}
6905
6906
#[test]
6907
fn many_edited_files_diff_in_parallel() {
6908
    // Enough edited files that the builder diffs them in parallel; the
6909
    // commit must hold exactly what is on disk, and a second snapshot
6910
    // must find nothing left to commit.
6911
    hermetic();
6912
    let dir = tempfile::tempdir().unwrap();
6913
    let root = dir.path();
6914
    let repo = Repo::init(root).unwrap();
6915
    let text = |i: usize, round: usize| {
6916
        let mut s = String::new();
6917
        for line in 0..50 {
6918
            if round > 0 && line % 7 == i % 7 {
6919
                s.push_str(&format!("edited {round} {i} {line}\n"));
6920
            } else {
6921
                s.push_str(&format!("file {i} line {line}\n"));
6922
            }
6923
        }
6924
        if round > 0 && i.is_multiple_of(3) {
6925
            s.push_str("appended\n");
6926
        }
6927
        s
6928
    };
6929
    for i in 0..40 {
6930
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
6931
    }
6932
    repo.commit("first", &[]).unwrap();
6933
    for i in 0..40 {
6934
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
6935
    }
6936
    let h = repo.commit("edit every file", &[]).unwrap();
6937
    let snap = repo.load_state(&[h]).unwrap().materialize();
6938
    for i in 0..40 {
6939
        let want = text(i, 1);
6940
        assert!(
6941
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
6942
            "d/f{i}.txt as committed"
6943
        );
6944
    }
6945
    assert!(
6946
        repo.commit("nothing", &[]).is_err(),
6947
        "nothing left to commit"
6948
    );
6949
}
6950
6951
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
6952
/// is known (fetch printed "up to date" while main was behind), a change
6953
/// only fetched resolves and says where it is, and a checkout whose only
6954
/// remote is not `origin` uses that one.
6955
#[test]
6956
fn a_fetched_change_shows_as_behind_and_resolves() {
6957
    hermetic();
6958
    let dir = tempfile::tempdir().unwrap();
6959
    let root = dir.path();
6960
    let origin = Repo::init(&root.join("origin")).unwrap();
6961
    drop(origin);
6962
    let url = root.join("origin").to_string_lossy().to_string();
6963
    let a = Repo::clone(&url, &root.join("a"))
6964
        .unwrap()
6965
        .with_home(root.join("home-a"));
6966
    write(&root.join("a"), "f.txt", b"one\n");
6967
    a.commit("one", &[]).unwrap();
6968
    a.push("origin", false).unwrap();
6969
    let b = Repo::clone(&url, &root.join("b"))
6970
        .unwrap()
6971
        .with_home(root.join("home-b"));
6972
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
6973
6974
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
6975
    let h2 = a.commit("two", &[]).unwrap();
6976
    a.push("origin", false).unwrap();
6977
    b.fetch("origin").unwrap();
6978
    // Fetched, not pulled: one behind, the change found and placed.
6979
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
6980
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
6981
    assert_eq!(
6982
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
6983
            .unwrap(),
6984
        h2
6985
    );
6986
    assert_eq!(
6987
        b.remote_only_location(&h2).unwrap().as_deref(),
6988
        Some("origin/main")
6989
    );
6990
    // Fetching again changes nothing: still behind, which is what the
6991
    // CLI now says rather than "up to date".
6992
    b.fetch("origin").unwrap();
6993
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
6994
    b.pull("origin").unwrap();
6995
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
6996
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
6997
6998
    // One remote, not called origin: it is the default.
6999
    let mut c = Repo::init(&root.join("c")).unwrap();
7000
    assert_eq!(c.default_remote(), "origin");
7001
    c.config.set("remote.earth.url", &url).unwrap();
7002
    assert_eq!(c.default_remote(), "earth");
7003
    c.config.set("remote.origin.url", &url).unwrap();
7004
    assert_eq!(c.default_remote(), "origin");
7005
}
7006
7007
/// oxygen#57: a clone from a relative local path records the remote as an
7008
/// absolute path, so fetch still finds it from inside the clone.
7009
#[test]
7010
fn a_clone_from_a_relative_path_records_it_absolute() {
7011
    hermetic();
7012
    let dir = tempfile::tempdir().unwrap();
7013
    let root = dir.path();
7014
    Repo::init(&root.join("origin")).unwrap();
7015
    let rel = crate::protocol::stored_url("relative/repo");
7016
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7017
    assert_eq!(
7018
        crate::protocol::stored_url("https://hub.example/o/n"),
7019
        "https://hub.example/o/n"
7020
    );
7021
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7022
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7023
    // A bucket is kept as written: it is not a path.
7024
    assert_eq!(
7025
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7026
        "s3://bucket/prefix?profile=p"
7027
    );
7028
    let url = root.join("origin").to_string_lossy().to_string();
7029
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7030
    assert_eq!(b.config.remotes["origin"], url);
7031
    b.fetch("origin").unwrap();
7032
}
7033
7034
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7035
/// and gets its subrepos at their pins from this workspace's copies, with
7036
/// their remotes pointing where the subrepos come from.
7037
#[test]
7038
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7039
    hermetic();
7040
    let dir = tempfile::tempdir().unwrap();
7041
    let root = dir.path();
7042
    Repo::init(&root.join("lib-origin")).unwrap();
7043
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7044
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7045
        .unwrap()
7046
        .with_home(root.join("home"));
7047
    write(&root.join("lib"), "lib.txt", b"v1\n");
7048
    let l1 = lib.commit("lib v1", &[]).unwrap();
7049
    assert!(lib.push("origin", false).unwrap()[0].ok);
7050
7051
    let app_dir = root.join("app");
7052
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7053
    write(&app_dir, "main.txt", b"app\n");
7054
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7055
    app.commit("app with lib", &[]).unwrap();
7056
    // A second bookmark, and the main workspace on another.
7057
    app.bookmark_create("develop", None).unwrap();
7058
    app.bookmark_create("feature", None).unwrap();
7059
    let mut app = app;
7060
    app.bookmark_switch("feature", false).unwrap();
7061
    assert_eq!(app.config.bookmark, "feature");
7062
7063
    // The library's origin goes away: the subrepo must come from here.
7064
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7065
    let heads = app.resolve_heads("develop").unwrap();
7066
    let ws = app
7067
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7068
        .unwrap();
7069
    assert_eq!(
7070
        ws.config.bookmark, "develop",
7071
        "the new workspace is on develop"
7072
    );
7073
    assert_eq!(
7074
        app.config.bookmark, "feature",
7075
        "and this one stays on its own"
7076
    );
7077
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7078
    assert_eq!(
7079
        sub.config.remotes["origin"], lib_url,
7080
        "its origin is the subrepo's URL"
7081
    );
7082
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7083
    assert_eq!(
7084
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7085
        b"v1\n"
7086
    );
7087
}
7088
7089
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7090
/// operators and the predicates, over a small graph with two heads and
7091
/// a rename.
7092
#[test]
7093
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7094
    hermetic();
7095
    let dir = tempfile::tempdir().unwrap();
7096
    let root = dir.path();
7097
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7098
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7099
        .unwrap();
7100
    write(root, "src/a.rs", b"one\n");
7101
    let a = repo.commit("first: add a", &[]).unwrap();
7102
    write(root, "src/a.rs", b"one\ntwo\n");
7103
    let b = repo.commit("second: grow a", &[]).unwrap();
7104
    // A second head, independent of b: a new file on top of a.
7105
    repo.checkout(&[a], false, "checkout a").unwrap();
7106
    write(root, "docs/notes.md", b"notes\n");
7107
    let c = repo.commit("third: notes", &[]).unwrap();
7108
    // Back to both heads, then rename a.rs: the node keeps its identity.
7109
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7110
        .unwrap();
7111
    fs::remove_file(root.join("src/a.rs")).unwrap();
7112
    write(root, "src/z.rs", b"one\ntwo\n");
7113
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7114
    let wc = repo.working_copy().unwrap().0;
7115
    // A saved revset is checked when set.
7116
    repo.set_user_config("revset.mine", "author(me) & ::main")
7117
        .unwrap();
7118
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7119
    let set = |src: &str| -> Vec<ChangeHash> {
7120
        let mut v = repo.revset(src).unwrap().hashes;
7121
        v.sort();
7122
        v
7123
    };
7124
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7125
        let mut v = hs.to_vec();
7126
        v.sort();
7127
        v
7128
    };
7129
7130
    // Changes commute: a new file depends on nothing and the rename on the
7131
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7132
    // copy on the three heads b, c, d.
7133
    let heads = sorted(&repo.bookmark_heads().unwrap());
7134
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7135
    assert!(heads.contains(&d) && heads.contains(&c));
7136
    // Symbols and closures.
7137
    assert_eq!(set("main"), heads);
7138
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7139
    assert_eq!(set("@"), vec![wc]);
7140
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7141
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7142
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7143
    assert_eq!(
7144
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7145
        sorted(&[a, b])
7146
    );
7147
    // Ranges: what main has beyond b, and `..` forms.
7148
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7149
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7150
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7151
    // Operators and precedence: ~ binds tighter than &, & than |.
7152
    assert_eq!(
7153
        set(&format!("::main ~ #{}", d.short(12))),
7154
        sorted(&[a, b, c])
7155
    );
7156
    assert_eq!(
7157
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7158
        sorted(&[b, c])
7159
    );
7160
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7161
    // Relations.
7162
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7163
    head_deps.sort();
7164
    head_deps.dedup();
7165
    assert_eq!(set("deps(main)"), head_deps);
7166
    let on_a: Vec<ChangeHash> = [b, c, d]
7167
        .into_iter()
7168
        .filter(|h| meta(h).deps.contains(&a))
7169
        .collect();
7170
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7171
    assert_eq!(set("heads(::main)"), heads);
7172
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7173
    assert_eq!(
7174
        set(&format!(
7175
            "heads(#{} | #{} | #{})",
7176
            a.short(12),
7177
            b.short(12),
7178
            c.short(12)
7179
        )),
7180
        sorted(&[b, c])
7181
    );
7182
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7183
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7184
    assert_eq!(set("none()"), vec![]);
7185
    // Predicates: author by name, email, key prefix and `me`.
7186
    let key = repo.config.author_key.unwrap();
7187
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7188
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7189
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7190
    assert_eq!(set("author(me) & ::main").len(), 4);
7191
    assert_eq!(set("author(nobody)"), vec![]);
7192
    assert_eq!(set("description(notes)"), vec![c]);
7193
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7194
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7195
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7196
    // touches follows the node through the rename, in the current state.
7197
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7198
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7199
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7200
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7201
    // Newest first in the result order.
7202
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7203
    // The saved revset, and errors that say what is wrong.
7204
    assert_eq!(set("mine()").len(), 4);
7205
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7206
    assert!(e.contains("unknown function nosuch()"), "{e}");
7207
    let e = repo.revset("main &").unwrap_err().to_string();
7208
    assert!(e.contains("at character"), "{e}");
7209
    let e = repo.revset("zzzz").unwrap_err().to_string();
7210
    assert!(e.contains("no change matches"), "{e}");
7211
    let e = repo
7212
        .revset_with_budget("::main", std::time::Duration::ZERO)
7213
        .unwrap_err()
7214
        .to_string();
7215
    assert!(e.contains("budget"), "{e}");
7216
    // The log entries carry the bookmark's heads and the working copy.
7217
    let entries = repo.log_revset("::@").unwrap();
7218
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7219
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7220
    // push); then a signed change, a tag, and a revocation.
7221
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7222
    assert_eq!(set("signed_by(me)"), vec![]);
7223
    repo.sign_change(&d).unwrap();
7224
    assert_eq!(set("signed_by(me)"), vec![d]);
7225
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7226
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7227
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7228
    assert_eq!(set("delegated()"), vec![]);
7229
    assert_eq!(set("revoked()"), vec![]);
7230
    assert_eq!(set("attested(tag)"), vec![]);
7231
    repo.tag_create("v1", &[b], "first").unwrap();
7232
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7233
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7234
    assert_eq!(set("attested(receipt)"), vec![]);
7235
    assert_eq!(set("built(test)"), vec![]);
7236
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7237
    assert!(e.contains("tag, receipt or ref"), "{e}");
7238
    repo.revoke_identity(&key, "test").unwrap();
7239
    assert_eq!(set("revoked()"), vec![d]);
7240
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7241
}
7242
7243
#[test]
7244
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7245
    let dir = tempfile::tempdir().unwrap();
7246
    let root = dir.path();
7247
    let home = root.join("home");
7248
    // Ada's identity lives in the user file; repository `a` pins the same
7249
    // key in its own file, repository `b` names none.
7250
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7251
    let (key, _) = a
7252
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7253
        .unwrap();
7254
    a.config.set("author.key", &key.to_hex()).unwrap();
7255
    a.save_config().unwrap();
7256
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7257
    let r = a
7258
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7259
        .unwrap();
7260
    assert_eq!(
7261
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7262
        r.new.to_hex(),
7263
        "the user file follows"
7264
    );
7265
    assert_eq!(
7266
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7267
        r.new.to_hex(),
7268
        "the pinning repository follows"
7269
    );
7270
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7271
    assert_eq!(
7272
        b.config.author_key,
7273
        Some(r.new),
7274
        "a checkout without a pin follows the user file"
7275
    );
7276
    // A repository-scoped identity leaves the user file alone.
7277
    let other_home = root.join("home2");
7278
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7279
    let (ck, _) = c
7280
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7281
        .unwrap();
7282
    assert!(!other_home.join("config.toml").exists());
7283
    let r2 = c.rotate_identity().unwrap();
7284
    assert_ne!(r2.new, ck);
7285
    assert_eq!(
7286
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7287
        r2.new.to_hex()
7288
    );
7289
    assert!(
7290
        !other_home.join("config.toml").exists(),
7291
        "a repository-scoped identity stays repository-scoped"
7292
    );
7293
    // Several delegates in one rotation; a repeat is refused.
7294
    let (d1, d2) = (
7295
        SecretKey::generate().identity("D1", "d1@x", 1),
7296
        SecretKey::generate().identity("D2", "d2@x", 1),
7297
    );
7298
    let r3 = c
7299
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7300
        .unwrap();
7301
    assert_eq!(r3.identity.delegates.len(), 2);
7302
    assert!(c
7303
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7304
        .is_err());
7305
}
7306
7307
/// Two unrelated histories that both add the same file, joined by two
7308
/// independent merges on two branches, then those branches merged: Git
7309
/// merges identical additions cleanly, and the import must too (#71,
7310
/// found in VS Code's history).
7311
#[test]
7312
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7313
    // Batches of one: every merge renders apart from the state, where a
7314
    // file whose graph the state had built came out empty (#71).
7315
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7316
    hermetic();
7317
    if std::process::Command::new("git")
7318
        .arg("--version")
7319
        .output()
7320
        .is_err()
7321
    {
7322
        eprintln!("git not installed; skipping");
7323
        return;
7324
    }
7325
    let dir = tempfile::tempdir().unwrap();
7326
    let root = dir.path();
7327
    let g = root.join("src.git");
7328
    fs::create_dir_all(&g).unwrap();
7329
    let git = |args: &[&str]| -> String {
7330
        let out = std::process::Command::new("git")
7331
            .arg("-C")
7332
            .arg(&g)
7333
            .args([
7334
                "-c",
7335
                "user.name=Grace",
7336
                "-c",
7337
                "[email protected]",
7338
                "-c",
7339
                "commit.gpgsign=false",
7340
            ])
7341
            .args(args)
7342
            .output()
7343
            .unwrap();
7344
        assert!(
7345
            out.status.success(),
7346
            "git {args:?}: {}",
7347
            String::from_utf8_lossy(&out.stderr)
7348
        );
7349
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7350
    };
7351
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7352
    // History A: main.
7353
    git(&["init", "-q", "-b", "main"]);
7354
    write(&g, "gulpfile.js", text);
7355
    write(&g, "a.txt", b"a\n");
7356
    git(&["add", "."]);
7357
    git(&["commit", "-q", "-m", "A root"]);
7358
    // History B: an unrelated root adding the same file, identical.
7359
    git(&["checkout", "-q", "--orphan", "fork"]);
7360
    git(&["rm", "-q", "-r", "--cached", "."]);
7361
    for f in ["gulpfile.js", "a.txt"] {
7362
        let _ = fs::remove_file(g.join(f));
7363
    }
7364
    write(&g, "gulpfile.js", text);
7365
    write(&g, "b.txt", b"b\n");
7366
    git(&["add", "."]);
7367
    git(&["commit", "-q", "-m", "B root"]);
7368
    // Two branches from main, each joining B on its own.
7369
    git(&["checkout", "-q", "-b", "one", "main"]);
7370
    git(&[
7371
        "merge",
7372
        "-q",
7373
        "--no-ff",
7374
        "--allow-unrelated-histories",
7375
        "-m",
7376
        "join on one",
7377
        "fork",
7378
    ]);
7379
    git(&["checkout", "-q", "-b", "two", "main"]);
7380
    write(&g, "a.txt", b"a\ntwo\n");
7381
    git(&["commit", "-q", "-am", "work on two"]);
7382
    git(&[
7383
        "merge",
7384
        "-q",
7385
        "--no-ff",
7386
        "--allow-unrelated-histories",
7387
        "-m",
7388
        "join on two",
7389
        "fork",
7390
    ]);
7391
    // Then the two joins meet, and the file is reformatted after.
7392
    git(&["checkout", "-q", "main"]);
7393
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7394
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7395
    write(
7396
        &g,
7397
        "gulpfile.js",
7398
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7399
    );
7400
    git(&["commit", "-q", "-am", "after"]);
7401
7402
    let dest = root.join("dest");
7403
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7404
    repo.import_git(&g, "main").unwrap();
7405
    let v = repo.verify_git_import(&g, "main").unwrap();
7406
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7407
    assert_eq!(
7408
        fs::read(dest.join("gulpfile.js")).unwrap(),
7409
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7410
    );
7411
}
7412
7413
/// As above, but the two joins keep different copies (each branch had a
7414
/// different version when it joined), and later work edits each copy:
7415
/// the shape of VS Code's c67ef57cda90 (#71).
7416
#[test]
7417
fn git_import_joins_where_each_join_kept_a_different_copy() {
7418
    // Batches of one: every merge renders apart from the state, where a
7419
    // file whose graph the state had built came out empty (#71).
7420
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7421
    hermetic();
7422
    if std::process::Command::new("git")
7423
        .arg("--version")
7424
        .output()
7425
        .is_err()
7426
    {
7427
        eprintln!("git not installed; skipping");
7428
        return;
7429
    }
7430
    let dir = tempfile::tempdir().unwrap();
7431
    let root = dir.path();
7432
    let g = root.join("src.git");
7433
    fs::create_dir_all(&g).unwrap();
7434
    let run = |args: &[&str]| {
7435
        std::process::Command::new("git")
7436
            .arg("-C")
7437
            .arg(&g)
7438
            .args([
7439
                "-c",
7440
                "user.name=Grace",
7441
                "-c",
7442
                "[email protected]",
7443
                "-c",
7444
                "commit.gpgsign=false",
7445
            ])
7446
            .args(args)
7447
            .output()
7448
            .unwrap()
7449
    };
7450
    let git = |args: &[&str]| -> String {
7451
        let out = run(args);
7452
        assert!(
7453
            out.status.success(),
7454
            "git {args:?}: {}",
7455
            String::from_utf8_lossy(&out.stderr)
7456
        );
7457
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7458
    };
7459
    git(&["init", "-q", "-b", "main"]);
7460
    write(
7461
        &g,
7462
        "gulpfile.js",
7463
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7464
    );
7465
    git(&["add", "."]);
7466
    git(&["commit", "-q", "-m", "A root"]);
7467
    write(
7468
        &g,
7469
        "gulpfile.js",
7470
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7471
    );
7472
    git(&["commit", "-q", "-am", "whitespace"]);
7473
    git(&["checkout", "-q", "--orphan", "fork"]);
7474
    git(&["rm", "-q", "-r", "--cached", "."]);
7475
    let _ = fs::remove_file(g.join("gulpfile.js"));
7476
    write(
7477
        &g,
7478
        "gulpfile.js",
7479
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7480
    );
7481
    git(&["add", "."]);
7482
    git(&["commit", "-q", "-m", "B root"]);
7483
    // Branch one joins B keeping main's copy; branch two keeps B's.
7484
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7485
        git(&["checkout", "-q", "-b", branch, "main"]);
7486
        let _ = run(&[
7487
            "merge",
7488
            "-q",
7489
            "--no-ff",
7490
            "--allow-unrelated-histories",
7491
            "-m",
7492
            "join",
7493
            "fork",
7494
        ]);
7495
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7496
        git(&["add", "gulpfile.js"]);
7497
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7498
    }
7499
    // Each branch then edits its copy.
7500
    git(&["checkout", "-q", "one"]);
7501
    write(
7502
        &g,
7503
        "gulpfile.js",
7504
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7505
    );
7506
    git(&["commit", "-q", "-am", "tslint on one"]);
7507
    git(&["checkout", "-q", "two"]);
7508
    write(
7509
        &g,
7510
        "gulpfile.js",
7511
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7512
    );
7513
    write(&g, "extra.txt", b"x\n");
7514
    write(&g, "more.txt", b"m\n");
7515
    git(&["add", "."]);
7516
    git(&["commit", "-q", "-am", "fmt on two"]);
7517
    // They meet: resolved by hand.
7518
    git(&["checkout", "-q", "one"]);
7519
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7520
    write(
7521
        &g,
7522
        "gulpfile.js",
7523
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7524
    );
7525
    git(&["add", "gulpfile.js"]);
7526
    git(&["commit", "-q", "-m", "merge two into one"]);
7527
7528
    let dest = root.join("dest");
7529
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7530
    repo.import_git(&g, "one").unwrap();
7531
    let v = repo.verify_git_import(&g, "one").unwrap();
7532
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7533
}
7534
7535
/// oxygen#68: on a store that is not this disk's directory, the operation
7536
/// head is the store's reference record, moved by compare-and-swap. Two
7537
/// handles recording from the same head both get through, merged; a swap
7538
/// from a stale version is refused; a second repository cannot start on a
7539
/// store that already holds one.
7540
#[test]
7541
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
7542
    use crate::strata::{MemoryStore, Store as _};
7543
    let backend = std::sync::Arc::new(MemoryStore::new());
7544
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
7545
    let dir = tempfile::tempdir().unwrap();
7546
    let a = Repo::init(dir.path()).unwrap();
7547
    assert!(
7548
        !dir.path().join(".oxy/ops/head").exists(),
7549
        "the head is not a file"
7550
    );
7551
    let (h0, op0) = a.head_op().unwrap();
7552
    let record = backend
7553
        .read_ref(HEAD_RECORD)
7554
        .unwrap()
7555
        .expect("the head is the store's record");
7556
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
7557
7558
    let b = Repo::open(dir.path()).unwrap();
7559
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
7560
    let mut va = op0.view.clone();
7561
    va.bookmarks.insert("from-a".into(), state);
7562
    let mut vb = op0.view.clone();
7563
    vb.bookmarks.insert("from-b".into(), state);
7564
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
7565
    assert_eq!(b.head_ref().unwrap(), rb);
7566
    // a recorded from h0 too: the head moved, so the two are merged.
7567
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
7568
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
7569
    assert_eq!(head, ra);
7570
    assert!(
7571
        op.command.ends_with("(merged with a concurrent operation)"),
7572
        "{}",
7573
        op.command
7574
    );
7575
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
7576
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
7577
7578
    // A swap from a version that is no longer current moves nothing.
7579
    let (h, v) = a.read_head().unwrap();
7580
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
7581
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
7582
    assert_eq!(a.head_ref().unwrap(), rb);
7583
7584
    let other = tempfile::tempdir().unwrap();
7585
    let err = Repo::init(other.path())
7586
        .err()
7587
        .expect("the store already holds a log")
7588
        .to_string();
7589
    assert!(
7590
        err.contains("already holds a repository's operation log"),
7591
        "{err}"
7592
    );
7593
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
7594
}
7595
7596
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
7597
/// objects and operation head there, with `.oxy/cache` in front: it works
7598
/// as one on disk does, reopens, and survives losing its cache.
7599
#[test]
7600
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
7601
    hermetic();
7602
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
7603
        return;
7604
    }
7605
    let dir = tempfile::tempdir().unwrap();
7606
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
7607
    let url = format!("dir://{}", bucket.display());
7608
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
7609
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
7610
    write(&root, "a.txt", b"one\n");
7611
    let h1 = repo.commit("First", &[]).unwrap();
7612
    write(&root, "a.txt", b"one\ntwo\n");
7613
    let h2 = repo.commit("Second", &[]).unwrap();
7614
    assert!(
7615
        !root.join(".oxy/ops/head").exists(),
7616
        "the head is in the store"
7617
    );
7618
    assert!(bucket.join("ops/head").is_file());
7619
    assert!(root.join(".oxy/cache").is_dir());
7620
    drop(repo);
7621
7622
    // Reopened, and again with no cache at all: everything comes from the store.
7623
    for drop_cache in [false, true] {
7624
        if drop_cache {
7625
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
7626
        }
7627
        let repo = Repo::open(&root).unwrap();
7628
        let log: Vec<String> = repo
7629
            .op_log()
7630
            .unwrap()
7631
            .into_iter()
7632
            .map(|(_, op)| op.command)
7633
            .collect();
7634
        assert!(log.len() >= 3, "{log:?}");
7635
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
7636
        let heads = repo
7637
            .store()
7638
            .get_state(&repo.view().unwrap().bookmarks["main"])
7639
            .unwrap()
7640
            .heads;
7641
        assert_eq!(heads, vec![h2]);
7642
        assert_eq!(
7643
            repo.load_state(&heads).unwrap().materialize().files.len(),
7644
            1
7645
        );
7646
    }
7647
7648
    // A second repository cannot start on the same store.
7649
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
7650
        .err()
7651
        .unwrap()
7652
        .to_string();
7653
    assert!(
7654
        err.contains("already holds a repository's operation log"),
7655
        "{err}"
7656
    );
7657
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
7658
        .err()
7659
        .unwrap()
7660
        .to_string();
7661
    assert!(err.contains("cannot open that kind of store"), "{err}");
7662
}
7663
7664
/// oxygen#75: the prompt's quick check agrees with status in a repository
7665
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
7666
/// another state, clean again once that pin is committed. (It compared the
7667
/// subrepo's directory as if it were a file, so it was always dirty.)
7668
#[test]
7669
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
7670
    hermetic();
7671
    let dir = tempfile::tempdir().unwrap();
7672
    let root = dir.path();
7673
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7674
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7675
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7676
        .unwrap()
7677
        .with_home(root.join("home"));
7678
    write(&root.join("lib"), "lib.txt", b"v1\n");
7679
    lib.commit("lib v1", &[]).unwrap();
7680
    assert!(lib.push("origin", false).unwrap()[0].ok);
7681
    let app_dir = root.join("app");
7682
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7683
    write(&app_dir, "main.txt", b"app\n");
7684
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7685
    app.commit("app with lib", &[]).unwrap();
7686
    // Out of the racy window, so the stat-only path decides.
7687
    std::thread::sleep(std::time::Duration::from_millis(2100));
7688
    let reopen = || Repo::open(&app_dir).unwrap();
7689
    assert_eq!(
7690
        reopen().quick_dirty().unwrap(),
7691
        Some(false),
7692
        "clean, as status says"
7693
    );
7694
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
7695
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
7696
    nested.commit("lib v2", &[]).unwrap();
7697
    assert_eq!(
7698
        reopen().quick_dirty().unwrap(),
7699
        Some(true),
7700
        "the subrepo moved"
7701
    );
7702
    reopen().commit("pin lib v2", &[]).unwrap();
7703
    std::thread::sleep(std::time::Duration::from_millis(2100));
7704
    assert_eq!(
7705
        reopen().quick_dirty().unwrap(),
7706
        Some(false),
7707
        "the new pin is committed"
7708
    );
7709
}
7710
7711
#[test]
7712
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
7713
    // oxygen#72: a .oxymodules section with no subrepo behind it.
7714
    hermetic();
7715
    let dir = tempfile::tempdir().unwrap();
7716
    let root = dir.path();
7717
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7718
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7719
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7720
        .unwrap()
7721
        .with_home(root.join("home"));
7722
    write(&root.join("lib"), "lib.txt", b"v1\n");
7723
    lib.commit("lib v1", &[]).unwrap();
7724
    assert!(lib.push("origin", false).unwrap()[0].ok);
7725
    let app_dir = root.join("app");
7726
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7727
    write(
7728
        &app_dir,
7729
        ".oxymodules",
7730
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
7731
    );
7732
    let unpinned = app.unpinned_modules().unwrap();
7733
    assert_eq!(unpinned.len(), 1);
7734
    assert_eq!(unpinned[0].0, "libs/lib");
7735
    assert_eq!(unpinned[0].1.url, lib_url);
7736
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
7737
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7738
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
7739
}
7740
7741
#[test]
7742
fn the_bookmark_revset_function_names_only_bookmarks() {
7743
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
7744
    hermetic();
7745
    let dir = tempfile::tempdir().unwrap();
7746
    let repo = Repo::init(dir.path()).unwrap();
7747
    write(dir.path(), "a.txt", b"a\n");
7748
    let a = repo.commit("A", &[]).unwrap();
7749
    write(dir.path(), "b.txt", b"b\n");
7750
    let b = repo.commit("B", &[]).unwrap();
7751
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
7752
    heads.sort();
7753
    let mut want = repo.bookmark_heads().unwrap();
7754
    want.sort();
7755
    assert_eq!(heads, want);
7756
    assert!(heads.contains(&b));
7757
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
7758
    // A change prefix is a symbol, not a bookmark.
7759
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
7760
    assert!(repo.revset(&prefix).is_ok());
7761
    let e = repo
7762
        .revset(&format!("bookmark({prefix})"))
7763
        .unwrap_err()
7764
        .to_string();
7765
    assert!(e.contains("no such bookmark"), "{e}");
7766
}
7767
7768
#[test]
7769
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
7770
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
7771
    // pinning the subrepo, and the nested repository on disk at that pin.
7772
    hermetic();
7773
    let dir = tempfile::tempdir().unwrap();
7774
    let root = dir.path();
7775
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7776
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7777
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7778
        .unwrap()
7779
        .with_home(root.join("home"));
7780
    write(&root.join("lib"), "lib.txt", b"v1\n");
7781
    lib.commit("lib v1", &[]).unwrap();
7782
    assert!(lib.push("origin", false).unwrap()[0].ok);
7783
    let app_dir = root.join("app");
7784
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7785
    write(&app_dir, "main.txt", b"app\n");
7786
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7787
    // The stale state: registered in .oxymodules, never pinned.
7788
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
7789
    app.commit("initial", &[]).unwrap();
7790
    let stale = app.bookmark_heads().unwrap();
7791
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
7792
    app.commit("pin lib", &[]).unwrap();
7793
    let newer = app.bookmark_heads().unwrap();
7794
    app.checkout(&stale, false, "test").unwrap();
7795
    write(&app_dir, "notes.txt", b"mine\n");
7796
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
7797
    assert_eq!(carried, vec!["notes.txt".to_string()]);
7798
    assert!(app_dir.join("notes.txt").exists());
7799
}
7800
7801
#[test]
7802
fn a_bookmark_only_behind_its_remote_catches_up() {
7803
    // oxygen#74: switch takes the remote's state rather than a stale one.
7804
    hermetic();
7805
    let dir = tempfile::tempdir().unwrap();
7806
    let root = dir.path();
7807
    let _origin = Repo::init(&root.join("origin")).unwrap();
7808
    let url = root.join("origin").to_string_lossy().to_string();
7809
    let one = Repo::clone(&url, &root.join("one"))
7810
        .unwrap()
7811
        .with_home(root.join("home"));
7812
    write(&root.join("one"), "a.txt", b"a\n");
7813
    one.commit("A", &[]).unwrap();
7814
    assert!(one.push("origin", false).unwrap()[0].ok);
7815
    let two = Repo::clone(&url, &root.join("two"))
7816
        .unwrap()
7817
        .with_home(root.join("home"));
7818
    write(&root.join("two"), "b.txt", b"b\n");
7819
    two.commit("B", &[]).unwrap();
7820
    assert!(two.push("origin", false).unwrap()[0].ok);
7821
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
7822
    one.fetch("origin").unwrap();
7823
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
7824
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
7825
    // Local work the remote lacks: left alone.
7826
    write(&root.join("one"), "c.txt", b"c\n");
7827
    one.commit("C", &[]).unwrap();
7828
    write(&root.join("two"), "d.txt", b"d\n");
7829
    two.commit("D", &[]).unwrap();
7830
    assert!(two.push("origin", false).unwrap()[0].ok);
7831
    one.fetch("origin").unwrap();
7832
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
7833
}
7834
7835
#[test]
7836
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
7837
    // oxygen#83: remotes earth and gcs, origin removed.
7838
    hermetic();
7839
    let dir = tempfile::tempdir().unwrap();
7840
    let root = dir.path();
7841
    let _up = Repo::init(&root.join("up")).unwrap();
7842
    let url = root.join("up").to_string_lossy().to_string();
7843
    let other = Repo::clone(&url, &root.join("other"))
7844
        .unwrap()
7845
        .with_home(root.join("home"));
7846
    write(&root.join("other"), "a.txt", b"a\n");
7847
    other.commit("a", &[]).unwrap();
7848
    assert!(other.push("origin", false).unwrap()[0].ok);
7849
    let mut one = Repo::clone(&url, &root.join("one"))
7850
        .unwrap()
7851
        .with_home(root.join("home"));
7852
    one.config.set("remote.earth.url", &url).unwrap();
7853
    one.config.set("remote.gcs.url", &url).unwrap();
7854
    one.config.set("remote.origin.url", "").unwrap();
7855
    one.save_config().unwrap();
7856
    write(&root.join("other"), "b.txt", b"b\n");
7857
    other.commit("b", &[]).unwrap();
7858
    assert!(other.push("origin", false).unwrap()[0].ok);
7859
    one.fetch("earth").unwrap();
7860
    let b = one
7861
        .bookmarks()
7862
        .unwrap()
7863
        .into_iter()
7864
        .find(|b| b.name == "main")
7865
        .unwrap();
7866
    assert_eq!(
7867
        (b.remote.as_deref(), b.behind),
7868
        (Some("earth"), Some(1)),
7869
        "a stale origin copy is not used"
7870
    );
7871
    assert_eq!(
7872
        one.default_remote(),
7873
        "origin",
7874
        "no default chosen among several"
7875
    );
7876
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
7877
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
7878
    one.config.set("core.remote", "earth").unwrap();
7879
    assert_eq!(one.default_remote(), "earth");
7880
}
7881
7882
#[test]
7883
fn a_missing_author_identity_says_how_to_fix_it() {
7884
    // oxygen#82: an agent home's author.key naming an identity the
7885
    // repository does not hold.
7886
    hermetic();
7887
    let dir = tempfile::tempdir().unwrap();
7888
    let mut repo = Repo::init(dir.path()).unwrap();
7889
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
7890
    repo.config.set("author.key", &missing.to_hex()).unwrap();
7891
    let e = repo.identity(&missing).unwrap_err().to_string();
7892
    assert!(
7893
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
7894
        "{e}"
7895
    );
7896
    assert!(e.contains("this repository's config"), "{e}");
7897
}
7898
7899
#[test]
7900
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
7901
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
7902
    // the working copy, a pull with nothing new left it there, and status
7903
    // said "clean".
7904
    hermetic();
7905
    let dir = tempfile::tempdir().unwrap();
7906
    let root = dir.path();
7907
    let _up = Repo::init(&root.join("up")).unwrap();
7908
    let url = root.join("up").to_string_lossy().to_string();
7909
    let other = Repo::clone(&url, &root.join("other"))
7910
        .unwrap()
7911
        .with_home(root.join("home"));
7912
    write(&root.join("other"), "a.txt", b"a\n");
7913
    other.commit("a", &[]).unwrap();
7914
    assert!(other.push("origin", false).unwrap()[0].ok);
7915
    let one = Repo::clone(&url, &root.join("one"))
7916
        .unwrap()
7917
        .with_home(root.join("home"));
7918
    write(&root.join("other"), "b.txt", b"b\n");
7919
    other.commit("b", &[]).unwrap();
7920
    assert!(other.push("origin", false).unwrap()[0].ok);
7921
    one.fetch("origin").unwrap();
7922
    // The bookmark moves; the working copy does not.
7923
    let theirs = one.resolve_heads("origin/main").unwrap();
7924
    one.bookmark_set("main", &theirs).unwrap();
7925
    assert!(!root.join("one/b.txt").exists());
7926
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
7927
    let r = one.pull("origin").unwrap();
7928
    assert!(
7929
        !r.changed && r.checked_out,
7930
        "nothing new, but the working copy caught up"
7931
    );
7932
    assert!(root.join("one/b.txt").exists());
7933
    assert_eq!(one.working_copy_behind().unwrap(), None);
7934
}
7935
7936
#[test]
7937
fn touched_nodes_cache_answers_as_the_changes_do() {
7938
    hermetic();
7939
    let dir = tempfile::tempdir().unwrap();
7940
    let repo = Repo::init(dir.path()).unwrap();
7941
    write(dir.path(), "a.txt", b"one\n");
7942
    write(dir.path(), "b.txt", b"x\n");
7943
    repo.snapshot("t").unwrap();
7944
    let c1 = repo.commit("first", &[]).unwrap();
7945
    write(dir.path(), "b.txt", b"y\n");
7946
    repo.snapshot("t").unwrap();
7947
    repo.commit("b only", &[]).unwrap();
7948
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
7949
    write(dir.path(), "c.txt", b"one\ntwo\n");
7950
    repo.snapshot("t").unwrap();
7951
    let c3 = repo.commit("rename and edit", &[]).unwrap();
7952
    // Uncommitted work, so the working copy touches a file too.
7953
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
7954
    repo.snapshot("t").unwrap();
7955
7956
    let path = dir.path().join(".oxy/index/touched");
7957
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
7958
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
7959
    assert!(path.exists(), "the first query writes the cache");
7960
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
7961
    assert_eq!(cold, warm, "the cache answers as the changes do");
7962
    let (wc, _) = repo.working_copy().unwrap();
7963
    assert_eq!(
7964
        cold,
7965
        vec![wc, c3, c1],
7966
        "renames followed, the working copy included"
7967
    );
7968
7969
    // Working-copy changes are not kept: they are replaced by every snapshot.
7970
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
7971
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
7972
    assert!(cached.contains(&c1) && cached.contains(&c3));
7973
7974
    // A damaged cache is ignored, not trusted.
7975
    let mut bytes = fs::read(&path).unwrap();
7976
    let last = bytes.len() - 40;
7977
    bytes[last] ^= 1;
7978
    fs::write(&path, &bytes).unwrap();
7979
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
7980
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
7981
    assert_eq!(hashes(touches), vec![c3, c1]);
7982
}
7983
7984
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
7985
/// file back where it was leave two placements at one place, which the
7986
/// tree shows as one file. Removing it, and then its directory, retires
7987
/// both, so no copy is left under a directory that is gone.
7988
#[test]
7989
fn git_import_removes_every_copy_of_a_file_at_one_place() {
7990
    hermetic();
7991
    if std::process::Command::new("git")
7992
        .arg("--version")
7993
        .output()
7994
        .is_err()
7995
    {
7996
        eprintln!("git not installed; skipping");
7997
        return;
7998
    }
7999
    let dir = tempfile::tempdir().unwrap();
8000
    let root = dir.path();
8001
    let g = root.join("src.git");
8002
    fs::create_dir_all(&g).unwrap();
8003
    let git = |args: &[&str]| {
8004
        let out = std::process::Command::new("git")
8005
            .arg("-C")
8006
            .arg(&g)
8007
            .args([
8008
                "-c",
8009
                "user.name=Grace",
8010
                "-c",
8011
                "[email protected]",
8012
                "-c",
8013
                "commit.gpgsign=false",
8014
            ])
8015
            .args(args)
8016
            .output()
8017
            .unwrap();
8018
        assert!(
8019
            out.status.success(),
8020
            "git {args:?}: {}",
8021
            String::from_utf8_lossy(&out.stderr)
8022
        );
8023
    };
8024
    git(&["init", "-q", "-b", "main"]);
8025
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8026
    write(&g, "keep.txt", b"k\n");
8027
    git(&["add", "."]);
8028
    git(&["commit", "-qm", "base"]);
8029
    fs::create_dir_all(g.join("d/sub")).unwrap();
8030
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8031
    git(&["commit", "-qm", "into sub"]);
8032
    git(&["checkout", "-qb", "side"]);
8033
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8034
    git(&["commit", "-qm", "back, on side"]);
8035
    git(&["checkout", "-q", "main"]);
8036
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8037
    git(&["commit", "-qm", "back, on main"]);
8038
    git(&["merge", "-q", "--no-edit", "side"]);
8039
    git(&["rm", "-rq", "d"]);
8040
    git(&["commit", "-qm", "d goes"]);
8041
8042
    let repo = Repo::init(&root.join("o")).unwrap();
8043
    repo.import_git(&g, "main").unwrap();
8044
    let v = repo.verify_git_import(&g, "main").unwrap();
8045
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8046
    let st = repo
8047
        .load_state_history(&repo.bookmark_heads().unwrap())
8048
        .unwrap();
8049
    let view = st.tree().view();
8050
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8051
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8052
}
8053
8054
/// oxygen#94: a state index's file histories are read, and checked by
8055
/// their own hashes, only when a file is built. One found damaged is an
8056
/// error that says so, the index is removed, and the next read rebuilds it.
8057
#[test]
8058
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8059
    hermetic();
8060
    let dir = tempfile::tempdir().unwrap();
8061
    let repo = Repo::init(dir.path()).unwrap();
8062
    for i in 0..6 {
8063
        write(
8064
            dir.path(),
8065
            &format!("f{i}.txt"),
8066
            format!("one {i}\n").as_bytes(),
8067
        );
8068
    }
8069
    repo.snapshot("t").unwrap();
8070
    repo.commit("first", &[]).unwrap();
8071
    for i in 0..6 {
8072
        write(
8073
            dir.path(),
8074
            &format!("f{i}.txt"),
8075
            format!("one {i}\ntwo\n").as_bytes(),
8076
        );
8077
    }
8078
    repo.snapshot("t").unwrap();
8079
    repo.commit("second", &[]).unwrap();
8080
    let want: Vec<Vec<u8>> = (0..6)
8081
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8082
        .collect();
8083
    // The index of the working copy's base, holding every file's history
8084
    // (a few changes behind, an index is replayed onto, not rewritten).
8085
    let (_, wc) = repo.working_copy().unwrap();
8086
    let base = repo.load_state_history(&wc.deps).unwrap();
8087
    repo.write_state_index(&wc.deps, &base);
8088
    for (i, w) in want.iter().enumerate() {
8089
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8090
    }
8091
    let index = repo.state_indexes();
8092
    assert!(!index.is_empty(), "a state index was written");
8093
    // The histories are last in the file: damage the last of them.
8094
    let mut bytes = fs::read(&index[0]).unwrap();
8095
    let last = bytes.len() - 1;
8096
    bytes[last] ^= 0x40;
8097
    fs::write(&index[0], &bytes).unwrap();
8098
8099
    let reads: Vec<_> = (0..6)
8100
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8101
        .collect();
8102
    let damaged: Vec<String> = reads
8103
        .iter()
8104
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8105
        .collect();
8106
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8107
    assert!(
8108
        damaged[0].contains("state index was damaged")
8109
            && damaged[0].contains("run the command again"),
8110
        "{}",
8111
        damaged[0]
8112
    );
8113
    // Every file reads right again, from an index rebuilt from history.
8114
    for (i, w) in want.iter().enumerate() {
8115
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8116
    }
8117
}
8118
8119
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8120
/// objects alone and in dependency order, and the last moves the bookmark.
8121
/// The remote ends with every change and the same state, and says how each
8122
/// part went.
8123
#[test]
8124
fn a_long_push_goes_in_parts() {
8125
    hermetic();
8126
    let dir = tempfile::tempdir().unwrap();
8127
    let root = dir.path();
8128
    let origin = root.join("origin");
8129
    Repo::init_bare_unbound(&origin).unwrap();
8130
    let main = root.join("main");
8131
    let mut repo = Repo::init(&main).unwrap();
8132
    repo.config
8133
        .set("remote.origin.url", &origin.to_string_lossy())
8134
        .unwrap();
8135
    // One byte: every change is a part of its own.
8136
    repo.config.set("push.batch-bytes", "1").unwrap();
8137
    repo.save_config().unwrap();
8138
    for i in 0..6 {
8139
        write(
8140
            &main,
8141
            &format!("f{i}.txt"),
8142
            format!("file {i}\n").as_bytes(),
8143
        );
8144
        repo.commit(&format!("c{i}"), &[]).unwrap();
8145
    }
8146
    let mut parts = Vec::new();
8147
    let results = repo
8148
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8149
        .unwrap();
8150
    assert!(
8151
        results.iter().any(|r| r.ok && r.name == "main"),
8152
        "{results:?}"
8153
    );
8154
    assert_eq!(parts.len(), 6, "{parts:?}");
8155
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8156
8157
    let remote = Repo::open(&origin).unwrap();
8158
    let heads = repo.bookmark_heads().unwrap();
8159
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8160
    assert_eq!(
8161
        remote.log_state(&heads).unwrap().len(),
8162
        repo.log_state(&heads).unwrap().len()
8163
    );
8164
    // A push of objects alone reports how it went, as `objects`.
8165
    let got = remote
8166
        .receive_push(Bundle::default(), vec![], None, vec![])
8167
        .unwrap();
8168
    assert_eq!(got.len(), 1);
8169
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8170
}
8171
8172
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8173
/// own commits (Git author email = its email, any case) with its key, and
8174
/// leaves anyone else's with the zero key; the history verifies as before.
8175
#[test]
8176
fn git_import_claims_your_own_commits() {
8177
    hermetic();
8178
    if std::process::Command::new("git")
8179
        .arg("--version")
8180
        .output()
8181
        .is_err()
8182
    {
8183
        eprintln!("git not installed; skipping");
8184
        return;
8185
    }
8186
    let dir = tempfile::tempdir().unwrap();
8187
    let root = dir.path();
8188
    let g = root.join("src.git");
8189
    fs::create_dir_all(&g).unwrap();
8190
    let git = |who: &str, args: &[&str]| {
8191
        let (name, email) = who.split_once(' ').unwrap();
8192
        let out = std::process::Command::new("git")
8193
            .arg("-C")
8194
            .arg(&g)
8195
            .args([
8196
                "-c",
8197
                &format!("user.name={name}"),
8198
                "-c",
8199
                &format!("user.email={email}"),
8200
                "-c",
8201
                "commit.gpgsign=false",
8202
            ])
8203
            .args(args)
8204
            .output()
8205
            .unwrap();
8206
        assert!(
8207
            out.status.success(),
8208
            "git {args:?}: {}",
8209
            String::from_utf8_lossy(&out.stderr)
8210
        );
8211
    };
8212
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8213
    write(&g, "a.txt", b"a\n");
8214
    git("Grace [email protected]", &["add", "."]);
8215
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8216
    write(&g, "b.txt", b"b\n");
8217
    git("Ada [email protected]", &["add", "."]);
8218
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8219
8220
    let mut repo = Repo::init(&root.join("o")).unwrap();
8221
    let (key, _) = repo
8222
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8223
        .unwrap();
8224
    repo.config.set("git.claim", "true").unwrap();
8225
    repo.save_config().unwrap();
8226
    let repo = Repo::open(&root.join("o")).unwrap();
8227
    repo.import_git(&g, "main").unwrap();
8228
    let v = repo.verify_git_import(&g, "main").unwrap();
8229
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8230
    let heads = repo.bookmark_heads().unwrap();
8231
    let by_message: std::collections::HashMap<String, KeyId> = repo
8232
        .log_state(&heads)
8233
        .unwrap()
8234
        .into_iter()
8235
        .map(|e| {
8236
            (
8237
                e.change.message.lines().next().unwrap_or("").to_string(),
8238
                e.change.author,
8239
            )
8240
        })
8241
        .collect();
8242
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8243
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8244
}
8245
8246
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8247
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8248
#[test]
8249
fn removing_a_remote_leaves_nothing_of_it() {
8250
    hermetic();
8251
    let dir = tempfile::tempdir().unwrap();
8252
    let origin = dir.path().join("origin");
8253
    Repo::init_bare_unbound(&origin).unwrap();
8254
    let main = dir.path().join("main");
8255
    let mut repo = Repo::init(&main).unwrap();
8256
    repo.config
8257
        .set("remote.origin.url", &origin.to_string_lossy())
8258
        .unwrap();
8259
    repo.config
8260
        .set("remote.origin.token", "secret-ish")
8261
        .unwrap();
8262
    repo.config
8263
        .set("remote.keep.url", &origin.to_string_lossy())
8264
        .unwrap();
8265
    repo.save_config().unwrap();
8266
    write(&main, "a.txt", b"a\n");
8267
    repo.commit("a", &[]).unwrap();
8268
    assert!(repo.push("origin", false).unwrap()[0].ok);
8269
    assert!(
8270
        repo.view().unwrap().remotes.contains_key("origin"),
8271
        "a tracking bookmark"
8272
    );
8273
8274
    repo.remove_remote("origin").unwrap();
8275
    let again = Repo::open(&main).unwrap();
8276
    assert!(
8277
        !again
8278
            .config
8279
            .repo_layer()
8280
            .keys()
8281
            .any(|k| k.starts_with("remote.origin.")),
8282
        "{:?}",
8283
        again.config.repo_layer()
8284
    );
8285
    assert!(!again.config.remotes.contains_key("origin"));
8286
    assert!(
8287
        !again.view().unwrap().remotes.contains_key("origin"),
8288
        "its tracking bookmarks go"
8289
    );
8290
    assert!(
8291
        again.config.remotes.contains_key("keep"),
8292
        "another remote stays"
8293
    );
8294
    let mut again = again;
8295
    assert!(
8296
        again.remove_remote("origin").is_err(),
8297
        "a second removal is refused"
8298
    );
8299
}
8300
8301
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
8302
/// unreachable from history, so gc prunes it, unless the host names it:
8303
/// then it and its chunks stay, and it reads back whole.
8304
#[test]
8305
fn gc_keeps_the_blobs_a_host_names() {
8306
    hermetic();
8307
    let dir = tempfile::tempdir().unwrap();
8308
    let repo = Repo::init(dir.path()).unwrap();
8309
    write(dir.path(), "a.txt", b"a\n");
8310
    repo.commit("a", &[]).unwrap();
8311
    // Large enough to be several chunks.
8312
    let body: Vec<u8> = (0..400_000u32)
8313
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
8314
        .collect();
8315
    let kept = repo.store_blob(&body).unwrap();
8316
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
8317
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
8318
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
8319
    assert!(!repo.store().has(&lost), "not named: pruned");
8320
    repo.gc(true).unwrap();
8321
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
8322
}
8323
8324
/// oxygen#99: undo in one workspace undoes that workspace's last command,
8325
/// never another workspace's, says what it undid, and goes further back
8326
/// when run again.
8327
#[test]
8328
fn undo_is_scoped_to_its_workspace() {
8329
    hermetic();
8330
    let dir = tempfile::tempdir().unwrap();
8331
    let root = dir.path().join("main");
8332
    let a = Repo::init(&root).unwrap();
8333
    write(&root, "base.txt", b"base\n");
8334
    let base = a.commit("base", &[]).unwrap();
8335
    a.bookmark_create("feature", None).unwrap();
8336
    let ws_dir = dir.path().join("ws");
8337
    let heads = a.resolve_heads("feature").unwrap();
8338
    let b = a
8339
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
8340
        .unwrap();
8341
8342
    // A commits on main, then B commits on feature: B's is the newest.
8343
    write(&root, "a.txt", b"a\n");
8344
    let ca = a.commit("from a", &[]).unwrap();
8345
    write(&ws_dir, "b.txt", b"b\n");
8346
    let cb = b.commit("from b", &[]).unwrap();
8347
8348
    // A's undo undoes A's commit and leaves B's.
8349
    let u = a.undo().unwrap();
8350
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8351
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
8352
    assert!(!u.changes.is_empty());
8353
    let view = a.view().unwrap();
8354
    // (Independent changes commute, so a bookmark's heads may hold base too.)
8355
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
8356
    assert!(
8357
        a.heads_of(&view, "feature").unwrap().contains(&cb),
8358
        "B's commit stands"
8359
    );
8360
    assert!(
8361
        a.store().get_change(&ca).is_ok(),
8362
        "the change itself is still in the store"
8363
    );
8364
    // A's working copy was clean, so its files followed; B's are untouched.
8365
    assert!(!root.join("a.txt").exists());
8366
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
8367
    assert!(ws_dir.join("b.txt").exists());
8368
8369
    // B's undo still finds B's own commit, under A's undo.
8370
    let u = b.undo().unwrap();
8371
    assert_eq!(u.command, "oxy commit -m \"from b\"");
8372
    assert!(!b
8373
        .heads_of(&b.view().unwrap(), "feature")
8374
        .unwrap()
8375
        .contains(&cb));
8376
    assert_eq!(
8377
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
8378
        vec![base],
8379
        "A's undo stands"
8380
    );
8381
8382
    // A's next undo goes past the commit it already undid, to adding B's
8383
    // workspace: refused, since B has worked there since.
8384
    let e = a.undo().unwrap_err().to_string();
8385
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
8386
}
8387
8388
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
8389
/// own commit's head, and the other workspace's head stays.
8390
#[test]
8391
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
8392
    hermetic();
8393
    let dir = tempfile::tempdir().unwrap();
8394
    let root = dir.path().join("main");
8395
    let a = Repo::init(&root).unwrap();
8396
    write(&root, "base.txt", b"base\n");
8397
    a.commit("base", &[]).unwrap();
8398
    let ws_dir = dir.path().join("ws");
8399
    let b = a.workspace_add(&ws_dir, None).unwrap();
8400
    write(&root, "a.txt", b"a\n");
8401
    let ca = a.commit("from a", &[]).unwrap();
8402
    write(&ws_dir, "b.txt", b"b\n");
8403
    let cb = b.commit("from b", &[]).unwrap();
8404
    let u = a.undo().unwrap();
8405
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8406
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
8407
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
8408
}
8409
8410
/// oxygen#99: an undo that would also take back what another workspace
8411
/// did since to the same bookmark is refused, naming it.
8412
#[test]
8413
fn undo_refuses_to_take_back_another_workspaces_work() {
8414
    hermetic();
8415
    let dir = tempfile::tempdir().unwrap();
8416
    let root = dir.path().join("main");
8417
    let a = Repo::init(&root).unwrap();
8418
    write(&root, "base.txt", b"base\n");
8419
    a.commit("base", &[]).unwrap();
8420
    let ws_dir = dir.path().join("ws");
8421
    let b = a.workspace_add(&ws_dir, None).unwrap();
8422
    // Both on main: A commits, then B builds on it, editing A's file.
8423
    write(&root, "a.txt", b"a\n");
8424
    a.commit("from a", &[]).unwrap();
8425
    let heads = b.resolve_heads("main").unwrap();
8426
    b.checkout(&heads, false, "oxy checkout").unwrap();
8427
    write(&ws_dir, "a.txt", b"a, then b\n");
8428
    b.commit("from b", &[]).unwrap();
8429
    let e = a.undo().unwrap_err().to_string();
8430
    assert!(
8431
        e.contains("bookmark main") && e.contains("builds on"),
8432
        "{e}"
8433
    );
8434
    assert!(e.contains("oxy op restore"), "{e}");
8435
}
8436
8437
/// oxygen#99: undoing a commit that was already pushed says so: the remote
8438
/// still has it.
8439
#[test]
8440
fn undo_says_when_the_commit_was_pushed() {
8441
    hermetic();
8442
    let dir = tempfile::tempdir().unwrap();
8443
    let root = dir.path();
8444
    Repo::init(&root.join("origin")).unwrap();
8445
    let url = root.join("origin").to_string_lossy().to_string();
8446
    let repo = Repo::clone(&url, &root.join("work"))
8447
        .unwrap()
8448
        .with_home(root.join("home"));
8449
    write(&root.join("work"), "a.txt", b"a\n");
8450
    repo.commit("a", &[]).unwrap();
8451
    assert!(repo.push("origin", false).unwrap()[0].ok);
8452
    // The push itself is passed over: the remote keeps what it was sent.
8453
    let u = repo.undo().unwrap();
8454
    assert_eq!(u.command, "oxy commit -m \"a\"");
8455
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
8456
}
8457
8458
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
8459
/// out of the snapshot and named; tracked files and files already in the
8460
/// working copy are not.
8461
#[test]
8462
fn large_new_files_are_left_out_of_snapshots() {
8463
    hermetic();
8464
    let dir = tempfile::tempdir().unwrap();
8465
    let root = dir.path();
8466
    let mut repo = Repo::init(root).unwrap();
8467
    repo.config.max_new_file = 1024;
8468
    write(root, "small.txt", b"small\n");
8469
    write(root, "big.bin", &vec![0u8; 4096]);
8470
    let s = repo.snapshot("oxy status").unwrap();
8471
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8472
    assert_eq!(paths, ["small.txt"]);
8473
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
8474
    repo.commit("small", &[]).unwrap();
8475
8476
    // A tracked file may grow past the limit.
8477
    write(root, "small.txt", &vec![b'x'; 4096]);
8478
    let s = repo.snapshot("oxy status").unwrap();
8479
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
8480
    // With no limit the big file is taken in, and stays once it is.
8481
    repo.config.max_new_file = 0;
8482
    let s = repo.snapshot("oxy status").unwrap();
8483
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
8484
    repo.config.max_new_file = 1024;
8485
    let s = repo.snapshot("oxy status").unwrap();
8486
    assert!(
8487
        s.statuses.iter().any(|p| p.path == "big.bin"),
8488
        "already in the working copy"
8489
    );
8490
    assert!(repo.skipped_large().is_empty());
8491
}
8492
8493
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
8494
/// snapshots expire, and kept while they have not.
8495
#[test]
8496
fn gc_prunes_what_only_expired_snapshots_held() {
8497
    hermetic();
8498
    let dir = tempfile::tempdir().unwrap();
8499
    let root = dir.path();
8500
    let mut repo = Repo::init(root).unwrap();
8501
    repo.config.gc_grace_days = 0;
8502
    write(root, "a.txt", b"a\n");
8503
    repo.commit("a", &[]).unwrap();
8504
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
8505
    write(root, "image.tar", &image);
8506
    repo.snapshot("oxy status").unwrap();
8507
    std::fs::remove_file(root.join("image.tar")).unwrap();
8508
    repo.snapshot("oxy status").unwrap();
8509
    let blob = Repo::blob_ref(&image);
8510
    assert!(repo.store().has(&blob));
8511
    repo.gc(true).unwrap();
8512
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
8513
    repo.config.snapshot_retention_days = 0;
8514
    repo.gc(true).unwrap();
8515
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
8516
    assert_eq!(
8517
        repo.file_at("a.txt", None).unwrap(),
8518
        b"a\n",
8519
        "committed files stay"
8520
    );
8521
}
8522
8523
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
8524
/// resolves, so JSON output feeds back into commands.
8525
#[test]
8526
fn a_full_hash_resolves_without_its_hash_sign() {
8527
    hermetic();
8528
    let dir = tempfile::tempdir().unwrap();
8529
    let root = dir.path();
8530
    let repo = Repo::init(root).unwrap();
8531
    write(root, "a.txt", b"a\n");
8532
    let h = repo.commit("a", &[]).unwrap();
8533
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
8534
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
8535
    assert!(repo
8536
        .resolve_change(&"0".repeat(64))
8537
        .unwrap_err()
8538
        .to_string()
8539
        .contains("no change matches"));
8540
}
8541
8542
#[test]
8543
fn a_pin_change_moves_only_the_pin() {
8544
    hermetic();
8545
    let dir = tempfile::tempdir().unwrap();
8546
    let root = dir.path();
8547
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8548
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8549
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8550
        .unwrap()
8551
        .with_home(root.join("home"));
8552
    write(&root.join("lib"), "lib.txt", b"v1\n");
8553
    lib.commit("lib v1", &[]).unwrap();
8554
    assert!(lib.push("origin", false).unwrap()[0].ok);
8555
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
8556
    let app_dir = root.join("app");
8557
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
8558
        .unwrap()
8559
        .with_home(root.join("home"));
8560
    write(&app_dir, "main.txt", b"app\n");
8561
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8562
    let a1 = app.commit("app with lib", &[]).unwrap();
8563
    // The library moves on.
8564
    write(&root.join("lib"), "more.txt", b"v2\n");
8565
    let l2 = lib.commit("lib v2", &[]).unwrap();
8566
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
8567
        panic!("an Oxygen pin")
8568
    };
8569
    let pin2 = crate::subrepo::Pin::Oxy {
8570
        repo,
8571
        heads: vec![l2],
8572
        bookmark,
8573
    };
8574
    let author = app.store().get_change(&a1).unwrap().author;
8575
    let change = app
8576
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
8577
        .unwrap();
8578
    let mut state = app.load_state(&[a1]).unwrap();
8579
    state.add(change).unwrap();
8580
    let files = state.materialize().files;
8581
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
8582
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
8583
        panic!("a pin is opaque")
8584
    };
8585
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
8586
    assert_eq!(read, pin2, "the new pin");
8587
    assert!(
8588
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
8589
        "nothing else changes"
8590
    );
8591
    // Only a subrepo's pin can be moved this way.
8592
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
8593
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
8594
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
8595
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
8596
}