OXYGENHUB
# 44f1ebe7aa5b oxygen / crates / oxy-core / src / repo / tests.rs
315.3 KiB · Rust · last changed A carried switch no longer says carried files were removed 18 days ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
use crate::protocol::SignedPolicy;
5
use crate::repo::{BisectStep, Selection};
6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
137
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
138
    assert!(d.contains("-fn main() {}"), "{d}");
139
140
    // Resolution by prefix.
141
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
142
    assert_eq!(
143
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
144
        h1
145
    );
146
    assert!(repo.resolve_change("zzzz").is_err());
147
148
    // Undo the commit: bookmark and working copy go back.
149
    repo.undo().unwrap();
150
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
151
    let s = repo.snapshot("oxy status").unwrap();
152
    assert!(
153
        !s.changed,
154
        "files on disk still match the pre-commit working copy"
155
    );
156
    assert_eq!(s.statuses.len(), 3);
157
}
158
159
/// Make `main` conflicted: two commits on the same base that edit the same line.
160
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
161
    let dir = tempfile::tempdir().unwrap();
162
    let root = dir.path();
163
    let repo = Repo::init(root).unwrap();
164
    write(root, "f.txt", b"a\nb\nc\n");
165
    let h1 = repo.commit("base", &[]).unwrap();
166
    write(root, "f.txt", b"a\nB\nc\n");
167
    let h2 = repo.commit("upper", &[]).unwrap();
168
    repo.checkout(&[h1], false, "checkout").unwrap();
169
    write(root, "f.txt", b"a\nX\nc\n");
170
    let h3 = repo.commit("ex", &[]).unwrap();
171
    (dir, repo, h1, h2, h3)
172
}
173
174
#[test]
175
fn concurrent_edits_conflict_and_can_be_resolved() {
176
    hermetic();
177
    let (dir, repo, h1, h2, h3) = conflicted_repo();
178
    let root = dir.path();
179
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
180
    assert_eq!(heads, [h2, h3].into_iter().collect());
181
    let st = repo.load_state(&[h2, h3]).unwrap();
182
    assert!(st.materialize().is_conflicted());
183
184
    // Checking out main writes markers.
185
    let r = repo
186
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
187
        .unwrap();
188
    assert!(r.conflicted);
189
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
190
    assert!(
191
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
192
        "{marked}"
193
    );
194
    assert!(
195
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
196
        "{marked}"
197
    );
198
    assert!(has_conflict_markers(marked.as_bytes()));
199
    // Untouched markers: clean working copy; commit has nothing to do.
200
    let s = repo.snapshot("status").unwrap();
201
    assert!(s.statuses.is_empty());
202
    assert!(!s.resolves);
203
204
    // Partially edited file that still has markers cannot be committed.
205
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
206
    let s = repo.snapshot("status").unwrap();
207
    assert_eq!(
208
        statuses(&s),
209
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
210
    );
211
    assert!(repo.commit("no", &[]).is_err());
212
213
    // Resolve by keeping one side and adding a line elsewhere.
214
    write(root, "f.txt", b"a\nX\nc\nd\n");
215
    let s = repo.snapshot("status").unwrap();
216
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
217
    assert!(s.resolves);
218
    let h4 = repo.commit("resolve", &[]).unwrap();
219
    let c4 = repo.store().get_change(&h4).unwrap();
220
    assert_eq!(c4.kind, ChangeKind::Resolution);
221
    let mut want = vec![h1, h2, h3];
222
    want.sort();
223
    assert_eq!(
224
        c4.deps, want,
225
        "a resolution depends on exactly the contributors and what it references"
226
    );
227
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
228
    let snap = repo.load_state(&[h4]).unwrap().materialize();
229
    assert!(!snap.is_conflicted());
230
    assert!(
231
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
232
    );
233
    assert!(!repo.snapshot("status").unwrap().changed);
234
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
235
    // whatever order the changes arrive in.
236
    let mut st = State::new();
237
    for h in [h4, h3, h1, h2] {
238
        st.add_unchecked(repo.store().get_change(&h).unwrap());
239
    }
240
    st.validate().unwrap();
241
    assert!(
242
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
243
    );
244
}
245
246
#[test]
247
fn resolution_may_keep_both_sides_or_neither() {
248
    hermetic();
249
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
250
    let root = dir.path();
251
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
252
        .unwrap();
253
    // Keep both sides in a chosen order.
254
    write(root, "f.txt", b"a\nX\nB\nc\n");
255
    let h = repo.commit("both", &[]).unwrap();
256
    let snap = repo.load_state(&[h]).unwrap().materialize();
257
    assert!(!snap.is_conflicted());
258
    assert!(
259
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
260
    );
261
    // Undo and instead drop the whole region.
262
    repo.undo().unwrap();
263
    write(root, "f.txt", b"a\nc\n");
264
    let h = repo.commit("neither", &[]).unwrap();
265
    let snap = repo.load_state(&[h]).unwrap().materialize();
266
    assert!(!snap.is_conflicted());
267
    assert!(
268
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
269
    );
270
}
271
272
#[test]
273
fn name_conflict_resolved_by_removing_a_candidate() {
274
    hermetic();
275
    let dir = tempfile::tempdir().unwrap();
276
    let root = dir.path();
277
    let repo = Repo::init(root).unwrap();
278
    write(root, "keep.txt", b"k\n");
279
    let h1 = repo.commit("base", &[]).unwrap();
280
    write(root, "new.txt", b"one\n");
281
    repo.commit("one", &[]).unwrap();
282
    repo.checkout(&[h1], false, "checkout").unwrap();
283
    write(root, "new.txt", b"two\n");
284
    repo.commit("two", &[]).unwrap();
285
    let r = repo
286
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
287
        .unwrap();
288
    assert!(r.conflicted);
289
    assert!(
290
        root.join("new.txt.oxy-conflict-1").exists()
291
            && root.join("new.txt.oxy-conflict-2").exists()
292
    );
293
    assert!(!root.join("new.txt").exists());
294
    // Candidate numbering follows change-hash order, so pick by content:
295
    // keep the "two" candidate under the real name and drop the other.
296
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
297
        (1, 2)
298
    } else {
299
        (2, 1)
300
    };
301
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
302
    fs::rename(
303
        root.join(format!("new.txt.oxy-conflict-{keep}")),
304
        root.join("new.txt"),
305
    )
306
    .unwrap();
307
    let h = repo.commit("pick two", &[]).unwrap();
308
    assert_eq!(
309
        repo.store().get_change(&h).unwrap().kind,
310
        ChangeKind::Resolution
311
    );
312
    // The resolution does not touch keep.txt, so it does not depend on h1;
313
    // the bookmark keeps both as heads and their union is the state.
314
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
315
    assert_eq!(heads, [h1, h].into_iter().collect());
316
    let snap = repo
317
        .load_state(&repo.bookmark_heads().unwrap())
318
        .unwrap()
319
        .materialize();
320
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
321
    assert_eq!(
322
        snap.files.keys().cloned().collect::<Vec<_>>(),
323
        ["keep.txt", "new.txt"]
324
    );
325
    assert!(
326
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
327
    );
328
}
329
330
#[test]
331
fn identities_and_signed_commits() {
332
    hermetic();
333
    let dir = tempfile::tempdir().unwrap();
334
    let root = dir.path();
335
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
336
    write(root, "a.txt", b"a\n");
337
    let h0 = repo.commit("unsigned", &[]).unwrap();
338
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
339
    assert_eq!(
340
        repo.store().get_change(&h0).unwrap().author,
341
        ObjectRef::ZERO
342
    );
343
344
    let (key, id) = repo
345
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
346
        .unwrap();
347
    assert_eq!(id.hash(), key);
348
    assert_eq!(repo.config.author_key, Some(key));
349
    // Config survives reopen; the secret key is found again.
350
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
351
    assert_eq!(reopened.config.author_key, Some(key));
352
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
353
354
    // Default core.sign = seal: commits carry the author but no signature.
355
    write(root, "a.txt", b"a\nb\n");
356
    let h1 = repo.commit("authored", &[]).unwrap();
357
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
358
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
359
    // Signing later works too.
360
    repo.sign_change(&h1).unwrap();
361
    assert!(
362
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
363
    );
364
365
    repo.config.set("core.sign", "change").unwrap();
366
    repo.save_config().unwrap();
367
    write(root, "a.txt", b"a\nb\nc\n");
368
    let h2 = repo.commit("signed", &[]).unwrap();
369
    assert_eq!(
370
        repo.verify_change(&h2).unwrap(),
371
        SignatureStatus::Valid {
372
            key,
373
            name: "Ada".into(),
374
            email: "[email protected]".into(),
375
            sealed: false,
376
            revoked: false
377
        }
378
    );
379
380
    // A signature by a key that is not the author or a delegate is rejected
381
    // when the change names an author; an anonymous change (made before any
382
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
383
    let other = SecretKey::generate();
384
    let other_id = other.identity("Mallory", "[email protected]", 0);
385
    let other_key = repo.store().put_identity(&other_id).unwrap();
386
    write(root, "a.txt", b"a\nb\nc\nd\n");
387
    repo.config.set("core.sign", "seal").unwrap();
388
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
389
    let forged = other.sign(Domain::Change, &other_key, &h3);
390
    repo.store().put_signature(&h3, &forged).unwrap();
391
    assert!(
392
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
393
    );
394
    let adopted = other.sign(Domain::Change, &other_key, &h0);
395
    repo.store().put_signature(&h0, &adopted).unwrap();
396
    assert!(
397
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
398
    );
399
400
    // Tampering with the stored signature invalidates it.
401
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
402
    sig.ed[0] ^= 1;
403
    repo.store().put_signature(&h2, &sig).unwrap();
404
    assert!(matches!(
405
        repo.verify_change(&h2).unwrap(),
406
        SignatureStatus::Invalid(_)
407
    ));
408
409
    // Without the secret key, signing at commit fails cleanly.
410
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
411
    write(root, "a.txt", b"z\n");
412
    assert!(no_keys.commit("cannot sign", &[]).is_err());
413
}
414
415
#[test]
416
fn checkout_moves_the_working_copy() {
417
    hermetic();
418
    let dir = tempfile::tempdir().unwrap();
419
    let root = dir.path();
420
    let repo = Repo::init(root).unwrap();
421
    write(root, "a.txt", b"one\n");
422
    write(root, "sub/deep/b.txt", b"b\n");
423
    let h1 = repo.commit("first", &[]).unwrap();
424
    write(root, "a.txt", b"two\n");
425
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
426
    write(root, "bin.dat", &[0, 1, 2, 3]);
427
    let h2 = repo.commit("second", &[]).unwrap();
428
429
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
430
    assert_eq!(
431
        r,
432
        CheckoutReport {
433
            written: 2,
434
            removed: 1,
435
            removed_paths: vec!["bin.dat".into()],
436
            conflicted: false,
437
            notes: vec![],
438
            lacks: 1,
439
        }
440
    );
441
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
442
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
443
    assert!(!root.join("bin.dat").exists());
444
    let (_, wc) = repo.working_copy().unwrap();
445
    assert_eq!(wc.deps, vec![h1]);
446
    assert!(
447
        !repo.snapshot("status").unwrap().changed,
448
        "checkout leaves a clean working copy"
449
    );
450
    // The bookmark still points at h2.
451
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
452
453
    // Dirty working copy refuses without --discard.
454
    write(root, "a.txt", b"dirty\n");
455
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
456
    let r = repo
457
        .checkout(&[h2], true, "oxy checkout --discard")
458
        .unwrap();
459
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
460
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
461
    assert!(!root.join("sub").exists(), "empty directories are pruned");
462
    assert_eq!(r.removed, 1);
463
    assert!(!repo.snapshot("status").unwrap().changed);
464
465
    // Refuses to write through a symlinked directory.
466
    #[cfg(unix)]
467
    {
468
        fs::remove_dir_all(root.join("sub")).ok();
469
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
470
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
471
    }
472
}
473
474
#[test]
475
fn large_files_are_chunked_and_read_back() {
476
    hermetic();
477
    let dir = tempfile::tempdir().unwrap();
478
    let repo = Repo::init(dir.path()).unwrap();
479
    let mut big = vec![0u8; 700 * 1024];
480
    for (i, b) in big.iter_mut().enumerate() {
481
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
482
    }
483
    let r = repo.store_blob(&big).unwrap();
484
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
485
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
486
    assert_eq!(repo.read_blob(&r).unwrap(), big);
487
    assert_eq!(Repo::blob_ref(&big), r);
488
}
489
490
#[test]
491
fn clone_push_pull_with_seals_and_attestations() {
492
    hermetic();
493
    let dir = tempfile::tempdir().unwrap();
494
    let root = dir.path();
495
    let origin_path = root.join("origin");
496
    let origin = Repo::init(&origin_path).unwrap();
497
    let origin_url = origin_path.to_string_lossy().to_string();
498
499
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
500
    let mut a = Repo::clone(&origin_url, &root.join("a"))
501
        .unwrap()
502
        .with_home(root.join("home-a"));
503
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
504
    let (key_a, _) = a
505
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
506
        .unwrap();
507
    write(&root.join("a"), "f.txt", b"a\n");
508
    let h1 = a.commit("first", &[]).unwrap();
509
    let results = a.push("origin", false).unwrap();
510
    assert!(results[0].ok, "{}", results[0].reason);
511
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
512
    // The change was sealed at push and the reference attested.
513
    assert!(
514
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
515
    );
516
    assert_eq!(
517
        origin.verify_change(&h1).unwrap(),
518
        SignatureStatus::Unsigned
519
    );
520
    let serial_of = |att: &SignedAttest| match att.attest.body {
521
        AttestBody::Ref { serial, .. } => serial,
522
        _ => unreachable!(),
523
    };
524
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
525
    // A bookmark new to the remote starts at the clock (past any deleted
526
    // namesake's serial); later updates count up from there.
527
    let first = serial_of(&att);
528
    assert!(first > 1_000_000_000_000, "{first}");
529
    let again = a.push("origin", false).unwrap();
530
    assert!(again[0].ok && again[0].reason.contains("up to date"));
531
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
532
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
533
534
    // B clones and sees the file and the seal.
535
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
536
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
537
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
538
    assert!(matches!(
539
        b.authenticate_change(&h1).unwrap(),
540
        SignatureStatus::Valid { sealed: true, .. }
541
    ));
542
543
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
544
    write(&root.join("b"), "f.txt", b"a\nb\n");
545
    let h2 = b.commit("second", &[]).unwrap();
546
    assert!(b.push("origin", false).unwrap()[0].ok);
547
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
548
549
    // A commits an independent change; push is refused until A pulls.
550
    write(&root.join("a"), "g.txt", b"g\n");
551
    let h3 = a.commit("third", &[]).unwrap();
552
    assert!(a.push("origin", false).is_err());
553
    let pr = a.pull("origin").unwrap();
554
    assert!(pr.changed && pr.checked_out);
555
    let mut want = vec![h2, h3];
556
    want.sort();
557
    assert_eq!(pr.heads, want);
558
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
559
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
560
    let results = a.push("origin", false).unwrap();
561
    assert!(results[0].ok, "{}", results[0].reason);
562
    let mut origin_heads = origin.bookmark_heads().unwrap();
563
    origin_heads.sort();
564
    assert_eq!(origin_heads, want);
565
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
566
    assert_eq!(serial_of(&att), first + 1);
567
568
    // B pulls and ends up identical.
569
    let pr = b.pull("origin").unwrap();
570
    assert_eq!(pr.heads, want);
571
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
572
    assert!(!b.snapshot("status").unwrap().changed);
573
574
    // Concurrent edits of the same line: the union is a reified conflict.
575
    write(&root.join("a"), "f.txt", b"a\nA\n");
576
    a.commit("a-edit", &[]).unwrap();
577
    a.push("origin", false).unwrap();
578
    write(&root.join("b"), "f.txt", b"a\nB\n");
579
    b.commit("b-edit", &[]).unwrap();
580
    let pr = b.pull("origin").unwrap();
581
    assert!(pr.changed && pr.checked_out);
582
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
583
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
584
    write(&root.join("b"), "f.txt", b"a\nAB\n");
585
    let hr = b.commit("resolve", &[]).unwrap();
586
    assert_eq!(
587
        b.store().get_change(&hr).unwrap().kind,
588
        ChangeKind::Resolution
589
    );
590
    assert!(b.push("origin", false).unwrap()[0].ok);
591
    a.pull("origin").unwrap();
592
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
593
    // The resolution depends on the conflicting edits, but nothing depends
594
    // on "third" (it only added g.txt), so it stays a head beside it.
595
    let mut want = vec![hr, h3];
596
    want.sort();
597
    assert_eq!(a.bookmark_heads().unwrap(), want);
598
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
599
}
600
601
#[test]
602
fn receive_push_rejects_bad_updates() {
603
    hermetic();
604
    let dir = tempfile::tempdir().unwrap();
605
    let root = dir.path();
606
    let origin = Repo::init(&root.join("origin")).unwrap();
607
    let url = root.join("origin").to_string_lossy().to_string();
608
    let mut a = Repo::clone(&url, &root.join("a"))
609
        .unwrap()
610
        .with_home(root.join("home"));
611
    let (key, _) = a
612
        .create_identity("Ada", "a@b", IdentityScope::Repo)
613
        .unwrap();
614
    write(&root.join("a"), "f.txt", b"x\n");
615
    let h1 = a.commit("one", &[]).unwrap();
616
    assert!(a.push("origin", false).unwrap()[0].ok);
617
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
618
    let s1 = origin
619
        .store()
620
        .put_state(&StateObject::new(vec![h1]))
621
        .unwrap();
622
623
    // Missing head.
624
    let ghost = origin
625
        .store()
626
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
627
        .unwrap();
628
    let r = origin
629
        .receive_push(
630
            Bundle::default(),
631
            vec![RefUpdate {
632
                name: "main".into(),
633
                old_state: s1,
634
                new_state: ghost,
635
                force: false,
636
                attestation: None,
637
            }],
638
            None,
639
            vec![],
640
        )
641
        .unwrap();
642
    assert!(
643
        !r[0].ok && r[0].reason.contains("missing"),
644
        "{}",
645
        r[0].reason
646
    );
647
648
    // Stale old_state.
649
    let r = origin
650
        .receive_push(
651
            Bundle::default(),
652
            vec![RefUpdate {
653
                name: "main".into(),
654
                old_state: empty,
655
                new_state: s1,
656
                force: false,
657
                attestation: None,
658
            }],
659
            None,
660
            vec![],
661
        )
662
        .unwrap();
663
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
664
665
    // Non-fast-forward without force is refused; with force it passes.
666
    let r = origin
667
        .receive_push(
668
            Bundle::default(),
669
            vec![RefUpdate {
670
                name: "main".into(),
671
                old_state: s1,
672
                new_state: empty,
673
                force: false,
674
                attestation: None,
675
            }],
676
            None,
677
            vec![],
678
        )
679
        .unwrap();
680
    assert!(
681
        !r[0].ok && r[0].reason.contains("fast-forward"),
682
        "{}",
683
        r[0].reason
684
    );
685
    let r = origin
686
        .receive_push(
687
            Bundle::default(),
688
            vec![RefUpdate {
689
                name: "main".into(),
690
                old_state: s1,
691
                new_state: empty,
692
                force: true,
693
                attestation: None,
694
            }],
695
            None,
696
            vec![],
697
        )
698
        .unwrap();
699
    assert!(r[0].ok);
700
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
701
702
    // Attestation with a stale serial is a rollback and is refused.
703
    let sa = a
704
        .sign_attest(&Attest {
705
            repo: a.id().unwrap(),
706
            hlc: Hlc::now(),
707
            body: AttestBody::Ref {
708
                name: "main".into(),
709
                old_state: empty,
710
                new_state: s1,
711
                serial: 1,
712
            },
713
        })
714
        .unwrap();
715
    let r = origin
716
        .receive_push(
717
            Bundle::default(),
718
            vec![RefUpdate {
719
                name: "main".into(),
720
                old_state: empty,
721
                new_state: s1,
722
                force: false,
723
                attestation: Some(sa.clone()),
724
            }],
725
            None,
726
            vec![],
727
        )
728
        .unwrap();
729
    assert!(
730
        !r[0].ok && r[0].reason.contains("serial"),
731
        "{}",
732
        r[0].reason
733
    );
734
    // An attestation for a different update is refused too.
735
    let sa2 = a
736
        .sign_attest(&Attest {
737
            repo: a.id().unwrap(),
738
            hlc: Hlc::now(),
739
            body: AttestBody::Ref {
740
                name: "main".into(),
741
                old_state: s1,
742
                new_state: empty,
743
                serial: 5,
744
            },
745
        })
746
        .unwrap();
747
    let r = origin
748
        .receive_push(
749
            Bundle::default(),
750
            vec![RefUpdate {
751
                name: "main".into(),
752
                old_state: empty,
753
                new_state: s1,
754
                force: false,
755
                attestation: Some(sa2),
756
            }],
757
            None,
758
            vec![],
759
        )
760
        .unwrap();
761
    assert!(
762
        !r[0].ok && r[0].reason.contains("describe"),
763
        "{}",
764
        r[0].reason
765
    );
766
    let _ = key;
767
}
768
769
#[test]
770
fn user_config_supplies_defaults_and_clones_sign() {
771
    hermetic();
772
    let dir = tempfile::tempdir().unwrap();
773
    let root = dir.path();
774
    let home = root.join("home");
775
    let origin = Repo::init(&root.join("origin")).unwrap();
776
    let url = root.join("origin").to_string_lossy().to_string();
777
778
    // Identity at user scope: the repository file stays free of author keys.
779
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
780
    let (key, _) = a
781
        .create_identity("Ada", "[email protected]", IdentityScope::User)
782
        .unwrap();
783
    assert!(!a.config.repo_layer().contains_key("author.key"));
784
    assert_eq!(a.config.author_key, Some(key));
785
    assert!(home.join("config.toml").exists());
786
    a.set_user_config("core.sign", "change").unwrap();
787
    assert!(a.config.sign_changes);
788
789
    // Repository settings override user settings and are the only ones saved.
790
    a.config.set("core.sign", "seal").unwrap();
791
    a.save_config().unwrap();
792
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
793
    assert!(!again.config.sign_changes);
794
    assert_eq!(again.config.author_key, Some(key));
795
    assert_eq!(
796
        read_config_file(&root.join("a/.oxy/config"))
797
            .unwrap()
798
            .get("core.sign")
799
            .map(String::as_str),
800
        Some("seal")
801
    );
802
803
    // A fresh clone made by this user signs with the user-level identity,
804
    // even though the clone's store has never seen the identity object.
805
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
806
    assert!(b.config.sign_changes);
807
    write(&root.join("b"), "f.txt", b"f\n");
808
    let h = b.commit("signed from a clone", &[]).unwrap();
809
    assert!(
810
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
811
    );
812
    assert!(b.push("origin", false).unwrap()[0].ok);
813
    assert!(matches!(
814
        origin.verify_change(&h).unwrap(),
815
        SignatureStatus::Valid { .. }
816
    ));
817
}
818
819
#[test]
820
fn format1_repositories_are_migrated_on_open() {
821
    hermetic();
822
    use crate::oplog::{Format1Op, Format1View};
823
    let dir = tempfile::tempdir().unwrap();
824
    let root = dir.path();
825
    let repo = Repo::init(root).unwrap();
826
    write(root, "a.txt", b"a\n");
827
    let h1 = repo.commit("one", &[]).unwrap();
828
    let (wc_hash, _) = repo.working_copy().unwrap();
829
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
830
    let mut v1 = Format1View::default();
831
    v1.bookmarks.insert("main".into(), vec![]);
832
    v1.workspaces.insert(repo.workspace(), wc_hash);
833
    let init = Format1Op {
834
        parents: vec![],
835
        hlc: Hlc::default(),
836
        command: "oxy init".into(),
837
        view: v1.clone(),
838
    };
839
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
840
    v1.bookmarks.insert("main".into(), vec![h1]);
841
    let commit = Format1Op {
842
        parents: vec![init_ref],
843
        hlc: Hlc::default(),
844
        command: "oxy commit".into(),
845
        view: v1,
846
    };
847
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
848
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
849
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
850
    drop(repo);
851
852
    let repo = Repo::open(root).unwrap();
853
    assert_eq!(
854
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
855
        FORMAT_LINE
856
    );
857
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
858
    let ops = repo.op_log().unwrap();
859
    assert_eq!(
860
        ops.iter()
861
            .map(|(_, o)| o.command.as_str())
862
            .collect::<Vec<_>>(),
863
        ["oxy commit", "oxy init"]
864
    );
865
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
866
    assert!(!repo.snapshot("status").unwrap().changed);
867
    // Reopening again is a no-op.
868
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
869
}
870
871
#[test]
872
fn undo_skips_snapshot_operations() {
873
    hermetic();
874
    let dir = tempfile::tempdir().unwrap();
875
    let root = dir.path();
876
    let repo = Repo::init(root).unwrap();
877
    write(root, "a.txt", b"a\n");
878
    let h1 = repo.commit("a", &[]).unwrap();
879
    // A later command snapshots new edits on top of the commit.
880
    write(root, "b.txt", b"b\n");
881
    let s = repo.snapshot("oxy status").unwrap();
882
    assert!(s.changed);
883
    assert!(repo.head_op().unwrap().1.is_snapshot());
884
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
885
    // Undo must undo the commit, not the snapshot.
886
    repo.undo().unwrap();
887
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
888
    let s = repo.snapshot("oxy status").unwrap();
889
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
890
    assert_eq!(
891
        paths,
892
        ["a.txt", "b.txt"],
893
        "both files are back in the working copy"
894
    );
895
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
896
    // Only snapshots remain above `init`, so there is nothing left to undo.
897
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
898
    assert!(repo.undo().is_err());
899
}
900
901
#[test]
902
fn independent_changes_commute_and_make_multiple_heads() {
903
    hermetic();
904
    let dir = tempfile::tempdir().unwrap();
905
    let root = dir.path();
906
    let repo = Repo::init(root).unwrap();
907
    write(root, "a.txt", b"a\n");
908
    let h1 = repo.commit("a", &[]).unwrap();
909
    write(root, "b.txt", b"b\n");
910
    let h2 = repo.commit("b", &[]).unwrap();
911
    let c2 = repo.store().get_change(&h2).unwrap();
912
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
913
    let mut heads = repo.bookmark_heads().unwrap();
914
    heads.sort();
915
    let mut want = vec![h1, h2];
916
    want.sort();
917
    assert_eq!(heads, want);
918
    // Editing a.txt depends on h1 only.
919
    write(root, "a.txt", b"a\na2\n");
920
    let h3 = repo.commit("a2", &[]).unwrap();
921
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
922
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
923
    assert_eq!(heads, [h2, h3].into_iter().collect());
924
    // Explicit dependency.
925
    write(root, "c.txt", b"c\n");
926
    let h4 = repo.commit("c", &[h2]).unwrap();
927
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
928
}
929
930
#[test]
931
fn mode_change_and_text_binary_switch() {
932
    hermetic();
933
    let dir = tempfile::tempdir().unwrap();
934
    let root = dir.path();
935
    let repo = Repo::init(root).unwrap();
936
    write(root, "run.sh", b"#!/bin/sh\n");
937
    repo.commit("add script", &[]).unwrap();
938
    #[cfg(unix)]
939
    {
940
        use std::os::unix::fs::PermissionsExt;
941
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
942
        let s = repo.snapshot("status").unwrap();
943
        assert_eq!(
944
            statuses(&s),
945
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
946
        );
947
        let h = repo.commit("exec", &[]).unwrap();
948
        let snap = repo.load_state(&[h]).unwrap().materialize();
949
        assert!(snap.files["run.sh"].mode.exec);
950
    }
951
    // Text → binary → text.
952
    write(root, "run.sh", b"\0binary");
953
    let h = repo.commit("binary", &[]).unwrap();
954
    let snap = repo.load_state(&[h]).unwrap().materialize();
955
    assert!(snap.files["run.sh"].mode.opaque);
956
    write(root, "run.sh", b"text again\n");
957
    let h = repo.commit("text", &[]).unwrap();
958
    let snap = repo.load_state(&[h]).unwrap().materialize();
959
    assert!(!snap.files["run.sh"].mode.opaque);
960
    assert!(
961
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
962
    );
963
    assert!(!snap.is_conflicted());
964
}
965
966
#[test]
967
fn trust_policy_governs_pushes_and_fetches() {
968
    hermetic();
969
    let dir = tempfile::tempdir().unwrap();
970
    let root = dir.path();
971
    let origin = Repo::init(&root.join("origin")).unwrap();
972
    let url = root.join("origin").to_string_lossy().to_string();
973
974
    // A is the root. Before the policy, an unsigned push from B is fine.
975
    let mut a = Repo::clone(&url, &root.join("a"))
976
        .unwrap()
977
        .with_home(root.join("home-a"));
978
    let (key_a, _) = a
979
        .create_identity("Ada", "[email protected]", IdentityScope::User)
980
        .unwrap();
981
    let mut b = Repo::clone(&url, &root.join("b"))
982
        .unwrap()
983
        .with_home(root.join("home-b"));
984
    write(&root.join("b"), "b.txt", b"b\n");
985
    b.commit("unsigned before policy", &[]).unwrap();
986
    assert!(b.push("origin", false).unwrap()[0].ok);
987
988
    // A creates the policy and pushes it; origin now enforces it.
989
    write(&root.join("a"), "a.txt", b"a\n");
990
    a.commit("a", &[]).unwrap();
991
    let sp = a.policy_init().unwrap();
992
    assert_eq!(sp.policy.serial, 1);
993
    a.pull("origin").unwrap();
994
    let results = a.push("origin", false).unwrap();
995
    assert!(results.iter().all(|r| r.ok), "{results:?}");
996
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
997
998
    // B pulls the policy. Without an identity B cannot push at all.
999
    b.pull("origin").unwrap();
1000
    assert!(
1001
        b.current_policy().unwrap().is_some(),
1002
        "the policy arrived with the fetch"
1003
    );
1004
    assert!(b.push("origin", false).is_err());
1005
    // With an identity the policy does not list, the push is rejected by origin.
1006
    let (key_b, id_b) = b
1007
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1008
        .unwrap();
1009
    write(&root.join("b"), "b.txt", b"b2\n");
1010
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1011
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1012
    let r = b.push("origin", false).unwrap();
1013
    assert!(
1014
        !r[0].ok && r[0].reason.contains("may not update"),
1015
        "{:?}",
1016
        r
1017
    );
1018
1019
    // A grants B (identity handed over as a file) and publishes the policy.
1020
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1021
    assert_eq!(sp.policy.serial, 2);
1022
    let r = a.push("origin", false).unwrap();
1023
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1024
    // B must fetch the new policy before pushing.
1025
    assert!(b
1026
        .push("origin", false)
1027
        .unwrap_or_else(|e| vec![RefResult {
1028
            name: "main".into(),
1029
            ok: false,
1030
            reason: e.to_string()
1031
        }])
1032
        .iter()
1033
        .all(|x| !x.ok));
1034
    b.pull("origin").unwrap();
1035
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1036
    let r = b.push("origin", false).unwrap();
1037
    assert!(r[0].ok, "{:?}", r);
1038
    // Origin verified B's change under the policy.
1039
    let heads = origin.bookmark_heads().unwrap();
1040
    for h in &heads {
1041
        let c = origin.store().get_change(h).unwrap();
1042
        if c.author == key_b {
1043
            origin
1044
                .change_allowed(
1045
                    h,
1046
                    &origin.current_policy().unwrap().unwrap().1.policy,
1047
                    "main",
1048
                )
1049
                .unwrap();
1050
        }
1051
    }
1052
1053
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1054
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1055
    forged.serial = 3;
1056
    forged.roots = vec![key_b];
1057
    let fh = forged.hash();
1058
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1059
    let forged = SignedPolicy {
1060
        policy: forged,
1061
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1062
    };
1063
    let r = origin
1064
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1065
        .unwrap();
1066
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1067
    let stale = a.current_policy().unwrap().unwrap().1;
1068
    let mut old = stale.clone();
1069
    old.policy.serial = 1;
1070
    let r = origin
1071
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1072
        .unwrap();
1073
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1074
1075
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1076
    a.pull("origin").unwrap();
1077
    a.policy_revoke(&key_b).unwrap();
1078
    let r = a.push("origin", false).unwrap();
1079
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1080
    b.pull("origin").unwrap();
1081
    write(&root.join("b"), "b.txt", b"b3\n");
1082
    b.commit("b3", &[]).unwrap();
1083
    let r = b.push("origin", false).unwrap();
1084
    assert!(!r[0].ok, "{:?}", r);
1085
1086
    // A clone by a third party receives and verifies everything.
1087
    let c = Repo::clone(&url, &root.join("c"))
1088
        .unwrap()
1089
        .with_home(root.join("home-c"));
1090
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1091
    assert!(c
1092
        .current_policy()
1093
        .unwrap()
1094
        .unwrap()
1095
        .1
1096
        .policy
1097
        .roots
1098
        .contains(&key_a));
1099
    assert!(!c.snapshot("status").unwrap().changed);
1100
}
1101
1102
/// oxygen#66: a gc says what it is doing, phase by phase.
1103
#[test]
1104
fn gc_reports_its_phases() {
1105
    hermetic();
1106
    let dir = tempfile::tempdir().unwrap();
1107
    let repo = Repo::init(dir.path()).unwrap();
1108
    for i in 0..3 {
1109
        write(
1110
            dir.path(),
1111
            &format!("f{i}.txt"),
1112
            format!("{i}\n").as_bytes(),
1113
        );
1114
        repo.commit(&format!("c{i}"), &[]).unwrap();
1115
    }
1116
    let mut phases = Vec::new();
1117
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1118
        .unwrap();
1119
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1120
    assert!(
1121
        phases.iter().any(|p| p.starts_with("pruning")),
1122
        "{phases:?}"
1123
    );
1124
    assert!(
1125
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1126
        "{phases:?}"
1127
    );
1128
    assert!(
1129
        phases
1130
            .iter()
1131
            .any(|p| p.starts_with("writing the index of ")),
1132
        "{phases:?}"
1133
    );
1134
}
1135
1136
#[test]
1137
fn gc_packs_objects_and_history_still_works() {
1138
    hermetic();
1139
    let dir = tempfile::tempdir().unwrap();
1140
    let root = dir.path();
1141
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1142
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1143
        .unwrap();
1144
    repo.set_user_config("core.sign", "change").unwrap();
1145
    write(root, "a.txt", b"one\n");
1146
    let h1 = repo.commit("one", &[]).unwrap();
1147
    write(root, "a.txt", b"two\n");
1148
    write(root, "big.bin", &vec![0u8; 100_000]);
1149
    let h2 = repo.commit("two", &[]).unwrap();
1150
    // Several snapshots leave superseded working-copy versions behind.
1151
    for i in 0..5 {
1152
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1153
        repo.snapshot("status").unwrap();
1154
    }
1155
    write(root, "a.txt", b"two\n");
1156
    repo.snapshot("status").unwrap();
1157
    let before = repo.store().list().unwrap();
1158
    assert!(repo.store().loose_count().unwrap() > 0);
1159
1160
    // With the default retention every operation's view is a root: nothing prunes.
1161
    let r = repo.gc(true).unwrap();
1162
    assert_eq!(r.packed.objects, before.len());
1163
    assert_eq!(r.pruned.objects, 0);
1164
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1165
    assert_eq!(repo.store().list().unwrap(), before);
1166
1167
    // With zero retention only the current view is a root: superseded
1168
    // working copies go, everything reachable stays.
1169
    repo.config.set("core.op-retention", "0").unwrap();
1170
    repo.save_config().unwrap();
1171
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1172
    let r = repo.gc(true).unwrap();
1173
    assert!(r.pruned.objects >= 5, "{r:?}");
1174
    let after = repo.store().list().unwrap();
1175
    assert!(after.len() < before.len());
1176
    assert!(after.contains(&h1) && after.contains(&h2));
1177
    for (_, op) in repo.op_log().unwrap() {
1178
        assert!(!op.command.is_empty(), "operation objects are all kept");
1179
    }
1180
    // Everything still works from the pruned, packed store.
1181
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1182
    assert!(matches!(
1183
        repo.verify_change(&h2).unwrap(),
1184
        SignatureStatus::Valid { .. }
1185
    ));
1186
    assert_eq!(repo.log().unwrap().len(), 3);
1187
    repo.checkout(&[h1], false, "checkout").unwrap();
1188
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1189
    repo.checkout(&[h2], false, "checkout").unwrap();
1190
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1191
    assert!(!repo.snapshot("status").unwrap().changed);
1192
    // Grace period defers pruning of young garbage.
1193
    write(root, "a.txt", b"three\n");
1194
    repo.commit("three", &[]).unwrap();
1195
    let r = repo.gc(false).unwrap();
1196
    assert_eq!(r.pruned.objects, 0);
1197
    assert!(r.pruned.deferred > 0);
1198
    let r = repo.gc(true).unwrap();
1199
    assert!(r.pruned.objects > 0);
1200
    assert_eq!(repo.log().unwrap().len(), 4);
1201
    // Restoring the default retention makes the old views roots again; the
1202
    // working copies they name were pruned, which gc tolerates.
1203
    repo.config.set("core.op-retention", "90").unwrap();
1204
    repo.save_config().unwrap();
1205
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1206
    let r = repo.gc(false).unwrap();
1207
    assert_eq!(r.pruned.objects, 0);
1208
    assert_eq!(repo.log().unwrap().len(), 4);
1209
}
1210
1211
#[test]
1212
fn describe_amend_abandon_heads() {
1213
    hermetic();
1214
    let dir = tempfile::tempdir().unwrap();
1215
    let root = dir.path();
1216
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1217
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1218
        .unwrap();
1219
    repo.set_user_config("core.sign", "change").unwrap();
1220
    write(root, "a.txt", b"one\n");
1221
    let h1 = repo.commit("first", &[]).unwrap();
1222
    write(root, "a.txt", b"one\ntwo\n");
1223
    let h2 = repo.commit("secnod", &[]).unwrap();
1224
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1225
1226
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1227
    let h2b = repo.describe(&h2, "second").unwrap();
1228
    assert_ne!(h2b, h2);
1229
    let c = repo.store().get_change(&h2b).unwrap();
1230
    assert_eq!(
1231
        (c.change_id, c.message.as_str(), c.deps.clone()),
1232
        (id2, "second", vec![h1])
1233
    );
1234
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1235
    assert!(matches!(
1236
        repo.verify_change(&h2b).unwrap(),
1237
        SignatureStatus::Valid { .. }
1238
    ));
1239
    let s = repo.snapshot("status").unwrap();
1240
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1241
    assert_eq!(
1242
        repo.resolve_change(&id2.short(8)).unwrap(),
1243
        h2b,
1244
        "the old object is no longer reachable from the log"
1245
    );
1246
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1247
    let h1b = repo.describe(&h1, "first, described").unwrap();
1248
    assert_ne!(h1b, h1);
1249
    let heads = repo.bookmark_heads().unwrap();
1250
    assert_eq!(heads.len(), 1);
1251
    let top = repo.store().get_change(&heads[0]).unwrap();
1252
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1253
    assert!(
1254
        matches!(
1255
            repo.verify_change(&heads[0]).unwrap(),
1256
            SignatureStatus::Valid { .. }
1257
        ),
1258
        "rewritten own change is re-signed"
1259
    );
1260
    let (_, wc) = repo.working_copy().unwrap();
1261
    assert_eq!(
1262
        wc.deps,
1263
        vec![heads[0]],
1264
        "the working copy follows the rewrite"
1265
    );
1266
    assert!(!repo.snapshot("status").unwrap().changed);
1267
    let snap = repo.load_state(&heads).unwrap().materialize();
1268
    assert!(
1269
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1270
    );
1271
1272
    // amend: fold an edit into the head; the result is one change from h1.
1273
    write(root, "a.txt", b"one\ntwo\nthree\n");
1274
    write(root, "b.txt", b"b\n");
1275
    let h2c = repo.amend(None).unwrap();
1276
    let c = repo.store().get_change(&h2c).unwrap();
1277
    assert_eq!(c.change_id, id2);
1278
    assert_eq!(c.message, "second");
1279
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1280
    assert_eq!(
1281
        repo.log().unwrap().len(),
1282
        3,
1283
        "working copy, amended head, first"
1284
    );
1285
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1286
    assert!(
1287
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1288
    );
1289
    assert!(snap.files.contains_key("b.txt"));
1290
    assert!(!repo.snapshot("status").unwrap().changed);
1291
    assert!(
1292
        repo.amend(None).is_err(),
1293
        "clean working copy and no message"
1294
    );
1295
    let h2d = repo.amend(Some("second, amended")).unwrap();
1296
    assert_eq!(
1297
        repo.store().get_change(&h2d).unwrap().message,
1298
        "second, amended"
1299
    );
1300
1301
    // abandon: the head goes, its content stays as uncommitted work.
1302
    repo.abandon(&h2d).unwrap();
1303
    assert_eq!(
1304
        repo.bookmark_heads().unwrap(),
1305
        vec![h1b],
1306
        "the described first change is the head again"
1307
    );
1308
    let s = repo.snapshot("status").unwrap();
1309
    let paths: Vec<_> = s
1310
        .statuses
1311
        .iter()
1312
        .map(|p| (p.path.as_str(), p.status))
1313
        .collect();
1314
    assert_eq!(
1315
        paths,
1316
        vec![
1317
            ("a.txt", ChangeStatus::Modified),
1318
            ("b.txt", ChangeStatus::Added)
1319
        ]
1320
    );
1321
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1322
    let h3 = repo.commit("recommitted", &[]).unwrap();
1323
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1324
    // undo brings the abandoned head back.
1325
    repo.undo().unwrap();
1326
    repo.undo().unwrap();
1327
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1328
1329
    // Abandoning a non-head whose dependent references its atoms reifies
1330
    // the references (here: a.txt vanishes with it, so the dependent's edit
1331
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1332
    let base = repo.bookmark_heads().unwrap()[0];
1333
    let base_change = repo.store().get_change(&base).unwrap();
1334
    let h1_now = base_change.deps[0];
1335
    let notes = repo.abandon(&h1_now).unwrap();
1336
    assert!(
1337
        !notes.is_empty(),
1338
        "the dependent's edit of a.txt was reified"
1339
    );
1340
    let heads = repo.bookmark_heads().unwrap();
1341
    let after = repo.load_state(&heads).unwrap().materialize();
1342
    assert!(
1343
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1344
        "{:?}",
1345
        after.files.keys()
1346
    );
1347
    repo.undo().unwrap();
1348
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1349
    write(root, "c.txt", b"c\n");
1350
    let hc = repo.commit("c", &[]).unwrap();
1351
    write(root, "d.txt", b"d\n");
1352
    let hd = repo.commit("d", &[hc]).unwrap();
1353
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1354
    repo.abandon(&hc).unwrap();
1355
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1356
    assert!(!heads.contains(&hc));
1357
    let d_now = heads
1358
        .iter()
1359
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1360
        .copied()
1361
        .unwrap();
1362
    assert!(
1363
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1364
        "d inherited c's (empty) dependencies"
1365
    );
1366
    let s = repo.snapshot("status").unwrap();
1367
    assert_eq!(
1368
        s.statuses
1369
            .iter()
1370
            .map(|p| p.path.as_str())
1371
            .collect::<Vec<_>>(),
1372
        vec!["c.txt"],
1373
        "c's content is now uncommitted work"
1374
    );
1375
}
1376
1377
#[test]
1378
fn git_export_mirrors_history() {
1379
    hermetic();
1380
    if std::process::Command::new("git")
1381
        .arg("--version")
1382
        .output()
1383
        .is_err()
1384
    {
1385
        eprintln!("git not installed; skipping");
1386
        return;
1387
    }
1388
    let dir = tempfile::tempdir().unwrap();
1389
    let root = dir.path();
1390
    let mut repo = Repo::init(&root.join("r"))
1391
        .unwrap()
1392
        .with_home(root.join("home"));
1393
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1394
        .unwrap();
1395
    let r = root.join("r");
1396
    write(&r, "README.md", b"hello\n");
1397
    write(&r, "src/main.rs", b"fn main() {}\n");
1398
    let h1 = repo.commit("first", &[]).unwrap();
1399
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1400
    write(&r, "logo.png", b"\x89PNG\0\0");
1401
    let h2 = repo.commit("second", &[]).unwrap();
1402
1403
    let git_dir = root.join("mirror.git");
1404
    let rep = repo.git_export(&git_dir).unwrap();
1405
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1406
    let git = |args: &[&str]| -> String {
1407
        let out = std::process::Command::new("git")
1408
            .arg("-C")
1409
            .arg(&git_dir)
1410
            .args(args)
1411
            .output()
1412
            .unwrap();
1413
        assert!(
1414
            out.status.success(),
1415
            "{}",
1416
            String::from_utf8_lossy(&out.stderr)
1417
        );
1418
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1419
    };
1420
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1421
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1422
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1423
    let body = git(&["log", "-1", "--format=%B", "main"]);
1424
    assert!(
1425
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1426
        "{body}"
1427
    );
1428
    assert!(body.contains("Change-Id: "), "{body}");
1429
    assert_eq!(
1430
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1431
        "Ada Lovelace <[email protected]>"
1432
    );
1433
    assert_eq!(
1434
        git(&["ls-tree", "--name-only", "main"]),
1435
        "README.md\nlogo.png\nsrc"
1436
    );
1437
1438
    // Re-export is incremental.
1439
    let rep = repo.git_export(&git_dir).unwrap();
1440
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1441
1442
    // An independent change makes two heads; the next state is one more
1443
    // commit on the linear branch whose tree is the union.
1444
    repo.checkout(&[h1], false, "checkout").unwrap();
1445
    write(&r, "other.txt", b"o\n");
1446
    let h3 = repo.commit("third", &[]).unwrap();
1447
    let rep = repo.git_export(&git_dir).unwrap();
1448
    assert_eq!((rep.exported, rep.heads), (1, 2));
1449
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1450
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1451
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1452
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1453
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1454
    assert_eq!(
1455
        git(&["ls-tree", "--name-only", "main"]),
1456
        "README.md\nlogo.png\nother.txt\nsrc"
1457
    );
1458
    let body = git(&["log", "-1", "--format=%B", "main"]);
1459
    assert!(
1460
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1461
        "{body}"
1462
    );
1463
    // A rewrite is a new state whose one new change is the rewritten one.
1464
    repo.describe(&h3, "third, described").unwrap();
1465
    let rep = repo.git_export(&git_dir).unwrap();
1466
    assert_eq!(rep.exported, 1);
1467
    assert_eq!(
1468
        git(&["log", "-1", "--format=%s", "main"]),
1469
        "third, described"
1470
    );
1471
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1472
    let _ = h2;
1473
}
1474
1475
#[test]
1476
fn git_import_reproduces_trees() {
1477
    git_import_reproduces_trees_with(None);
1478
}
1479
1480
/// The same import with every merge rendered in batches of one file
1481
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1482
#[test]
1483
fn git_import_reproduces_trees_in_batches() {
1484
    git_import_reproduces_trees_with(Some(1));
1485
}
1486
1487
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1488
    crate::repo::git::set_merge_batch_for_tests(batch);
1489
    hermetic();
1490
    if std::process::Command::new("git")
1491
        .arg("--version")
1492
        .output()
1493
        .is_err()
1494
    {
1495
        eprintln!("git not installed; skipping");
1496
        return;
1497
    }
1498
    let dir = tempfile::tempdir().unwrap();
1499
    let root = dir.path();
1500
    let g = root.join("src.git");
1501
    fs::create_dir_all(&g).unwrap();
1502
    let git = |args: &[&str]| -> String {
1503
        let out = std::process::Command::new("git")
1504
            .arg("-C")
1505
            .arg(&g)
1506
            .args([
1507
                "-c",
1508
                "user.name=Grace",
1509
                "-c",
1510
                "[email protected]",
1511
                "-c",
1512
                "commit.gpgsign=false",
1513
            ])
1514
            .args(args)
1515
            .output()
1516
            .unwrap();
1517
        assert!(
1518
            out.status.success(),
1519
            "git {args:?}: {}",
1520
            String::from_utf8_lossy(&out.stderr)
1521
        );
1522
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1523
    };
1524
    git(&["init", "-q", "-b", "main"]);
1525
    write(&g, "README.md", b"# Hi\n");
1526
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1527
    git(&["add", "."]);
1528
    git(&["commit", "-q", "-m", "initial"]);
1529
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1530
    write(&g, "run.sh", b"#!/bin/sh\n");
1531
    #[cfg(unix)]
1532
    {
1533
        use std::os::unix::fs::PermissionsExt;
1534
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1535
    }
1536
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1537
    git(&["add", "."]);
1538
    git(&[
1539
        "commit",
1540
        "-q",
1541
        "-m",
1542
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1543
    ]);
1544
    // A branch that edits README, merged back with a conflict-free merge.
1545
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1546
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1547
    git(&["commit", "-q", "-am", "readme"]);
1548
    git(&["checkout", "-q", "main"]);
1549
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1550
    // A branch from the initial commit inserting at the same place as
1551
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1552
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1553
    git(&["checkout", "-q", "-b", "clash", &initial]);
1554
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1555
    git(&["commit", "-q", "-am", "clash"]);
1556
    git(&["checkout", "-q", "main"]);
1557
    let _ = std::process::Command::new("git")
1558
        .arg("-C")
1559
        .arg(&g)
1560
        .args(["merge", "-q", "clash"])
1561
        .output();
1562
    write(
1563
        &g,
1564
        "src/lib.rs",
1565
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1566
    );
1567
    git(&["add", "."]);
1568
    git(&["commit", "-q", "-m", "resolve clash"]);
1569
    git(&["rm", "-q", "logo.png"]);
1570
    git(&["commit", "-q", "-m", "drop logo"]);
1571
    // A rename with a small edit is imported as a move of the same node.
1572
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1573
    write(
1574
        &g,
1575
        "src/lib2.rs",
1576
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1577
    );
1578
    git(&["add", "."]);
1579
    git(&["commit", "-q", "-m", "rename lib"]);
1580
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1581
    // run.sh is the same as in the first parent's tree, but the merged
1582
    // change touched it, so the importer must compare it, not skip it.
1583
    git(&["checkout", "-q", "-b", "discarded"]);
1584
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1585
    git(&["commit", "-q", "-am", "discarded edit"]);
1586
    git(&["checkout", "-q", "main"]);
1587
    git(&[
1588
        "merge",
1589
        "-q",
1590
        "-s",
1591
        "ours",
1592
        "-m",
1593
        "merge discarded, keeping ours",
1594
        "discarded",
1595
    ]);
1596
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1597
1598
    let dest = root.join("oxy");
1599
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1600
    let rep = repo.import_git(&g, "main").unwrap();
1601
    assert_eq!(rep.commits, expected_count);
1602
    assert_eq!(rep.merges, 3);
1603
    assert_eq!(
1604
        fs::read(dest.join("run.sh")).unwrap(),
1605
        b"#!/bin/sh\n",
1606
        "the ours merge kept main's run.sh"
1607
    );
1608
    let v = repo.verify_git_import(&g, "main").unwrap();
1609
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1610
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1611
    // The working copy equals the Git tree at main.
1612
    assert_eq!(
1613
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1614
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1615
    );
1616
    assert!(!dest.join("src/lib.rs").exists());
1617
    assert_eq!(
1618
        fs::read(dest.join("README.md")).unwrap(),
1619
        b"# Hi\n\nMore.\n"
1620
    );
1621
    assert!(!dest.join("logo.png").exists());
1622
    #[cfg(unix)]
1623
    {
1624
        use std::os::unix::fs::PermissionsExt;
1625
        assert!(
1626
            fs::metadata(dest.join("run.sh"))
1627
                .unwrap()
1628
                .permissions()
1629
                .mode()
1630
                & 0o111
1631
                != 0
1632
        );
1633
    }
1634
    assert!(
1635
        !repo.snapshot("status").unwrap().changed,
1636
        "clean after import"
1637
    );
1638
    let heads = repo.bookmark_heads().unwrap();
1639
    let st = repo.load_state(&heads).unwrap();
1640
    assert!(!st.materialize().is_conflicted());
1641
    assert_eq!(st.len(), expected_count);
1642
    let tip = repo
1643
        .log()
1644
        .unwrap()
1645
        .into_iter()
1646
        .find(|e| e.change.message.starts_with("rename lib"))
1647
        .unwrap();
1648
    let c = repo.store().get_change(&tip.hash).unwrap();
1649
    assert!(
1650
        c.tree_ops
1651
            .iter()
1652
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1653
        "{:?}",
1654
        c.tree_ops
1655
    );
1656
    assert!(!c
1657
        .tree_ops
1658
        .iter()
1659
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1660
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1661
    let log = repo.log().unwrap();
1662
    let second = log
1663
        .iter()
1664
        .find(|e| e.change.message.starts_with("second"))
1665
        .unwrap();
1666
    assert_eq!(
1667
        second.change.change_id,
1668
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1669
    );
1670
    assert!(second
1671
        .change
1672
        .message
1673
        .contains("Git-Author: Grace <[email protected]>"));
1674
    let resolve = log
1675
        .iter()
1676
        .find(|e| e.change.message.starts_with("resolve clash"))
1677
        .unwrap();
1678
    assert_eq!(
1679
        resolve.change.kind,
1680
        ChangeKind::Resolution,
1681
        "a conflicting Git merge becomes a resolution"
1682
    );
1683
    // Re-importing into another fresh repository gives the same ChangeIds.
1684
    let repo2 = Repo::init(&root.join("oxy2"))
1685
        .unwrap()
1686
        .with_home(root.join("home"));
1687
    repo2.import_git(&g, "main").unwrap();
1688
    // New nodes' identifiers derive from the commit (spec §23), so the
1689
    // re-import is not just the same ChangeIds but the same changes.
1690
    assert_eq!(
1691
        repo2.bookmark_heads().unwrap(),
1692
        repo.bookmark_heads().unwrap()
1693
    );
1694
    let ids: BTreeSet<ChangeId> = repo
1695
        .log()
1696
        .unwrap()
1697
        .iter()
1698
        .filter(|e| !e.is_working_copy)
1699
        .map(|e| e.change.change_id)
1700
        .collect();
1701
    let ids2: BTreeSet<ChangeId> = repo2
1702
        .log()
1703
        .unwrap()
1704
        .iter()
1705
        .filter(|e| !e.is_working_copy)
1706
        .map(|e| e.change.change_id)
1707
        .collect();
1708
    assert_eq!(ids, ids2);
1709
    // Round trip back out to Git reproduces the tip tree.
1710
    let mirror = root.join("mirror.git");
1711
    repo.git_export(&mirror).unwrap();
1712
    let out = std::process::Command::new("git")
1713
        .arg("-C")
1714
        .arg(&mirror)
1715
        .args(["show", "main:src/lib2.rs"])
1716
        .output()
1717
        .unwrap();
1718
    assert_eq!(
1719
        String::from_utf8_lossy(&out.stdout),
1720
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1721
    );
1722
    let out = std::process::Command::new("git")
1723
        .arg("-C")
1724
        .arg(&mirror)
1725
        .args(["show", "main:src/lib.rs"])
1726
        .output()
1727
        .unwrap();
1728
    assert!(
1729
        !out.status.success(),
1730
        "the old path is gone from the export"
1731
    );
1732
}
1733
1734
#[test]
1735
fn checkpoints_accelerate_loading_and_stay_correct() {
1736
    hermetic();
1737
    let dir = tempfile::tempdir().unwrap();
1738
    let root = dir.path();
1739
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1740
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1741
    repo.save_config().unwrap();
1742
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1743
    let mut hashes = Vec::new();
1744
    for i in 0..12 {
1745
        write(
1746
            root,
1747
            "a.txt",
1748
            format!(
1749
                "{}\n",
1750
                (0..=i)
1751
                    .map(|k| k.to_string())
1752
                    .collect::<Vec<_>>()
1753
                    .join("\n")
1754
            )
1755
            .as_bytes(),
1756
        );
1757
        write(root, &format!("f{i}.txt"), b"x\n");
1758
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1759
    }
1760
    let (_, cp) = repo
1761
        .latest_checkpoint("main")
1762
        .unwrap()
1763
        .expect("automatic checkpoint");
1764
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1765
    // Loading through the checkpoint equals loading everything.
1766
    let heads = repo.bookmark_heads().unwrap();
1767
    let fast = repo.load_state(&heads).unwrap();
1768
    let full = repo.load_state_full(&heads).unwrap();
1769
    assert_eq!(fast.len(), full.len());
1770
    assert_eq!(fast.heads(), full.heads());
1771
    let (a, b) = (fast.materialize(), full.materialize());
1772
    assert_eq!(
1773
        a.files.keys().collect::<Vec<_>>(),
1774
        b.files.keys().collect::<Vec<_>>()
1775
    );
1776
    for (p, f) in &a.files {
1777
        assert_eq!(f.content, b.files[p].content, "{p}");
1778
    }
1779
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1780
    // A head set that does not contain the checkpoint's heads falls back.
1781
    assert!(repo
1782
        .load_state_checkpointed(&[hashes[0]])
1783
        .unwrap()
1784
        .is_none());
1785
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1786
    // Everything else keeps working on top of the checkpoint.
1787
    assert!(!repo.snapshot("status").unwrap().changed);
1788
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1789
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1790
    let (r, n, bytes) = repo.checkpoint().unwrap();
1791
    assert!(n >= 12 && bytes > 0);
1792
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1793
    write(root, "a.txt", b"after\n");
1794
    let h_after = repo.commit("after", &[]).unwrap();
1795
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1796
    assert!(st.contains(&h_after));
1797
    assert!(
1798
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1799
    );
1800
    assert_eq!(repo.log().unwrap().len(), 14);
1801
    // Checkpoints survive gc.
1802
    repo.gc(true).unwrap();
1803
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1804
    assert!(repo
1805
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1806
        .unwrap()
1807
        .is_some());
1808
}
1809
1810
#[test]
1811
fn quick_status_for_prompts() {
1812
    hermetic();
1813
    let dir = tempfile::tempdir().unwrap();
1814
    let root = dir.path();
1815
    let origin = Repo::init(&root.join("origin")).unwrap();
1816
    let url = root.join("origin").to_string_lossy().to_string();
1817
    let a = Repo::clone(&url, &root.join("a"))
1818
        .unwrap()
1819
        .with_home(root.join("home"));
1820
    let ops_before = a.op_log().unwrap().len();
1821
    let info = a.quick_status().unwrap();
1822
    assert_eq!(
1823
        (
1824
            info.bookmark.as_str(),
1825
            info.heads,
1826
            info.dirty,
1827
            info.conflicted,
1828
            info.ahead,
1829
            info.behind
1830
        ),
1831
        ("main", 0, false, false, Some(0), Some(0))
1832
    );
1833
    write(&root.join("a"), "f.txt", b"f\n");
1834
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1835
    assert_eq!(
1836
        a.op_log().unwrap().len(),
1837
        ops_before,
1838
        "quick_status records nothing"
1839
    );
1840
    // A snapshotted but uncommitted change is still dirty.
1841
    a.snapshot("status").unwrap();
1842
    assert!(a.quick_status().unwrap().dirty);
1843
    a.commit("f", &[]).unwrap();
1844
    let info = a.quick_status().unwrap();
1845
    assert!(!info.dirty, "clean right after a commit");
1846
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
1847
    assert_eq!(
1848
        info.format("%b %c%d%x%A%D"),
1849
        format!("main {}+1", info.change_id)
1850
    );
1851
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1852
    // Touching a file without changing it is not dirty; changing content of
1853
    // the same size is.
1854
    let p = root.join("a/f.txt");
1855
    let content = fs::read(&p).unwrap();
1856
    fs::write(&p, &content).unwrap();
1857
    assert!(!a.quick_status().unwrap().dirty);
1858
    fs::write(&p, b"g\n").unwrap();
1859
    assert!(a.quick_status().unwrap().dirty);
1860
    fs::write(&p, b"f\n").unwrap();
1861
    // Push, then a second clone commits and pushes: we are behind.
1862
    assert!(a.push("origin", false).unwrap()[0].ok);
1863
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
1864
    let b = Repo::clone(&url, &root.join("b"))
1865
        .unwrap()
1866
        .with_home(root.join("home-b"));
1867
    write(&root.join("b"), "g.txt", b"g\n");
1868
    b.commit("g", &[]).unwrap();
1869
    b.push("origin", false).unwrap();
1870
    a.fetch("origin").unwrap();
1871
    let info = a.quick_status().unwrap();
1872
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1873
    assert_eq!(info.format("%A%D"), "-1");
1874
    let _ = origin;
1875
}
1876
1877
#[test]
1878
fn lazy_blobs_are_fetched_on_first_read() {
1879
    hermetic();
1880
    let dir = tempfile::tempdir().unwrap();
1881
    let root = dir.path();
1882
    let origin_dir = root.join("origin");
1883
    let origin = Repo::init(&origin_dir)
1884
        .unwrap()
1885
        .with_home(root.join("home"));
1886
    let url = origin_dir.to_string_lossy().to_string();
1887
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1888
    write(&origin_dir, "big.bin", &big);
1889
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1890
    write(&origin_dir, "t.txt", b"t\n");
1891
    let h = origin.commit("blobs", &[]).unwrap();
1892
    let big_ref = Repo::blob_ref(&big);
1893
1894
    // Fetch only (no checkout) with a filter: the big blob stays absent.
1895
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1896
        .unwrap()
1897
        .with_home(root.join("home"));
1898
    let a = {
1899
        let mut a = a;
1900
        a.config.set("remote.origin.url", &url).unwrap();
1901
        a.config.set("filter.max-blob", "100K").unwrap();
1902
        a.save_config().unwrap();
1903
        a
1904
    };
1905
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1906
    a.fetch("origin").unwrap();
1907
    assert!(a.store().has(&h));
1908
    assert!(!a.store().has(&big_ref), "withheld");
1909
    assert!(
1910
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1911
        "small blob came along"
1912
    );
1913
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1914
1915
    // status and commit do not need it: adopt the state, edit a text file, commit.
1916
    let (op_ref, op) = a.head_op().unwrap();
1917
    let mut view = op.view.clone();
1918
    view.bookmarks.insert(
1919
        "main".into(),
1920
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1921
    );
1922
    a.record_op(&[op_ref], "adopt", view).unwrap();
1923
    // Checkout reads the blob lazily, which fetches it.
1924
    a.checkout(&[h], true, "checkout").unwrap();
1925
    assert!(a.store().has(&big_ref), "fetched on first read");
1926
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1927
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1928
    write(&root.join("a"), "t.txt", b"t2\n");
1929
    a.commit("text edit", &[]).unwrap();
1930
1931
    // clone --max-blob records the filter; the checkout fetches lazily.
1932
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
1933
    assert_eq!(b.config.max_blob, Some(1024));
1934
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1935
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1936
    assert!(parse_size("lots").is_err());
1937
}
1938
1939
#[test]
1940
fn sparse_checkout_materializes_only_chosen_paths() {
1941
    hermetic();
1942
    let dir = tempfile::tempdir().unwrap();
1943
    let root = dir.path();
1944
    let origin_dir = root.join("origin");
1945
    let origin = Repo::init(&origin_dir)
1946
        .unwrap()
1947
        .with_home(root.join("home"));
1948
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1949
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1950
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1951
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1952
    write(&origin_dir, "docs/logo.png", &logo);
1953
    write(&origin_dir, "README.md", b"# top\n");
1954
    let h1 = origin.commit("tree", &[]).unwrap();
1955
    let url = origin_dir.to_string_lossy().to_string();
1956
1957
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
1958
        .unwrap()
1959
        .with_home(root.join("home"));
1960
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1961
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1962
    assert!(root.join("a/src/main.rs").exists());
1963
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
1964
    assert!(
1965
        !a.store().has(&Repo::blob_ref(&logo)),
1966
        "out-of-scope blob never fetched"
1967
    );
1968
    assert!(
1969
        !a.snapshot("status").unwrap().changed,
1970
        "out-of-scope files are not removals"
1971
    );
1972
    assert!(!a.quick_status().unwrap().dirty);
1973
1974
    // Edits in scope commit normally and keep the rest of the tree intact.
1975
    write(
1976
        &root.join("a"),
1977
        "src/lib.rs",
1978
        b"pub fn a() {}\npub fn b() {}\n",
1979
    );
1980
    let h2 = a.commit("edit lib", &[]).unwrap();
1981
    let st = a.load_state(&[h2]).unwrap().materialize();
1982
    assert!(
1983
        st.files.contains_key("docs/guide.md"),
1984
        "the state still has everything"
1985
    );
1986
    assert!(a.push("origin", false).unwrap()[0].ok);
1987
    // Files created outside the scope are ignored by status.
1988
    write(&root.join("a"), "docs/new.md", b"ignored\n");
1989
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
1990
1991
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
1992
    let mut a = a;
1993
    a.config.set("filter.paths", "src,docs").unwrap();
1994
    a.save_config().unwrap();
1995
    let r = a
1996
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
1997
        .unwrap();
1998
    assert!(r.written >= 2);
1999
    assert_eq!(
2000
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2001
        logo,
2002
        "now fetched lazily"
2003
    );
2004
    assert!(!root.join("a/README.md").exists());
2005
    // Origin sees the change made under a sparse checkout with the full tree intact.
2006
    origin.pull("origin").err();
2007
    let full = origin
2008
        .load_state(&origin.bookmark_heads().unwrap())
2009
        .unwrap()
2010
        .materialize();
2011
    assert!(
2012
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2013
    );
2014
    assert!(full.files.contains_key("README.md"));
2015
    let _ = h1;
2016
}
2017
2018
#[test]
2019
fn shallow_clone_and_deepen() {
2020
    hermetic();
2021
    let dir = tempfile::tempdir().unwrap();
2022
    let root = dir.path();
2023
    let origin_dir = root.join("origin");
2024
    let origin = Repo::init(&origin_dir)
2025
        .unwrap()
2026
        .with_home(root.join("home"));
2027
    let mut hashes = Vec::new();
2028
    for i in 0..8 {
2029
        write(
2030
            &origin_dir,
2031
            "a.txt",
2032
            format!(
2033
                "{}\n",
2034
                (0..=i)
2035
                    .map(|k| k.to_string())
2036
                    .collect::<Vec<_>>()
2037
                    .join("\n")
2038
            )
2039
            .as_bytes(),
2040
        );
2041
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2042
    }
2043
    let url = origin_dir.to_string_lossy().to_string();
2044
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2045
        .unwrap()
2046
        .with_home(root.join("home"));
2047
    assert!(a.is_shallow());
2048
    assert_eq!(
2049
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2050
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2051
    );
2052
    assert!(
2053
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2054
        "three levels present"
2055
    );
2056
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2057
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2058
    assert_eq!(
2059
        a.log().unwrap().len(),
2060
        9,
2061
        "the log shows every change from the checkpoint's metadata"
2062
    );
2063
    assert!(!a.snapshot("status").unwrap().changed);
2064
    assert_eq!(a.quick_status().unwrap().heads, 1);
2065
2066
    // Work continues on top of the shallow history and pushes back.
2067
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2068
    let h_new = a.commit("c8", &[]).unwrap();
2069
    assert!(a.push("origin", false).unwrap()[0].ok);
2070
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2071
    // Fetching new work from origin into the shallow clone works too.
2072
    write(&origin_dir, "b.txt", b"b\n");
2073
    origin.pull("origin").err();
2074
    let (_, wc) = origin.working_copy().unwrap();
2075
    let _ = wc;
2076
    origin
2077
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2078
        .unwrap();
2079
    write(&origin_dir, "b.txt", b"b\n");
2080
    let h_b = origin.commit("b", &[]).unwrap();
2081
    let pr = a.pull("origin").unwrap();
2082
    assert!(pr.changed);
2083
    assert!(a.store().has(&h_b));
2084
    assert!(root.join("a/b.txt").exists());
2085
2086
    // Deepening fetches older history until the boundary is gone.
2087
    // Every commit also depends on the change that created the file, so two
2088
    // levels below the boundary hold h4, h3, and the root.
2089
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2090
    assert!(a.store().has(&hashes[3]));
2091
    assert!(a.is_shallow());
2092
    a.deepen("origin", 100).unwrap();
2093
    assert!(!a.is_shallow(), "boundary reached the root");
2094
    assert!(a.store().has(&hashes[0]));
2095
    assert_eq!(
2096
        a.load_state_full(&a.bookmark_heads().unwrap())
2097
            .unwrap()
2098
            .len(),
2099
        10
2100
    );
2101
}
2102
2103
#[test]
2104
fn tags_are_immutable_named_states_and_travel() {
2105
    hermetic();
2106
    let dir = tempfile::tempdir().unwrap();
2107
    let root = dir.path();
2108
    let origin = Repo::init(&root.join("origin")).unwrap();
2109
    let url = root.join("origin").to_string_lossy().to_string();
2110
    let mut a = Repo::clone(&url, &root.join("a"))
2111
        .unwrap()
2112
        .with_home(root.join("home-a"));
2113
    let (key_a, _) = a
2114
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2115
        .unwrap();
2116
    write(&root.join("a"), "f.txt", b"1\n");
2117
    let h1 = a.commit("one", &[]).unwrap();
2118
    write(&root.join("a"), "f.txt", b"1\n2\n");
2119
    let h2 = a.commit("two", &[]).unwrap();
2120
2121
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2122
    assert_eq!(
2123
        (t.heads.clone(), t.signer.as_deref()),
2124
        (vec![h1], Some("Ada"))
2125
    );
2126
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2127
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2128
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2129
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2130
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2131
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2132
    assert_eq!(sa.sigs[0].key, key_a);
2133
    // Checkout by tag.
2134
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2135
        .unwrap();
2136
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2137
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2138
        .unwrap();
2139
2140
    // Push carries the tag; a second attestation for the name is refused.
2141
    let r = a.push("origin", false).unwrap();
2142
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2143
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2144
    let mut forged = a
2145
        .tag_refs()
2146
        .unwrap()
2147
        .into_iter()
2148
        .find(|t| t.name == "v1")
2149
        .unwrap();
2150
    forged.state = origin
2151
        .store()
2152
        .put_state(&StateObject::new(vec![h2]))
2153
        .unwrap();
2154
    forged.heads = vec![h2];
2155
    forged.attestation = None;
2156
    let r = origin
2157
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2158
        .unwrap();
2159
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2160
2161
    // A clone gets the tag; a later tag arrives on fetch.
2162
    let b = Repo::clone(&url, &root.join("b"))
2163
        .unwrap()
2164
        .with_home(root.join("home-b"));
2165
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2166
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2167
    a.tag_create("v2", &[h2], "second").unwrap();
2168
    a.push("origin", false).unwrap();
2169
    let rep = b.fetch("origin").unwrap();
2170
    assert_eq!(rep.new_tags, 1);
2171
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2172
2173
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2174
    a.policy_init().unwrap();
2175
    a.push("origin", false).unwrap();
2176
    let unattested = crate::protocol::TagRef {
2177
        name: "v3".into(),
2178
        state: origin
2179
            .store()
2180
            .put_state(&StateObject::new(vec![h2]))
2181
            .unwrap(),
2182
        heads: vec![h2],
2183
        attestation: None,
2184
    };
2185
    let r = origin
2186
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2187
        .unwrap();
2188
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2189
    a.tag_create("v3", &[h2], "").unwrap();
2190
    let r = a.push("origin", false).unwrap();
2191
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2192
    assert!(a.gc(true).is_ok());
2193
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2194
}
2195
2196
#[test]
2197
fn multiple_workspaces_share_a_repository() {
2198
    hermetic();
2199
    let dir = tempfile::tempdir().unwrap();
2200
    let root = dir.path();
2201
    let main_dir = root.join("main");
2202
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2203
    write(&main_dir, "a.txt", b"a\n");
2204
    let h1 = repo.commit("a", &[]).unwrap();
2205
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2206
2207
    // A second workspace elsewhere, checked out on the bookmark.
2208
    let ws_dir = root.join("ws2");
2209
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2210
    assert!(ws_dir.join(".oxy").is_file());
2211
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2212
    assert_ne!(ws.workspace(), repo.workspace());
2213
    let list = repo.workspaces().unwrap();
2214
    assert_eq!(list.len(), 2);
2215
    assert!(list
2216
        .iter()
2217
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2218
    assert!(!ws.snapshot("status").unwrap().changed);
2219
2220
    // Work in the second workspace: its own working copy, shared bookmark.
2221
    write(&ws_dir, "b.txt", b"b\n");
2222
    let s = ws.snapshot("status").unwrap();
2223
    assert_eq!(s.statuses.len(), 1);
2224
    assert!(
2225
        !repo.snapshot("status").unwrap().changed,
2226
        "the first workspace is untouched"
2227
    );
2228
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2229
    let mut heads = repo.bookmark_heads().unwrap();
2230
    heads.sort();
2231
    let mut want = vec![h1, h2];
2232
    want.sort();
2233
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2234
    assert!(!main_dir.join("b.txt").exists());
2235
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2236
        .unwrap();
2237
    assert!(main_dir.join("b.txt").exists());
2238
2239
    // Reopening from inside the second workspace finds the shared repository.
2240
    let reopened = Repo::open(&ws_dir).unwrap();
2241
    assert_eq!(reopened.workspace(), ws.workspace());
2242
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2243
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2244
2245
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2246
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2247
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2248
    repo.workspace_forget(&ws.workspace()).unwrap();
2249
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2250
    assert!(ws_dir.join("b.txt").exists());
2251
    assert!(
2252
        ws.snapshot("status").is_err(),
2253
        "a forgotten workspace is no longer in the view"
2254
    );
2255
2256
    // The working-copy lock: re-entrant in a thread; a lock whose process
2257
    // is gone is taken over, and a live process's is not, however old.
2258
    let lock = repo.lock_snapshot().unwrap();
2259
    let again = repo.lock_working_copy().unwrap();
2260
    drop(again);
2261
    drop(lock);
2262
    let lock_path = main_dir
2263
        .join(".oxy/workspaces")
2264
        .join(repo.workspace().to_hex())
2265
        .join("lock");
2266
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2267
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2268
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2269
    age(&lock_path);
2270
    assert!(
2271
        !super::workspace::lock_is_stale(&lock_path),
2272
        "a live process keeps its lock"
2273
    );
2274
    fs::write(&lock_path, "4294967295").unwrap();
2275
    age(&lock_path);
2276
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2277
}
2278
2279
#[test]
2280
fn attributes_binary_eol_nocompress_lockable() {
2281
    hermetic();
2282
    let dir = tempfile::tempdir().unwrap();
2283
    let root = dir.path();
2284
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2285
    write(
2286
        root,
2287
        ".oxyattributes",
2288
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2289
    );
2290
    write(root, "plain.dat", b"no nul bytes here\n");
2291
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2292
    write(root, "assets/model.bin", b"\0model");
2293
    let h = repo.commit("attrs", &[]).unwrap();
2294
    let snap = repo.load_state(&[h]).unwrap().materialize();
2295
    assert!(
2296
        snap.files["plain.dat"].mode.opaque,
2297
        "binary attribute forces opaque without NUL bytes"
2298
    );
2299
    assert!(
2300
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2301
        "stored with LF"
2302
    );
2303
    assert!(
2304
        !repo.snapshot("status").unwrap().changed,
2305
        "CRLF on disk equals LF in the state"
2306
    );
2307
    // nocompress chunks pack raw.
2308
    let r = repo.gc(true).unwrap();
2309
    assert!(r.packed.objects > 0);
2310
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2311
    fs::remove_file(root.join("notes.txt")).unwrap();
2312
    repo.checkout(&[h], true, "co").unwrap();
2313
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2314
    assert!(fs::metadata(root.join("assets/model.bin"))
2315
        .unwrap()
2316
        .permissions()
2317
        .readonly());
2318
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2319
    repo.lock_path("assets/model.bin").unwrap();
2320
    assert!(!fs::metadata(root.join("assets/model.bin"))
2321
        .unwrap()
2322
        .permissions()
2323
        .readonly());
2324
    assert!(repo.is_locked("assets/model.bin"));
2325
    write(root, "assets/model.bin", b"\0model2");
2326
    repo.commit("edit model", &[]).unwrap();
2327
    repo.unlock_path("assets/model.bin").unwrap();
2328
    assert!(fs::metadata(root.join("assets/model.bin"))
2329
        .unwrap()
2330
        .permissions()
2331
        .readonly());
2332
    // A later checkout can still overwrite a read-only lockable file.
2333
    repo.checkout(&[h], true, "co").unwrap();
2334
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2335
}
2336
2337
#[cfg(unix)]
2338
#[test]
2339
fn hooks_can_veto_observe_and_add_dependencies() {
2340
    use std::os::unix::fs::PermissionsExt;
2341
    hermetic();
2342
    let dir = tempfile::tempdir().unwrap();
2343
    let root = dir.path();
2344
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2345
    let hooks = root.join(".oxy/hooks");
2346
    fs::create_dir_all(&hooks).unwrap();
2347
    let hook = |name: &str, body: &str| {
2348
        let p = hooks.join(name);
2349
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2350
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2351
    };
2352
    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");
2353
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2354
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2355
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2356
    write(root, ".oxyignore", b".last-*\n");
2357
    write(root, "a.txt", b"a\n");
2358
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2359
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2360
    let h1 = repo.commit("first", &[]).unwrap();
2361
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2362
    assert!(
2363
        pre.contains("\"event\":\"pre-commit\"")
2364
            && pre.contains("\"path\":\"a.txt\"")
2365
            && pre.contains("\"message\":\"first\""),
2366
        "{pre}"
2367
    );
2368
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2369
    assert!(post.contains(&h1.to_hex()), "{post}");
2370
    repo.checkout(&[h1], false, "co").unwrap();
2371
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2372
        .unwrap()
2373
        .contains("post-checkout"));
2374
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2375
    repo.save_config().unwrap();
2376
    let err = repo.push("origin", false).unwrap_err().to_string();
2377
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2378
2379
    // semantic-deps: only when enabled; adds an explicit dependency.
2380
    write(root, "b.txt", b"b\n");
2381
    hook(
2382
        "semantic-deps",
2383
        &format!(
2384
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2385
            h1.to_hex()
2386
        ),
2387
    );
2388
    let h2 = repo.commit("b without hook", &[]).unwrap();
2389
    assert!(
2390
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2391
        "hook disabled by default"
2392
    );
2393
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2394
    repo.save_config().unwrap();
2395
    write(root, "c.txt", b"c\n");
2396
    let h3 = repo.commit("c with hook", &[]).unwrap();
2397
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2398
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2399
    assert!(
2400
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2401
        "{sem}"
2402
    );
2403
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2404
}
2405
2406
#[test]
2407
fn amend_into_older_change_and_split() {
2408
    hermetic();
2409
    let dir = tempfile::tempdir().unwrap();
2410
    let root = dir.path();
2411
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2412
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2413
        .unwrap();
2414
    repo.set_user_config("core.sign", "change").unwrap();
2415
    write(root, "a.txt", b"one\ntwo\n");
2416
    let h0 = repo.commit("base", &[]).unwrap();
2417
    write(root, "a.txt", b"one\nTWO\n");
2418
    let h1 = repo.commit("edit two", &[]).unwrap();
2419
    write(root, "a.txt", b"one\nTWO\nthree\n");
2420
    let h2 = repo.commit("add three", &[]).unwrap();
2421
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2422
2423
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2424
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2425
    let h1b = repo.amend_into(&h1, None).unwrap();
2426
    assert_ne!(h1b, h1);
2427
    let c1b = repo.store().get_change(&h1b).unwrap();
2428
    assert_eq!(c1b.change_id, id1);
2429
    assert_eq!(c1b.deps, vec![h0]);
2430
    assert!(matches!(
2431
        repo.verify_change(&h1b).unwrap(),
2432
        SignatureStatus::Valid { .. }
2433
    ));
2434
    let heads = repo.bookmark_heads().unwrap();
2435
    assert_eq!(heads.len(), 1);
2436
    let top = repo.store().get_change(&heads[0]).unwrap();
2437
    assert_eq!(top.message, "add three");
2438
    assert_eq!(
2439
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2440
        [h0, h1b].into_iter().collect(),
2441
        "depends on the file's creator and the rewritten line"
2442
    );
2443
    let snap = repo.load_state(&heads).unwrap().materialize();
2444
    assert!(
2445
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2446
    );
2447
    assert!(
2448
        !repo.snapshot("status").unwrap().changed,
2449
        "the working copy is clean after folding"
2450
    );
2451
    // Only h1b's own state shows the fix without "three".
2452
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2453
    assert!(
2454
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2455
    );
2456
    assert_eq!(repo.log().unwrap().len(), 4);
2457
2458
    // An edit to a line introduced by h2 cannot fold into h1.
2459
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2460
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2461
    assert!(err.contains("introduced after"), "{err}");
2462
    assert!(
2463
        repo.snapshot("status").unwrap().statuses.len() == 1,
2464
        "nothing was changed by the refusal"
2465
    );
2466
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2467
2468
    // Split the head that touches two files.
2469
    write(root, "b.txt", b"b\n");
2470
    write(root, "c.txt", b"c\n");
2471
    let h3 = repo.commit("b and c", &[]).unwrap();
2472
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2473
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2474
    let c_1 = repo.store().get_change(&p1).unwrap();
2475
    let c_2 = repo.store().get_change(&p2).unwrap();
2476
    assert!(c_1.message.contains("part 1: b.txt"));
2477
    assert_eq!(c_2.change_id, id3);
2478
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2479
    assert!(
2480
        heads.contains(&p1) && heads.contains(&p2),
2481
        "independent parts are both heads"
2482
    );
2483
    let snap = repo
2484
        .load_state(&repo.bookmark_heads().unwrap())
2485
        .unwrap()
2486
        .materialize();
2487
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2488
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2489
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2490
    assert!(!repo.snapshot("status").unwrap().changed);
2491
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2492
    let _ = h2;
2493
}
2494
2495
#[test]
2496
fn identity_lifecycle() {
2497
    hermetic();
2498
    let dir = tempfile::tempdir().unwrap();
2499
    let root = dir.path();
2500
    let origin = Repo::init(&root.join("origin")).unwrap();
2501
    let url = root.join("origin").to_string_lossy().to_string();
2502
    let mut a = Repo::clone(&url, &root.join("a"))
2503
        .unwrap()
2504
        .with_home(root.join("home-a"));
2505
    a.set_user_config("core.sign", "change").unwrap();
2506
    let (key_a, _) = a
2507
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2508
        .unwrap();
2509
    write(&root.join("a"), "a.txt", b"a\n");
2510
    let h1 = a.commit("one", &[]).unwrap();
2511
    assert!(a.policy_init().unwrap().applied);
2512
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2513
2514
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2515
    let mut e = Repo::init(&root.join("e"))
2516
        .unwrap()
2517
        .with_home(root.join("home-e"));
2518
    e.set_user_config("core.sign", "change").unwrap();
2519
    e.create_identity_with(
2520
        "Eve",
2521
        "[email protected]",
2522
        IdentityScope::User,
2523
        Some(Hlc::now().wall_ms - 1),
2524
    )
2525
    .unwrap();
2526
    write(&root.join("e"), "e.txt", b"e\n");
2527
    let he = e.commit("late", &[]).unwrap();
2528
    assert!(
2529
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2530
    );
2531
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2532
    let r = e
2533
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2534
        .unwrap();
2535
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2536
    write(&root.join("e"), "e.txt", b"e2\n");
2537
    let he2 = e.commit("in time", &[]).unwrap();
2538
    assert!(
2539
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2540
    );
2541
2542
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2543
    let r = a.rotate_identity().unwrap();
2544
    assert_eq!(r.old, key_a);
2545
    assert_eq!(a.config.author_key, Some(r.new));
2546
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2547
    assert!(r.policy.as_ref().unwrap().applied);
2548
    let (_, sp) = a.current_policy().unwrap().unwrap();
2549
    assert_eq!(
2550
        (sp.policy.serial, sp.policy.roots.clone()),
2551
        (2, vec![r.new])
2552
    );
2553
    assert!(
2554
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2555
        "superseded, not revoked"
2556
    );
2557
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2558
    assert!(
2559
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2560
    );
2561
    write(&root.join("a"), "a.txt", b"a2\n");
2562
    let h2 = a.commit("two", &[]).unwrap();
2563
    assert!(
2564
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2565
    );
2566
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2567
    let res = a.push("origin", false).unwrap();
2568
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2569
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2570
    let key_a = r.new;
2571
2572
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2573
    // identity object, so Ada's KeyId changes while her keys stay the same.
2574
    let mut b = Repo::clone(&url, &root.join("b"))
2575
        .unwrap()
2576
        .with_home(root.join("home-b"));
2577
    let (key_b, id_b) = b
2578
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2579
        .unwrap();
2580
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
2581
    assert_eq!(r.old, key_a);
2582
    let key_a2 = r.new;
2583
    assert_eq!(
2584
        a.identity(&key_a2).unwrap().delegates,
2585
        vec![Delegate::full(key_b)]
2586
    );
2587
    assert_eq!(
2588
        a.identity(&key_a2).unwrap().ed25519_pk,
2589
        a.identity(&key_a).unwrap().ed25519_pk
2590
    );
2591
    assert!(
2592
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2593
        "already a delegate"
2594
    );
2595
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2596
    write(&root.join("a"), "a.txt", b"a3\n");
2597
    let h3 = a.commit("three", &[]).unwrap();
2598
    assert!(
2599
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2600
        "the same secret signs under the new KeyId"
2601
    );
2602
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2603
    a.set_user_config("core.sign", "seal").unwrap();
2604
    write(&root.join("a"), "a.txt", b"a4\n");
2605
    let h4 = a.commit("four", &[]).unwrap();
2606
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2607
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2608
    a.store()
2609
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2610
        .unwrap();
2611
    assert!(
2612
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2613
    );
2614
    a.set_user_config("core.sign", "change").unwrap();
2615
    // Withdrawing the delegation re-issues the identity again.
2616
    let r = a.delegate_remove(&key_b).unwrap();
2617
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2618
    assert!(a.delegate_remove(&key_b).is_err());
2619
    let key_a3 = r.new;
2620
    let res = a.push("origin", false).unwrap();
2621
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2622
2623
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2624
    // both applied under the old threshold of 1. A grant then needs Bob too.
2625
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2626
    assert!(a.policy_root_add(id_b.clone()).is_err());
2627
    assert!(a.policy_set_threshold(3).is_err());
2628
    assert!(a.policy_set_threshold(2).unwrap().applied);
2629
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2630
    b.pull("origin").unwrap();
2631
    assert_eq!(
2632
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2633
        2
2634
    );
2635
    let mut c = Repo::init(&root.join("c"))
2636
        .unwrap()
2637
        .with_home(root.join("home-c"));
2638
    let (key_c, id_c) = c
2639
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2640
        .unwrap();
2641
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2642
    let proposal = a.policy_grant(id_c, None).unwrap();
2643
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2644
    assert_eq!(proposal.policy.serial, serial_before + 1);
2645
    assert_eq!(
2646
        a.current_policy().unwrap().unwrap().1.policy.serial,
2647
        serial_before,
2648
        "a proposal changes nothing yet"
2649
    );
2650
    // Bob signs the proposal, handed over as a file, and it applies for him.
2651
    let bytes = proposal.signed().encode();
2652
    let signed = b
2653
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2654
        .unwrap();
2655
    assert!(signed.applied && signed.sigs.len() == 2);
2656
    assert!(b
2657
        .current_policy()
2658
        .unwrap()
2659
        .unwrap()
2660
        .1
2661
        .policy
2662
        .authorizes(&key_c, "main"));
2663
    assert!(
2664
        b.policy_sign(signed.signed()).is_err(),
2665
        "a stale proposal is refused"
2666
    );
2667
    // Bob publishes it and Ada picks it up.
2668
    assert!(b
2669
        .push("origin", false)
2670
        .unwrap()
2671
        .iter()
2672
        .any(|x| x.name == "policy" && x.ok));
2673
    a.pull("origin").unwrap();
2674
    assert_eq!(
2675
        a.current_policy().unwrap().unwrap().1.policy.serial,
2676
        serial_before + 1
2677
    );
2678
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2679
    assert!(a.policy_revoke(&key_a3).is_err());
2680
    let u = a
2681
        .revoke_identity(&key_c, "left the project")
2682
        .unwrap()
2683
        .unwrap();
2684
    assert!(!u.applied);
2685
    assert!(a.is_revoked(&key_c).unwrap());
2686
    assert!(!b.is_revoked(&key_c).unwrap());
2687
    let u = b.policy_sign(u.signed()).unwrap();
2688
    assert!(u.applied && u.policy.is_revoked(&key_c));
2689
    assert!(b.is_revoked(&key_c).unwrap());
2690
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2691
    assert!(
2692
        b.policy_revoke(&key_a3).is_err(),
2693
        "would leave one root for a threshold of 2"
2694
    );
2695
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2696
    let key_c_own = c.config.author_key.unwrap();
2697
    assert!(c
2698
        .revoke_identity(&key_c_own, "lost laptop")
2699
        .unwrap()
2700
        .is_none());
2701
    assert!(c.is_revoked(&key_c_own).unwrap());
2702
    assert_eq!(key_c_own, key_c);
2703
}
2704
2705
#[test]
2706
fn renames_are_detected_and_tracked_as_moves() {
2707
    hermetic();
2708
    let dir = tempfile::tempdir().unwrap();
2709
    let root = dir.path();
2710
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2711
    write(
2712
        root,
2713
        "src/old.rs",
2714
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2715
    );
2716
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2717
    write(root, "tiny.txt", b"x\n");
2718
    let h1 = repo.commit("base", &[]).unwrap();
2719
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2720
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2721
2722
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2723
    // that shares nothing with the removed file.
2724
    fs::remove_file(root.join("src/old.rs")).unwrap();
2725
    write(
2726
        root,
2727
        "lib/new.rs",
2728
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2729
    );
2730
    fs::remove_file(root.join("img.bin")).unwrap();
2731
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2732
    fs::remove_file(root.join("tiny.txt")).unwrap();
2733
    write(root, "other.txt", b"completely different\n");
2734
    let snap = repo.snapshot("status").unwrap();
2735
    let statuses: Vec<(&str, ChangeStatus)> = snap
2736
        .statuses
2737
        .iter()
2738
        .map(|s| (s.path.as_str(), s.status))
2739
        .collect();
2740
    assert_eq!(
2741
        statuses,
2742
        vec![
2743
            ("assets/img.bin", ChangeStatus::Renamed),
2744
            ("lib/new.rs", ChangeStatus::Renamed),
2745
            ("other.txt", ChangeStatus::Added),
2746
            ("src", ChangeStatus::Removed),
2747
            ("tiny.txt", ChangeStatus::Removed)
2748
        ]
2749
    );
2750
    let h2 = repo.commit("move things", &[]).unwrap();
2751
    let c = repo.store().get_change(&h2).unwrap();
2752
    let moves: Vec<_> = c
2753
        .tree_ops
2754
        .iter()
2755
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2756
        .collect();
2757
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
2758
    assert!(c.tree_ops.iter().any(
2759
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2760
    ));
2761
    assert!(c.tree_ops.iter().any(
2762
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2763
    ));
2764
    let snap = repo.load_state(&[h2]).unwrap().materialize();
2765
    assert_eq!(
2766
        snap.files["lib/new.rs"].node, node_old,
2767
        "the node survives the rename"
2768
    );
2769
    assert!(
2770
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2771
    );
2772
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
2773
    assert!(render_change(
2774
        &c,
2775
        &repo.load_state(&[h1]).unwrap(),
2776
        &repo.load_state(&[h1]).unwrap().materialize()
2777
    )
2778
    .contains("R "));
2779
    // A fresh checkout reproduces the tree.
2780
    let other = tempfile::tempdir().unwrap();
2781
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
2782
    assert_eq!(
2783
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2784
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2785
    );
2786
    assert!(!other.path().join("src").exists());
2787
    assert!(!clone.snapshot("status").unwrap().changed);
2788
    // Similarity is line based, byte weighted.
2789
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2790
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2791
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2792
    assert_eq!(similarity(b"", b"x\n"), 0);
2793
}
2794
2795
#[test]
2796
fn git_fetch_and_push_round_trip() {
2797
    hermetic();
2798
    if std::process::Command::new("git")
2799
        .arg("--version")
2800
        .output()
2801
        .is_err()
2802
    {
2803
        eprintln!("git not installed; skipping");
2804
        return;
2805
    }
2806
    let dir = tempfile::tempdir().unwrap();
2807
    let root = dir.path();
2808
    let git_in = |d: &Path, args: &[&str]| -> String {
2809
        let out = std::process::Command::new("git")
2810
            .arg("-C")
2811
            .arg(d)
2812
            .args([
2813
                "-c",
2814
                "user.name=Grace",
2815
                "-c",
2816
                "[email protected]",
2817
                "-c",
2818
                "commit.gpgsign=false",
2819
            ])
2820
            .args(args)
2821
            .output()
2822
            .unwrap();
2823
        assert!(
2824
            out.status.success(),
2825
            "git {args:?}: {}",
2826
            String::from_utf8_lossy(&out.stderr)
2827
        );
2828
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2829
    };
2830
    // A bare "remote" and a work tree that pushes to it.
2831
    let remote = root.join("remote.git");
2832
    fs::create_dir_all(&remote).unwrap();
2833
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2834
    let work = root.join("work");
2835
    git_in(
2836
        root,
2837
        &[
2838
            "clone",
2839
            "-q",
2840
            remote.to_str().unwrap(),
2841
            work.to_str().unwrap(),
2842
        ],
2843
    );
2844
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2845
    write(&work, "README.md", b"# Project\n");
2846
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2847
    git_in(&work, &["add", "."]);
2848
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2849
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2850
    git_in(&work, &["commit", "-q", "-am", "second"]);
2851
    git_in(&work, &["push", "-q", "origin", "main"]);
2852
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2853
2854
    // Fetch into a fresh oxy repository.
2855
    let o = root.join("oxy");
2856
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
2857
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2858
        .unwrap();
2859
    let url = remote.to_string_lossy().to_string();
2860
    let r = repo.git_fetch(&url, "main").unwrap();
2861
    assert_eq!((r.commits, r.heads), (2, 1));
2862
    assert_eq!(
2863
        fs::read(o.join("src/lib.rs")).unwrap(),
2864
        b"pub fn a() {}\npub fn b() {}\n"
2865
    );
2866
    assert!(!repo.snapshot("status").unwrap().changed);
2867
    assert_eq!(
2868
        repo.git_fetch(&url, "main").unwrap().commits,
2869
        0,
2870
        "nothing new"
2871
    );
2872
2873
    // An oxy change, pushed back: one commit on top of the Git tip.
2874
    write(
2875
        &o,
2876
        "src/lib.rs",
2877
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2878
    );
2879
    write(&o, "NOTES.md", b"from oxy\n");
2880
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2881
    let r = repo.git_push(&url, "main").unwrap();
2882
    assert_eq!(r.exported, 1, "{r:?}");
2883
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2884
    assert_eq!(
2885
        git_in(&work, &["log", "--format=%s", "main"]),
2886
        "add c and notes\nsecond\ninitial"
2887
    );
2888
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2889
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2890
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
2891
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2892
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2893
    assert_eq!(
2894
        repo.git_push(&url, "main").unwrap().exported,
2895
        0,
2896
        "already pushed"
2897
    );
2898
2899
    // Git moves on; pushing without fetching is refused, fetching brings
2900
    // the commit in and the working copy follows.
2901
    write(&work, "README.md", b"# Project\n\nMore.\n");
2902
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2903
    git_in(&work, &["push", "-q", "origin", "main"]);
2904
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
2905
    assert!(repo
2906
        .git_push(&url, "main")
2907
        .unwrap_err()
2908
        .to_string()
2909
        .contains("fetch"));
2910
    let r = repo.git_fetch(&url, "main").unwrap();
2911
    assert_eq!(
2912
        (r.commits, r.heads),
2913
        (1, 2),
2914
        "the Git change and the oxy change commute"
2915
    );
2916
    assert_eq!(
2917
        fs::read(o.join("README.md")).unwrap(),
2918
        b"# Project\n\nMore.\n"
2919
    );
2920
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2921
    assert!(!repo.snapshot("status").unwrap().changed);
2922
    // Another oxy change pushes on top of Git's newest commit.
2923
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2924
    repo.commit("notes again", &[]).unwrap();
2925
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2926
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2927
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
2928
    assert_eq!(
2929
        fs::read(work.join("NOTES.md")).unwrap(),
2930
        b"from oxy\nagain\n"
2931
    );
2932
    assert_eq!(
2933
        git_in(&work, &["log", "--format=%s", "main"])
2934
            .lines()
2935
            .count(),
2936
        5
2937
    );
2938
}
2939
2940
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2941
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2942
#[test]
2943
#[ignore]
2944
fn bench_one_gibibyte_file() {
2945
    hermetic();
2946
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2947
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2948
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2949
        None => tempfile::tempdir().unwrap(),
2950
    };
2951
    let root = dir.path();
2952
    let repo = Repo::init(&root.join("r"))
2953
        .unwrap()
2954
        .with_home(root.join("home"));
2955
    let size = 1usize << 30;
2956
    let mut data = vec![0u8; size];
2957
    let mut x = 0x9e3779b97f4a7c15u64;
2958
    for chunk in data.chunks_mut(8) {
2959
        x ^= x << 13;
2960
        x ^= x >> 7;
2961
        x ^= x << 17;
2962
        let b = x.to_le_bytes();
2963
        chunk.copy_from_slice(&b[..chunk.len()]);
2964
    }
2965
    let t = std::time::Instant::now();
2966
    write(&root.join("r"), "big.bin", &data);
2967
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
2968
    let t = std::time::Instant::now();
2969
    let h = repo.commit("big", &[]).unwrap();
2970
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
2971
    let t = std::time::Instant::now();
2972
    assert!(!repo.snapshot("status").unwrap().changed);
2973
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
2974
    let t = std::time::Instant::now();
2975
    let objects = repo.store().list().unwrap().len();
2976
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
2977
    let t = std::time::Instant::now();
2978
    let g = repo.gc(true).unwrap();
2979
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
2980
    let t = std::time::Instant::now();
2981
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
2982
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
2983
    let t = std::time::Instant::now();
2984
    let back = fs::read(root.join("c/big.bin")).unwrap();
2985
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
2986
    eprintln!("read back and verify: {:.2?}", t.elapsed());
2987
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
2988
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
2989
    eprintln!(
2990
        "store size: {:.1} MiB for 1 GiB of data",
2991
        store_bytes as f64 / (1024.0 * 1024.0)
2992
    );
2993
}
2994
2995
fn walkdir_size(p: &Path) -> u64 {
2996
    let mut total = 0;
2997
    if let Ok(rd) = fs::read_dir(p) {
2998
        for e in rd.flatten() {
2999
            let path = e.path();
3000
            if path.is_dir() {
3001
                total += walkdir_size(&path);
3002
            } else if let Ok(m) = fs::metadata(&path) {
3003
                total += m.len();
3004
            }
3005
        }
3006
    }
3007
    total
3008
}
3009
3010
/// An opaque file whose size and mtime match the manifest is not read on
3011
/// the next snapshot: its blob comes from the manifest's stat cache.
3012
#[cfg(unix)]
3013
#[test]
3014
fn stat_cache_skips_reading_unchanged_opaque_files() {
3015
    use std::os::unix::fs::PermissionsExt;
3016
    hermetic();
3017
    let dir = tempfile::tempdir().unwrap();
3018
    let root = dir.path();
3019
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3020
    let mut big = vec![0u8; 300 * 1024];
3021
    for (i, b) in big.iter_mut().enumerate() {
3022
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3023
    }
3024
    big[0] = 0;
3025
    write(root, "big.bin", &big);
3026
    write(root, "a.txt", b"text\n");
3027
    let h1 = repo.commit("base", &[]).unwrap();
3028
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3029
    assert!(
3030
        m.entries["big.bin"].blob.is_some(),
3031
        "opaque files record their blob"
3032
    );
3033
    assert!(m.entries["a.txt"].blob.is_none());
3034
    let blob = m.entries["big.bin"].blob.unwrap();
3035
    assert!(repo.store().has(&blob));
3036
3037
    // Files modified within two seconds of the manifest are racy and still
3038
    // read; age the file so the cache applies, then snapshot to record it.
3039
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3040
    fs::File::options()
3041
        .write(true)
3042
        .open(root.join("big.bin"))
3043
        .unwrap()
3044
        .set_modified(old)
3045
        .unwrap();
3046
    assert!(!repo.snapshot("status").unwrap().changed);
3047
    // Now the file cannot be read at all; the snapshot succeeds without it.
3048
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3049
    let snap = repo.snapshot("status").unwrap();
3050
    assert!(
3051
        !snap.changed && snap.statuses.is_empty(),
3052
        "{:?}",
3053
        snap.statuses
3054
    );
3055
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3056
    // A real change (new mtime, new content) is seen and committed correctly.
3057
    let mut big2 = big.clone();
3058
    big2[10] ^= 0xff;
3059
    write(root, "big.bin", &big2);
3060
    let snap = repo.snapshot("status").unwrap();
3061
    assert_eq!(
3062
        snap.statuses
3063
            .iter()
3064
            .map(|s| (s.path.as_str(), s.status))
3065
            .collect::<Vec<_>>(),
3066
        vec![("big.bin", ChangeStatus::Modified)]
3067
    );
3068
    let h2 = repo.commit("edit", &[]).unwrap();
3069
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3070
    assert_eq!(
3071
        files["big.bin"].content,
3072
        FileContent::Opaque {
3073
            blobs: vec![Repo::blob_ref(&big2)]
3074
        }
3075
    );
3076
    // Checkout writes a manifest with blobs too, so the next status is cached.
3077
    repo.checkout(&[h1], false, "checkout").unwrap();
3078
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3079
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3080
    assert!(!repo.snapshot("status").unwrap().changed);
3081
}
3082
3083
#[test]
3084
fn status_json_lists_conflicts_with_contributors() {
3085
    hermetic();
3086
    let dir = tempfile::tempdir().unwrap();
3087
    let root = dir.path();
3088
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3089
    write(root, "a.txt", b"one\n");
3090
    let h1 = repo.commit("base", &[]).unwrap();
3091
    write(root, "a.txt", b"one\nleft\n");
3092
    let ha = repo.commit("left", &[]).unwrap();
3093
    repo.checkout(&[h1], true, "checkout").unwrap();
3094
    write(root, "a.txt", b"one\nright\n");
3095
    let hb = repo.commit("right", &[]).unwrap();
3096
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3097
    let snap = repo.snapshot("status").unwrap();
3098
    assert!(snap.base_snapshot.is_conflicted());
3099
    let json = repo.status_json(&snap).unwrap();
3100
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3101
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3102
    assert!(json.contains("\"conflicted\":true"), "{json}");
3103
    assert!(
3104
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3105
        "{json}"
3106
    );
3107
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3108
    assert!(json.contains("\"resolved\":false"), "{json}");
3109
    assert!(json.starts_with('{') && json.ends_with('}'));
3110
    // Resolve and the report says so; a clean copy has no conflicts.
3111
    write(root, "a.txt", b"one\nleft\nright\n");
3112
    let snap = repo.snapshot("status").unwrap();
3113
    let json = repo.status_json(&snap).unwrap();
3114
    assert!(json.contains("\"resolved\":true"), "{json}");
3115
    repo.commit("resolve", &[]).unwrap();
3116
    let snap = repo.snapshot("status").unwrap();
3117
    let json = repo.status_json(&snap).unwrap();
3118
    assert!(
3119
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3120
        "{json}"
3121
    );
3122
}
3123
3124
#[test]
3125
fn ignore_rules_do_not_untrack_files() {
3126
    hermetic();
3127
    let dir = tempfile::tempdir().unwrap();
3128
    let root = dir.path();
3129
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3130
    write(root, "src.c", b"int x;\n");
3131
    write(root, "build/out.o", b"\0obj");
3132
    write(root, "sub/keep.log", b"keep\n");
3133
    write(root, "sub/junk.log", b"junk\n");
3134
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3135
    let snap = repo.snapshot("status").unwrap();
3136
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3137
    assert_eq!(
3138
        added,
3139
        vec![".oxyignore", "src.c", "sub/keep.log"],
3140
        "anchored, glob, and negated rules"
3141
    );
3142
    let h1 = repo.commit("base", &[]).unwrap();
3143
    // Ignoring a tracked file changes nothing about it.
3144
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3145
    let snap = repo.snapshot("status").unwrap();
3146
    assert_eq!(
3147
        snap.statuses
3148
            .iter()
3149
            .map(|s| s.path.as_str())
3150
            .collect::<Vec<_>>(),
3151
        vec![".oxyignore"]
3152
    );
3153
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3154
    assert!(repo
3155
        .load_state(&[h2])
3156
        .unwrap()
3157
        .materialize()
3158
        .files
3159
        .contains_key("src.c"));
3160
    // Its edits are still seen, by status and by the prompt.
3161
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3162
    write(root, "src.c", b"int x, y;\n");
3163
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3164
    let snap = repo.snapshot("status").unwrap();
3165
    assert_eq!(
3166
        snap.statuses
3167
            .iter()
3168
            .map(|s| (s.path.as_str(), s.status))
3169
            .collect::<Vec<_>>(),
3170
        vec![("src.c", ChangeStatus::Modified)]
3171
    );
3172
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3173
    assert!(
3174
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3175
    );
3176
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3177
    fs::remove_file(root.join("src.c")).unwrap();
3178
    let snap = repo.snapshot("status").unwrap();
3179
    assert_eq!(
3180
        snap.statuses
3181
            .iter()
3182
            .map(|s| (s.path.as_str(), s.status))
3183
            .collect::<Vec<_>>(),
3184
        vec![("src.c", ChangeStatus::Removed)]
3185
    );
3186
    repo.checkout(&[h3], true, "checkout").unwrap();
3187
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3188
    assert!(!repo.snapshot("status").unwrap().changed);
3189
    let _ = h1;
3190
}
3191
3192
#[test]
3193
fn split_works_on_non_heads_by_node() {
3194
    hermetic();
3195
    let dir = tempfile::tempdir().unwrap();
3196
    let root = dir.path();
3197
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3198
    write(root, "a.txt", b"one\n");
3199
    write(root, "junk/x.lock", b"lock\n");
3200
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3201
    write(root, "a.txt", b"one\ntwo\n");
3202
    let h2 = repo.commit("more work", &[]).unwrap();
3203
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3204
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3205
    // h1 is not a head: split it by node.
3206
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3207
    assert_ne!(h1b, h1);
3208
    assert_eq!(
3209
        repo.store().get_change(&h1b).unwrap().change_id,
3210
        id1,
3211
        "the rest keeps the ChangeId"
3212
    );
3213
    let junk = repo.store().get_change(&hj).unwrap();
3214
    assert!(junk.tree_ops.iter().all(
3215
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3216
    ));
3217
    let heads = repo.bookmark_heads().unwrap();
3218
    assert!(
3219
        heads.contains(&hj),
3220
        "the split-off part is a head of its own"
3221
    );
3222
    let snap = repo.load_state(&heads).unwrap().materialize();
3223
    assert!(
3224
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3225
        "the dependent was rewritten onto the new hash"
3226
    );
3227
    assert!(snap.files.contains_key("junk/x.lock"));
3228
    let h2b = heads
3229
        .iter()
3230
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3231
        .copied()
3232
        .unwrap();
3233
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3234
    assert!(!repo.snapshot("status").unwrap().changed);
3235
    // Abandoning the split-off head removes the junk from history.
3236
    repo.abandon(&hj).unwrap();
3237
    let heads = repo.bookmark_heads().unwrap();
3238
    let snap = repo.load_state(&heads).unwrap().materialize();
3239
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3240
    assert!(snap.files.contains_key("a.txt"));
3241
    // A dependent that touches the split-off paths blocks the split.
3242
    write(root, "junk/y.lock", b"y\n");
3243
    let hb = repo.commit("junk base", &[]).unwrap();
3244
    write(root, "junk/y.lock", b"yy\n");
3245
    write(root, "b.txt", b"b\n");
3246
    repo.commit("touches junk", &[]).unwrap();
3247
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3248
    assert!(err.contains("depends on the split-off paths"), "{err}");
3249
}
3250
3251
#[test]
3252
fn bookmarks_switch_merge_and_push() {
3253
    hermetic();
3254
    let dir = tempfile::tempdir().unwrap();
3255
    let root = dir.path();
3256
    let origin = Repo::init(&root.join("origin")).unwrap();
3257
    let url = root.join("origin").to_string_lossy().to_string();
3258
    let mut repo = Repo::clone(&url, &root.join("r"))
3259
        .unwrap()
3260
        .with_home(root.join("home"));
3261
    let r = root.join("r");
3262
    write(&r, "a.txt", b"a\n");
3263
    let h_a = repo.commit("a", &[]).unwrap();
3264
    assert!(repo.push("origin", false).unwrap()[0].ok);
3265
3266
    // A bookmark at the working copy's base, then work on it.
3267
    assert!(repo.bookmark_create("bad name..", None).is_err());
3268
    assert!(repo.bookmark_create("-x", None).is_err());
3269
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3270
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3271
    repo.bookmark_switch("feature", false).unwrap();
3272
    assert_eq!(repo.config.bookmark, "feature");
3273
    write(&r, "a.txt", b"a\nb\n");
3274
    write(&r, "b.txt", b"b\n");
3275
    let h_b = repo.commit("b on feature", &[]).unwrap();
3276
    assert_eq!(
3277
        repo.bookmark_heads().unwrap(),
3278
        vec![h_b],
3279
        "b edits a.txt, so it depends on a"
3280
    );
3281
    assert_eq!(
3282
        repo.resolve_heads("main").unwrap(),
3283
        vec![h_a],
3284
        "main is untouched"
3285
    );
3286
    assert_eq!(
3287
        repo.resolve_change("feature").unwrap(),
3288
        h_b,
3289
        "a one-head bookmark names its change"
3290
    );
3291
    // Reopening keeps the workspace's bookmark.
3292
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3293
    assert_eq!(reopened.config.bookmark, "feature");
3294
    // Back to main: b.txt goes away; work there.
3295
    repo.bookmark_switch("main", false).unwrap();
3296
    assert!(!r.join("b.txt").exists());
3297
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3298
    write(&r, "c.txt", b"c\n");
3299
    let h_c = repo.commit("c on main", &[]).unwrap();
3300
    let list = repo.bookmarks().unwrap();
3301
    assert_eq!(
3302
        list.iter()
3303
            .map(|b| (b.name.as_str(), b.current))
3304
            .collect::<Vec<_>>(),
3305
        vec![("feature", false), ("main", true)]
3306
    );
3307
    assert_eq!(
3308
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3309
        Some(1),
3310
        "c is not on origin yet"
3311
    );
3312
    // Merge feature into main: the union, both heads, no merge change.
3313
    let m = repo.merge("feature").unwrap();
3314
    assert!(m.changed && m.checked_out);
3315
    let mut want = vec![h_b, h_c];
3316
    want.sort();
3317
    assert_eq!(m.heads, want);
3318
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3319
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3320
    assert!(repo.merge("main").is_err());
3321
    // The other bookmark can be pushed by name and appears at origin.
3322
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3323
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3324
    assert!(repo.push("origin", false).unwrap()[0].ok);
3325
    assert_eq!(
3326
        repo.bookmarks()
3327
            .unwrap()
3328
            .iter()
3329
            .find(|b| b.name == "main")
3330
            .unwrap()
3331
            .ahead,
3332
        Some(0)
3333
    );
3334
    // A second workspace inherits the current bookmark and can switch independently.
3335
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3336
    assert_eq!(ws.config.bookmark, "main");
3337
    let mut ws = ws;
3338
    ws.bookmark_switch("feature", false).unwrap();
3339
    assert_eq!(
3340
        Repo::open(&r).unwrap().config.bookmark,
3341
        "main",
3342
        "the first workspace is unaffected"
3343
    );
3344
    assert!(
3345
        repo.bookmark_delete("feature").is_err(),
3346
        "current bookmark of another workspace"
3347
    );
3348
    ws.bookmark_switch("main", false).unwrap();
3349
    // Set and delete.
3350
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3351
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3352
    repo.bookmark_delete("feature").unwrap();
3353
    assert!(repo.resolve_heads("feature").is_err());
3354
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3355
    assert!(
3356
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3357
        "changes of a deleted bookmark remain"
3358
    );
3359
}
3360
3361
#[test]
3362
fn oxygen_subrepos_pin_follow_and_update() {
3363
    hermetic();
3364
    let dir = tempfile::tempdir().unwrap();
3365
    let root = dir.path();
3366
    // A library repository with two commits, and a bare-ish origin for it.
3367
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3368
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3369
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3370
        .unwrap()
3371
        .with_home(root.join("home"));
3372
    write(&root.join("lib"), "lib.txt", b"v1\n");
3373
    let l1 = lib.commit("lib v1", &[]).unwrap();
3374
    assert!(lib.push("origin", false).unwrap()[0].ok);
3375
    let _ = lib_origin;
3376
3377
    // The application (a clone of its own origin) adds it as a subrepo.
3378
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3379
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3380
    let _ = app_origin;
3381
    let app_dir = root.join("app");
3382
    let app = Repo::clone(&app_url, &app_dir)
3383
        .unwrap()
3384
        .with_home(root.join("home"));
3385
    write(&app_dir, "main.txt", b"app\n");
3386
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3387
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3388
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3389
    let snap = app.snapshot("status").unwrap();
3390
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3391
    assert_eq!(
3392
        paths,
3393
        vec![".oxymodules", "libs/lib", "main.txt"],
3394
        "the nested files are not walked"
3395
    );
3396
    let a1 = app.commit("app with lib", &[]).unwrap();
3397
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3398
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3399
    assert!(!files.contains_key("libs/lib/lib.txt"));
3400
    assert!(!app.snapshot("status").unwrap().changed);
3401
    let subs = app.subrepos().unwrap();
3402
    assert_eq!(subs.len(), 1);
3403
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3404
3405
    // Advance the nested repository: the parent sees a modified pin.
3406
    let nested = Repo::open(&app_dir.join("libs/lib"))
3407
        .unwrap()
3408
        .with_home(root.join("home"));
3409
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3410
    let l2 = nested.commit("lib v2", &[]).unwrap();
3411
    assert!(nested.push("origin", false).unwrap()[0].ok);
3412
    let snap = app.snapshot("status").unwrap();
3413
    assert_eq!(
3414
        snap.statuses
3415
            .iter()
3416
            .map(|s| (s.path.as_str(), s.status))
3417
            .collect::<Vec<_>>(),
3418
        vec![("libs/lib", ChangeStatus::Modified)]
3419
    );
3420
    let a2 = app.commit("bump lib", &[]).unwrap();
3421
    // Checking out the older app state brings the nested working copy back
3422
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3423
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3424
    assert!(
3425
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3426
        "{:?}",
3427
        r.notes
3428
    );
3429
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3430
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3431
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3432
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3433
    assert!(!app.snapshot("status").unwrap().changed);
3434
    // A dirty nested repository is left alone and reported.
3435
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3436
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3437
    assert!(
3438
        r.notes.iter().any(|n| n.contains("uncommitted")),
3439
        "{:?}",
3440
        r.notes
3441
    );
3442
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3443
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3444
    let r = app.submodule_update(false, &[]).unwrap();
3445
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3446
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3447
    let _ = l2;
3448
3449
    // A fresh clone of the app has the pin but no nested repository until update --init.
3450
    assert!(app.push("origin", false).unwrap()[0].ok);
3451
    let clone_dir = root.join("app-clone");
3452
    let clone = Repo::clone(&app_url, &clone_dir)
3453
        .unwrap()
3454
        .with_home(root.join("home"));
3455
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3456
    assert_eq!(
3457
        clone.submodule_update(false, &[]).unwrap(),
3458
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3459
    );
3460
    assert_eq!(
3461
        clone.submodule_update(true, &[]).unwrap(),
3462
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3463
    );
3464
    assert_eq!(
3465
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3466
        b"v2\n"
3467
    );
3468
    assert!(!clone.snapshot("status").unwrap().changed);
3469
    // Removing the subrepo leaves the directory and drops the node.
3470
    clone.submodule_remove("libs/lib").unwrap();
3471
    let snap = clone.snapshot("status").unwrap();
3472
    assert!(
3473
        snap.statuses
3474
            .iter()
3475
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3476
        "{:?}",
3477
        snap.statuses
3478
    );
3479
    let c = clone.commit("drop lib", &[]).unwrap();
3480
    assert!(!clone
3481
        .load_state(&[c])
3482
        .unwrap()
3483
        .materialize()
3484
        .files
3485
        .contains_key("libs/lib"));
3486
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3487
    assert!(
3488
        !clone.snapshot("status").unwrap().changed,
3489
        "an unregistered nested repository is ignored"
3490
    );
3491
}
3492
3493
#[test]
3494
fn git_submodules_import_and_export_as_gitlinks() {
3495
    hermetic();
3496
    if std::process::Command::new("git")
3497
        .arg("--version")
3498
        .output()
3499
        .is_err()
3500
    {
3501
        eprintln!("git not installed; skipping");
3502
        return;
3503
    }
3504
    let dir = tempfile::tempdir().unwrap();
3505
    let root = dir.path();
3506
    let git_in = |d: &Path, args: &[&str]| -> String {
3507
        let out = std::process::Command::new("git")
3508
            .arg("-C")
3509
            .arg(d)
3510
            .args([
3511
                "-c",
3512
                "user.name=Grace",
3513
                "-c",
3514
                "[email protected]",
3515
                "-c",
3516
                "commit.gpgsign=false",
3517
                "-c",
3518
                "protocol.file.allow=always",
3519
            ])
3520
            .args(args)
3521
            .output()
3522
            .unwrap();
3523
        assert!(
3524
            out.status.success(),
3525
            "git {args:?}: {}",
3526
            String::from_utf8_lossy(&out.stderr)
3527
        );
3528
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3529
    };
3530
    let sub = root.join("sub");
3531
    fs::create_dir_all(&sub).unwrap();
3532
    git_in(&sub, &["init", "-q", "-b", "main"]);
3533
    write(&sub, "s.txt", b"sub\n");
3534
    git_in(&sub, &["add", "."]);
3535
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3536
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3537
    let g = root.join("main.git");
3538
    fs::create_dir_all(&g).unwrap();
3539
    git_in(&g, &["init", "-q", "-b", "main"]);
3540
    write(&g, "README.md", b"# app\n");
3541
    git_in(&g, &["add", "."]);
3542
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3543
    git_in(
3544
        &g,
3545
        &[
3546
            "submodule",
3547
            "add",
3548
            "-q",
3549
            sub.to_str().unwrap(),
3550
            "vendor/sub",
3551
        ],
3552
    );
3553
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3554
3555
    let dest = root.join("oxy");
3556
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3557
    let rep = repo.import_git(&g, "main").unwrap();
3558
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3559
    let files = repo
3560
        .load_state(&repo.bookmark_heads().unwrap())
3561
        .unwrap()
3562
        .materialize()
3563
        .files;
3564
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3565
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3566
        panic!()
3567
    };
3568
    assert_eq!(
3569
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3570
        crate::subrepo::Pin::Git {
3571
            sha: sub_sha.clone(),
3572
            branch: "HEAD".into()
3573
        }
3574
    );
3575
    let modules =
3576
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3577
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3578
    assert!(modules.entries["vendor/sub"].git);
3579
    assert!(
3580
        files.contains_key(".gitmodules"),
3581
        "the Git file is kept for round trips"
3582
    );
3583
    assert!(
3584
        !dest.join("vendor/sub/.git").exists(),
3585
        "not cloned until update --init"
3586
    );
3587
    assert!(!repo.snapshot("status").unwrap().changed);
3588
    // update --init clones it at the pinned commit; status is unchanged.
3589
    assert_eq!(
3590
        repo.submodule_update(true, &[]).unwrap(),
3591
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3592
    );
3593
    assert_eq!(
3594
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3595
        sub_sha
3596
    );
3597
    assert!(!repo.snapshot("status").unwrap().changed);
3598
    // Export writes the gitlink and .gitmodules back.
3599
    let mirror = root.join("mirror.git");
3600
    let rep = repo.git_export(&mirror).unwrap();
3601
    assert_eq!(rep.skipped_subrepos, 0);
3602
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3603
    assert!(
3604
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3605
        "{ls}"
3606
    );
3607
    assert_eq!(
3608
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3609
        ".gitmodules\nREADME.md\nvendor"
3610
    );
3611
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3612
    assert_eq!(
3613
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3614
        orig_tree,
3615
        "tree round trip"
3616
    );
3617
}
3618
3619
#[test]
3620
fn partial_commits_by_path_and_by_hunk() {
3621
    hermetic();
3622
    let dir = tempfile::tempdir().unwrap();
3623
    let root = dir.path();
3624
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3625
    write(root, "a.txt", b"1\n2\n3\n");
3626
    write(root, "b.txt", b"b\n");
3627
    let h0 = repo.commit("base", &[]).unwrap();
3628
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3629
    write(root, "b.txt", b"b\nbb\n");
3630
    write(root, "c.txt", b"c\n");
3631
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3632
    let h1 = repo
3633
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3634
        .unwrap();
3635
    let c1 = repo.store().get_change(&h1).unwrap();
3636
    assert!(
3637
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3638
        "{:?}",
3639
        c1.tree_ops
3640
    );
3641
    assert_eq!(c1.deps, vec![h0]);
3642
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3643
    assert!(
3644
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3645
    );
3646
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3647
    assert!(!files.contains_key("c.txt"));
3648
    let snap = repo.snapshot("status").unwrap();
3649
    assert_eq!(
3650
        snap.statuses
3651
            .iter()
3652
            .map(|s| (s.path.as_str(), s.status))
3653
            .collect::<Vec<_>>(),
3654
        vec![
3655
            ("b.txt", ChangeStatus::Modified),
3656
            ("c.txt", ChangeStatus::Added)
3657
        ]
3658
    );
3659
    assert_eq!(
3660
        fs::read(root.join("b.txt")).unwrap(),
3661
        b"b\nbb\n",
3662
        "disk untouched"
3663
    );
3664
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3665
    let (_, hunks) = repo.hunks().unwrap();
3666
    let b_hunk = hunks
3667
        .iter()
3668
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3669
        .unwrap()
3670
        .index;
3671
    let h2 = repo
3672
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3673
        .unwrap();
3674
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3675
    assert!(
3676
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3677
    );
3678
    assert!(!files.contains_key("c.txt"));
3679
    let snap = repo.snapshot("status").unwrap();
3680
    assert_eq!(
3681
        snap.statuses
3682
            .iter()
3683
            .map(|s| s.path.as_str())
3684
            .collect::<Vec<_>>(),
3685
        vec!["c.txt"]
3686
    );
3687
    // Choosing only the content hunk of a file in a new directory pulls in
3688
    // the directory and file additions it needs.
3689
    write(root, "d/e.txt", b"e\n");
3690
    let (_, hunks) = repo.hunks().unwrap();
3691
    let e_insert = hunks
3692
        .iter()
3693
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3694
        .unwrap()
3695
        .index;
3696
    let h3 = repo
3697
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3698
        .unwrap();
3699
    let c3 = repo.store().get_change(&h3).unwrap();
3700
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3701
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3702
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3703
    // Choosing a new file's addition hunk brings its content along.
3704
    write(root, "f/g.txt", b"g\n");
3705
    let (_, hunks) = repo.hunks().unwrap();
3706
    let g_add = hunks
3707
        .iter()
3708
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3709
        .unwrap()
3710
        .index;
3711
    let h4 = repo
3712
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3713
        .unwrap();
3714
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
3715
    assert!(
3716
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3717
    );
3718
    assert!(!repo
3719
        .snapshot("status")
3720
        .unwrap()
3721
        .statuses
3722
        .iter()
3723
        .any(|s| s.path == "f/g.txt"));
3724
    // Everything left commits normally; the working copy is then clean.
3725
    repo.commit("the rest", &[]).unwrap();
3726
    assert!(!repo.snapshot("status").unwrap().changed);
3727
    let files = repo
3728
        .load_state(&repo.bookmark_heads().unwrap())
3729
        .unwrap()
3730
        .materialize()
3731
        .files;
3732
    assert!(files.contains_key("c.txt"));
3733
}
3734
3735
#[test]
3736
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3737
    hermetic();
3738
    let dir = tempfile::tempdir().unwrap();
3739
    let root = dir.path();
3740
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3741
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3742
        .unwrap();
3743
    write(root, "a.txt", b"one\n");
3744
    let h1 = repo.commit("first", &[]).unwrap();
3745
    write(root, "a.txt", b"one\ntwo\n");
3746
    let h2 = repo.commit("second", &[]).unwrap();
3747
    let b = repo.blame("a.txt").unwrap();
3748
    assert_eq!(
3749
        b.iter()
3750
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3751
            .collect::<Vec<_>>(),
3752
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3753
    );
3754
    assert!(b.iter().all(|l| l.author == "Ada"));
3755
    assert_eq!(
3756
        b[0].change_id,
3757
        repo.store().get_change(&h1).unwrap().change_id
3758
    );
3759
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3760
    repo.commit("rename", &[]).unwrap();
3761
    let b = repo.blame("b.txt").unwrap();
3762
    assert_eq!(
3763
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3764
        vec![h1, h2],
3765
        "the node survives the rename"
3766
    );
3767
    assert!(repo.blame("a.txt").is_err());
3768
}
3769
3770
#[test]
3771
fn bisect_finds_the_first_bad_change() {
3772
    hermetic();
3773
    let dir = tempfile::tempdir().unwrap();
3774
    let root = dir.path();
3775
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3776
    let mut content = String::new();
3777
    let mut hashes = Vec::new();
3778
    for i in 1..=8 {
3779
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3780
        write(root, "f.txt", content.as_bytes());
3781
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3782
    }
3783
    // Each step appends after the previous line, so the chain is linear.
3784
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3785
    repo.bisect_start().unwrap();
3786
    assert!(matches!(
3787
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3788
        BisectStep::NeedMarks { good: 1, bad: 0 }
3789
    ));
3790
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3791
    assert!(
3792
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3793
        "{step:?}"
3794
    );
3795
    // Automated: bad when the bug line is present.
3796
    let step = repo
3797
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3798
        .unwrap();
3799
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3800
    assert_eq!(
3801
        repo.bisect_status().unwrap(),
3802
        Some(BisectStep::Found { culprit: hashes[4] })
3803
    );
3804
    repo.bisect_reset().unwrap();
3805
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3806
    assert!(repo.bisect_status().unwrap().is_none());
3807
    assert!(!repo.snapshot("status").unwrap().changed);
3808
    // Manual marks and a skip.
3809
    repo.bisect_start().unwrap();
3810
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3811
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3812
    let mut skipped_once = false;
3813
    let mut guard = 0;
3814
    while let BisectStep::Testing { .. } = step {
3815
        guard += 1;
3816
        assert!(guard < 20);
3817
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3818
        if !skipped_once && text.contains("line 6") {
3819
            // An untestable state away from the boundary: the search routes around it.
3820
            skipped_once = true;
3821
            step = repo.bisect_mark(None, &[]).unwrap();
3822
            continue;
3823
        }
3824
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3825
    }
3826
    assert!(skipped_once);
3827
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3828
    repo.bisect_reset().unwrap();
3829
    // Skipping the culprit itself leaves it among the candidates reported.
3830
    repo.bisect_start().unwrap();
3831
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3832
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3833
    let mut guard = 0;
3834
    while let BisectStep::Testing { heads, .. } = &step {
3835
        guard += 1;
3836
        assert!(guard < 20);
3837
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3838
        let is_culprit_state =
3839
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3840
        step = if is_culprit_state {
3841
            repo.bisect_mark(None, &[]).unwrap()
3842
        } else {
3843
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3844
        };
3845
    }
3846
    match step {
3847
        BisectStep::Inconclusive { candidates } => assert!(
3848
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3849
            "{candidates:?}"
3850
        ),
3851
        other => panic!("{other:?}"),
3852
    }
3853
    repo.bisect_reset().unwrap();
3854
}
3855
3856
#[test]
3857
fn squash_folds_a_change_into_its_dependency() {
3858
    hermetic();
3859
    let dir = tempfile::tempdir().unwrap();
3860
    let root = dir.path();
3861
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3862
    write(root, "a.txt", b"1\n");
3863
    let a = repo.commit("A", &[]).unwrap();
3864
    write(root, "a.txt", b"1\n2\n");
3865
    let c = repo.commit("C", &[]).unwrap();
3866
    write(root, "a.txt", b"1\n2\n3\n");
3867
    let e = repo.commit("E", &[]).unwrap();
3868
    write(root, "b.txt", b"b\n");
3869
    let b = repo.commit("B", &[]).unwrap();
3870
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3871
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3872
    // E depends on C which A lacks: refused, naming it.
3873
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3874
    assert!(err.contains(&c.short(12)), "{err}");
3875
    // C into A: A' has both, C is gone, E follows and still reads the same.
3876
    let a2 = repo.squash(&c, &a).unwrap();
3877
    let a2c = repo.store().get_change(&a2).unwrap();
3878
    assert_eq!(a2c.change_id, id_a);
3879
    assert!(a2c.deps.is_empty());
3880
    let heads = repo.bookmark_heads().unwrap();
3881
    let st = repo.load_state(&heads).unwrap();
3882
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
3883
    let e2 = st
3884
        .changes()
3885
        .find(|(_, m)| m.change_id == id_e)
3886
        .map(|(h, _)| *h)
3887
        .unwrap();
3888
    assert_eq!(
3889
        repo.store().get_change(&e2).unwrap().deps,
3890
        vec![a2],
3891
        "E now depends on A' alone"
3892
    );
3893
    let files = st.materialize().files;
3894
    assert!(
3895
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3896
    );
3897
    assert!(files.contains_key("b.txt"));
3898
    assert!(st.contains(&b));
3899
    assert!(!repo.snapshot("status").unwrap().changed);
3900
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3901
    // Undo restores the three original changes.
3902
    repo.undo().unwrap();
3903
    repo.undo().unwrap();
3904
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3905
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3906
}
3907
3908
#[test]
3909
fn rebase_re_expresses_a_change_against_another_base() {
3910
    hermetic();
3911
    let dir = tempfile::tempdir().unwrap();
3912
    let root = dir.path();
3913
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3914
    write(root, "a.txt", b"1\n2\n");
3915
    let a = repo.commit("A", &[]).unwrap();
3916
    write(root, "a.txt", b"1\n2\n3\n");
3917
    let c = repo.commit("C: append 3", &[]).unwrap();
3918
    write(root, "a.txt", b"1\n2\n3\n4\n");
3919
    let e = repo.commit("E: append 4", &[]).unwrap();
3920
    // A different base: A plus a change that prepends a line.
3921
    repo.checkout(&[a], true, "checkout").unwrap();
3922
    write(root, "a.txt", b"0\n1\n2\n");
3923
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3924
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3925
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3926
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3927
    let c2 = repo.rebase(&c, &[d]).unwrap();
3928
    let c2c = repo.store().get_change(&c2).unwrap();
3929
    assert_eq!(c2c.change_id, id_c);
3930
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3931
    let heads = repo.bookmark_heads().unwrap();
3932
    let st = repo.load_state(&heads).unwrap();
3933
    assert!(!st.contains(&c) && st.contains(&d));
3934
    let e2 = st
3935
        .changes()
3936
        .find(|(_, m)| m.change_id == id_e)
3937
        .map(|(h, _)| *h)
3938
        .unwrap();
3939
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
3940
    assert!(
3941
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3942
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3943
    );
3944
    let files = st.materialize().files;
3945
    assert!(
3946
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3947
        "{:?}",
3948
        files["a.txt"].content
3949
    );
3950
    assert!(!files["a.txt"].is_conflicted());
3951
    // Rebasing onto a state that already contains the change is refused.
3952
    assert!(repo.rebase(&c2, &[c2]).is_err());
3953
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
3954
    assert!(
3955
        err.contains("lacks dependencies"),
3956
        "E needs C, which D's state does not have: {err}"
3957
    );
3958
}
3959
3960
#[test]
3961
fn unsigned_tags_keep_their_message() {
3962
    hermetic();
3963
    let dir = tempfile::tempdir().unwrap();
3964
    let root = dir.path();
3965
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3966
    write(root, "a.txt", b"a\n");
3967
    repo.commit("a", &[]).unwrap();
3968
    assert!(repo.secret_key().unwrap().is_none());
3969
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
3970
        .unwrap();
3971
    let tags = repo.tags().unwrap();
3972
    assert_eq!(
3973
        (
3974
            tags[0].name.as_str(),
3975
            tags[0].message.as_str(),
3976
            tags[0].signer.as_deref()
3977
        ),
3978
        ("v1", "first release", None)
3979
    );
3980
    assert!(
3981
        repo.tag_refs().unwrap()[0].attestation.is_none(),
3982
        "an unsigned attestation is not advertised"
3983
    );
3984
}
3985
3986
#[test]
3987
fn fsck_passes_a_sound_repository_and_names_each_fault() {
3988
    // Files on disk are what this tests: tampering with them, and the
3989
    // directory store's crash points.
3990
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
3991
        return;
3992
    }
3993
    hermetic();
3994
    let dir = tempfile::tempdir().unwrap();
3995
    let root = dir.path();
3996
    let origin_path = root.join("origin");
3997
    let origin = Repo::init(&origin_path).unwrap();
3998
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
3999
        .unwrap()
4000
        .with_home(root.join("home-a"));
4001
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4002
        .unwrap();
4003
    write(&root.join("a"), "f.txt", b"one\n");
4004
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4005
    let h1 = a.commit("first", &[]).unwrap();
4006
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4007
    let h2 = a.commit("second", &[]).unwrap();
4008
    a.tag_create("v1", &[h2], "first release").unwrap();
4009
    a.checkpoint().unwrap();
4010
    assert!(a.push("origin", false).unwrap()[0].ok);
4011
4012
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4013
    for repo in [&a, &origin] {
4014
        let rep = repo.fsck().unwrap();
4015
        assert_eq!(rep.problems, vec![], "{rep:?}");
4016
        // The two commits, plus the working copy's change in `a`.
4017
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4018
        assert!(rep.ops > 1 && rep.objects > 5);
4019
    }
4020
    assert!(origin.fsck().unwrap().attestations >= 1);
4021
4022
    // A flipped byte in a stored object is corruption, named by hash.
4023
    let c1 = a.store().path_for(&h1);
4024
    let pristine = fs::read(&c1).unwrap();
4025
    let mut bytes = pristine.clone();
4026
    *bytes.last_mut().unwrap() ^= 1;
4027
    fs::write(&c1, &bytes).unwrap();
4028
    let rep = a.fsck().unwrap();
4029
    assert!(rep.errors() >= 1);
4030
    assert!(
4031
        rep.problems
4032
            .iter()
4033
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4034
        "{rep:?}"
4035
    );
4036
    fs::write(&c1, &pristine).unwrap();
4037
    assert_eq!(a.fsck().unwrap().errors(), 0);
4038
4039
    // A missing change is named with what needed it.
4040
    fs::remove_file(&c1).unwrap();
4041
    let rep = a.fsck().unwrap();
4042
    assert!(
4043
        rep.problems.iter().any(|p| p.severity == Severity::Error
4044
            && p.object == Some(h1)
4045
            && p.what.contains("change missing, needed by change")),
4046
        "{rep:?}"
4047
    );
4048
    fs::write(&c1, &pristine).unwrap();
4049
4050
    // A missing blob is an error in a full clone.
4051
    let c2 = a.store().get_change(&h1).unwrap();
4052
    let blob = c2
4053
        .edits
4054
        .iter()
4055
        .find_map(|e| match e {
4056
            Edit::Replace { new: Some(b), .. } => Some(*b),
4057
            _ => None,
4058
        })
4059
        .expect("the binary file is a blob");
4060
    let bp = a.store().path_for(&blob);
4061
    let blob_bytes = fs::read(&bp).unwrap();
4062
    fs::remove_file(&bp).unwrap();
4063
    let rep = a.fsck().unwrap();
4064
    assert!(
4065
        rep.problems
4066
            .iter()
4067
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4068
        "{rep:?}"
4069
    );
4070
    fs::write(&bp, &blob_bytes).unwrap();
4071
4072
    // A broken op log head is reported, not a crash.
4073
    let head = root.join("a/.oxy/ops/head");
4074
    let saved = fs::read(&head).unwrap();
4075
    fs::write(&head, b"not a hash").unwrap();
4076
    let rep = a.fsck().unwrap();
4077
    assert!(
4078
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4079
        "{rep:?}"
4080
    );
4081
    fs::write(&head, saved).unwrap();
4082
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4083
}
4084
4085
/// Copy a directory tree (for restoring a pristine repository).
4086
fn copy_tree(from: &Path, to: &Path) {
4087
    fs::create_dir_all(to).unwrap();
4088
    for e in fs::read_dir(from).unwrap() {
4089
        let e = e.unwrap();
4090
        let target = to.join(e.file_name());
4091
        if e.file_type().unwrap().is_dir() {
4092
            copy_tree(&e.path(), &target);
4093
        } else {
4094
            fs::copy(e.path(), &target).unwrap();
4095
        }
4096
    }
4097
}
4098
4099
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4100
/// would, and check that both repositories still open, pass `fsck`, and
4101
/// accept the same operation again.
4102
#[test]
4103
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4104
    // Files on disk are what this tests: tampering with them, and the
4105
    // directory store's crash points.
4106
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4107
        return;
4108
    }
4109
    use crate::durable::failpoint;
4110
    hermetic();
4111
    let dir = tempfile::tempdir().unwrap();
4112
    let pristine = dir.path().join("pristine");
4113
    let origin_path = pristine.join("origin");
4114
    Repo::init(&origin_path).unwrap();
4115
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4116
        .unwrap()
4117
        .with_home(dir.path().join("home"));
4118
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4119
        .unwrap();
4120
    write(&pristine.join("a"), "f.txt", b"one\n");
4121
    a.commit("first", &[]).unwrap();
4122
    assert!(a.push("origin", false).unwrap()[0].ok);
4123
    drop(a);
4124
4125
    type Op = fn(&Repo) -> Result<()>;
4126
    let edit_and_commit: Op = |r| {
4127
        write(r.root(), "f.txt", b"one\ntwo\n");
4128
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4129
        r.commit("second", &[]).map(|_| ())
4130
    };
4131
    let push: Op = |r| {
4132
        let res = r.push("origin", false)?;
4133
        if res.iter().all(|x| x.ok) {
4134
            Ok(())
4135
        } else {
4136
            Err(RepoError::Msg(format!("{res:?}")))
4137
        }
4138
    };
4139
4140
    for (name, prepare, op) in [
4141
        ("commit", None, edit_and_commit),
4142
        ("push", Some(edit_and_commit), push),
4143
    ] {
4144
        let mut steps = 0;
4145
        for n in 1.. {
4146
            let run = dir.path().join(format!("{name}-{n}"));
4147
            copy_tree(&pristine, &run);
4148
            // Clones record their remote by path; point it at this copy.
4149
            let open = |p: &Path| {
4150
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4151
                r.config
4152
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4153
                    .unwrap();
4154
                r.save_config().unwrap();
4155
                r
4156
            };
4157
            let a = open(&run.join("a"));
4158
            if let Some(prep) = prepare {
4159
                prep(&a).unwrap();
4160
            }
4161
            failpoint::crash_after(n);
4162
            let outcome = op(&a);
4163
            let crashed = failpoint::disarm();
4164
            drop(a);
4165
            if !crashed {
4166
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4167
                steps = n - 1;
4168
                break;
4169
            }
4170
            assert!(
4171
                outcome.is_err(),
4172
                "{name}: a crash at step {n} was swallowed"
4173
            );
4174
            for repo in ["a", "origin"] {
4175
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4176
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4177
                });
4178
                let rep = r.fsck().unwrap();
4179
                assert_eq!(
4180
                    rep.errors(),
4181
                    0,
4182
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4183
                    rep.problems
4184
                );
4185
            }
4186
            // The interrupted operation can simply be run again.
4187
            let a = open(&run.join("a"));
4188
            // A crash after the commit point leaves the commit done.
4189
            let landed = a
4190
                .bookmark_heads()
4191
                .unwrap()
4192
                .iter()
4193
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4194
            let again = match (name, landed) {
4195
                ("commit", true) => Ok(()),
4196
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4197
                _ => op(&a),
4198
            };
4199
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4200
            assert_eq!(a.fsck().unwrap().errors(), 0);
4201
            fs::remove_dir_all(&run).unwrap();
4202
        }
4203
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4204
    }
4205
}
4206
4207
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4208
/// running at the same time lose nothing: every commit ends up on the
4209
/// bookmark, locally and on the remote, and the repository passes fsck.
4210
#[test]
4211
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4212
    hermetic();
4213
    let dir = tempfile::tempdir().unwrap();
4214
    let root = dir.path();
4215
    let origin = root.join("origin");
4216
    Repo::init_bare_unbound(&origin).unwrap();
4217
    let main = root.join("main");
4218
    let mut repo = Repo::init(&main).unwrap();
4219
    repo.config
4220
        .set("remote.origin.url", &origin.to_string_lossy())
4221
        .unwrap();
4222
    repo.save_config().unwrap();
4223
    write(&main, "seed.txt", b"seed\n");
4224
    repo.commit("seed", &[]).unwrap();
4225
    let second = root.join("second");
4226
    repo.workspace_add(&second, None).unwrap();
4227
    drop(repo);
4228
4229
    const EACH: usize = 15;
4230
    std::thread::scope(|s| {
4231
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4232
            s.spawn(move || {
4233
                let r = Repo::open(&dir).unwrap();
4234
                for i in 0..EACH {
4235
                    write(
4236
                        &dir,
4237
                        &format!("{tag}-{i}.txt"),
4238
                        format!("{tag} {i}\n").as_bytes(),
4239
                    );
4240
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4241
                    if push && i % 5 == 4 {
4242
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4243
                        let _ = r.push("origin", false);
4244
                    }
4245
                }
4246
            });
4247
        }
4248
    });
4249
4250
    let repo = Repo::open(&main).unwrap();
4251
    let heads = repo.bookmark_heads().unwrap();
4252
    let state = repo.load_state(&heads).unwrap();
4253
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4254
    for tag in ["a", "b"] {
4255
        for i in 0..EACH {
4256
            assert!(
4257
                messages.contains(&format!("{tag} {i}")),
4258
                "lost commit {tag} {i}; have {messages:?}"
4259
            );
4260
        }
4261
    }
4262
    let rep = repo.fsck().unwrap();
4263
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4264
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4265
    let hosted = Repo::open(&origin).unwrap();
4266
    let hosted_heads = hosted.bookmark_heads().unwrap();
4267
    assert_eq!(
4268
        hosted.load_state(&hosted_heads).unwrap().len(),
4269
        state.len(),
4270
        "the remote has every commit"
4271
    );
4272
}
4273
4274
/// Two operations recorded from the same parent (what two processes do
4275
/// when they race) are merged: both bookmarks' heads survive, and a
4276
/// change made on one side only is kept.
4277
#[test]
4278
fn operations_from_the_same_parent_are_merged() {
4279
    hermetic();
4280
    let dir = tempfile::tempdir().unwrap();
4281
    let root = dir.path();
4282
    let repo = Repo::init(root).unwrap();
4283
    write(root, "a.txt", b"a\n");
4284
    let a = repo.commit("a", &[]).unwrap();
4285
    write(root, "b.txt", b"b\n");
4286
    let b = repo.commit("b", &[]).unwrap();
4287
    let (x, op) = repo.head_op().unwrap();
4288
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4289
4290
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4291
    let mut one = op.view.clone();
4292
    one.bookmarks.insert("main".into(), state(vec![a]));
4293
    one.bookmarks.insert("topic".into(), state(vec![a]));
4294
    let mut two = op.view.clone();
4295
    two.bookmarks.insert("main".into(), state(vec![b]));
4296
    repo.record_op(&[x], "one", one).unwrap();
4297
    let merged = repo.record_op(&[x], "two", two).unwrap();
4298
4299
    let (head, op) = repo.head_op().unwrap();
4300
    assert_eq!(head, merged);
4301
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4302
    assert!(op.command.contains("merged with a concurrent operation"));
4303
    let mut main = repo
4304
        .store()
4305
        .get_state(&op.view.bookmarks["main"])
4306
        .unwrap()
4307
        .heads;
4308
    main.sort();
4309
    let mut want = vec![a, b];
4310
    want.sort();
4311
    assert_eq!(main, want, "both sides' heads are kept");
4312
    assert!(
4313
        op.view.bookmarks.contains_key("topic"),
4314
        "a one-sided change survives"
4315
    );
4316
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4317
}
4318
4319
#[test]
4320
fn failed_requests_come_with_a_next_step() {
4321
    use crate::protocol::hint_for;
4322
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4323
        .unwrap()
4324
        .contains("token"));
4325
    assert!(hint_for("…: HTTP 403: forbidden")
4326
        .unwrap()
4327
        .contains("repo:write"));
4328
    assert!(hint_for("…: HTTP 404: no such repository")
4329
        .unwrap()
4330
        .contains("owner and repository name"));
4331
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4332
        .unwrap()
4333
        .contains("oxyhub-ca.pem"));
4334
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4335
        .unwrap()
4336
        .contains("running"));
4337
    assert!(hint_for("Dns Failed: failed to lookup address information")
4338
        .unwrap()
4339
        .contains("resolve"));
4340
    assert_eq!(hint_for("something else entirely"), None);
4341
}
4342
4343
#[test]
4344
fn doctor_names_problems_and_what_to_do() {
4345
    hermetic();
4346
    let dir = tempfile::tempdir().unwrap();
4347
    let root = dir.path();
4348
    let origin = root.join("origin");
4349
    Repo::init_bare_unbound(&origin).unwrap();
4350
    let mut repo = Repo::init(&root.join("r"))
4351
        .unwrap()
4352
        .with_home(root.join("home"));
4353
    let find = |r: &DoctorReport, area: &str, h: Health| {
4354
        r.checks
4355
            .iter()
4356
            .find(|c| c.area == area && c.health == h)
4357
            .cloned()
4358
    };
4359
4360
    let r = repo.doctor(true);
4361
    assert!(find(&r, "identity", Health::Warn)
4362
        .unwrap()
4363
        .hint
4364
        .unwrap()
4365
        .contains("oxy identity create"));
4366
    assert!(find(&r, "repository", Health::Ok).is_some());
4367
4368
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4369
        .unwrap();
4370
    repo.config.set("author.name", "Ada").unwrap();
4371
    repo.config.set("author.email", "[email protected]").unwrap();
4372
    repo.config
4373
        .set("remote.origin.url", &origin.to_string_lossy())
4374
        .unwrap();
4375
    repo.config
4376
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4377
        .unwrap();
4378
    repo.config.set("remote.down.token", "t").unwrap();
4379
    repo.config
4380
        .set("remote.badca.url", "https://example.invalid/a/b")
4381
        .unwrap();
4382
    repo.config
4383
        .set(
4384
            "remote.badca.ca",
4385
            &root.join("missing.pem").to_string_lossy(),
4386
        )
4387
        .unwrap();
4388
    repo.save_config().unwrap();
4389
4390
    let r = repo.doctor(true);
4391
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4392
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4393
    assert!(find(&r, "remote origin", Health::Ok)
4394
        .unwrap()
4395
        .message
4396
        .contains("first push binds it"));
4397
    let down = find(&r, "remote down", Health::Fail).unwrap();
4398
    assert!(
4399
        down.hint.as_deref().unwrap_or("").contains("running"),
4400
        "{down:?}"
4401
    );
4402
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4403
    assert!(
4404
        badca.hint.unwrap().contains("remote.badca.ca"),
4405
        "the remote's own name is in the hint"
4406
    );
4407
    assert_eq!(r.worst(), Health::Fail);
4408
4409
    // Offline, nothing is contacted.
4410
    let r = repo.doctor(false);
4411
    assert!(find(&r, "remote down", Health::Fail).is_none());
4412
    assert!(find(&r, "remote down", Health::Ok)
4413
        .unwrap()
4414
        .message
4415
        .contains("not contacted"));
4416
}
4417
4418
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4419
/// after it. Inserting after `b` and then deleting `b`, one commit after
4420
/// the other, must not leave a delete/insert conflict.
4421
#[test]
4422
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4423
    hermetic();
4424
    let dir = tempfile::tempdir().unwrap();
4425
    let root = dir.path();
4426
    let repo = Repo::init(root).unwrap();
4427
    write(root, "f", b"a\nb\nc\n");
4428
    repo.commit("base", &[]).unwrap();
4429
    write(root, "f", b"a\nb\nx\nc\n");
4430
    let insert = repo.commit("insert x after b", &[]).unwrap();
4431
    write(root, "f", b"a\nx\nc\n");
4432
    let delete = repo.commit("delete b", &[]).unwrap();
4433
    assert!(
4434
        repo.store()
4435
            .get_change(&delete)
4436
            .unwrap()
4437
            .deps
4438
            .contains(&insert),
4439
        "the deletion depends on the insertion below the deleted line"
4440
    );
4441
    let heads = repo.bookmark_heads().unwrap();
4442
    assert_eq!(heads, vec![delete]);
4443
    let snap = repo.load_state(&heads).unwrap().materialize();
4444
    assert!(!snap.is_conflicted());
4445
    assert!(
4446
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4447
    );
4448
}
4449
4450
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4451
/// replacement depends on the change that set the blob it replaces.
4452
#[test]
4453
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4454
    hermetic();
4455
    let dir = tempfile::tempdir().unwrap();
4456
    let root = dir.path();
4457
    let repo = Repo::init(root).unwrap();
4458
    write(root, "bin", b"\0A");
4459
    let v1 = repo.commit("v1", &[]).unwrap();
4460
    write(root, "bin", b"\0B");
4461
    let v2 = repo.commit("v2", &[]).unwrap();
4462
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4463
    write(root, "bin", b"\0A");
4464
    let v3 = repo.commit("back to A", &[]).unwrap();
4465
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4466
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4467
    let state = repo.load_state(&[v3]).unwrap();
4468
    let snap = state.materialize();
4469
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4470
        panic!("opaque")
4471
    };
4472
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4473
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4474
}
4475
4476
/// Spec §23: a binary file changed on two branches and merged in Git to
4477
/// one side's version comes back as that version at the merge, and the
4478
/// import verifies commit by commit.
4479
#[test]
4480
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4481
    hermetic();
4482
    if std::process::Command::new("git")
4483
        .arg("--version")
4484
        .output()
4485
        .is_err()
4486
    {
4487
        eprintln!("git not installed; skipping");
4488
        return;
4489
    }
4490
    let dir = tempfile::tempdir().unwrap();
4491
    let root = dir.path();
4492
    let g = root.join("src.git");
4493
    fs::create_dir_all(&g).unwrap();
4494
    let git = |args: &[&str]| -> String {
4495
        let out = std::process::Command::new("git")
4496
            .arg("-C")
4497
            .arg(&g)
4498
            .args([
4499
                "-c",
4500
                "user.name=Grace",
4501
                "-c",
4502
                "[email protected]",
4503
                "-c",
4504
                "commit.gpgsign=false",
4505
            ])
4506
            .args(args)
4507
            .output()
4508
            .unwrap();
4509
        assert!(
4510
            out.status.success(),
4511
            "git {args:?}: {}",
4512
            String::from_utf8_lossy(&out.stderr)
4513
        );
4514
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4515
    };
4516
    git(&["init", "-q", "-b", "main"]);
4517
    write(&g, "logo.bin", b"\0base");
4518
    write(&g, "notes.txt", b"a\nb\nc\n");
4519
    git(&["add", "."]);
4520
    git(&["commit", "-qm", "base"]);
4521
    git(&["checkout", "-qb", "side"]);
4522
    write(&g, "logo.bin", b"\0side");
4523
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4524
    git(&["commit", "-qam", "side"]);
4525
    git(&["checkout", "-q", "main"]);
4526
    write(&g, "logo.bin", b"\0main");
4527
    git(&["commit", "-qam", "main"]);
4528
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4529
    let _ = std::process::Command::new("git")
4530
        .arg("-C")
4531
        .arg(&g)
4532
        .args([
4533
            "-c",
4534
            "user.name=G",
4535
            "-c",
4536
            "user.email=g@e",
4537
            "merge",
4538
            "-q",
4539
            "side",
4540
        ])
4541
        .output();
4542
    write(&g, "logo.bin", b"\0main");
4543
    git(&["add", "."]);
4544
    git(&["commit", "-qm", "merge side"]);
4545
    // Then a revert of the binary to its first version.
4546
    write(&g, "logo.bin", b"\0base");
4547
    git(&["commit", "-qam", "back to base"]);
4548
4549
    let repo = Repo::init(&root.join("o")).unwrap();
4550
    let rep = repo.import_git(&g, "main").unwrap();
4551
    assert_eq!(rep.merges, 1);
4552
    let v = repo.verify_git_import(&g, "main").unwrap();
4553
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4554
    assert_eq!(v.commits, 5);
4555
    let snap = repo
4556
        .load_state(&repo.bookmark_heads().unwrap())
4557
        .unwrap()
4558
        .materialize();
4559
    assert!(!snap.is_conflicted());
4560
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4561
        panic!("opaque")
4562
    };
4563
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4564
}
4565
4566
/// Spec §7.7 on a file system without executable bits or symlinks: the
4567
/// recorded bit is kept, and a symlink checked out as a plain file holding
4568
/// its target is still that symlink.
4569
#[cfg(unix)]
4570
#[test]
4571
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4572
    use crate::portable::Platform;
4573
    use std::os::unix::fs::PermissionsExt;
4574
    hermetic();
4575
    let dir = tempfile::tempdir().unwrap();
4576
    let root = dir.path();
4577
    let repo = Repo::init(root).unwrap();
4578
    write(root, "run.sh", b"#!/bin/sh\n");
4579
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4580
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4581
    repo.commit("script and link", &[]).unwrap();
4582
    drop(repo);
4583
4584
    // What checking out on Windows leaves: no exec bit, the link as a file.
4585
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4586
    fs::remove_file(root.join("link")).unwrap();
4587
    write(root, "link", b"run.sh");
4588
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4589
    let s = win.snapshot("oxy status").unwrap();
4590
    assert!(
4591
        s.statuses.is_empty(),
4592
        "nothing changed on Windows: {:?}",
4593
        statuses(&s)
4594
    );
4595
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4596
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4597
    write(root, "link", b"other");
4598
    let h = win.commit("edit on Windows", &[]).unwrap();
4599
    let snap = win.load_state(&[h]).unwrap().materialize();
4600
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4601
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4602
    // The same working copy read as Linux sees the lost bit and the plain file.
4603
    let linux = Repo::open(root).unwrap();
4604
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4605
}
4606
4607
/// Paths that collide on case-insensitive or Windows file systems are
4608
/// named at checkout there, and by doctor everywhere.
4609
#[test]
4610
fn paths_other_platforms_cannot_hold_are_reported() {
4611
    use crate::portable::Platform;
4612
    hermetic();
4613
    let dir = tempfile::tempdir().unwrap();
4614
    let root = dir.path();
4615
    let repo = Repo::init(root).unwrap();
4616
    write(root, "README.md", b"a\n");
4617
    write(root, "readme.md", b"b\n");
4618
    write(root, "src/aux.c", b"int x;\n");
4619
    let h = repo.commit("unportable", &[]).unwrap();
4620
    let r = repo.doctor(false);
4621
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4622
    assert_eq!(port.health, Health::Warn);
4623
    assert!(
4624
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4625
        "{}",
4626
        port.message
4627
    );
4628
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4629
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4630
    assert!(
4631
        rep.notes
4632
            .iter()
4633
            .any(|n| n.contains("README.md and readme.md")),
4634
        "{:?}",
4635
        rep.notes
4636
    );
4637
    assert!(
4638
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4639
        "macOS allows aux.c"
4640
    );
4641
}
4642
4643
#[test]
4644
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4645
    hermetic();
4646
    let dir = tempfile::tempdir().unwrap();
4647
    let repo = Repo::init(dir.path()).unwrap();
4648
    write(dir.path(), "a.txt", b"one\n");
4649
    write(dir.path(), "other.txt", b"x\n");
4650
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4651
    repo.snapshot("t").unwrap();
4652
    let c1 = repo.commit("first", &[]).unwrap();
4653
    write(dir.path(), "other.txt", b"y\n");
4654
    repo.snapshot("t").unwrap();
4655
    repo.commit("other only", &[]).unwrap();
4656
    write(dir.path(), "a.txt", b"one\ntwo\n");
4657
    repo.snapshot("t").unwrap();
4658
    let c3 = repo.commit("second line", &[]).unwrap();
4659
    write(dir.path(), "other.txt", b"z\n");
4660
    repo.snapshot("t").unwrap();
4661
    repo.commit("other again", &[]).unwrap();
4662
4663
    let heads = repo.bookmark_heads().unwrap();
4664
    let state = repo.load_state(&heads).unwrap();
4665
    let full: Vec<ChangeHash> = repo
4666
        .log_for_path_in("a.txt", &heads)
4667
        .unwrap()
4668
        .iter()
4669
        .map(|e| e.hash)
4670
        .collect();
4671
    assert_eq!(
4672
        full,
4673
        vec![c3, c1],
4674
        "newest first, only changes touching the path"
4675
    );
4676
    let newest: Vec<ChangeHash> = repo
4677
        .log_for_path_of(&state, "a.txt", Some(1))
4678
        .unwrap()
4679
        .iter()
4680
        .map(|e| e.hash)
4681
        .collect();
4682
    assert_eq!(newest, vec![c3], "stops at the first");
4683
    assert_eq!(
4684
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4685
        2
4686
    );
4687
    assert!(repo
4688
        .log_for_path_of(&state, "missing.txt", Some(1))
4689
        .is_err());
4690
    assert_eq!(
4691
        repo.log_state(&heads).unwrap().len(),
4692
        repo.log_of(&state).len()
4693
    );
4694
4695
    let tree = state.tree().view();
4696
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4697
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4698
    assert_eq!(
4699
        via_state
4700
            .iter()
4701
            .map(|l| (l.hash, l.text.clone()))
4702
            .collect::<Vec<_>>(),
4703
        via_heads
4704
            .iter()
4705
            .map(|l| (l.hash, l.text.clone()))
4706
            .collect::<Vec<_>>()
4707
    );
4708
    assert_eq!(
4709
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4710
        vec![c1, c3]
4711
    );
4712
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4713
}
4714
4715
/// A text file whose stat matches the manifest and whose recorded hash is
4716
/// the base's content is taken from the base without reading it; anything
4717
/// else is read, so no edit is missed (spec §12.3).
4718
#[cfg(unix)]
4719
#[test]
4720
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4721
    use std::os::unix::fs::PermissionsExt;
4722
    hermetic();
4723
    let dir = tempfile::tempdir().unwrap();
4724
    let root = dir.path();
4725
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4726
    write(root, "a.txt", b"one\ntwo\n");
4727
    write(root, "b.txt", b"bee\n");
4728
    repo.commit("base", &[]).unwrap();
4729
    let age = |p: &str| {
4730
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4731
        fs::File::options()
4732
            .write(true)
4733
            .open(root.join(p))
4734
            .unwrap()
4735
            .set_modified(old)
4736
            .unwrap();
4737
    };
4738
    age("a.txt");
4739
    age("b.txt");
4740
    assert!(
4741
        !repo.snapshot("status").unwrap().changed,
4742
        "records the aged stat"
4743
    );
4744
4745
    // Clean and equal to the base: not read at all.
4746
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4747
    let snap = repo.snapshot("status").unwrap();
4748
    assert!(
4749
        !snap.changed && snap.statuses.is_empty(),
4750
        "{:?}",
4751
        snap.statuses
4752
    );
4753
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4754
4755
    // An uncommitted edit that is older than the manifest: stat-clean, but
4756
    // its hash is not the base's, so it is read and stays visible.
4757
    write(root, "b.txt", b"bee edited\n");
4758
    age("b.txt");
4759
    let first = repo.snapshot("status").unwrap();
4760
    assert_eq!(
4761
        statuses(&first),
4762
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4763
    );
4764
    let again = repo.snapshot("status").unwrap();
4765
    assert_eq!(
4766
        statuses(&again),
4767
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4768
        "still seen once stat-clean"
4769
    );
4770
    assert!(!again.changed, "and the working copy hashes the same");
4771
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4772
    assert!(
4773
        repo.snapshot("status").is_err(),
4774
        "an edited file must be read, never taken from the base"
4775
    );
4776
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4777
4778
    // A same-size edit made just now is racy and read.
4779
    write(root, "a.txt", b"one\nTWO\n");
4780
    assert_eq!(
4781
        statuses(&repo.snapshot("status").unwrap()),
4782
        vec![
4783
            ("a.txt".to_string(), ChangeStatus::Modified),
4784
            ("b.txt".to_string(), ChangeStatus::Modified)
4785
        ]
4786
    );
4787
    // Committing makes the edits the base: both are clean and served from it again.
4788
    repo.commit("edits", &[]).unwrap();
4789
    age("a.txt");
4790
    age("b.txt");
4791
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4792
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4793
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4794
    let snap = repo.snapshot("status").unwrap();
4795
    assert!(!snap.changed && snap.statuses.is_empty());
4796
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4797
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4798
}
4799
4800
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4801
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4802
/// file is unchanged, and loading through the checkpoint equals a full load.
4803
#[test]
4804
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4805
    hermetic();
4806
    let dir = tempfile::tempdir().unwrap();
4807
    let root = dir.path();
4808
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4809
    let long: String = (0..300)
4810
        .map(|i| format!("line {i} of a long file\n"))
4811
        .collect();
4812
    write(root, "long.txt", long.as_bytes());
4813
    write(root, "short.txt", b"short\n");
4814
    repo.commit("base", &[]).unwrap();
4815
    let (r1, _, _) = repo.checkpoint().unwrap();
4816
    let cp1 = crate::objects::Checkpoint::decode(
4817
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4818
    )
4819
    .unwrap();
4820
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4821
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4822
4823
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4824
    repo.gc(true).unwrap();
4825
    assert!(repo.store().has(&graphs1[0]));
4826
    let report = repo.fsck().unwrap();
4827
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4828
4829
    // Loading through the checkpoint equals a full load.
4830
    write(root, "short.txt", b"short, edited\n");
4831
    repo.commit("edit the short file", &[]).unwrap();
4832
    let heads = repo.bookmark_heads().unwrap();
4833
    let fast = repo.load_state(&heads).unwrap();
4834
    let full = repo.load_state_full(&heads).unwrap();
4835
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4836
4837
    // The next checkpoint shares the unchanged long file's graph.
4838
    let (r2, _, _) = repo.checkpoint().unwrap();
4839
    let cp2 = crate::objects::Checkpoint::decode(
4840
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
4841
    )
4842
    .unwrap();
4843
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
4844
4845
    // A shallow clone's bundle carries the graph blob with the checkpoint.
4846
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
4847
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
4848
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
4849
4850
    // A version 1 checkpoint written by an older oxy still loads.
4851
    let state = repo.load_state_full(&heads).unwrap();
4852
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
4853
    let cp_old = crate::objects::Checkpoint {
4854
        heads: cp2.heads.clone(),
4855
        count: cp2.count,
4856
        payload: old,
4857
    };
4858
    let r_old = repo
4859
        .store()
4860
        .put(ObjectType::Checkpoint, &cp_old.encode())
4861
        .unwrap();
4862
    repo.install_checkpoint("main", &r_old).unwrap();
4863
    assert_eq!(
4864
        repo.load_state(&heads).unwrap().checkpoint_payload(),
4865
        full.checkpoint_payload()
4866
    );
4867
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4868
4869
    // A lost graph blob fails the load loudly rather than dropping the
4870
    // file, and fsck reports it (a fresh repository, objects still loose).
4871
    let dir2 = tempfile::tempdir().unwrap();
4872
    let root2 = dir2.path();
4873
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
4874
    write(root2, "long.txt", long.as_bytes());
4875
    repo2.commit("base", &[]).unwrap();
4876
    let (r, _, _) = repo2.checkpoint().unwrap();
4877
    let cp = crate::objects::Checkpoint::decode(
4878
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
4879
    )
4880
    .unwrap();
4881
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
4882
    repo2.store().remove_loose_for_test(&graph).unwrap();
4883
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
4884
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
4885
}
4886
4887
/// A new repository has not stored the user's identity yet (that happens
4888
/// at the first signed change); looking it up falls back to the key
4889
/// directory, and a file there that does not hash to the key is refused.
4890
#[test]
4891
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
4892
    hermetic();
4893
    let dir = tempfile::tempdir().unwrap();
4894
    let home = dir.path().join("home");
4895
    let mut first = Repo::init(&dir.path().join("a"))
4896
        .unwrap()
4897
        .with_home(home.clone());
4898
    let (key, _) = first
4899
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4900
        .unwrap();
4901
    let fresh = Repo::init(&dir.path().join("b"))
4902
        .unwrap()
4903
        .with_home(home.clone());
4904
    assert!(!fresh.store().has(&key), "nothing stored yet");
4905
    let id = fresh.identity(&key).unwrap();
4906
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
4907
    // A key file that is not this identity is an error, not a wrong answer.
4908
    let keys = fresh.keys_dir.clone();
4909
    let (other, _) = first
4910
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4911
        .unwrap();
4912
    fs::copy(
4913
        keys.join(format!("{}.identity", other.to_hex())),
4914
        keys.join(format!("{}.identity", key.to_hex())),
4915
    )
4916
    .unwrap();
4917
    assert!(fresh
4918
        .identity(&key)
4919
        .unwrap_err()
4920
        .to_string()
4921
        .contains("does not hold identity"));
4922
}
4923
4924
/// Status snapshots (spec §12.3): a text file whose stat matches the
4925
/// manifest, and whose base graph key is the one the manifest recorded it
4926
/// equal to, is neither read nor rendered; any edit, and any change to the
4927
/// file's graph in the base, brings it back.
4928
#[cfg(unix)]
4929
#[test]
4930
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
4931
    use std::os::unix::fs::PermissionsExt;
4932
    hermetic();
4933
    let dir = tempfile::tempdir().unwrap();
4934
    let root = dir.path();
4935
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4936
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
4937
        write(root, p, c.as_bytes());
4938
    }
4939
    repo.commit("base", &[]).unwrap();
4940
    let age = |p: &str| {
4941
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4942
        fs::File::options()
4943
            .write(true)
4944
            .open(root.join(p))
4945
            .unwrap()
4946
            .set_modified(old)
4947
            .unwrap();
4948
    };
4949
    let lock = |p: &str, mode: u32| {
4950
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
4951
    };
4952
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4953
        age(p);
4954
    }
4955
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4956
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4957
    assert!(
4958
        m.entries.values().all(|e| e.graph.is_some()),
4959
        "keys recorded"
4960
    );
4961
4962
    // Unreadable files prove they are not read; the status snapshot does
4963
    // not render them either, and its base lacks their graphs.
4964
    lock("a.txt", 0o000);
4965
    lock("b.txt", 0o000);
4966
    let snap = repo.snapshot_status("status").unwrap();
4967
    assert!(!snap.changed && snap.statuses.is_empty());
4968
    assert_eq!(
4969
        snap.base_snapshot
4970
            .unrendered
4971
            .iter()
4972
            .cloned()
4973
            .collect::<Vec<_>>(),
4974
        vec!["a.txt", "b.txt", "d/c.txt"]
4975
    );
4976
    assert!(!snap.base.is_full());
4977
    assert!(!snap.base_snapshot.is_conflicted());
4978
    // A full snapshot does not read them either, but renders everything.
4979
    let full = repo.snapshot("status").unwrap();
4980
    assert!(full.statuses.is_empty() && full.base.is_full());
4981
    assert!(full.base_snapshot.unrendered.is_empty());
4982
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
4983
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
4984
4985
    // An edit is seen; the file is rendered, the others still are not.
4986
    write(root, "d/c.txt", b"sea edited\n");
4987
    let snap = repo.snapshot_status("status").unwrap();
4988
    assert_eq!(
4989
        statuses(&snap),
4990
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
4991
    );
4992
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
4993
    // So is a mode change of an unread file.
4994
    lock("b.txt", 0o100);
4995
    assert_eq!(
4996
        statuses(&repo.snapshot_status("status").unwrap()),
4997
        vec![
4998
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
4999
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5000
        ]
5001
    );
5002
    lock("b.txt", 0o000);
5003
5004
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5005
    // stays unread, c.txt is read once and then skipped too.
5006
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5007
        .unwrap();
5008
    age("d/c.txt");
5009
    let snap = repo.snapshot_status("status").unwrap();
5010
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5011
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5012
    lock("d/c.txt", 0o000);
5013
    let snap = repo.snapshot_status("status").unwrap();
5014
    assert!(snap.statuses.is_empty());
5015
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5016
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5017
        lock(p, 0o644);
5018
    }
5019
}
5020
5021
/// Attributes decide how a file compares with the base, so a changed
5022
/// `.oxyattributes` makes every text file be compared again.
5023
#[cfg(unix)]
5024
#[test]
5025
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5026
    hermetic();
5027
    let dir = tempfile::tempdir().unwrap();
5028
    let root = dir.path();
5029
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5030
    write(root, "a.txt", b"crlf\r\n");
5031
    repo.commit("base", &[]).unwrap();
5032
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5033
    fs::File::options()
5034
        .write(true)
5035
        .open(root.join("a.txt"))
5036
        .unwrap()
5037
        .set_modified(old)
5038
        .unwrap();
5039
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5040
    assert!(repo
5041
        .snapshot_status("status")
5042
        .unwrap()
5043
        .base_snapshot
5044
        .unrendered
5045
        .contains("a.txt"));
5046
    // With eol=lf, a.txt as stored no longer equals the base.
5047
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5048
    let snap = repo.snapshot_status("status").unwrap();
5049
    assert_eq!(
5050
        statuses(&snap),
5051
        vec![
5052
            (".oxyattributes".to_string(), ChangeStatus::Added),
5053
            ("a.txt".to_string(), ChangeStatus::Modified)
5054
        ]
5055
    );
5056
}
5057
5058
/// Bookmarks with `/` in their names: pushing records their
5059
/// attestations, and checkpoints are kept for them, beside `feature`
5060
/// itself.
5061
#[test]
5062
fn bookmarks_with_slashes_push_and_checkpoint() {
5063
    hermetic();
5064
    let dir = tempfile::tempdir().unwrap();
5065
    let root = dir.path();
5066
    let origin = Repo::init(&root.join("origin")).unwrap();
5067
    let url = root.join("origin").to_string_lossy().to_string();
5068
    let mut repo = Repo::clone(&url, &root.join("r"))
5069
        .unwrap()
5070
        .with_home(root.join("home"));
5071
    // With an identity, pushes carry reference attestations: the case
5072
    // that failed, since the attestation is a file named after the bookmark.
5073
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5074
        .unwrap();
5075
    let r = root.join("r");
5076
    write(&r, "a.txt", b"a\n");
5077
    let h_a = repo.commit("a", &[]).unwrap();
5078
    assert!(repo.push("origin", false).unwrap()[0].ok);
5079
    repo.bookmark_create("feature", None).unwrap();
5080
    repo.bookmark_create("feature/x", None).unwrap();
5081
    repo.bookmark_switch("feature/x", false).unwrap();
5082
    write(&r, "b.txt", b"b\n");
5083
    let h_b = repo.commit("b", &[]).unwrap();
5084
    for name in ["feature", "feature/x"] {
5085
        let res = repo.push_bookmark("origin", name, false).unwrap();
5086
        assert!(res[0].ok, "{name}: {res:?}");
5087
    }
5088
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5089
    assert_eq!(
5090
        origin.resolve_heads("feature/x").unwrap(),
5091
        repo.resolve_heads("feature/x").unwrap()
5092
    );
5093
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5094
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5095
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5096
5097
    // A checkpoint of feature/x is found again when loading its state.
5098
    let (cp, _, _) = repo.checkpoint().unwrap();
5099
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5100
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5101
    let heads = repo.resolve_heads("feature/x").unwrap();
5102
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5103
}
5104
5105
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5106
/// never the remote's own bookmark, and a bookmark created again later is
5107
/// accepted although the deletion's attestation stays the latest.
5108
#[test]
5109
fn bookmarks_are_deleted_on_a_remote() {
5110
    hermetic();
5111
    let dir = tempfile::tempdir().unwrap();
5112
    let root = dir.path();
5113
    let origin = Repo::init(&root.join("origin")).unwrap();
5114
    let url = root.join("origin").to_string_lossy().to_string();
5115
    let mut repo = Repo::clone(&url, &root.join("r"))
5116
        .unwrap()
5117
        .with_home(root.join("home"));
5118
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5119
        .unwrap();
5120
    let r = root.join("r");
5121
    write(&r, "a.txt", b"a\n");
5122
    repo.commit("a", &[]).unwrap();
5123
    assert!(repo.push("origin", false).unwrap()[0].ok);
5124
    repo.bookmark_create("feature/x", None).unwrap();
5125
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5126
    assert!(origin.resolve_heads("feature/x").is_ok());
5127
5128
    let res = repo.push_delete("origin", "feature/x").unwrap();
5129
    assert!(res[0].ok, "{res:?}");
5130
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5131
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5132
    assert!(
5133
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5134
        "the deletion is attested"
5135
    );
5136
    assert!(
5137
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5138
        "the local bookmark stays"
5139
    );
5140
    assert!(!repo
5141
        .view()
5142
        .unwrap()
5143
        .remotes
5144
        .get("origin")
5145
        .is_some_and(|m| m.contains_key("feature/x")));
5146
5147
    // Pushing it again creates it again, past the deletion's serial.
5148
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5149
    assert!(res[0].ok, "{res:?}");
5150
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5151
5152
    // Nothing to delete, and never the remote's own bookmark.
5153
    assert!(repo.push_delete("origin", "nope").is_err());
5154
    let res = repo.push_delete("origin", "main").unwrap();
5155
    assert!(
5156
        !res[0].ok && res[0].reason.contains("default bookmark"),
5157
        "{res:?}"
5158
    );
5159
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5160
}
5161
5162
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5163
/// when the target has the same versions of the files it touches, and is
5164
/// refused, untouched, when it has others.
5165
#[test]
5166
fn switching_bookmarks_carries_uncommitted_work() {
5167
    hermetic();
5168
    let dir = tempfile::tempdir().unwrap();
5169
    let root = dir.path();
5170
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5171
    write(root, "a.txt", b"a\n");
5172
    write(root, "b.txt", b"b\n");
5173
    write(root, "gone.txt", b"gone\n");
5174
    repo.commit("base", &[]).unwrap();
5175
    repo.bookmark_create("feature", None).unwrap();
5176
    // Started on main, belongs on feature: edit, add, remove.
5177
    write(root, "a.txt", b"a\nmore\n");
5178
    write(root, "new.txt", b"new\n");
5179
    fs::remove_file(root.join("gone.txt")).unwrap();
5180
    let (report, carried) = repo.bookmark_switch_carry("feature").unwrap();
5181
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5182
    // oxygen#120: the new file was carried, not removed.
5183
    assert_eq!(
5184
        (report.removed, report.removed_paths.len()),
5185
        (0, 0),
5186
        "{report:?}"
5187
    );
5188
    assert_eq!(repo.config.bookmark, "feature");
5189
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5190
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5191
    assert!(!root.join("gone.txt").exists());
5192
    let snap = repo.snapshot("status").unwrap();
5193
    assert_eq!(
5194
        statuses(&snap),
5195
        vec![
5196
            ("a.txt".to_string(), ChangeStatus::Modified),
5197
            ("gone.txt".to_string(), ChangeStatus::Removed),
5198
            ("new.txt".to_string(), ChangeStatus::Added)
5199
        ]
5200
    );
5201
    repo.commit("the work", &[]).unwrap();
5202
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5203
5204
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5205
    repo.bookmark_switch("main", false).unwrap();
5206
    write(root, "b.txt", b"b on main\n");
5207
    repo.commit("b on main", &[]).unwrap();
5208
    repo.bookmark_switch("feature", false).unwrap();
5209
    write(root, "b.txt", b"b edited\n");
5210
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5211
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5212
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5213
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5214
}
5215
5216
/// Merging and checking out (feedback 3): a working copy without changes
5217
/// follows a merge whichever state it sat on; a refused checkout names
5218
/// what is in the way; `checkout --carry` takes the work along.
5219
#[test]
5220
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5221
    hermetic();
5222
    let dir = tempfile::tempdir().unwrap();
5223
    let root = dir.path();
5224
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5225
    write(root, "a.txt", b"a\n");
5226
    let h1 = repo.commit("a", &[]).unwrap();
5227
    write(root, "b.txt", b"b\n");
5228
    repo.commit("b", &[]).unwrap();
5229
    repo.bookmark_create("feature", None).unwrap();
5230
    repo.bookmark_switch("feature", false).unwrap();
5231
    write(root, "c.txt", b"c\n");
5232
    repo.commit("c on feature", &[]).unwrap();
5233
    repo.bookmark_switch("main", false).unwrap();
5234
    // The working copy sits on an older state than main's heads.
5235
    repo.checkout(&[h1], false, "checkout").unwrap();
5236
    assert!(!root.join("b.txt").exists());
5237
    let m = repo.merge("feature").unwrap();
5238
    assert!(m.checked_out, "a clean working copy follows the merge");
5239
    for f in ["a.txt", "b.txt", "c.txt"] {
5240
        assert!(root.join(f).exists(), "{f}");
5241
    }
5242
5243
    // A refusal says which paths are in the way and what to do.
5244
    fs::remove_file(root.join("b.txt")).unwrap();
5245
    write(root, "a.txt", b"a edited\n");
5246
    let err = repo
5247
        .checkout(&[h1], false, "checkout")
5248
        .unwrap_err()
5249
        .to_string();
5250
    assert!(
5251
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5252
        "{err}"
5253
    );
5254
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5255
    // is carried as absent (h1 has none either, so that is refused).
5256
    let err = repo
5257
        .checkout_carry(&[h1], "the first change", "checkout")
5258
        .unwrap_err()
5259
        .to_string();
5260
    assert!(
5261
        err.contains("b.txt") && err.contains("the first change"),
5262
        "{err}"
5263
    );
5264
    write(root, "b.txt", b"b\n");
5265
    let (_, carried) = repo
5266
        .checkout_carry(&[h1], "the first change", "checkout")
5267
        .unwrap();
5268
    assert_eq!(carried, vec!["a.txt"]);
5269
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5270
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5271
}
5272
5273
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5274
/// user identity not stored in a new repository yet is fine while its
5275
/// secret key is there; an added subrepo is listed as not committed yet.
5276
#[test]
5277
fn a_new_repository_is_healthy_before_its_first_commit() {
5278
    hermetic();
5279
    let dir = tempfile::tempdir().unwrap();
5280
    let root = dir.path();
5281
    let home = root.join("home");
5282
    let mut first = Repo::init(&root.join("first"))
5283
        .unwrap()
5284
        .with_home(home.clone());
5285
    let (key, _) = first
5286
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5287
        .unwrap();
5288
    let repo = Repo::init(&root.join("second"))
5289
        .unwrap()
5290
        .with_home(home.clone());
5291
    // Only the secret key: no identity object anywhere this repository sees.
5292
    let keys = repo.keys_dir.clone();
5293
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5294
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5295
    let r = repo.doctor(true);
5296
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5297
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5298
    assert!(id.message.contains("first signed change"), "{}", id.message);
5299
5300
    // A subrepo added and not committed yet is listed, pinned where it is.
5301
    let lib = root.join("lib");
5302
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5303
    write(&lib, "x.txt", b"x\n");
5304
    l.commit("x", &[]).unwrap();
5305
    let second = root.join("second");
5306
    write(&second, "a.txt", b"a\n");
5307
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5308
        .unwrap();
5309
    let subs = repo.subrepos().unwrap();
5310
    assert_eq!(subs.len(), 1);
5311
    assert_eq!(
5312
        (subs[0].path.as_str(), subs[0].committed),
5313
        ("deps/lib", false)
5314
    );
5315
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5316
    repo.commit("add lib", &[]).unwrap();
5317
    let subs = repo.subrepos().unwrap();
5318
    assert!(subs[0].committed, "committed now");
5319
}
5320
5321
/// Commit, diff, hunks and discard use the partial snapshot: a file
5322
/// unchanged since the manifest is neither read nor rendered, and showing
5323
/// a change renders only what it edits, the same as from a full base.
5324
#[cfg(unix)]
5325
#[test]
5326
fn commits_and_diffs_leave_unchanged_files_alone() {
5327
    use std::os::unix::fs::PermissionsExt;
5328
    hermetic();
5329
    let dir = tempfile::tempdir().unwrap();
5330
    let root = dir.path();
5331
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5332
    write(root, "big.txt", b"lots\nof\nlines\n");
5333
    write(root, "a.txt", b"one\ntwo\n");
5334
    repo.commit("base", &[]).unwrap();
5335
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5336
    for f in ["big.txt", "a.txt"] {
5337
        fs::File::options()
5338
            .write(true)
5339
            .open(root.join(f))
5340
            .unwrap()
5341
            .set_modified(old)
5342
            .unwrap();
5343
    }
5344
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5345
    // big.txt cannot be read at all from here on.
5346
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5347
5348
    write(root, "a.txt", b"one\nTWO\nthree\n");
5349
    let diff = repo.diff_files(None).unwrap();
5350
    assert_eq!(
5351
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5352
        ["a.txt"]
5353
    );
5354
    let (_, hunks) = repo.hunks().unwrap();
5355
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5356
    let h = repo.commit("edit a", &[]).unwrap();
5357
5358
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5359
    let c = repo.store().get_change(&h).unwrap();
5360
    let full = repo.load_state(&c.deps).unwrap();
5361
    let want = render_change(&c, &full, &full.materialize());
5362
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5363
    let (base, snap) = repo.change_base(&c).unwrap();
5364
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5365
5366
    // Discarding works the same way.
5367
    write(root, "a.txt", b"scratch\n");
5368
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5369
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5370
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5371
}
5372
5373
/// A replace conflict (spec §9.3) is settled by a change that writes one
5374
/// candidate, or new bytes, at the path when the caller names it; a plain
5375
/// snapshot of a checkout never settles it on its own.
5376
#[test]
5377
fn replace_conflicts_are_settled_when_asked() {
5378
    hermetic();
5379
    let dir = tempfile::tempdir().unwrap();
5380
    let root = dir.path();
5381
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5382
    let blob = |n: u8| {
5383
        let mut v = vec![0u8; 64];
5384
        v[1] = n;
5385
        v
5386
    };
5387
    write(root, "img.bin", &blob(1));
5388
    repo.commit("add img", &[]).unwrap();
5389
    repo.bookmark_create("other", None).unwrap();
5390
    write(root, "img.bin", &blob(2));
5391
    repo.commit("img two", &[]).unwrap();
5392
    repo.bookmark_switch("other", false).unwrap();
5393
    write(root, "img.bin", &blob(3));
5394
    repo.commit("img three", &[]).unwrap();
5395
    repo.bookmark_switch("main", false).unwrap();
5396
    repo.merge("other").unwrap();
5397
    let heads = repo.bookmark_heads().unwrap();
5398
    let merged = repo.load_state(&heads).unwrap().materialize();
5399
    assert!(
5400
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5401
        "a replace conflict"
5402
    );
5403
    // A snapshot of the checkout records nothing.
5404
    assert!(repo
5405
        .snapshot("status")
5406
        .unwrap()
5407
        .statuses
5408
        .iter()
5409
        .all(|s| s.path != "img.bin"));
5410
5411
    // Keeping candidate 3 settles it.
5412
    let author = repo.author();
5413
    let edits = [FileEdit {
5414
        path: "img.bin".into(),
5415
        content: Some(blob(3)),
5416
    }];
5417
    let c = repo
5418
        .build_change(&heads, &edits, "keep three", author)
5419
        .unwrap();
5420
    assert_eq!(c.kind, ChangeKind::Resolution);
5421
    let mut st = repo.load_state(&heads).unwrap();
5422
    for d in &c.deps {
5423
        assert!(st.contains(d));
5424
    }
5425
    assert!(
5426
        heads.iter().all(|h| c.deps.contains(h)),
5427
        "depends on both contributors"
5428
    );
5429
    st.add(c).unwrap();
5430
    let after = st.materialize();
5431
    assert!(!after.is_conflicted());
5432
    assert_eq!(
5433
        after.files["img.bin"].content,
5434
        FileContent::Opaque {
5435
            blobs: vec![Repo::blob_ref(&blob(3))]
5436
        }
5437
    );
5438
5439
    // New bytes settle it too.
5440
    let edits = [FileEdit {
5441
        path: "img.bin".into(),
5442
        content: Some(blob(9)),
5443
    }];
5444
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5445
    let mut st = repo.load_state(&heads).unwrap();
5446
    st.add(c).unwrap();
5447
    assert_eq!(
5448
        st.materialize().files["img.bin"].content,
5449
        FileContent::Opaque {
5450
            blobs: vec![Repo::blob_ref(&blob(9))]
5451
        }
5452
    );
5453
}
5454
5455
/// The history of a range of lines (spec §27): the changes that wrote
5456
/// or deleted its atoms, or deleted atoms from between them; edits outside
5457
/// the range and changes the range's lines survived are not in it.
5458
#[test]
5459
fn line_ranges_have_exact_histories() {
5460
    hermetic();
5461
    let dir = tempfile::tempdir().unwrap();
5462
    let root = dir.path();
5463
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5464
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5465
    let base = repo.commit("add f", &[]).unwrap();
5466
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5467
    let outside = repo.commit("change the import", &[]).unwrap();
5468
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5469
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5470
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5471
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5472
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5473
    let after = repo.commit("add b after a", &[]).unwrap();
5474
    let heads = repo.bookmark_heads().unwrap();
5475
5476
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5477
    let hist: Vec<ChangeHash> = repo
5478
        .line_history(&heads, "f.rs", 2, 4)
5479
        .unwrap()
5480
        .iter()
5481
        .map(|e| e.hash)
5482
        .collect();
5483
    for (h, what) in [
5484
        (base, "wrote it"),
5485
        (inside, "edited a line"),
5486
        (deleted, "deleted a line from inside"),
5487
    ] {
5488
        assert!(hist.contains(&h), "{what}");
5489
    }
5490
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5491
        assert!(!hist.contains(&h), "{what}");
5492
    }
5493
    assert_eq!(hist[0], deleted, "newest first");
5494
    // One line: only what touched it.
5495
    let one: Vec<ChangeHash> = repo
5496
        .line_history(&heads, "f.rs", 1, 1)
5497
        .unwrap()
5498
        .iter()
5499
        .map(|e| e.hash)
5500
        .collect();
5501
    assert!(one.contains(&outside) && !one.contains(&inside));
5502
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5503
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5504
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5505
}
5506
5507
#[test]
5508
fn receipts_are_kept_with_their_state_and_verified() {
5509
    use crate::receipt::{Receipt, SignedReceipt};
5510
    hermetic();
5511
    let dir = tempfile::tempdir().unwrap();
5512
    let root = dir.path();
5513
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5514
    write(root, "a.txt", b"1\n");
5515
    repo.commit("A", &[]).unwrap();
5516
    let heads = repo.bookmark_heads().unwrap();
5517
    let state = repo
5518
        .store()
5519
        .put_state(&StateObject::new(heads.clone()))
5520
        .unwrap();
5521
    let out = repo.store_blob(b"built\n").unwrap();
5522
    let receipt = Receipt {
5523
        job_name: "build".into(),
5524
        pipeline_hash: ObjectRef([1; 32]),
5525
        scope_tree_hash: ObjectRef([2; 32]),
5526
        inputs: vec![],
5527
        environment: ObjectRef([3; 32]),
5528
        outputs: vec![out],
5529
        exit_code: 0,
5530
        duration_ms: 42,
5531
    };
5532
    let sk = SecretKey::generate();
5533
    let runner = sk.identity("earth-1", "runner@earth", 1);
5534
    let sr = SignedReceipt::sign(
5535
        receipt.clone(),
5536
        repo.id().unwrap(),
5537
        state,
5538
        "demo#1",
5539
        &runner,
5540
        &sk,
5541
    );
5542
5543
    let r = repo.add_receipt(&sr).unwrap();
5544
    let found = repo.receipts(&heads).unwrap();
5545
    assert_eq!(found.len(), 1);
5546
    assert_eq!(found[0].attest, r);
5547
    assert_eq!(found[0].signed, sr);
5548
    assert!(found[0].problem.is_none() && !found[0].revoked);
5549
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5550
5551
    // Another repository's receipt, or a forged one, is refused.
5552
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5553
    assert!(repo
5554
        .add_receipt(&elsewhere)
5555
        .unwrap_err()
5556
        .to_string()
5557
        .contains("another repository"));
5558
    let mut forged = sr.clone();
5559
    forged.receipt.exit_code = 1;
5560
    assert!(repo
5561
        .add_receipt(&forged)
5562
        .unwrap_err()
5563
        .to_string()
5564
        .contains("does not verify"));
5565
5566
    // gc keeps the receipt, its runner and its output while the state lives.
5567
    repo.gc(true).unwrap();
5568
    assert_eq!(repo.receipts(&heads).unwrap().len(), 1);
5569
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5570
    assert!(repo.fsck().unwrap().problems.is_empty());
5571
}
5572
5573
#[test]
5574
fn status_leaves_an_unchanged_manifest_alone() {
5575
    hermetic();
5576
    let dir = tempfile::tempdir().unwrap();
5577
    let root = dir.path();
5578
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5579
    write(root, "a.txt", b"1\n");
5580
    write(root, "b.txt", b"2\n");
5581
    repo.commit("A", &[]).unwrap();
5582
    // Files last touched well outside the racy window.
5583
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5584
    for f in ["a.txt", "b.txt"] {
5585
        fs::File::options()
5586
            .write(true)
5587
            .open(root.join(f))
5588
            .unwrap()
5589
            .set_modified(old)
5590
            .unwrap();
5591
    }
5592
    repo.snapshot_status("status").unwrap();
5593
    let path = repo.manifest_path();
5594
    let first = fs::read(&path).unwrap();
5595
    repo.snapshot_status("status").unwrap();
5596
    assert_eq!(
5597
        fs::read(&path).unwrap(),
5598
        first,
5599
        "an unchanged tree does not rewrite the manifest"
5600
    );
5601
    // A change rewrites it.
5602
    write(root, "a.txt", b"1\n2\n");
5603
    repo.snapshot_status("status").unwrap();
5604
    assert_ne!(fs::read(&path).unwrap(), first);
5605
}
5606
5607
#[test]
5608
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5609
    hermetic();
5610
    let dir = tempfile::tempdir().unwrap();
5611
    let root = dir.path();
5612
    let origin_path = root.join("origin");
5613
    Repo::init(&origin_path).unwrap();
5614
    let origin_url = origin_path.to_string_lossy().to_string();
5615
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5616
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5617
    write(&root.join("a"), "big.txt", big.as_bytes());
5618
    write(&root.join("a"), "small.txt", b"small\n");
5619
    let h1 = a.commit("large", &[]).unwrap();
5620
    let (_, body) = a.store().get(&h1).unwrap();
5621
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5622
    assert!(a.push("origin", false).unwrap()[0].ok);
5623
5624
    // A clone reads the text from the blobs that came with the change.
5625
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5626
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5627
    // An edit in the middle of the stored insert is an ordinary change.
5628
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5629
    write(&root.join("b"), "big.txt", edited.as_bytes());
5630
    let h2 = b.commit("edit", &[]).unwrap();
5631
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5632
    assert!(b.push("origin", false).unwrap()[0].ok);
5633
    assert!(a.pull("origin").unwrap().checked_out);
5634
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5635
    assert_eq!(
5636
        a.fsck().unwrap().errors(),
5637
        0,
5638
        "{:?}",
5639
        a.fsck().unwrap().problems
5640
    );
5641
5642
    // With zero retention gc keeps the text blobs of every kept change.
5643
    let mut a = Repo::open(&root.join("a")).unwrap();
5644
    a.config.set("core.op-retention", "0").unwrap();
5645
    a.save_config().unwrap();
5646
    let a = Repo::open(&root.join("a")).unwrap();
5647
    a.gc(true).unwrap();
5648
    let a = Repo::open(&root.join("a")).unwrap();
5649
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5650
    assert_eq!(
5651
        a.fsck().unwrap().errors(),
5652
        0,
5653
        "{:?}",
5654
        a.fsck().unwrap().problems
5655
    );
5656
    // And a clone of the packed repository reads them from its packs.
5657
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5658
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5659
    drop(c);
5660
}
5661
5662
#[test]
5663
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5664
    hermetic();
5665
    let dir = tempfile::tempdir().unwrap();
5666
    let root = dir.path();
5667
    let repo = Repo::init(root).unwrap();
5668
    write(root, "a.txt", b"a\n");
5669
    let a = repo.commit("a", &[]).unwrap();
5670
    write(root, "b.txt", b"b\n");
5671
    repo.commit("b", &[]).unwrap();
5672
    let (x, op) = repo.head_op().unwrap();
5673
    let ws = *op.view.workspaces.keys().next().unwrap();
5674
    let mut one = op.view.clone();
5675
    one.workspaces.insert(ws, a);
5676
    let mut two = op.view.clone();
5677
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5678
    let first = repo.record_op(&[x], "one", one).unwrap();
5679
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5680
    assert!(
5681
        e.to_string()
5682
            .contains("changed this working copy at the same time"),
5683
        "{e}"
5684
    );
5685
    assert_eq!(
5686
        repo.head_op().unwrap().0,
5687
        first,
5688
        "the second is not recorded"
5689
    );
5690
}
5691
5692
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5693
/// rewrote the working copy recorded the half-written files as edits, and
5694
/// its view replaced the switch's.
5695
#[test]
5696
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5697
    hermetic();
5698
    let dir = tempfile::tempdir().unwrap();
5699
    let root = dir.path().to_path_buf();
5700
    let mut repo = Repo::init(&root).unwrap();
5701
    write(&root, "keep.txt", b"keep\n");
5702
    repo.commit("base", &[]).unwrap();
5703
    repo.bookmark_create("small", None).unwrap();
5704
    for i in 0..300 {
5705
        write(
5706
            &root,
5707
            &format!("many/f{i}.txt"),
5708
            format!("file {i}\n").as_bytes(),
5709
        );
5710
    }
5711
    repo.commit("many", &[]).unwrap();
5712
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5713
    let watcher = {
5714
        let (root, stop) = (root.clone(), stop.clone());
5715
        std::thread::spawn(move || {
5716
            let r = Repo::open(&root).unwrap();
5717
            let mut ran = 0;
5718
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
5719
                if r.snapshot_status("oxy status").is_ok() {
5720
                    ran += 1;
5721
                }
5722
            }
5723
            ran
5724
        })
5725
    };
5726
    for i in 0..20 {
5727
        let to = if i % 2 == 0 { "small" } else { "main" };
5728
        repo.bookmark_switch(to, false).unwrap();
5729
    }
5730
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
5731
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
5732
    // Back on main, clean, with every file where main has it.
5733
    let repo = Repo::open(&root).unwrap();
5734
    let s = repo.snapshot_status("oxy status").unwrap();
5735
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
5736
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
5737
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
5738
    assert!(root.join("many/f299.txt").exists());
5739
}
5740
5741
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
5742
/// put a subrepo that was ahead of its pin back at the pin and moved the
5743
/// subrepo's own bookmark backwards.
5744
#[test]
5745
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
5746
    hermetic();
5747
    let dir = tempfile::tempdir().unwrap();
5748
    let root = dir.path();
5749
    Repo::init(&root.join("lib-origin")).unwrap();
5750
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5751
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
5752
    write(&root.join("lib"), "lib.txt", b"v1\n");
5753
    lib.commit("lib v1", &[]).unwrap();
5754
    assert!(lib.push("origin", false).unwrap()[0].ok);
5755
5756
    let app_dir = root.join("app");
5757
    let mut app = Repo::init(&app_dir).unwrap();
5758
    write(&app_dir, "main.txt", b"app\n");
5759
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5760
    app.commit("app with lib", &[]).unwrap();
5761
    app.bookmark_create("feature", None).unwrap();
5762
5763
    // New work in the subrepo, not yet pinned by the parent.
5764
    let nested_dir = app_dir.join("libs/lib");
5765
    let nested = Repo::open(&nested_dir).unwrap();
5766
    write(&nested_dir, "new.txt", b"new\n");
5767
    let l2 = nested.commit("lib: new file", &[]).unwrap();
5768
    drop(nested);
5769
5770
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
5771
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
5772
    let nested = Repo::open(&nested_dir).unwrap();
5773
    assert!(
5774
        nested.bookmark_heads().unwrap().contains(&l2),
5775
        "its bookmark kept its work"
5776
    );
5777
    assert!(nested_dir.join("new.txt").exists(), "and its files");
5778
    let s = app.snapshot("status").unwrap();
5779
    assert_eq!(
5780
        statuses(&s),
5781
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
5782
    );
5783
}
5784
5785
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
5786
/// moving `main` to a change this clone had pushed on another bookmark,
5787
/// the first `pull` said "Already up to date" while `main` was behind.
5788
#[test]
5789
fn pull_takes_a_remote_move_to_changes_already_here() {
5790
    hermetic();
5791
    let dir = tempfile::tempdir().unwrap();
5792
    let root = dir.path();
5793
    let origin_path = root.join("origin");
5794
    let origin = Repo::init(&origin_path).unwrap();
5795
    let url = origin_path.to_string_lossy().to_string();
5796
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
5797
    write(&root.join("b"), "base.txt", b"base\n");
5798
    b.commit("base", &[]).unwrap();
5799
    assert!(b.push("origin", false).unwrap()[0].ok);
5800
5801
    // A feature bookmark with one change, pushed.
5802
    b.bookmark_create("feat", None).unwrap();
5803
    b.bookmark_switch("feat", false).unwrap();
5804
    write(&root.join("b"), "x.txt", b"x\n");
5805
    let x = b.commit("x", &[]).unwrap();
5806
    assert!(b.push("origin", false).unwrap()[0].ok);
5807
    b.bookmark_switch("main", false).unwrap();
5808
5809
    // The remote lands it: its main moves to the feature's state.
5810
    let feat = origin
5811
        .store()
5812
        .get_state(&origin.view().unwrap().bookmarks["feat"])
5813
        .unwrap()
5814
        .heads;
5815
    origin.bookmark_set("main", &feat).unwrap();
5816
5817
    let r = b.pull("origin").unwrap();
5818
    assert!(r.changed, "{r:?}");
5819
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
5820
    let main = b
5821
        .bookmarks()
5822
        .unwrap()
5823
        .into_iter()
5824
        .find(|m| m.name == "main")
5825
        .unwrap();
5826
    assert_eq!(main.behind, Some(0), "{main:?}");
5827
}
5828
5829
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
5830
/// to one only the remote has makes a local bookmark from it; a pull moves
5831
/// every local bookmark the remote has too; a clone checks out the remote's
5832
/// default bookmark.
5833
#[test]
5834
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
5835
    hermetic();
5836
    let dir = tempfile::tempdir().unwrap();
5837
    let root = dir.path();
5838
    let origin_path = root.join("origin");
5839
    let mut origin = Repo::init(&origin_path).unwrap();
5840
    let url = origin_path.to_string_lossy().to_string();
5841
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
5842
    write(&root.join("a"), "base.txt", b"base\n");
5843
    a.commit("base", &[]).unwrap();
5844
    assert!(a.push("origin", false).unwrap()[0].ok);
5845
    a.bookmark_create("develop", None).unwrap();
5846
    a.bookmark_switch("develop", false).unwrap();
5847
    write(&root.join("a"), "base.txt", b"base\nd1\n");
5848
    let d1 = a.commit("d1", &[]).unwrap();
5849
    assert!(a.push("origin", false).unwrap()[0].ok);
5850
5851
    // A clone has main only; origin/develop is a name all the same.
5852
    let c_root = root.join("c");
5853
    let mut c = Repo::clone(&url, &c_root).unwrap();
5854
    assert_eq!(c.config.bookmark, "main");
5855
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
5856
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
5857
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
5858
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
5859
5860
    // Switching makes the local bookmark from origin's.
5861
    c.bookmark_switch("develop", false).unwrap();
5862
    assert_eq!(c.config.bookmark, "develop");
5863
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
5864
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
5865
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
5866
    assert!(c.bookmark_switch("nowhere", false).is_err());
5867
5868
    // Both bookmarks move on the remote; one pull takes both.
5869
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
5870
    let d2 = a.commit("d2", &[]).unwrap();
5871
    assert!(a.push("origin", false).unwrap()[0].ok);
5872
    a.bookmark_switch("main", false).unwrap();
5873
    write(&root.join("a"), "m.txt", b"m\n");
5874
    let m = a.commit("m", &[]).unwrap();
5875
    assert!(a.push("origin", false).unwrap()[0].ok);
5876
    let r = c.pull("origin").unwrap();
5877
    assert!(r.changed && r.checked_out, "{r:?}");
5878
    assert_eq!(r.heads, vec![d2]);
5879
    assert_eq!(r.others, vec!["main".to_string()]);
5880
    assert!(c.resolve_heads("main").unwrap().contains(&m));
5881
    assert_eq!(
5882
        fs::read(c_root.join("base.txt")).unwrap(),
5883
        b"base\nd1\nd2\n"
5884
    );
5885
    let again = c.pull("origin").unwrap();
5886
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
5887
5888
    // A clone checks out the remote's default bookmark.
5889
    origin.config.set("workspace.bookmark", "develop").unwrap();
5890
    origin.save_config().unwrap();
5891
    let e = Repo::clone(&url, &root.join("e")).unwrap();
5892
    assert_eq!(e.config.bookmark, "develop");
5893
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
5894
    let reopened = Repo::open(&root.join("e")).unwrap();
5895
    assert_eq!(reopened.config.bookmark, "develop");
5896
    // REMOTE/NAME names the remote's bookmark to switch to.
5897
    let mut e = reopened;
5898
    e.bookmark_switch("origin/main", false).unwrap();
5899
    assert_eq!(e.config.bookmark, "main");
5900
    assert!(e.bookmark_heads().unwrap().contains(&m));
5901
}
5902
5903
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
5904
/// op restore goes back to an operation, files included, and undo takes
5905
/// the restore back whole; op revert undoes one operation alone; each
5906
/// operation's changes are described from the views.
5907
#[test]
5908
fn operations_can_be_read_restored_and_reverted() {
5909
    hermetic();
5910
    let dir = tempfile::tempdir().unwrap();
5911
    let root = dir.path();
5912
    let repo = Repo::init(root).unwrap();
5913
    write(root, "a.txt", b"a\n");
5914
    let first = repo.commit("first", &[]).unwrap();
5915
    write(root, "a.txt", b"a\nb\n");
5916
    let second = repo.commit("second", &[]).unwrap();
5917
    let at_second = repo.head_op().unwrap().0.to_hex();
5918
    repo.bookmark_create("keep", None).unwrap();
5919
    let created = repo.head_op().unwrap().0.to_hex();
5920
    write(root, "n.txt", b"n\n");
5921
    let third = repo.commit("third", &[]).unwrap();
5922
5923
    // What each operation changed.
5924
    let ops = repo.op_log().unwrap();
5925
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
5926
    assert!(
5927
        changes
5928
            .iter()
5929
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
5930
        "{changes:?}"
5931
    );
5932
    assert!(changes
5933
        .iter()
5934
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
5935
5936
    // Reading at an earlier operation.
5937
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
5938
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
5939
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
5940
    write(root, "z.txt", b"z\n");
5941
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
5942
    fs::remove_file(root.join("z.txt")).unwrap();
5943
    assert!(repo.resolve_op("zz").is_err());
5944
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
5945
5946
    // Restore goes back, files and all; undo takes it back whole.
5947
    repo.op_restore(&at_second, false).unwrap();
5948
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
5949
    assert!(!root.join("n.txt").exists());
5950
    repo.undo().unwrap();
5951
    let mut heads = repo.bookmark_heads().unwrap();
5952
    heads.sort();
5953
    let mut want = vec![second, third];
5954
    want.sort();
5955
    assert_eq!(heads, want);
5956
    assert!(
5957
        root.join("n.txt").exists(),
5958
        "the files came back with the undo"
5959
    );
5960
5961
    // Revert the bookmark's creation alone: the commit after it stays.
5962
    let r = repo.op_revert(&created).unwrap();
5963
    assert_eq!(r.reverted, vec!["keep".to_string()]);
5964
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
5965
    assert!(repo
5966
        .load_state(&repo.bookmark_heads().unwrap())
5967
        .unwrap()
5968
        .contains(&third));
5969
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
5970
    let _ = first;
5971
}
5972
5973
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
5974
/// from the status cache while every file is as the snapshot left it, and
5975
/// from a snapshot again as soon as one is not.
5976
#[test]
5977
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
5978
    hermetic();
5979
    let dir = tempfile::tempdir().unwrap();
5980
    let root = dir.path();
5981
    let repo = Repo::init(root).unwrap();
5982
    write(root, "a.txt", b"a\n");
5983
    write(root, "b.txt", b"b\n");
5984
    repo.commit("base", &[]).unwrap();
5985
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
5986
5987
    write(root, "a.txt", b"a\nmore\n");
5988
    assert_eq!(
5989
        repo.status_by_manifest().unwrap(),
5990
        None,
5991
        "no snapshot of the edit yet"
5992
    );
5993
    let snap = repo.snapshot_status("oxy status").unwrap();
5994
    assert_eq!(snap.statuses.len(), 1);
5995
    let cached = repo
5996
        .status_by_manifest()
5997
        .unwrap()
5998
        .expect("answered from the cache");
5999
    assert_eq!(cached.len(), 1);
6000
    assert_eq!(
6001
        (cached[0].path.as_str(), cached[0].status),
6002
        ("a.txt", ChangeStatus::Modified)
6003
    );
6004
6005
    // Any further change sends status back to a snapshot.
6006
    write(root, "a.txt", b"a\nmore\nand more\n");
6007
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6008
    repo.snapshot_status("oxy status").unwrap();
6009
    assert!(repo.status_by_manifest().unwrap().is_some());
6010
    write(root, "new.txt", b"n\n");
6011
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6012
    fs::remove_file(root.join("new.txt")).unwrap();
6013
    assert!(
6014
        repo.status_by_manifest().unwrap().is_some(),
6015
        "back as it was"
6016
    );
6017
    fs::remove_file(root.join("b.txt")).unwrap();
6018
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6019
    write(root, "b.txt", b"b\n");
6020
6021
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6022
    repo.snapshot_status("oxy status").unwrap();
6023
    repo.commit("more", &[]).unwrap();
6024
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6025
}
6026
6027
/// oxygen#41: while the status cache holds, the working copy's diff is
6028
/// rendered from the stored working-copy change, and says exactly what a
6029
/// snapshot's diff says.
6030
#[test]
6031
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6032
    hermetic();
6033
    let dir = tempfile::tempdir().unwrap();
6034
    let root = dir.path();
6035
    let repo = Repo::init(root).unwrap();
6036
    write(root, "a.txt", b"one\ntwo\nthree\n");
6037
    write(root, "gone.txt", b"bye\n");
6038
    repo.commit("base", &[]).unwrap();
6039
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6040
    write(root, "new.txt", b"hello\n");
6041
    fs::remove_file(root.join("gone.txt")).unwrap();
6042
    let snap = repo.snapshot_status("oxy status").unwrap();
6043
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6044
    assert!(
6045
        repo.status_by_manifest().unwrap().is_some(),
6046
        "the cache holds"
6047
    );
6048
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6049
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6050
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6051
}
6052
6053
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6054
/// while none has moved, the check stats the tracked files without listing
6055
/// the tree, and a file added or removed anywhere moves its directory's
6056
/// time, so the tree is listed again.
6057
#[test]
6058
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6059
    hermetic();
6060
    let dir = tempfile::tempdir().unwrap();
6061
    let root = dir.path();
6062
    let repo = Repo::init(root).unwrap();
6063
    write(root, "a.txt", b"a\n");
6064
    write(root, "sub/deep/b.txt", b"b\n");
6065
    repo.commit("base", &[]).unwrap();
6066
    // Out of the racy window: every file and directory a minute old.
6067
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6068
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6069
        fs::File::open(root.join(p))
6070
            .unwrap()
6071
            .set_modified(old)
6072
            .unwrap();
6073
    }
6074
    repo.snapshot_status("oxy status").unwrap();
6075
    repo.write_manifest(false, false).unwrap();
6076
    let m = repo.read_manifest().unwrap().unwrap().2;
6077
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6078
    assert_eq!(
6079
        repo.disk_differs_by_dirs(&m),
6080
        Some(false),
6081
        "no listing needed"
6082
    );
6083
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6084
6085
    // A same-size edit with a new time: found by its stat.
6086
    write(root, "sub/deep/b.txt", b"c\n");
6087
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6088
    write(root, "sub/deep/b.txt", b"b\n");
6089
    fs::File::open(root.join("sub/deep/b.txt"))
6090
        .unwrap()
6091
        .set_modified(old)
6092
        .unwrap();
6093
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6094
6095
    // A new file moves its directory's time: the tree must be listed.
6096
    write(root, "sub/deep/new.txt", b"n\n");
6097
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6098
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6099
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6100
    // A removed one too.
6101
    fs::remove_file(root.join("a.txt")).unwrap();
6102
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6103
}
6104
6105
/// oxygen#41: a commit right after a status takes the snapshot the status
6106
/// left (the status cache holds) rather than walking again, and commits
6107
/// exactly what a snapshot would have.
6108
#[test]
6109
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6110
    hermetic();
6111
    let dir = tempfile::tempdir().unwrap();
6112
    let root = dir.path();
6113
    let repo = Repo::init(root).unwrap();
6114
    write(root, "a.txt", b"a\nb\n");
6115
    write(root, ".oxyattributes", b"*.bin binary\n");
6116
    repo.commit("base", &[]).unwrap();
6117
    write(root, "a.txt", b"a\nB\n");
6118
    write(root, "new.txt", b"new\n");
6119
    let snap = repo.snapshot_status("oxy status").unwrap();
6120
    let cached = repo
6121
        .snapshot_from_cache()
6122
        .unwrap()
6123
        .expect("the cache holds");
6124
    assert_eq!(cached.wc_hash, snap.wc_hash);
6125
    assert_eq!(cached.statuses, snap.statuses);
6126
    assert!(
6127
        !cached.attributes.is_empty(),
6128
        "the .oxyattributes file was read"
6129
    );
6130
    let h = repo.commit("edit", &[]).unwrap();
6131
    let c = repo.store().get_change(&h).unwrap();
6132
    assert_eq!(
6133
        c.tree_ops.len() + c.edits.len(),
6134
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6135
    );
6136
    assert_eq!(
6137
        repo.status_by_manifest().unwrap(),
6138
        Some(vec![]),
6139
        "clean after the commit"
6140
    );
6141
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6142
}
6143
6144
/// oxygen#41: a clean check that verified racy entries restamps the
6145
/// manifest, so later checks can trust them, and a same-size rewrite
6146
/// straight afterwards is still found: entries within two seconds of the
6147
/// new time stay racy.
6148
#[test]
6149
fn a_verified_clean_check_restamps_the_manifest_safely() {
6150
    hermetic();
6151
    let dir = tempfile::tempdir().unwrap();
6152
    let root = dir.path();
6153
    let repo = Repo::init(root).unwrap();
6154
    write(root, "a.txt", b"one\n");
6155
    repo.commit("one", &[]).unwrap();
6156
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6157
    assert!(repo.clean_by_manifest().unwrap());
6158
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6159
    assert!(after > before, "restamped");
6160
    write(root, "a.txt", b"two\n");
6161
    assert!(
6162
        !repo.clean_by_manifest().unwrap(),
6163
        "a same-size rewrite is still seen"
6164
    );
6165
}
6166
6167
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6168
/// stored insert's text blob only when it builds that file's graph, and
6169
/// builds the same graph a full load does.
6170
#[test]
6171
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6172
    hermetic();
6173
    let dir = tempfile::tempdir().unwrap();
6174
    let root = dir.path();
6175
    let repo = Repo::init(root).unwrap();
6176
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6177
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6178
    write(root, "big.txt", big.as_bytes());
6179
    write(root, "other.txt", other.as_bytes());
6180
    let h = repo.commit("two large files", &[]).unwrap();
6181
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6182
    let h2 = repo.commit("append", &[]).unwrap();
6183
6184
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6185
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6186
        FileContent::Text { bytes, .. } => bytes.clone(),
6187
        other => panic!("{other:?}"),
6188
    };
6189
    // Built on demand, every graph renders as the full load's.
6190
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6191
    let big_node = full.files["big.txt"].node;
6192
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6193
    repo.load_all_graphs(&mut hist).unwrap();
6194
    let rendered = hist.materialize();
6195
    for p in ["big.txt", "other.txt"] {
6196
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6197
    }
6198
6199
    // Without other.txt's text blob, history still loads and big.txt still
6200
    // builds: nothing read the other text.
6201
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6202
    assert_eq!(texts.len(), 2);
6203
    let content = |r: &ObjectRef| -> Vec<u8> {
6204
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6205
        blob.chunks
6206
            .iter()
6207
            .flat_map(|c| repo.store().get(c).unwrap().1)
6208
            .collect()
6209
    };
6210
    let other_text = texts
6211
        .iter()
6212
        .filter_map(|t| match t {
6213
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6214
            _ => None,
6215
        })
6216
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6217
        .unwrap();
6218
    repo.store().remove_loose_for_test(&other_text).unwrap();
6219
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6220
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6221
    assert!(repo
6222
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6223
        .is_err());
6224
}
6225
6226
/// oxygen#35: the first status after a commit read and rendered every
6227
/// file (79 s and more than 14 GB on the Linux tree), because the
6228
/// manifest had no graph keys for files the commit added.
6229
#[test]
6230
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6231
    use std::os::unix::fs::PermissionsExt;
6232
    hermetic();
6233
    let dir = tempfile::tempdir().unwrap();
6234
    let root = dir.path();
6235
    let repo = Repo::init(root).unwrap();
6236
    let files = ["a.txt", "b.txt", "d/c.txt"];
6237
    for p in files {
6238
        write(root, p, format!("{p}\n").as_bytes());
6239
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6240
        fs::File::options()
6241
            .write(true)
6242
            .open(root.join(p))
6243
            .unwrap()
6244
            .set_modified(old)
6245
            .unwrap();
6246
    }
6247
    repo.commit("added", &[]).unwrap();
6248
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6249
    assert!(
6250
        m.entries.values().all(|e| e.graph.is_some()),
6251
        "keys recorded at commit"
6252
    );
6253
    // Unreadable files prove the next status reads none of them.
6254
    for p in files {
6255
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6256
    }
6257
    let snap = repo.snapshot_status("status").unwrap();
6258
    for p in files {
6259
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6260
    }
6261
    assert!(!snap.changed && snap.statuses.is_empty());
6262
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6263
}
6264
6265
/// oxygen#35: a checkout reads, renders and writes only the files whose
6266
/// graphs differ, and renders the rest a batch at a time.
6267
#[test]
6268
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6269
    use std::os::unix::fs::PermissionsExt;
6270
    hermetic();
6271
    let dir = tempfile::tempdir().unwrap();
6272
    let root = dir.path();
6273
    let origin = root.join("origin");
6274
    let mut repo = Repo::init(&origin).unwrap();
6275
    // More files than one batch holds.
6276
    let n = 2100;
6277
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6278
    for i in 0..n {
6279
        let p = format!("f/{i:04}.txt");
6280
        write(&origin, &p, format!("file {i}\n").as_bytes());
6281
        fs::File::options()
6282
            .write(true)
6283
            .open(origin.join(&p))
6284
            .unwrap()
6285
            .set_modified(old)
6286
            .unwrap();
6287
    }
6288
    repo.commit("many", &[]).unwrap();
6289
    repo.bookmark_create("feature", None).unwrap();
6290
    repo.bookmark_switch("feature", false).unwrap();
6291
    write(&origin, "f/0007.txt", b"changed\n");
6292
    repo.commit("one change", &[]).unwrap();
6293
6294
    // Switching back to main must not read the unchanged files.
6295
    for i in 0..n {
6296
        if i != 7 {
6297
            let p = origin.join(format!("f/{i:04}.txt"));
6298
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6299
        }
6300
    }
6301
    let r = repo.bookmark_switch("main", false).unwrap();
6302
    for i in 0..n {
6303
        let p = origin.join(format!("f/{i:04}.txt"));
6304
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6305
    }
6306
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6307
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6308
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6309
6310
    // A clone renders every file, across batches.
6311
    let c = root.join("clone");
6312
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6313
    for i in [0, 2047, 2048, n - 1] {
6314
        assert_eq!(
6315
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6316
            format!("file {i}\n").as_bytes()
6317
        );
6318
    }
6319
    let cloned = Repo::open(&c).unwrap();
6320
    assert!(cloned
6321
        .snapshot_status("status")
6322
        .unwrap()
6323
        .statuses
6324
        .is_empty());
6325
}
6326
6327
/// A file written just before the manifest (inside the racy window) is
6328
/// checked by its hash: trusted when equal, caught when edited in place
6329
/// with the same size and time.
6330
#[test]
6331
fn a_racy_manifest_entry_is_checked_by_hash() {
6332
    hermetic();
6333
    let dir = tempfile::tempdir().unwrap();
6334
    let root = dir.path();
6335
    let repo = Repo::init(root).unwrap();
6336
    write(root, "a.txt", b"one\n");
6337
    repo.commit("fresh", &[]).unwrap();
6338
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6339
    let t = fs::metadata(root.join("a.txt"))
6340
        .unwrap()
6341
        .modified()
6342
        .unwrap();
6343
    write(root, "a.txt", b"two\n");
6344
    fs::File::options()
6345
        .write(true)
6346
        .open(root.join("a.txt"))
6347
        .unwrap()
6348
        .set_modified(t)
6349
        .unwrap();
6350
    assert!(
6351
        !repo.clean_by_manifest().unwrap(),
6352
        "same size and time, other bytes"
6353
    );
6354
    assert_eq!(
6355
        statuses(&repo.snapshot_status("status").unwrap()),
6356
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6357
    );
6358
}
6359
6360
/// A fetch on one machine moves changes as stored, text blobs among the
6361
/// objects; a change whose text blob did not come is refused, not stored.
6362
#[test]
6363
fn a_raw_bundle_without_a_changes_text_is_refused() {
6364
    hermetic();
6365
    let dir = tempfile::tempdir().unwrap();
6366
    let root = dir.path();
6367
    let a = Repo::init(&root.join("a")).unwrap();
6368
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6369
    write(&root.join("a"), "big.txt", big.as_bytes());
6370
    let h = a.commit("big", &[]).unwrap();
6371
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6372
    assert_eq!(bundle.raw_changes.len(), 1);
6373
    assert!(bundle.changes.is_empty());
6374
    let b = Repo::init(&root.join("b")).unwrap();
6375
    let mut without = bundle.clone();
6376
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6377
    let e = b.import_bundle(&without, false).unwrap_err();
6378
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6379
    assert!(!b.store().has(&h));
6380
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6381
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6382
}
6383
6384
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6385
/// again was a second node for one Git path, so a file moved into it on
6386
/// another line, where the first node still stood, ended up in two places.
6387
/// An import now brings the directory back rather than make a new one.
6388
#[test]
6389
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6390
    hermetic();
6391
    if std::process::Command::new("git")
6392
        .arg("--version")
6393
        .output()
6394
        .is_err()
6395
    {
6396
        eprintln!("git not installed; skipping");
6397
        return;
6398
    }
6399
    let dir = tempfile::tempdir().unwrap();
6400
    let root = dir.path();
6401
    let g = root.join("src.git");
6402
    fs::create_dir_all(&g).unwrap();
6403
    let git = |args: &[&str]| -> String {
6404
        let out = std::process::Command::new("git")
6405
            .arg("-C")
6406
            .arg(&g)
6407
            .args([
6408
                "-c",
6409
                "user.name=Grace",
6410
                "-c",
6411
                "[email protected]",
6412
                "-c",
6413
                "commit.gpgsign=false",
6414
            ])
6415
            .args(args)
6416
            .output()
6417
            .unwrap();
6418
        assert!(
6419
            out.status.success(),
6420
            "git {args:?}: {}",
6421
            String::from_utf8_lossy(&out.stderr)
6422
        );
6423
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6424
    };
6425
    git(&["init", "-q", "-b", "main"]);
6426
    write(&g, "d/a.txt", b"a\n");
6427
    write(&g, "c/x.txt", b"x\n");
6428
    git(&["add", "."]);
6429
    git(&["commit", "-qm", "base"]);
6430
    // One line: move x into d while d still stands.
6431
    git(&["checkout", "-qb", "side"]);
6432
    git(&["mv", "c/x.txt", "d/x.txt"]);
6433
    git(&["commit", "-qm", "x into d"]);
6434
    // The other: d goes, comes back, and x moves into it too.
6435
    git(&["checkout", "-q", "main"]);
6436
    git(&["rm", "-q", "d/a.txt"]);
6437
    git(&["commit", "-qm", "d goes"]);
6438
    write(&g, "d/b.txt", b"b\n");
6439
    git(&["add", "."]);
6440
    git(&["commit", "-qm", "d comes back"]);
6441
    git(&["mv", "c/x.txt", "d/x.txt"]);
6442
    git(&["commit", "-qm", "x into d again"]);
6443
    git(&["merge", "-q", "--no-edit", "side"]);
6444
6445
    let repo = Repo::init(&root.join("o")).unwrap();
6446
    repo.import_git(&g, "main").unwrap();
6447
    let v = repo.verify_git_import(&g, "main").unwrap();
6448
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6449
    let st = repo
6450
        .load_state_history(&repo.bookmark_heads().unwrap())
6451
        .unwrap();
6452
    let view = st.tree().view();
6453
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6454
    // The directory is the one the first commit made.
6455
    // Commits made in one second tie on time: find the first by its message.
6456
    let first = repo
6457
        .log()
6458
        .unwrap()
6459
        .into_iter()
6460
        .find(|e| e.change.message.starts_with("base"))
6461
        .unwrap();
6462
    let base = repo
6463
        .load_state_history(&[first.hash])
6464
        .unwrap()
6465
        .tree()
6466
        .view();
6467
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6468
}
6469
6470
/// oxygen#30, the rest: a placement left under a directory another line
6471
/// removed is out of sight, so no diff reaches it; the merge that settles
6472
/// where the file is retires it.
6473
#[test]
6474
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6475
    hermetic();
6476
    if std::process::Command::new("git")
6477
        .arg("--version")
6478
        .output()
6479
        .is_err()
6480
    {
6481
        eprintln!("git not installed; skipping");
6482
        return;
6483
    }
6484
    let dir = tempfile::tempdir().unwrap();
6485
    let root = dir.path();
6486
    let g = root.join("src.git");
6487
    fs::create_dir_all(&g).unwrap();
6488
    let run = |args: &[&str]| {
6489
        std::process::Command::new("git")
6490
            .arg("-C")
6491
            .arg(&g)
6492
            .args([
6493
                "-c",
6494
                "user.name=Grace",
6495
                "-c",
6496
                "[email protected]",
6497
                "-c",
6498
                "commit.gpgsign=false",
6499
            ])
6500
            .args(args)
6501
            .output()
6502
            .unwrap()
6503
    };
6504
    let git = |args: &[&str]| {
6505
        let out = run(args);
6506
        assert!(
6507
            out.status.success(),
6508
            "git {args:?}: {}",
6509
            String::from_utf8_lossy(&out.stderr)
6510
        );
6511
    };
6512
    git(&["init", "-q", "-b", "main"]);
6513
    write(&g, "c/x.txt", b"x\n");
6514
    write(&g, "keep.txt", b"k\n");
6515
    git(&["add", "."]);
6516
    git(&["commit", "-qm", "base"]);
6517
    // One line renames the file within c; the other moves it out of c,
6518
    // which goes.
6519
    git(&["checkout", "-qb", "side"]);
6520
    git(&["mv", "c/x.txt", "c/y.txt"]);
6521
    git(&["commit", "-qm", "rename within c"]);
6522
    git(&["checkout", "-q", "main"]);
6523
    fs::create_dir_all(g.join("n")).unwrap();
6524
    git(&["mv", "c/x.txt", "n/x.txt"]);
6525
    git(&["commit", "-qm", "move out of c"]);
6526
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6527
    let _ = run(&["merge", "-q", "side"]);
6528
    let _ = run(&[
6529
        "rm",
6530
        "-q",
6531
        "--cached",
6532
        "--ignore-unmatch",
6533
        "c/y.txt",
6534
        "c/x.txt",
6535
    ]);
6536
    let _ = std::fs::remove_dir_all(g.join("c"));
6537
    write(&g, "n/x.txt", b"x\n");
6538
    git(&["add", "-A"]);
6539
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6540
6541
    let repo = Repo::init(&root.join("o")).unwrap();
6542
    repo.import_git(&g, "main").unwrap();
6543
    let v = repo.verify_git_import(&g, "main").unwrap();
6544
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6545
    let st = repo
6546
        .load_state_history(&repo.bookmark_heads().unwrap())
6547
        .unwrap();
6548
    let view = st.tree().view();
6549
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6550
    assert!(view.entries.contains_key("n/x.txt"));
6551
}
6552
6553
/// oxygen#30, orphans: a file added on one line into a directory the other
6554
/// line removed is placed where the tree cannot show it; Git's merge keeps
6555
/// the file, and the import's merge leaves exactly one of it.
6556
#[test]
6557
fn git_import_merge_leaves_no_orphan_behind() {
6558
    hermetic();
6559
    if std::process::Command::new("git")
6560
        .arg("--version")
6561
        .output()
6562
        .is_err()
6563
    {
6564
        eprintln!("git not installed; skipping");
6565
        return;
6566
    }
6567
    let dir = tempfile::tempdir().unwrap();
6568
    let root = dir.path();
6569
    let g = root.join("src.git");
6570
    fs::create_dir_all(&g).unwrap();
6571
    let git = |args: &[&str]| {
6572
        let out = std::process::Command::new("git")
6573
            .arg("-C")
6574
            .arg(&g)
6575
            .args([
6576
                "-c",
6577
                "user.name=Grace",
6578
                "-c",
6579
                "[email protected]",
6580
                "-c",
6581
                "commit.gpgsign=false",
6582
            ])
6583
            .args(args)
6584
            .output()
6585
            .unwrap();
6586
        assert!(
6587
            out.status.success(),
6588
            "git {args:?}: {}",
6589
            String::from_utf8_lossy(&out.stderr)
6590
        );
6591
    };
6592
    git(&["init", "-q", "-b", "main"]);
6593
    write(&g, "d/f.txt", b"f\n");
6594
    write(&g, "keep.txt", b"k\n");
6595
    git(&["add", "."]);
6596
    git(&["commit", "-qm", "base"]);
6597
    git(&["checkout", "-qb", "side"]);
6598
    write(&g, "d/new.txt", b"new\n");
6599
    git(&["add", "."]);
6600
    git(&["commit", "-qm", "add into d"]);
6601
    git(&["checkout", "-q", "main"]);
6602
    git(&["rm", "-q", "d/f.txt"]);
6603
    git(&["commit", "-qm", "d goes"]);
6604
    git(&["merge", "-q", "--no-edit", "side"]);
6605
6606
    let repo = Repo::init(&root.join("o")).unwrap();
6607
    repo.import_git(&g, "main").unwrap();
6608
    let v = repo.verify_git_import(&g, "main").unwrap();
6609
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6610
    let st = repo
6611
        .load_state_history(&repo.bookmark_heads().unwrap())
6612
        .unwrap();
6613
    let view = st.tree().view();
6614
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6615
    assert!(view.entries.contains_key("d/new.txt"));
6616
}
6617
6618
/// fsck checks a change's text as the blobs it is stored in, without
6619
/// decoding it: a missing text blob is an error named for the change.
6620
#[test]
6621
fn fsck_names_a_missing_text_blob() {
6622
    hermetic();
6623
    let dir = tempfile::tempdir().unwrap();
6624
    let root = dir.path();
6625
    let repo = Repo::init(root).unwrap();
6626
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6627
    write(root, "big.txt", big.as_bytes());
6628
    let h = repo.commit("big", &[]).unwrap();
6629
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6630
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6631
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6632
        panic!("a stored text")
6633
    };
6634
    repo.store().remove_loose_for_test(&b).unwrap();
6635
    let rep = repo.fsck().unwrap();
6636
    assert!(rep.errors() > 0);
6637
    assert!(
6638
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6639
        "{:?}",
6640
        rep.problems
6641
    );
6642
}
6643
6644
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6645
/// reached with that remote's token and CA (a private subrepo then clones
6646
/// for anyone who can read the parent); another hub gets none of them.
6647
#[test]
6648
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6649
    hermetic();
6650
    let dir = tempfile::tempdir().unwrap();
6651
    let mut repo = Repo::init(dir.path()).unwrap();
6652
    repo.config
6653
        .set(
6654
            "remote.origin.url",
6655
            "https://Hub.example:7343/doomsdayone/metalgear",
6656
        )
6657
        .unwrap();
6658
    repo.config.set("remote.origin.token", "secret").unwrap();
6659
    repo.config
6660
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6661
        .unwrap();
6662
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6663
    assert_eq!(same.token.as_deref(), Some("secret"));
6664
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6665
    for other in [
6666
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6667
        "https://hub.example/doomsdayone/rstar-api",
6668
        "http://hub.example:7343/doomsdayone/rstar-api",
6669
    ] {
6670
        let o = repo.credentials_for(other);
6671
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6672
    }
6673
}
6674
6675
/// oxygen#47: a remote with no token of its own uses the user's credential
6676
/// store for its hub, and a nested checkout finds its parent's remote
6677
/// token there instead of keeping a copy.
6678
#[test]
6679
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
6680
    hermetic();
6681
    let home = tempfile::tempdir().unwrap();
6682
    let dir = tempfile::tempdir().unwrap();
6683
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
6684
    parent
6685
        .config
6686
        .set("remote.origin.url", "https://hub.example/o/parent")
6687
        .unwrap();
6688
    parent.save_config().unwrap();
6689
    assert_eq!(parent.remote_options("origin").token, None);
6690
    crate::credentials::Credentials::at(home.path())
6691
        .save("https://hub.example", "stored", Some("andy"), None)
6692
        .unwrap();
6693
    assert_eq!(
6694
        parent.remote_options("origin").token.as_deref(),
6695
        Some("stored")
6696
    );
6697
6698
    let empty_home = tempfile::tempdir().unwrap();
6699
    let nested = dir.path().join("deps").join("child");
6700
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
6701
    child
6702
        .config
6703
        .set("remote.origin.url", "https://hub.example/o/child")
6704
        .unwrap();
6705
    child.save_config().unwrap();
6706
    assert_eq!(child.remote_options("origin").token, None);
6707
    parent
6708
        .config
6709
        .set("remote.origin.token", "checkout")
6710
        .unwrap();
6711
    parent.save_config().unwrap();
6712
    assert_eq!(
6713
        child.remote_options("origin").token.as_deref(),
6714
        Some("checkout")
6715
    );
6716
    // Another hub's checkout token is not borrowed.
6717
    child
6718
        .config
6719
        .set("remote.origin.url", "https://other.example/o/child")
6720
        .unwrap();
6721
    assert_eq!(child.remote_options("origin").token, None);
6722
}
6723
6724
#[test]
6725
fn the_metadata_cache_survives_a_torn_tail() {
6726
    hermetic();
6727
    let dir = tempfile::tempdir().unwrap();
6728
    let root = dir.path();
6729
    let repo = Repo::init(root).unwrap();
6730
    write(root, "a.txt", b"1\n");
6731
    let h = repo.commit("first", &[]).unwrap();
6732
    let meta = repo.store().get_change_meta(&h).unwrap();
6733
    let cache = repo.store().dir().join("metas");
6734
    let len = fs::metadata(&cache).unwrap().len();
6735
    assert!(len > 0, "a change read is cached");
6736
    // A torn record at the end: the cache reads up to it and cuts it off.
6737
    fs::OpenOptions::new()
6738
        .append(true)
6739
        .open(&cache)
6740
        .unwrap()
6741
        .write_all(&[7; 20])
6742
        .unwrap();
6743
    let again = Repo::open(root).unwrap();
6744
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
6745
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
6746
}
6747
6748
#[test]
6749
fn a_manifest_that_does_not_check_reads_as_none() {
6750
    hermetic();
6751
    let dir = tempfile::tempdir().unwrap();
6752
    let root = dir.path();
6753
    let repo = Repo::init(root).unwrap();
6754
    write(root, "a.txt", b"1\n");
6755
    repo.commit("first", &[]).unwrap();
6756
    let path = repo.manifest_path();
6757
    let mut bytes = fs::read(&path).unwrap();
6758
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
6759
    let last = bytes.len() - 1;
6760
    bytes[last] ^= 1;
6761
    fs::write(&path, &bytes).unwrap();
6762
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
6763
    // The next status reads the files and writes it again.
6764
    let again = Repo::open(root).unwrap();
6765
    assert!(!again.snapshot("status").unwrap().changed);
6766
    assert!(again.read_manifest().unwrap().is_some());
6767
}
6768
6769
#[test]
6770
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
6771
    hermetic();
6772
    let dir = tempfile::tempdir().unwrap();
6773
    let root = dir.path();
6774
    let repo = Repo::init(root).unwrap();
6775
    write(root, "a.txt", b"1\n");
6776
    write(root, "b.txt", b"2\n");
6777
    // b.txt outside the racy window, so snapshots take it as unchanged.
6778
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6779
    fs::File::options()
6780
        .write(true)
6781
        .open(root.join("b.txt"))
6782
        .unwrap()
6783
        .set_modified(old)
6784
        .unwrap();
6785
    repo.commit("first", &[]).unwrap();
6786
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
6787
    repo.snapshot_status("status").unwrap();
6788
    write(root, "a.txt", b"1\n2\n");
6789
    repo.commit("second", &[]).unwrap();
6790
    assert!(
6791
        repo.clean_by_manifest().unwrap(),
6792
        "after a commit of one file"
6793
    );
6794
    // Edited, seen by a status, edited again, then committed: the status
6795
    // left the first edit's stat, which the commit must not keep.
6796
    write(root, "a.txt", b"1\n2\n3\n");
6797
    repo.snapshot_status("status").unwrap();
6798
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
6799
    repo.commit("third", &[]).unwrap();
6800
    assert!(
6801
        repo.clean_by_manifest().unwrap(),
6802
        "after an edit a status saw"
6803
    );
6804
}
6805
6806
#[test]
6807
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
6808
    hermetic();
6809
    let dir = tempfile::tempdir().unwrap();
6810
    let root = dir.path();
6811
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6812
    write(root, "a.txt", b"1\n2\n");
6813
    let a = repo.commit("A", &[]).unwrap();
6814
    repo.bookmark_create("develop", Some(&[a])).unwrap();
6815
    write(root, "a.txt", b"1\nX\n");
6816
    let c = repo.commit("C: 2 to X", &[]).unwrap();
6817
    repo.bookmark_switch("develop", false).unwrap();
6818
    write(root, "a.txt", b"1\nY\n");
6819
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
6820
    repo.bookmark_switch("main", false).unwrap();
6821
6822
    let err = repo.rebase(&c, &[d]).unwrap_err();
6823
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
6824
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
6825
    assert!(r.changed && r.checked_out);
6826
    let snap = repo.snapshot_status("status").unwrap();
6827
    assert!(
6828
        snap.base_snapshot.is_conflicted(),
6829
        "the conflict is in the working copy"
6830
    );
6831
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
6832
    assert!(text.contains('X') && text.contains('Y'), "{text}");
6833
6834
    write(root, "a.txt", b"1\nXY\n");
6835
    repo.commit("Resolve", &[]).unwrap();
6836
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
6837
    assert!(st.contains(&c) && st.contains(&d));
6838
    let files = st.materialize().files;
6839
    assert!(!files["a.txt"].is_conflicted());
6840
    assert!(
6841
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
6842
    );
6843
6844
    // A change the current bookmark does not hold is refused.
6845
    repo.bookmark_switch("develop", false).unwrap();
6846
    write(root, "b.txt", b"b\n");
6847
    let e = repo.commit("E", &[]).unwrap();
6848
    repo.bookmark_switch("main", false).unwrap();
6849
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
6850
    assert!(
6851
        err.to_string().contains("not on the current bookmark"),
6852
        "{err}"
6853
    );
6854
}
6855
6856
#[test]
6857
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
6858
    hermetic();
6859
    let dir = tempfile::tempdir().unwrap();
6860
    let root = dir.path();
6861
    let repo = Repo::init(root).unwrap();
6862
    write(root, "a.txt", b"a\n");
6863
    write(root, "kept.log", b"tracked\n");
6864
    repo.commit("first", &[]).unwrap();
6865
    write(root, "build.log", b"made\n");
6866
    let snap = repo.snapshot_status("status").unwrap();
6867
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
6868
    // A rule written afterwards leaves the added file out again, while the
6869
    // committed one stays tracked.
6870
    write(root, ".gitignore", b"*.log\n");
6871
    let snap = repo.snapshot_status("status").unwrap();
6872
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
6873
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
6874
    write(root, "kept.log", b"tracked, edited\n");
6875
    let snap = repo.snapshot_status("status").unwrap();
6876
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
6877
}
6878
6879
#[test]
6880
fn shed_graphs_come_back_the_same() {
6881
    hermetic();
6882
    let dir = tempfile::tempdir().unwrap();
6883
    let root = dir.path();
6884
    let repo = Repo::init(root).unwrap();
6885
    write(root, "a.txt", b"1\n2\n3\n");
6886
    write(root, "b.txt", b"x\n");
6887
    repo.commit("first", &[]).unwrap();
6888
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
6889
    repo.commit("second", &[]).unwrap();
6890
    let heads = repo.bookmark_heads().unwrap();
6891
    let mut st = repo.load_state_history(&heads).unwrap();
6892
    let view = st.tree().view();
6893
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
6894
        .iter()
6895
        .map(|p| view.entries[*p].node)
6896
        .collect();
6897
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6898
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6899
    assert_eq!(st.built_count(), 2);
6900
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
6901
    assert_eq!((shed, st.built_count()), (2, 0));
6902
    // A later change applies on top of the shed history.
6903
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
6904
    let h3 = repo.commit("third", &[]).unwrap();
6905
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
6906
    st.add_known(h3, skeleton, texts);
6907
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6908
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6909
    assert_eq!(after[1], before[1]);
6910
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
6911
}
6912
6913
#[test]
6914
fn many_edited_files_diff_in_parallel() {
6915
    // Enough edited files that the builder diffs them in parallel; the
6916
    // commit must hold exactly what is on disk, and a second snapshot
6917
    // must find nothing left to commit.
6918
    hermetic();
6919
    let dir = tempfile::tempdir().unwrap();
6920
    let root = dir.path();
6921
    let repo = Repo::init(root).unwrap();
6922
    let text = |i: usize, round: usize| {
6923
        let mut s = String::new();
6924
        for line in 0..50 {
6925
            if round > 0 && line % 7 == i % 7 {
6926
                s.push_str(&format!("edited {round} {i} {line}\n"));
6927
            } else {
6928
                s.push_str(&format!("file {i} line {line}\n"));
6929
            }
6930
        }
6931
        if round > 0 && i.is_multiple_of(3) {
6932
            s.push_str("appended\n");
6933
        }
6934
        s
6935
    };
6936
    for i in 0..40 {
6937
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
6938
    }
6939
    repo.commit("first", &[]).unwrap();
6940
    for i in 0..40 {
6941
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
6942
    }
6943
    let h = repo.commit("edit every file", &[]).unwrap();
6944
    let snap = repo.load_state(&[h]).unwrap().materialize();
6945
    for i in 0..40 {
6946
        let want = text(i, 1);
6947
        assert!(
6948
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
6949
            "d/f{i}.txt as committed"
6950
        );
6951
    }
6952
    assert!(
6953
        repo.commit("nothing", &[]).is_err(),
6954
        "nothing left to commit"
6955
    );
6956
}
6957
6958
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
6959
/// is known (fetch printed "up to date" while main was behind), a change
6960
/// only fetched resolves and says where it is, and a checkout whose only
6961
/// remote is not `origin` uses that one.
6962
#[test]
6963
fn a_fetched_change_shows_as_behind_and_resolves() {
6964
    hermetic();
6965
    let dir = tempfile::tempdir().unwrap();
6966
    let root = dir.path();
6967
    let origin = Repo::init(&root.join("origin")).unwrap();
6968
    drop(origin);
6969
    let url = root.join("origin").to_string_lossy().to_string();
6970
    let a = Repo::clone(&url, &root.join("a"))
6971
        .unwrap()
6972
        .with_home(root.join("home-a"));
6973
    write(&root.join("a"), "f.txt", b"one\n");
6974
    a.commit("one", &[]).unwrap();
6975
    a.push("origin", false).unwrap();
6976
    let b = Repo::clone(&url, &root.join("b"))
6977
        .unwrap()
6978
        .with_home(root.join("home-b"));
6979
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
6980
6981
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
6982
    let h2 = a.commit("two", &[]).unwrap();
6983
    a.push("origin", false).unwrap();
6984
    b.fetch("origin").unwrap();
6985
    // Fetched, not pulled: one behind, the change found and placed.
6986
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
6987
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
6988
    assert_eq!(
6989
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
6990
            .unwrap(),
6991
        h2
6992
    );
6993
    assert_eq!(
6994
        b.remote_only_location(&h2).unwrap().as_deref(),
6995
        Some("origin/main")
6996
    );
6997
    // Fetching again changes nothing: still behind, which is what the
6998
    // CLI now says rather than "up to date".
6999
    b.fetch("origin").unwrap();
7000
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7001
    b.pull("origin").unwrap();
7002
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7003
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7004
7005
    // One remote, not called origin: it is the default.
7006
    let mut c = Repo::init(&root.join("c")).unwrap();
7007
    assert_eq!(c.default_remote(), "origin");
7008
    c.config.set("remote.earth.url", &url).unwrap();
7009
    assert_eq!(c.default_remote(), "earth");
7010
    c.config.set("remote.origin.url", &url).unwrap();
7011
    assert_eq!(c.default_remote(), "origin");
7012
}
7013
7014
/// oxygen#57: a clone from a relative local path records the remote as an
7015
/// absolute path, so fetch still finds it from inside the clone.
7016
#[test]
7017
fn a_clone_from_a_relative_path_records_it_absolute() {
7018
    hermetic();
7019
    let dir = tempfile::tempdir().unwrap();
7020
    let root = dir.path();
7021
    Repo::init(&root.join("origin")).unwrap();
7022
    let rel = crate::protocol::stored_url("relative/repo");
7023
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7024
    assert_eq!(
7025
        crate::protocol::stored_url("https://hub.example/o/n"),
7026
        "https://hub.example/o/n"
7027
    );
7028
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7029
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7030
    // A bucket is kept as written: it is not a path.
7031
    assert_eq!(
7032
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7033
        "s3://bucket/prefix?profile=p"
7034
    );
7035
    let url = root.join("origin").to_string_lossy().to_string();
7036
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7037
    assert_eq!(b.config.remotes["origin"], url);
7038
    b.fetch("origin").unwrap();
7039
}
7040
7041
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7042
/// and gets its subrepos at their pins from this workspace's copies, with
7043
/// their remotes pointing where the subrepos come from.
7044
#[test]
7045
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7046
    hermetic();
7047
    let dir = tempfile::tempdir().unwrap();
7048
    let root = dir.path();
7049
    Repo::init(&root.join("lib-origin")).unwrap();
7050
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7051
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7052
        .unwrap()
7053
        .with_home(root.join("home"));
7054
    write(&root.join("lib"), "lib.txt", b"v1\n");
7055
    let l1 = lib.commit("lib v1", &[]).unwrap();
7056
    assert!(lib.push("origin", false).unwrap()[0].ok);
7057
7058
    let app_dir = root.join("app");
7059
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7060
    write(&app_dir, "main.txt", b"app\n");
7061
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7062
    app.commit("app with lib", &[]).unwrap();
7063
    // A second bookmark, and the main workspace on another.
7064
    app.bookmark_create("develop", None).unwrap();
7065
    app.bookmark_create("feature", None).unwrap();
7066
    let mut app = app;
7067
    app.bookmark_switch("feature", false).unwrap();
7068
    assert_eq!(app.config.bookmark, "feature");
7069
7070
    // The library's origin goes away: the subrepo must come from here.
7071
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7072
    let heads = app.resolve_heads("develop").unwrap();
7073
    let ws = app
7074
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7075
        .unwrap();
7076
    assert_eq!(
7077
        ws.config.bookmark, "develop",
7078
        "the new workspace is on develop"
7079
    );
7080
    assert_eq!(
7081
        app.config.bookmark, "feature",
7082
        "and this one stays on its own"
7083
    );
7084
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7085
    assert_eq!(
7086
        sub.config.remotes["origin"], lib_url,
7087
        "its origin is the subrepo's URL"
7088
    );
7089
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7090
    assert_eq!(
7091
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7092
        b"v1\n"
7093
    );
7094
}
7095
7096
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7097
/// operators and the predicates, over a small graph with two heads and
7098
/// a rename.
7099
#[test]
7100
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7101
    hermetic();
7102
    let dir = tempfile::tempdir().unwrap();
7103
    let root = dir.path();
7104
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7105
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7106
        .unwrap();
7107
    write(root, "src/a.rs", b"one\n");
7108
    let a = repo.commit("first: add a", &[]).unwrap();
7109
    write(root, "src/a.rs", b"one\ntwo\n");
7110
    let b = repo.commit("second: grow a", &[]).unwrap();
7111
    // A second head, independent of b: a new file on top of a.
7112
    repo.checkout(&[a], false, "checkout a").unwrap();
7113
    write(root, "docs/notes.md", b"notes\n");
7114
    let c = repo.commit("third: notes", &[]).unwrap();
7115
    // Back to both heads, then rename a.rs: the node keeps its identity.
7116
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7117
        .unwrap();
7118
    fs::remove_file(root.join("src/a.rs")).unwrap();
7119
    write(root, "src/z.rs", b"one\ntwo\n");
7120
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7121
    let wc = repo.working_copy().unwrap().0;
7122
    // A saved revset is checked when set.
7123
    repo.set_user_config("revset.mine", "author(me) & ::main")
7124
        .unwrap();
7125
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7126
    let set = |src: &str| -> Vec<ChangeHash> {
7127
        let mut v = repo.revset(src).unwrap().hashes;
7128
        v.sort();
7129
        v
7130
    };
7131
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7132
        let mut v = hs.to_vec();
7133
        v.sort();
7134
        v
7135
    };
7136
7137
    // Changes commute: a new file depends on nothing and the rename on the
7138
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7139
    // copy on the three heads b, c, d.
7140
    let heads = sorted(&repo.bookmark_heads().unwrap());
7141
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7142
    assert!(heads.contains(&d) && heads.contains(&c));
7143
    // Symbols and closures.
7144
    assert_eq!(set("main"), heads);
7145
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7146
    assert_eq!(set("@"), vec![wc]);
7147
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7148
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7149
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7150
    assert_eq!(
7151
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7152
        sorted(&[a, b])
7153
    );
7154
    // Ranges: what main has beyond b, and `..` forms.
7155
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7156
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7157
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7158
    // Operators and precedence: ~ binds tighter than &, & than |.
7159
    assert_eq!(
7160
        set(&format!("::main ~ #{}", d.short(12))),
7161
        sorted(&[a, b, c])
7162
    );
7163
    assert_eq!(
7164
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7165
        sorted(&[b, c])
7166
    );
7167
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7168
    // Relations.
7169
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7170
    head_deps.sort();
7171
    head_deps.dedup();
7172
    assert_eq!(set("deps(main)"), head_deps);
7173
    let on_a: Vec<ChangeHash> = [b, c, d]
7174
        .into_iter()
7175
        .filter(|h| meta(h).deps.contains(&a))
7176
        .collect();
7177
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7178
    assert_eq!(set("heads(::main)"), heads);
7179
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7180
    assert_eq!(
7181
        set(&format!(
7182
            "heads(#{} | #{} | #{})",
7183
            a.short(12),
7184
            b.short(12),
7185
            c.short(12)
7186
        )),
7187
        sorted(&[b, c])
7188
    );
7189
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7190
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7191
    assert_eq!(set("none()"), vec![]);
7192
    // Predicates: author by name, email, key prefix and `me`.
7193
    let key = repo.config.author_key.unwrap();
7194
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7195
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7196
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7197
    assert_eq!(set("author(me) & ::main").len(), 4);
7198
    assert_eq!(set("author(nobody)"), vec![]);
7199
    assert_eq!(set("description(notes)"), vec![c]);
7200
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7201
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7202
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7203
    // touches follows the node through the rename, in the current state.
7204
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7205
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7206
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7207
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7208
    // Newest first in the result order.
7209
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7210
    // The saved revset, and errors that say what is wrong.
7211
    assert_eq!(set("mine()").len(), 4);
7212
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7213
    assert!(e.contains("unknown function nosuch()"), "{e}");
7214
    let e = repo.revset("main &").unwrap_err().to_string();
7215
    assert!(e.contains("at character"), "{e}");
7216
    let e = repo.revset("zzzz").unwrap_err().to_string();
7217
    assert!(e.contains("no change matches"), "{e}");
7218
    let e = repo
7219
        .revset_with_budget("::main", std::time::Duration::ZERO)
7220
        .unwrap_err()
7221
        .to_string();
7222
    assert!(e.contains("budget"), "{e}");
7223
    // The log entries carry the bookmark's heads and the working copy.
7224
    let entries = repo.log_revset("::@").unwrap();
7225
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7226
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7227
    // push); then a signed change, a tag, and a revocation.
7228
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7229
    assert_eq!(set("signed_by(me)"), vec![]);
7230
    repo.sign_change(&d).unwrap();
7231
    assert_eq!(set("signed_by(me)"), vec![d]);
7232
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7233
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7234
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7235
    assert_eq!(set("delegated()"), vec![]);
7236
    assert_eq!(set("revoked()"), vec![]);
7237
    assert_eq!(set("attested(tag)"), vec![]);
7238
    repo.tag_create("v1", &[b], "first").unwrap();
7239
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7240
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7241
    assert_eq!(set("attested(receipt)"), vec![]);
7242
    assert_eq!(set("built(test)"), vec![]);
7243
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7244
    assert!(e.contains("tag, receipt or ref"), "{e}");
7245
    repo.revoke_identity(&key, "test").unwrap();
7246
    assert_eq!(set("revoked()"), vec![d]);
7247
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7248
}
7249
7250
#[test]
7251
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7252
    let dir = tempfile::tempdir().unwrap();
7253
    let root = dir.path();
7254
    let home = root.join("home");
7255
    // Ada's identity lives in the user file; repository `a` pins the same
7256
    // key in its own file, repository `b` names none.
7257
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7258
    let (key, _) = a
7259
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7260
        .unwrap();
7261
    a.config.set("author.key", &key.to_hex()).unwrap();
7262
    a.save_config().unwrap();
7263
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7264
    let r = a
7265
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7266
        .unwrap();
7267
    assert_eq!(
7268
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7269
        r.new.to_hex(),
7270
        "the user file follows"
7271
    );
7272
    assert_eq!(
7273
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7274
        r.new.to_hex(),
7275
        "the pinning repository follows"
7276
    );
7277
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7278
    assert_eq!(
7279
        b.config.author_key,
7280
        Some(r.new),
7281
        "a checkout without a pin follows the user file"
7282
    );
7283
    // A repository-scoped identity leaves the user file alone.
7284
    let other_home = root.join("home2");
7285
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7286
    let (ck, _) = c
7287
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7288
        .unwrap();
7289
    assert!(!other_home.join("config.toml").exists());
7290
    let r2 = c.rotate_identity().unwrap();
7291
    assert_ne!(r2.new, ck);
7292
    assert_eq!(
7293
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7294
        r2.new.to_hex()
7295
    );
7296
    assert!(
7297
        !other_home.join("config.toml").exists(),
7298
        "a repository-scoped identity stays repository-scoped"
7299
    );
7300
    // Several delegates in one rotation; a repeat is refused.
7301
    let (d1, d2) = (
7302
        SecretKey::generate().identity("D1", "d1@x", 1),
7303
        SecretKey::generate().identity("D2", "d2@x", 1),
7304
    );
7305
    let r3 = c
7306
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7307
        .unwrap();
7308
    assert_eq!(r3.identity.delegates.len(), 2);
7309
    assert!(c
7310
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7311
        .is_err());
7312
}
7313
7314
/// Two unrelated histories that both add the same file, joined by two
7315
/// independent merges on two branches, then those branches merged: Git
7316
/// merges identical additions cleanly, and the import must too (#71,
7317
/// found in VS Code's history).
7318
#[test]
7319
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7320
    // Batches of one: every merge renders apart from the state, where a
7321
    // file whose graph the state had built came out empty (#71).
7322
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7323
    hermetic();
7324
    if std::process::Command::new("git")
7325
        .arg("--version")
7326
        .output()
7327
        .is_err()
7328
    {
7329
        eprintln!("git not installed; skipping");
7330
        return;
7331
    }
7332
    let dir = tempfile::tempdir().unwrap();
7333
    let root = dir.path();
7334
    let g = root.join("src.git");
7335
    fs::create_dir_all(&g).unwrap();
7336
    let git = |args: &[&str]| -> String {
7337
        let out = std::process::Command::new("git")
7338
            .arg("-C")
7339
            .arg(&g)
7340
            .args([
7341
                "-c",
7342
                "user.name=Grace",
7343
                "-c",
7344
                "[email protected]",
7345
                "-c",
7346
                "commit.gpgsign=false",
7347
            ])
7348
            .args(args)
7349
            .output()
7350
            .unwrap();
7351
        assert!(
7352
            out.status.success(),
7353
            "git {args:?}: {}",
7354
            String::from_utf8_lossy(&out.stderr)
7355
        );
7356
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7357
    };
7358
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7359
    // History A: main.
7360
    git(&["init", "-q", "-b", "main"]);
7361
    write(&g, "gulpfile.js", text);
7362
    write(&g, "a.txt", b"a\n");
7363
    git(&["add", "."]);
7364
    git(&["commit", "-q", "-m", "A root"]);
7365
    // History B: an unrelated root adding the same file, identical.
7366
    git(&["checkout", "-q", "--orphan", "fork"]);
7367
    git(&["rm", "-q", "-r", "--cached", "."]);
7368
    for f in ["gulpfile.js", "a.txt"] {
7369
        let _ = fs::remove_file(g.join(f));
7370
    }
7371
    write(&g, "gulpfile.js", text);
7372
    write(&g, "b.txt", b"b\n");
7373
    git(&["add", "."]);
7374
    git(&["commit", "-q", "-m", "B root"]);
7375
    // Two branches from main, each joining B on its own.
7376
    git(&["checkout", "-q", "-b", "one", "main"]);
7377
    git(&[
7378
        "merge",
7379
        "-q",
7380
        "--no-ff",
7381
        "--allow-unrelated-histories",
7382
        "-m",
7383
        "join on one",
7384
        "fork",
7385
    ]);
7386
    git(&["checkout", "-q", "-b", "two", "main"]);
7387
    write(&g, "a.txt", b"a\ntwo\n");
7388
    git(&["commit", "-q", "-am", "work on two"]);
7389
    git(&[
7390
        "merge",
7391
        "-q",
7392
        "--no-ff",
7393
        "--allow-unrelated-histories",
7394
        "-m",
7395
        "join on two",
7396
        "fork",
7397
    ]);
7398
    // Then the two joins meet, and the file is reformatted after.
7399
    git(&["checkout", "-q", "main"]);
7400
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7401
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7402
    write(
7403
        &g,
7404
        "gulpfile.js",
7405
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7406
    );
7407
    git(&["commit", "-q", "-am", "after"]);
7408
7409
    let dest = root.join("dest");
7410
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7411
    repo.import_git(&g, "main").unwrap();
7412
    let v = repo.verify_git_import(&g, "main").unwrap();
7413
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7414
    assert_eq!(
7415
        fs::read(dest.join("gulpfile.js")).unwrap(),
7416
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7417
    );
7418
}
7419
7420
/// As above, but the two joins keep different copies (each branch had a
7421
/// different version when it joined), and later work edits each copy:
7422
/// the shape of VS Code's c67ef57cda90 (#71).
7423
#[test]
7424
fn git_import_joins_where_each_join_kept_a_different_copy() {
7425
    // Batches of one: every merge renders apart from the state, where a
7426
    // file whose graph the state had built came out empty (#71).
7427
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7428
    hermetic();
7429
    if std::process::Command::new("git")
7430
        .arg("--version")
7431
        .output()
7432
        .is_err()
7433
    {
7434
        eprintln!("git not installed; skipping");
7435
        return;
7436
    }
7437
    let dir = tempfile::tempdir().unwrap();
7438
    let root = dir.path();
7439
    let g = root.join("src.git");
7440
    fs::create_dir_all(&g).unwrap();
7441
    let run = |args: &[&str]| {
7442
        std::process::Command::new("git")
7443
            .arg("-C")
7444
            .arg(&g)
7445
            .args([
7446
                "-c",
7447
                "user.name=Grace",
7448
                "-c",
7449
                "[email protected]",
7450
                "-c",
7451
                "commit.gpgsign=false",
7452
            ])
7453
            .args(args)
7454
            .output()
7455
            .unwrap()
7456
    };
7457
    let git = |args: &[&str]| -> String {
7458
        let out = run(args);
7459
        assert!(
7460
            out.status.success(),
7461
            "git {args:?}: {}",
7462
            String::from_utf8_lossy(&out.stderr)
7463
        );
7464
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7465
    };
7466
    git(&["init", "-q", "-b", "main"]);
7467
    write(
7468
        &g,
7469
        "gulpfile.js",
7470
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7471
    );
7472
    git(&["add", "."]);
7473
    git(&["commit", "-q", "-m", "A root"]);
7474
    write(
7475
        &g,
7476
        "gulpfile.js",
7477
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7478
    );
7479
    git(&["commit", "-q", "-am", "whitespace"]);
7480
    git(&["checkout", "-q", "--orphan", "fork"]);
7481
    git(&["rm", "-q", "-r", "--cached", "."]);
7482
    let _ = fs::remove_file(g.join("gulpfile.js"));
7483
    write(
7484
        &g,
7485
        "gulpfile.js",
7486
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7487
    );
7488
    git(&["add", "."]);
7489
    git(&["commit", "-q", "-m", "B root"]);
7490
    // Branch one joins B keeping main's copy; branch two keeps B's.
7491
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7492
        git(&["checkout", "-q", "-b", branch, "main"]);
7493
        let _ = run(&[
7494
            "merge",
7495
            "-q",
7496
            "--no-ff",
7497
            "--allow-unrelated-histories",
7498
            "-m",
7499
            "join",
7500
            "fork",
7501
        ]);
7502
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7503
        git(&["add", "gulpfile.js"]);
7504
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7505
    }
7506
    // Each branch then edits its copy.
7507
    git(&["checkout", "-q", "one"]);
7508
    write(
7509
        &g,
7510
        "gulpfile.js",
7511
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7512
    );
7513
    git(&["commit", "-q", "-am", "tslint on one"]);
7514
    git(&["checkout", "-q", "two"]);
7515
    write(
7516
        &g,
7517
        "gulpfile.js",
7518
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7519
    );
7520
    write(&g, "extra.txt", b"x\n");
7521
    write(&g, "more.txt", b"m\n");
7522
    git(&["add", "."]);
7523
    git(&["commit", "-q", "-am", "fmt on two"]);
7524
    // They meet: resolved by hand.
7525
    git(&["checkout", "-q", "one"]);
7526
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7527
    write(
7528
        &g,
7529
        "gulpfile.js",
7530
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7531
    );
7532
    git(&["add", "gulpfile.js"]);
7533
    git(&["commit", "-q", "-m", "merge two into one"]);
7534
7535
    let dest = root.join("dest");
7536
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7537
    repo.import_git(&g, "one").unwrap();
7538
    let v = repo.verify_git_import(&g, "one").unwrap();
7539
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7540
}
7541
7542
/// oxygen#68: on a store that is not this disk's directory, the operation
7543
/// head is the store's reference record, moved by compare-and-swap. Two
7544
/// handles recording from the same head both get through, merged; a swap
7545
/// from a stale version is refused; a second repository cannot start on a
7546
/// store that already holds one.
7547
#[test]
7548
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
7549
    use crate::strata::{MemoryStore, Store as _};
7550
    let backend = std::sync::Arc::new(MemoryStore::new());
7551
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
7552
    let dir = tempfile::tempdir().unwrap();
7553
    let a = Repo::init(dir.path()).unwrap();
7554
    assert!(
7555
        !dir.path().join(".oxy/ops/head").exists(),
7556
        "the head is not a file"
7557
    );
7558
    let (h0, op0) = a.head_op().unwrap();
7559
    let record = backend
7560
        .read_ref(HEAD_RECORD)
7561
        .unwrap()
7562
        .expect("the head is the store's record");
7563
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
7564
7565
    let b = Repo::open(dir.path()).unwrap();
7566
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
7567
    let mut va = op0.view.clone();
7568
    va.bookmarks.insert("from-a".into(), state);
7569
    let mut vb = op0.view.clone();
7570
    vb.bookmarks.insert("from-b".into(), state);
7571
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
7572
    assert_eq!(b.head_ref().unwrap(), rb);
7573
    // a recorded from h0 too: the head moved, so the two are merged.
7574
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
7575
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
7576
    assert_eq!(head, ra);
7577
    assert!(
7578
        op.command.ends_with("(merged with a concurrent operation)"),
7579
        "{}",
7580
        op.command
7581
    );
7582
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
7583
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
7584
7585
    // A swap from a version that is no longer current moves nothing.
7586
    let (h, v) = a.read_head().unwrap();
7587
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
7588
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
7589
    assert_eq!(a.head_ref().unwrap(), rb);
7590
7591
    let other = tempfile::tempdir().unwrap();
7592
    let err = Repo::init(other.path())
7593
        .err()
7594
        .expect("the store already holds a log")
7595
        .to_string();
7596
    assert!(
7597
        err.contains("already holds a repository's operation log"),
7598
        "{err}"
7599
    );
7600
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
7601
}
7602
7603
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
7604
/// objects and operation head there, with `.oxy/cache` in front: it works
7605
/// as one on disk does, reopens, and survives losing its cache.
7606
#[test]
7607
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
7608
    hermetic();
7609
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
7610
        return;
7611
    }
7612
    let dir = tempfile::tempdir().unwrap();
7613
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
7614
    let url = format!("dir://{}", bucket.display());
7615
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
7616
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
7617
    write(&root, "a.txt", b"one\n");
7618
    let h1 = repo.commit("First", &[]).unwrap();
7619
    write(&root, "a.txt", b"one\ntwo\n");
7620
    let h2 = repo.commit("Second", &[]).unwrap();
7621
    assert!(
7622
        !root.join(".oxy/ops/head").exists(),
7623
        "the head is in the store"
7624
    );
7625
    assert!(bucket.join("ops/head").is_file());
7626
    assert!(root.join(".oxy/cache").is_dir());
7627
    drop(repo);
7628
7629
    // Reopened, and again with no cache at all: everything comes from the store.
7630
    for drop_cache in [false, true] {
7631
        if drop_cache {
7632
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
7633
        }
7634
        let repo = Repo::open(&root).unwrap();
7635
        let log: Vec<String> = repo
7636
            .op_log()
7637
            .unwrap()
7638
            .into_iter()
7639
            .map(|(_, op)| op.command)
7640
            .collect();
7641
        assert!(log.len() >= 3, "{log:?}");
7642
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
7643
        let heads = repo
7644
            .store()
7645
            .get_state(&repo.view().unwrap().bookmarks["main"])
7646
            .unwrap()
7647
            .heads;
7648
        assert_eq!(heads, vec![h2]);
7649
        assert_eq!(
7650
            repo.load_state(&heads).unwrap().materialize().files.len(),
7651
            1
7652
        );
7653
    }
7654
7655
    // A second repository cannot start on the same store.
7656
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
7657
        .err()
7658
        .unwrap()
7659
        .to_string();
7660
    assert!(
7661
        err.contains("already holds a repository's operation log"),
7662
        "{err}"
7663
    );
7664
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
7665
        .err()
7666
        .unwrap()
7667
        .to_string();
7668
    assert!(err.contains("cannot open that kind of store"), "{err}");
7669
}
7670
7671
/// oxygen#75: the prompt's quick check agrees with status in a repository
7672
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
7673
/// another state, clean again once that pin is committed. (It compared the
7674
/// subrepo's directory as if it were a file, so it was always dirty.)
7675
#[test]
7676
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
7677
    hermetic();
7678
    let dir = tempfile::tempdir().unwrap();
7679
    let root = dir.path();
7680
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7681
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7682
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7683
        .unwrap()
7684
        .with_home(root.join("home"));
7685
    write(&root.join("lib"), "lib.txt", b"v1\n");
7686
    lib.commit("lib v1", &[]).unwrap();
7687
    assert!(lib.push("origin", false).unwrap()[0].ok);
7688
    let app_dir = root.join("app");
7689
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7690
    write(&app_dir, "main.txt", b"app\n");
7691
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7692
    app.commit("app with lib", &[]).unwrap();
7693
    // Out of the racy window, so the stat-only path decides.
7694
    std::thread::sleep(std::time::Duration::from_millis(2100));
7695
    let reopen = || Repo::open(&app_dir).unwrap();
7696
    assert_eq!(
7697
        reopen().quick_dirty().unwrap(),
7698
        Some(false),
7699
        "clean, as status says"
7700
    );
7701
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
7702
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
7703
    nested.commit("lib v2", &[]).unwrap();
7704
    assert_eq!(
7705
        reopen().quick_dirty().unwrap(),
7706
        Some(true),
7707
        "the subrepo moved"
7708
    );
7709
    reopen().commit("pin lib v2", &[]).unwrap();
7710
    std::thread::sleep(std::time::Duration::from_millis(2100));
7711
    assert_eq!(
7712
        reopen().quick_dirty().unwrap(),
7713
        Some(false),
7714
        "the new pin is committed"
7715
    );
7716
}
7717
7718
#[test]
7719
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
7720
    // oxygen#72: a .oxymodules section with no subrepo behind it.
7721
    hermetic();
7722
    let dir = tempfile::tempdir().unwrap();
7723
    let root = dir.path();
7724
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7725
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7726
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7727
        .unwrap()
7728
        .with_home(root.join("home"));
7729
    write(&root.join("lib"), "lib.txt", b"v1\n");
7730
    lib.commit("lib v1", &[]).unwrap();
7731
    assert!(lib.push("origin", false).unwrap()[0].ok);
7732
    let app_dir = root.join("app");
7733
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7734
    write(
7735
        &app_dir,
7736
        ".oxymodules",
7737
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
7738
    );
7739
    let unpinned = app.unpinned_modules().unwrap();
7740
    assert_eq!(unpinned.len(), 1);
7741
    assert_eq!(unpinned[0].0, "libs/lib");
7742
    assert_eq!(unpinned[0].1.url, lib_url);
7743
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
7744
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7745
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
7746
}
7747
7748
#[test]
7749
fn the_bookmark_revset_function_names_only_bookmarks() {
7750
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
7751
    hermetic();
7752
    let dir = tempfile::tempdir().unwrap();
7753
    let repo = Repo::init(dir.path()).unwrap();
7754
    write(dir.path(), "a.txt", b"a\n");
7755
    let a = repo.commit("A", &[]).unwrap();
7756
    write(dir.path(), "b.txt", b"b\n");
7757
    let b = repo.commit("B", &[]).unwrap();
7758
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
7759
    heads.sort();
7760
    let mut want = repo.bookmark_heads().unwrap();
7761
    want.sort();
7762
    assert_eq!(heads, want);
7763
    assert!(heads.contains(&b));
7764
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
7765
    // A change prefix is a symbol, not a bookmark.
7766
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
7767
    assert!(repo.revset(&prefix).is_ok());
7768
    let e = repo
7769
        .revset(&format!("bookmark({prefix})"))
7770
        .unwrap_err()
7771
        .to_string();
7772
    assert!(e.contains("no such bookmark"), "{e}");
7773
}
7774
7775
#[test]
7776
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
7777
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
7778
    // pinning the subrepo, and the nested repository on disk at that pin.
7779
    hermetic();
7780
    let dir = tempfile::tempdir().unwrap();
7781
    let root = dir.path();
7782
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7783
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7784
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7785
        .unwrap()
7786
        .with_home(root.join("home"));
7787
    write(&root.join("lib"), "lib.txt", b"v1\n");
7788
    lib.commit("lib v1", &[]).unwrap();
7789
    assert!(lib.push("origin", false).unwrap()[0].ok);
7790
    let app_dir = root.join("app");
7791
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7792
    write(&app_dir, "main.txt", b"app\n");
7793
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7794
    // The stale state: registered in .oxymodules, never pinned.
7795
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
7796
    app.commit("initial", &[]).unwrap();
7797
    let stale = app.bookmark_heads().unwrap();
7798
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
7799
    app.commit("pin lib", &[]).unwrap();
7800
    let newer = app.bookmark_heads().unwrap();
7801
    app.checkout(&stale, false, "test").unwrap();
7802
    write(&app_dir, "notes.txt", b"mine\n");
7803
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
7804
    assert_eq!(carried, vec!["notes.txt".to_string()]);
7805
    assert!(app_dir.join("notes.txt").exists());
7806
}
7807
7808
#[test]
7809
fn a_bookmark_only_behind_its_remote_catches_up() {
7810
    // oxygen#74: switch takes the remote's state rather than a stale one.
7811
    hermetic();
7812
    let dir = tempfile::tempdir().unwrap();
7813
    let root = dir.path();
7814
    let _origin = Repo::init(&root.join("origin")).unwrap();
7815
    let url = root.join("origin").to_string_lossy().to_string();
7816
    let one = Repo::clone(&url, &root.join("one"))
7817
        .unwrap()
7818
        .with_home(root.join("home"));
7819
    write(&root.join("one"), "a.txt", b"a\n");
7820
    one.commit("A", &[]).unwrap();
7821
    assert!(one.push("origin", false).unwrap()[0].ok);
7822
    let two = Repo::clone(&url, &root.join("two"))
7823
        .unwrap()
7824
        .with_home(root.join("home"));
7825
    write(&root.join("two"), "b.txt", b"b\n");
7826
    two.commit("B", &[]).unwrap();
7827
    assert!(two.push("origin", false).unwrap()[0].ok);
7828
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
7829
    one.fetch("origin").unwrap();
7830
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
7831
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
7832
    // Local work the remote lacks: left alone.
7833
    write(&root.join("one"), "c.txt", b"c\n");
7834
    one.commit("C", &[]).unwrap();
7835
    write(&root.join("two"), "d.txt", b"d\n");
7836
    two.commit("D", &[]).unwrap();
7837
    assert!(two.push("origin", false).unwrap()[0].ok);
7838
    one.fetch("origin").unwrap();
7839
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
7840
}
7841
7842
#[test]
7843
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
7844
    // oxygen#83: remotes earth and gcs, origin removed.
7845
    hermetic();
7846
    let dir = tempfile::tempdir().unwrap();
7847
    let root = dir.path();
7848
    let _up = Repo::init(&root.join("up")).unwrap();
7849
    let url = root.join("up").to_string_lossy().to_string();
7850
    let other = Repo::clone(&url, &root.join("other"))
7851
        .unwrap()
7852
        .with_home(root.join("home"));
7853
    write(&root.join("other"), "a.txt", b"a\n");
7854
    other.commit("a", &[]).unwrap();
7855
    assert!(other.push("origin", false).unwrap()[0].ok);
7856
    let mut one = Repo::clone(&url, &root.join("one"))
7857
        .unwrap()
7858
        .with_home(root.join("home"));
7859
    one.config.set("remote.earth.url", &url).unwrap();
7860
    one.config.set("remote.gcs.url", &url).unwrap();
7861
    one.config.set("remote.origin.url", "").unwrap();
7862
    one.save_config().unwrap();
7863
    write(&root.join("other"), "b.txt", b"b\n");
7864
    other.commit("b", &[]).unwrap();
7865
    assert!(other.push("origin", false).unwrap()[0].ok);
7866
    one.fetch("earth").unwrap();
7867
    let b = one
7868
        .bookmarks()
7869
        .unwrap()
7870
        .into_iter()
7871
        .find(|b| b.name == "main")
7872
        .unwrap();
7873
    assert_eq!(
7874
        (b.remote.as_deref(), b.behind),
7875
        (Some("earth"), Some(1)),
7876
        "a stale origin copy is not used"
7877
    );
7878
    assert_eq!(
7879
        one.default_remote(),
7880
        "origin",
7881
        "no default chosen among several"
7882
    );
7883
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
7884
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
7885
    one.config.set("core.remote", "earth").unwrap();
7886
    assert_eq!(one.default_remote(), "earth");
7887
}
7888
7889
#[test]
7890
fn a_missing_author_identity_says_how_to_fix_it() {
7891
    // oxygen#82: an agent home's author.key naming an identity the
7892
    // repository does not hold.
7893
    hermetic();
7894
    let dir = tempfile::tempdir().unwrap();
7895
    let mut repo = Repo::init(dir.path()).unwrap();
7896
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
7897
    repo.config.set("author.key", &missing.to_hex()).unwrap();
7898
    let e = repo.identity(&missing).unwrap_err().to_string();
7899
    assert!(
7900
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
7901
        "{e}"
7902
    );
7903
    assert!(e.contains("this repository's config"), "{e}");
7904
}
7905
7906
#[test]
7907
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
7908
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
7909
    // the working copy, a pull with nothing new left it there, and status
7910
    // said "clean".
7911
    hermetic();
7912
    let dir = tempfile::tempdir().unwrap();
7913
    let root = dir.path();
7914
    let _up = Repo::init(&root.join("up")).unwrap();
7915
    let url = root.join("up").to_string_lossy().to_string();
7916
    let other = Repo::clone(&url, &root.join("other"))
7917
        .unwrap()
7918
        .with_home(root.join("home"));
7919
    write(&root.join("other"), "a.txt", b"a\n");
7920
    other.commit("a", &[]).unwrap();
7921
    assert!(other.push("origin", false).unwrap()[0].ok);
7922
    let one = Repo::clone(&url, &root.join("one"))
7923
        .unwrap()
7924
        .with_home(root.join("home"));
7925
    write(&root.join("other"), "b.txt", b"b\n");
7926
    other.commit("b", &[]).unwrap();
7927
    assert!(other.push("origin", false).unwrap()[0].ok);
7928
    one.fetch("origin").unwrap();
7929
    // The bookmark moves; the working copy does not.
7930
    let theirs = one.resolve_heads("origin/main").unwrap();
7931
    one.bookmark_set("main", &theirs).unwrap();
7932
    assert!(!root.join("one/b.txt").exists());
7933
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
7934
    let r = one.pull("origin").unwrap();
7935
    assert!(
7936
        !r.changed && r.checked_out,
7937
        "nothing new, but the working copy caught up"
7938
    );
7939
    assert!(root.join("one/b.txt").exists());
7940
    assert_eq!(one.working_copy_behind().unwrap(), None);
7941
}
7942
7943
#[test]
7944
fn touched_nodes_cache_answers_as_the_changes_do() {
7945
    hermetic();
7946
    let dir = tempfile::tempdir().unwrap();
7947
    let repo = Repo::init(dir.path()).unwrap();
7948
    write(dir.path(), "a.txt", b"one\n");
7949
    write(dir.path(), "b.txt", b"x\n");
7950
    repo.snapshot("t").unwrap();
7951
    let c1 = repo.commit("first", &[]).unwrap();
7952
    write(dir.path(), "b.txt", b"y\n");
7953
    repo.snapshot("t").unwrap();
7954
    repo.commit("b only", &[]).unwrap();
7955
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
7956
    write(dir.path(), "c.txt", b"one\ntwo\n");
7957
    repo.snapshot("t").unwrap();
7958
    let c3 = repo.commit("rename and edit", &[]).unwrap();
7959
    // Uncommitted work, so the working copy touches a file too.
7960
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
7961
    repo.snapshot("t").unwrap();
7962
7963
    let path = dir.path().join(".oxy/index/touched");
7964
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
7965
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
7966
    assert!(path.exists(), "the first query writes the cache");
7967
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
7968
    assert_eq!(cold, warm, "the cache answers as the changes do");
7969
    let (wc, _) = repo.working_copy().unwrap();
7970
    assert_eq!(
7971
        cold,
7972
        vec![wc, c3, c1],
7973
        "renames followed, the working copy included"
7974
    );
7975
7976
    // Working-copy changes are not kept: they are replaced by every snapshot.
7977
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
7978
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
7979
    assert!(cached.contains(&c1) && cached.contains(&c3));
7980
7981
    // A damaged cache is ignored, not trusted.
7982
    let mut bytes = fs::read(&path).unwrap();
7983
    let last = bytes.len() - 40;
7984
    bytes[last] ^= 1;
7985
    fs::write(&path, &bytes).unwrap();
7986
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
7987
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
7988
    assert_eq!(hashes(touches), vec![c3, c1]);
7989
}
7990
7991
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
7992
/// file back where it was leave two placements at one place, which the
7993
/// tree shows as one file. Removing it, and then its directory, retires
7994
/// both, so no copy is left under a directory that is gone.
7995
#[test]
7996
fn git_import_removes_every_copy_of_a_file_at_one_place() {
7997
    hermetic();
7998
    if std::process::Command::new("git")
7999
        .arg("--version")
8000
        .output()
8001
        .is_err()
8002
    {
8003
        eprintln!("git not installed; skipping");
8004
        return;
8005
    }
8006
    let dir = tempfile::tempdir().unwrap();
8007
    let root = dir.path();
8008
    let g = root.join("src.git");
8009
    fs::create_dir_all(&g).unwrap();
8010
    let git = |args: &[&str]| {
8011
        let out = std::process::Command::new("git")
8012
            .arg("-C")
8013
            .arg(&g)
8014
            .args([
8015
                "-c",
8016
                "user.name=Grace",
8017
                "-c",
8018
                "[email protected]",
8019
                "-c",
8020
                "commit.gpgsign=false",
8021
            ])
8022
            .args(args)
8023
            .output()
8024
            .unwrap();
8025
        assert!(
8026
            out.status.success(),
8027
            "git {args:?}: {}",
8028
            String::from_utf8_lossy(&out.stderr)
8029
        );
8030
    };
8031
    git(&["init", "-q", "-b", "main"]);
8032
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8033
    write(&g, "keep.txt", b"k\n");
8034
    git(&["add", "."]);
8035
    git(&["commit", "-qm", "base"]);
8036
    fs::create_dir_all(g.join("d/sub")).unwrap();
8037
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8038
    git(&["commit", "-qm", "into sub"]);
8039
    git(&["checkout", "-qb", "side"]);
8040
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8041
    git(&["commit", "-qm", "back, on side"]);
8042
    git(&["checkout", "-q", "main"]);
8043
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8044
    git(&["commit", "-qm", "back, on main"]);
8045
    git(&["merge", "-q", "--no-edit", "side"]);
8046
    git(&["rm", "-rq", "d"]);
8047
    git(&["commit", "-qm", "d goes"]);
8048
8049
    let repo = Repo::init(&root.join("o")).unwrap();
8050
    repo.import_git(&g, "main").unwrap();
8051
    let v = repo.verify_git_import(&g, "main").unwrap();
8052
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8053
    let st = repo
8054
        .load_state_history(&repo.bookmark_heads().unwrap())
8055
        .unwrap();
8056
    let view = st.tree().view();
8057
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8058
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8059
}
8060
8061
/// oxygen#94: a state index's file histories are read, and checked by
8062
/// their own hashes, only when a file is built. One found damaged is an
8063
/// error that says so, the index is removed, and the next read rebuilds it.
8064
#[test]
8065
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8066
    hermetic();
8067
    let dir = tempfile::tempdir().unwrap();
8068
    let repo = Repo::init(dir.path()).unwrap();
8069
    for i in 0..6 {
8070
        write(
8071
            dir.path(),
8072
            &format!("f{i}.txt"),
8073
            format!("one {i}\n").as_bytes(),
8074
        );
8075
    }
8076
    repo.snapshot("t").unwrap();
8077
    repo.commit("first", &[]).unwrap();
8078
    for i in 0..6 {
8079
        write(
8080
            dir.path(),
8081
            &format!("f{i}.txt"),
8082
            format!("one {i}\ntwo\n").as_bytes(),
8083
        );
8084
    }
8085
    repo.snapshot("t").unwrap();
8086
    repo.commit("second", &[]).unwrap();
8087
    let want: Vec<Vec<u8>> = (0..6)
8088
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8089
        .collect();
8090
    // The index of the working copy's base, holding every file's history
8091
    // (a few changes behind, an index is replayed onto, not rewritten).
8092
    let (_, wc) = repo.working_copy().unwrap();
8093
    let base = repo.load_state_history(&wc.deps).unwrap();
8094
    repo.write_state_index(&wc.deps, &base);
8095
    for (i, w) in want.iter().enumerate() {
8096
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8097
    }
8098
    let index = repo.state_indexes();
8099
    assert!(!index.is_empty(), "a state index was written");
8100
    // The histories are last in the file: damage the last of them.
8101
    let mut bytes = fs::read(&index[0]).unwrap();
8102
    let last = bytes.len() - 1;
8103
    bytes[last] ^= 0x40;
8104
    fs::write(&index[0], &bytes).unwrap();
8105
8106
    let reads: Vec<_> = (0..6)
8107
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8108
        .collect();
8109
    let damaged: Vec<String> = reads
8110
        .iter()
8111
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8112
        .collect();
8113
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8114
    assert!(
8115
        damaged[0].contains("state index was damaged")
8116
            && damaged[0].contains("run the command again"),
8117
        "{}",
8118
        damaged[0]
8119
    );
8120
    // Every file reads right again, from an index rebuilt from history.
8121
    for (i, w) in want.iter().enumerate() {
8122
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8123
    }
8124
}
8125
8126
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8127
/// objects alone and in dependency order, and the last moves the bookmark.
8128
/// The remote ends with every change and the same state, and says how each
8129
/// part went.
8130
#[test]
8131
fn a_long_push_goes_in_parts() {
8132
    hermetic();
8133
    let dir = tempfile::tempdir().unwrap();
8134
    let root = dir.path();
8135
    let origin = root.join("origin");
8136
    Repo::init_bare_unbound(&origin).unwrap();
8137
    let main = root.join("main");
8138
    let mut repo = Repo::init(&main).unwrap();
8139
    repo.config
8140
        .set("remote.origin.url", &origin.to_string_lossy())
8141
        .unwrap();
8142
    // One byte: every change is a part of its own.
8143
    repo.config.set("push.batch-bytes", "1").unwrap();
8144
    repo.save_config().unwrap();
8145
    for i in 0..6 {
8146
        write(
8147
            &main,
8148
            &format!("f{i}.txt"),
8149
            format!("file {i}\n").as_bytes(),
8150
        );
8151
        repo.commit(&format!("c{i}"), &[]).unwrap();
8152
    }
8153
    let mut parts = Vec::new();
8154
    let results = repo
8155
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8156
        .unwrap();
8157
    assert!(
8158
        results.iter().any(|r| r.ok && r.name == "main"),
8159
        "{results:?}"
8160
    );
8161
    assert_eq!(parts.len(), 6, "{parts:?}");
8162
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8163
8164
    let remote = Repo::open(&origin).unwrap();
8165
    let heads = repo.bookmark_heads().unwrap();
8166
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8167
    assert_eq!(
8168
        remote.log_state(&heads).unwrap().len(),
8169
        repo.log_state(&heads).unwrap().len()
8170
    );
8171
    // A push of objects alone reports how it went, as `objects`.
8172
    let got = remote
8173
        .receive_push(Bundle::default(), vec![], None, vec![])
8174
        .unwrap();
8175
    assert_eq!(got.len(), 1);
8176
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8177
}
8178
8179
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8180
/// own commits (Git author email = its email, any case) with its key, and
8181
/// leaves anyone else's with the zero key; the history verifies as before.
8182
#[test]
8183
fn git_import_claims_your_own_commits() {
8184
    hermetic();
8185
    if std::process::Command::new("git")
8186
        .arg("--version")
8187
        .output()
8188
        .is_err()
8189
    {
8190
        eprintln!("git not installed; skipping");
8191
        return;
8192
    }
8193
    let dir = tempfile::tempdir().unwrap();
8194
    let root = dir.path();
8195
    let g = root.join("src.git");
8196
    fs::create_dir_all(&g).unwrap();
8197
    let git = |who: &str, args: &[&str]| {
8198
        let (name, email) = who.split_once(' ').unwrap();
8199
        let out = std::process::Command::new("git")
8200
            .arg("-C")
8201
            .arg(&g)
8202
            .args([
8203
                "-c",
8204
                &format!("user.name={name}"),
8205
                "-c",
8206
                &format!("user.email={email}"),
8207
                "-c",
8208
                "commit.gpgsign=false",
8209
            ])
8210
            .args(args)
8211
            .output()
8212
            .unwrap();
8213
        assert!(
8214
            out.status.success(),
8215
            "git {args:?}: {}",
8216
            String::from_utf8_lossy(&out.stderr)
8217
        );
8218
    };
8219
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8220
    write(&g, "a.txt", b"a\n");
8221
    git("Grace [email protected]", &["add", "."]);
8222
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8223
    write(&g, "b.txt", b"b\n");
8224
    git("Ada [email protected]", &["add", "."]);
8225
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8226
8227
    let mut repo = Repo::init(&root.join("o")).unwrap();
8228
    let (key, _) = repo
8229
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8230
        .unwrap();
8231
    repo.config.set("git.claim", "true").unwrap();
8232
    repo.save_config().unwrap();
8233
    let repo = Repo::open(&root.join("o")).unwrap();
8234
    repo.import_git(&g, "main").unwrap();
8235
    let v = repo.verify_git_import(&g, "main").unwrap();
8236
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8237
    let heads = repo.bookmark_heads().unwrap();
8238
    let by_message: std::collections::HashMap<String, KeyId> = repo
8239
        .log_state(&heads)
8240
        .unwrap()
8241
        .into_iter()
8242
        .map(|e| {
8243
            (
8244
                e.change.message.lines().next().unwrap_or("").to_string(),
8245
                e.change.author,
8246
            )
8247
        })
8248
        .collect();
8249
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8250
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8251
}
8252
8253
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8254
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8255
#[test]
8256
fn removing_a_remote_leaves_nothing_of_it() {
8257
    hermetic();
8258
    let dir = tempfile::tempdir().unwrap();
8259
    let origin = dir.path().join("origin");
8260
    Repo::init_bare_unbound(&origin).unwrap();
8261
    let main = dir.path().join("main");
8262
    let mut repo = Repo::init(&main).unwrap();
8263
    repo.config
8264
        .set("remote.origin.url", &origin.to_string_lossy())
8265
        .unwrap();
8266
    repo.config
8267
        .set("remote.origin.token", "secret-ish")
8268
        .unwrap();
8269
    repo.config
8270
        .set("remote.keep.url", &origin.to_string_lossy())
8271
        .unwrap();
8272
    repo.save_config().unwrap();
8273
    write(&main, "a.txt", b"a\n");
8274
    repo.commit("a", &[]).unwrap();
8275
    assert!(repo.push("origin", false).unwrap()[0].ok);
8276
    assert!(
8277
        repo.view().unwrap().remotes.contains_key("origin"),
8278
        "a tracking bookmark"
8279
    );
8280
8281
    repo.remove_remote("origin").unwrap();
8282
    let again = Repo::open(&main).unwrap();
8283
    assert!(
8284
        !again
8285
            .config
8286
            .repo_layer()
8287
            .keys()
8288
            .any(|k| k.starts_with("remote.origin.")),
8289
        "{:?}",
8290
        again.config.repo_layer()
8291
    );
8292
    assert!(!again.config.remotes.contains_key("origin"));
8293
    assert!(
8294
        !again.view().unwrap().remotes.contains_key("origin"),
8295
        "its tracking bookmarks go"
8296
    );
8297
    assert!(
8298
        again.config.remotes.contains_key("keep"),
8299
        "another remote stays"
8300
    );
8301
    let mut again = again;
8302
    assert!(
8303
        again.remove_remote("origin").is_err(),
8304
        "a second removal is refused"
8305
    );
8306
}
8307
8308
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
8309
/// unreachable from history, so gc prunes it, unless the host names it:
8310
/// then it and its chunks stay, and it reads back whole.
8311
#[test]
8312
fn gc_keeps_the_blobs_a_host_names() {
8313
    hermetic();
8314
    let dir = tempfile::tempdir().unwrap();
8315
    let repo = Repo::init(dir.path()).unwrap();
8316
    write(dir.path(), "a.txt", b"a\n");
8317
    repo.commit("a", &[]).unwrap();
8318
    // Large enough to be several chunks.
8319
    let body: Vec<u8> = (0..400_000u32)
8320
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
8321
        .collect();
8322
    let kept = repo.store_blob(&body).unwrap();
8323
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
8324
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
8325
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
8326
    assert!(!repo.store().has(&lost), "not named: pruned");
8327
    repo.gc(true).unwrap();
8328
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
8329
}
8330
8331
/// oxygen#99: undo in one workspace undoes that workspace's last command,
8332
/// never another workspace's, says what it undid, and goes further back
8333
/// when run again.
8334
#[test]
8335
fn undo_is_scoped_to_its_workspace() {
8336
    hermetic();
8337
    let dir = tempfile::tempdir().unwrap();
8338
    let root = dir.path().join("main");
8339
    let a = Repo::init(&root).unwrap();
8340
    write(&root, "base.txt", b"base\n");
8341
    let base = a.commit("base", &[]).unwrap();
8342
    a.bookmark_create("feature", None).unwrap();
8343
    let ws_dir = dir.path().join("ws");
8344
    let heads = a.resolve_heads("feature").unwrap();
8345
    let b = a
8346
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
8347
        .unwrap();
8348
8349
    // A commits on main, then B commits on feature: B's is the newest.
8350
    write(&root, "a.txt", b"a\n");
8351
    let ca = a.commit("from a", &[]).unwrap();
8352
    write(&ws_dir, "b.txt", b"b\n");
8353
    let cb = b.commit("from b", &[]).unwrap();
8354
8355
    // A's undo undoes A's commit and leaves B's.
8356
    let u = a.undo().unwrap();
8357
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8358
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
8359
    assert!(!u.changes.is_empty());
8360
    let view = a.view().unwrap();
8361
    // (Independent changes commute, so a bookmark's heads may hold base too.)
8362
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
8363
    assert!(
8364
        a.heads_of(&view, "feature").unwrap().contains(&cb),
8365
        "B's commit stands"
8366
    );
8367
    assert!(
8368
        a.store().get_change(&ca).is_ok(),
8369
        "the change itself is still in the store"
8370
    );
8371
    // A's working copy was clean, so its files followed; B's are untouched.
8372
    assert!(!root.join("a.txt").exists());
8373
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
8374
    assert!(ws_dir.join("b.txt").exists());
8375
8376
    // B's undo still finds B's own commit, under A's undo.
8377
    let u = b.undo().unwrap();
8378
    assert_eq!(u.command, "oxy commit -m \"from b\"");
8379
    assert!(!b
8380
        .heads_of(&b.view().unwrap(), "feature")
8381
        .unwrap()
8382
        .contains(&cb));
8383
    assert_eq!(
8384
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
8385
        vec![base],
8386
        "A's undo stands"
8387
    );
8388
8389
    // A's next undo goes past the commit it already undid, to adding B's
8390
    // workspace: refused, since B has worked there since.
8391
    let e = a.undo().unwrap_err().to_string();
8392
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
8393
}
8394
8395
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
8396
/// own commit's head, and the other workspace's head stays.
8397
#[test]
8398
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
8399
    hermetic();
8400
    let dir = tempfile::tempdir().unwrap();
8401
    let root = dir.path().join("main");
8402
    let a = Repo::init(&root).unwrap();
8403
    write(&root, "base.txt", b"base\n");
8404
    a.commit("base", &[]).unwrap();
8405
    let ws_dir = dir.path().join("ws");
8406
    let b = a.workspace_add(&ws_dir, None).unwrap();
8407
    write(&root, "a.txt", b"a\n");
8408
    let ca = a.commit("from a", &[]).unwrap();
8409
    write(&ws_dir, "b.txt", b"b\n");
8410
    let cb = b.commit("from b", &[]).unwrap();
8411
    let u = a.undo().unwrap();
8412
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8413
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
8414
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
8415
}
8416
8417
/// oxygen#99: an undo that would also take back what another workspace
8418
/// did since to the same bookmark is refused, naming it.
8419
#[test]
8420
fn undo_refuses_to_take_back_another_workspaces_work() {
8421
    hermetic();
8422
    let dir = tempfile::tempdir().unwrap();
8423
    let root = dir.path().join("main");
8424
    let a = Repo::init(&root).unwrap();
8425
    write(&root, "base.txt", b"base\n");
8426
    a.commit("base", &[]).unwrap();
8427
    let ws_dir = dir.path().join("ws");
8428
    let b = a.workspace_add(&ws_dir, None).unwrap();
8429
    // Both on main: A commits, then B builds on it, editing A's file.
8430
    write(&root, "a.txt", b"a\n");
8431
    a.commit("from a", &[]).unwrap();
8432
    let heads = b.resolve_heads("main").unwrap();
8433
    b.checkout(&heads, false, "oxy checkout").unwrap();
8434
    write(&ws_dir, "a.txt", b"a, then b\n");
8435
    b.commit("from b", &[]).unwrap();
8436
    let e = a.undo().unwrap_err().to_string();
8437
    assert!(
8438
        e.contains("bookmark main") && e.contains("builds on"),
8439
        "{e}"
8440
    );
8441
    assert!(e.contains("oxy op restore"), "{e}");
8442
}
8443
8444
/// oxygen#99: undoing a commit that was already pushed says so: the remote
8445
/// still has it.
8446
#[test]
8447
fn undo_says_when_the_commit_was_pushed() {
8448
    hermetic();
8449
    let dir = tempfile::tempdir().unwrap();
8450
    let root = dir.path();
8451
    Repo::init(&root.join("origin")).unwrap();
8452
    let url = root.join("origin").to_string_lossy().to_string();
8453
    let repo = Repo::clone(&url, &root.join("work"))
8454
        .unwrap()
8455
        .with_home(root.join("home"));
8456
    write(&root.join("work"), "a.txt", b"a\n");
8457
    repo.commit("a", &[]).unwrap();
8458
    assert!(repo.push("origin", false).unwrap()[0].ok);
8459
    // The push itself is passed over: the remote keeps what it was sent.
8460
    let u = repo.undo().unwrap();
8461
    assert_eq!(u.command, "oxy commit -m \"a\"");
8462
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
8463
}
8464
8465
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
8466
/// out of the snapshot and named; tracked files and files already in the
8467
/// working copy are not.
8468
#[test]
8469
fn large_new_files_are_left_out_of_snapshots() {
8470
    hermetic();
8471
    let dir = tempfile::tempdir().unwrap();
8472
    let root = dir.path();
8473
    let mut repo = Repo::init(root).unwrap();
8474
    repo.config.max_new_file = 1024;
8475
    write(root, "small.txt", b"small\n");
8476
    write(root, "big.bin", &vec![0u8; 4096]);
8477
    let s = repo.snapshot("oxy status").unwrap();
8478
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8479
    assert_eq!(paths, ["small.txt"]);
8480
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
8481
    repo.commit("small", &[]).unwrap();
8482
8483
    // A tracked file may grow past the limit.
8484
    write(root, "small.txt", &vec![b'x'; 4096]);
8485
    let s = repo.snapshot("oxy status").unwrap();
8486
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
8487
    // With no limit the big file is taken in, and stays once it is.
8488
    repo.config.max_new_file = 0;
8489
    let s = repo.snapshot("oxy status").unwrap();
8490
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
8491
    repo.config.max_new_file = 1024;
8492
    let s = repo.snapshot("oxy status").unwrap();
8493
    assert!(
8494
        s.statuses.iter().any(|p| p.path == "big.bin"),
8495
        "already in the working copy"
8496
    );
8497
    assert!(repo.skipped_large().is_empty());
8498
}
8499
8500
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
8501
/// snapshots expire, and kept while they have not.
8502
#[test]
8503
fn gc_prunes_what_only_expired_snapshots_held() {
8504
    hermetic();
8505
    let dir = tempfile::tempdir().unwrap();
8506
    let root = dir.path();
8507
    let mut repo = Repo::init(root).unwrap();
8508
    repo.config.gc_grace_days = 0;
8509
    write(root, "a.txt", b"a\n");
8510
    repo.commit("a", &[]).unwrap();
8511
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
8512
    write(root, "image.tar", &image);
8513
    repo.snapshot("oxy status").unwrap();
8514
    std::fs::remove_file(root.join("image.tar")).unwrap();
8515
    repo.snapshot("oxy status").unwrap();
8516
    let blob = Repo::blob_ref(&image);
8517
    assert!(repo.store().has(&blob));
8518
    repo.gc(true).unwrap();
8519
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
8520
    repo.config.snapshot_retention_days = 0;
8521
    repo.gc(true).unwrap();
8522
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
8523
    assert_eq!(
8524
        repo.file_at("a.txt", None).unwrap(),
8525
        b"a\n",
8526
        "committed files stay"
8527
    );
8528
}