OXYGENHUB
# efad40f9ac8e oxygen / crates / oxy-core / src / repo / tests.rs
317.3 KiB · Rust · last changed A full change hash resolves without its # 24 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 (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5181
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5182
    assert_eq!(repo.config.bookmark, "feature");
5183
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5184
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5185
    assert!(!root.join("gone.txt").exists());
5186
    let snap = repo.snapshot("status").unwrap();
5187
    assert_eq!(
5188
        statuses(&snap),
5189
        vec![
5190
            ("a.txt".to_string(), ChangeStatus::Modified),
5191
            ("gone.txt".to_string(), ChangeStatus::Removed),
5192
            ("new.txt".to_string(), ChangeStatus::Added)
5193
        ]
5194
    );
5195
    repo.commit("the work", &[]).unwrap();
5196
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5197
5198
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5199
    repo.bookmark_switch("main", false).unwrap();
5200
    write(root, "b.txt", b"b on main\n");
5201
    repo.commit("b on main", &[]).unwrap();
5202
    repo.bookmark_switch("feature", false).unwrap();
5203
    write(root, "b.txt", b"b edited\n");
5204
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5205
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5206
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5207
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5208
}
5209
5210
/// Merging and checking out (feedback 3): a working copy without changes
5211
/// follows a merge whichever state it sat on; a refused checkout names
5212
/// what is in the way; `checkout --carry` takes the work along.
5213
#[test]
5214
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5215
    hermetic();
5216
    let dir = tempfile::tempdir().unwrap();
5217
    let root = dir.path();
5218
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5219
    write(root, "a.txt", b"a\n");
5220
    let h1 = repo.commit("a", &[]).unwrap();
5221
    write(root, "b.txt", b"b\n");
5222
    repo.commit("b", &[]).unwrap();
5223
    repo.bookmark_create("feature", None).unwrap();
5224
    repo.bookmark_switch("feature", false).unwrap();
5225
    write(root, "c.txt", b"c\n");
5226
    repo.commit("c on feature", &[]).unwrap();
5227
    repo.bookmark_switch("main", false).unwrap();
5228
    // The working copy sits on an older state than main's heads.
5229
    repo.checkout(&[h1], false, "checkout").unwrap();
5230
    assert!(!root.join("b.txt").exists());
5231
    let m = repo.merge("feature").unwrap();
5232
    assert!(m.checked_out, "a clean working copy follows the merge");
5233
    for f in ["a.txt", "b.txt", "c.txt"] {
5234
        assert!(root.join(f).exists(), "{f}");
5235
    }
5236
5237
    // A refusal says which paths are in the way and what to do.
5238
    fs::remove_file(root.join("b.txt")).unwrap();
5239
    write(root, "a.txt", b"a edited\n");
5240
    let err = repo
5241
        .checkout(&[h1], false, "checkout")
5242
        .unwrap_err()
5243
        .to_string();
5244
    assert!(
5245
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5246
        "{err}"
5247
    );
5248
    // --carry takes them along: h1 has a.txt as the base has it, and the
5249
    // removed b.txt is already as h1 has it (none), so that is no conflict
5250
    // either (oxygen#100).
5251
    let (_, carried) = repo
5252
        .checkout_carry(&[h1], "the first change", "checkout")
5253
        .unwrap();
5254
    assert_eq!(carried, vec!["a.txt"]);
5255
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5256
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5257
}
5258
5259
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5260
/// user identity not stored in a new repository yet is fine while its
5261
/// secret key is there; an added subrepo is listed as not committed yet.
5262
#[test]
5263
fn a_new_repository_is_healthy_before_its_first_commit() {
5264
    hermetic();
5265
    let dir = tempfile::tempdir().unwrap();
5266
    let root = dir.path();
5267
    let home = root.join("home");
5268
    let mut first = Repo::init(&root.join("first"))
5269
        .unwrap()
5270
        .with_home(home.clone());
5271
    let (key, _) = first
5272
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5273
        .unwrap();
5274
    let repo = Repo::init(&root.join("second"))
5275
        .unwrap()
5276
        .with_home(home.clone());
5277
    // Only the secret key: no identity object anywhere this repository sees.
5278
    let keys = repo.keys_dir.clone();
5279
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5280
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5281
    let r = repo.doctor(true);
5282
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5283
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5284
    assert!(id.message.contains("first signed change"), "{}", id.message);
5285
5286
    // A subrepo added and not committed yet is listed, pinned where it is.
5287
    let lib = root.join("lib");
5288
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5289
    write(&lib, "x.txt", b"x\n");
5290
    l.commit("x", &[]).unwrap();
5291
    let second = root.join("second");
5292
    write(&second, "a.txt", b"a\n");
5293
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5294
        .unwrap();
5295
    let subs = repo.subrepos().unwrap();
5296
    assert_eq!(subs.len(), 1);
5297
    assert_eq!(
5298
        (subs[0].path.as_str(), subs[0].committed),
5299
        ("deps/lib", false)
5300
    );
5301
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5302
    repo.commit("add lib", &[]).unwrap();
5303
    let subs = repo.subrepos().unwrap();
5304
    assert!(subs[0].committed, "committed now");
5305
}
5306
5307
/// Commit, diff, hunks and discard use the partial snapshot: a file
5308
/// unchanged since the manifest is neither read nor rendered, and showing
5309
/// a change renders only what it edits, the same as from a full base.
5310
#[cfg(unix)]
5311
#[test]
5312
fn commits_and_diffs_leave_unchanged_files_alone() {
5313
    use std::os::unix::fs::PermissionsExt;
5314
    hermetic();
5315
    let dir = tempfile::tempdir().unwrap();
5316
    let root = dir.path();
5317
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5318
    write(root, "big.txt", b"lots\nof\nlines\n");
5319
    write(root, "a.txt", b"one\ntwo\n");
5320
    repo.commit("base", &[]).unwrap();
5321
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5322
    for f in ["big.txt", "a.txt"] {
5323
        fs::File::options()
5324
            .write(true)
5325
            .open(root.join(f))
5326
            .unwrap()
5327
            .set_modified(old)
5328
            .unwrap();
5329
    }
5330
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5331
    // big.txt cannot be read at all from here on.
5332
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5333
5334
    write(root, "a.txt", b"one\nTWO\nthree\n");
5335
    let diff = repo.diff_files(None).unwrap();
5336
    assert_eq!(
5337
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5338
        ["a.txt"]
5339
    );
5340
    let (_, hunks) = repo.hunks().unwrap();
5341
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5342
    let h = repo.commit("edit a", &[]).unwrap();
5343
5344
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5345
    let c = repo.store().get_change(&h).unwrap();
5346
    let full = repo.load_state(&c.deps).unwrap();
5347
    let want = render_change(&c, &full, &full.materialize());
5348
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5349
    let (base, snap) = repo.change_base(&c).unwrap();
5350
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5351
5352
    // Discarding works the same way.
5353
    write(root, "a.txt", b"scratch\n");
5354
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5355
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5356
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5357
}
5358
5359
/// A replace conflict (spec §9.3) is settled by a change that writes one
5360
/// candidate, or new bytes, at the path when the caller names it; a plain
5361
/// snapshot of a checkout never settles it on its own.
5362
#[test]
5363
fn replace_conflicts_are_settled_when_asked() {
5364
    hermetic();
5365
    let dir = tempfile::tempdir().unwrap();
5366
    let root = dir.path();
5367
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5368
    let blob = |n: u8| {
5369
        let mut v = vec![0u8; 64];
5370
        v[1] = n;
5371
        v
5372
    };
5373
    write(root, "img.bin", &blob(1));
5374
    repo.commit("add img", &[]).unwrap();
5375
    repo.bookmark_create("other", None).unwrap();
5376
    write(root, "img.bin", &blob(2));
5377
    repo.commit("img two", &[]).unwrap();
5378
    repo.bookmark_switch("other", false).unwrap();
5379
    write(root, "img.bin", &blob(3));
5380
    repo.commit("img three", &[]).unwrap();
5381
    repo.bookmark_switch("main", false).unwrap();
5382
    repo.merge("other").unwrap();
5383
    let heads = repo.bookmark_heads().unwrap();
5384
    let merged = repo.load_state(&heads).unwrap().materialize();
5385
    assert!(
5386
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5387
        "a replace conflict"
5388
    );
5389
    // A snapshot of the checkout records nothing.
5390
    assert!(repo
5391
        .snapshot("status")
5392
        .unwrap()
5393
        .statuses
5394
        .iter()
5395
        .all(|s| s.path != "img.bin"));
5396
5397
    // Keeping candidate 3 settles it.
5398
    let author = repo.author();
5399
    let edits = [FileEdit {
5400
        path: "img.bin".into(),
5401
        content: Some(blob(3)),
5402
    }];
5403
    let c = repo
5404
        .build_change(&heads, &edits, "keep three", author)
5405
        .unwrap();
5406
    assert_eq!(c.kind, ChangeKind::Resolution);
5407
    let mut st = repo.load_state(&heads).unwrap();
5408
    for d in &c.deps {
5409
        assert!(st.contains(d));
5410
    }
5411
    assert!(
5412
        heads.iter().all(|h| c.deps.contains(h)),
5413
        "depends on both contributors"
5414
    );
5415
    st.add(c).unwrap();
5416
    let after = st.materialize();
5417
    assert!(!after.is_conflicted());
5418
    assert_eq!(
5419
        after.files["img.bin"].content,
5420
        FileContent::Opaque {
5421
            blobs: vec![Repo::blob_ref(&blob(3))]
5422
        }
5423
    );
5424
5425
    // New bytes settle it too.
5426
    let edits = [FileEdit {
5427
        path: "img.bin".into(),
5428
        content: Some(blob(9)),
5429
    }];
5430
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5431
    let mut st = repo.load_state(&heads).unwrap();
5432
    st.add(c).unwrap();
5433
    assert_eq!(
5434
        st.materialize().files["img.bin"].content,
5435
        FileContent::Opaque {
5436
            blobs: vec![Repo::blob_ref(&blob(9))]
5437
        }
5438
    );
5439
}
5440
5441
/// The history of a range of lines (spec §27): the changes that wrote
5442
/// or deleted its atoms, or deleted atoms from between them; edits outside
5443
/// the range and changes the range's lines survived are not in it.
5444
#[test]
5445
fn line_ranges_have_exact_histories() {
5446
    hermetic();
5447
    let dir = tempfile::tempdir().unwrap();
5448
    let root = dir.path();
5449
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5450
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5451
    let base = repo.commit("add f", &[]).unwrap();
5452
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5453
    let outside = repo.commit("change the import", &[]).unwrap();
5454
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5455
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5456
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5457
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5458
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5459
    let after = repo.commit("add b after a", &[]).unwrap();
5460
    let heads = repo.bookmark_heads().unwrap();
5461
5462
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5463
    let hist: Vec<ChangeHash> = repo
5464
        .line_history(&heads, "f.rs", 2, 4)
5465
        .unwrap()
5466
        .iter()
5467
        .map(|e| e.hash)
5468
        .collect();
5469
    for (h, what) in [
5470
        (base, "wrote it"),
5471
        (inside, "edited a line"),
5472
        (deleted, "deleted a line from inside"),
5473
    ] {
5474
        assert!(hist.contains(&h), "{what}");
5475
    }
5476
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5477
        assert!(!hist.contains(&h), "{what}");
5478
    }
5479
    assert_eq!(hist[0], deleted, "newest first");
5480
    // One line: only what touched it.
5481
    let one: Vec<ChangeHash> = repo
5482
        .line_history(&heads, "f.rs", 1, 1)
5483
        .unwrap()
5484
        .iter()
5485
        .map(|e| e.hash)
5486
        .collect();
5487
    assert!(one.contains(&outside) && !one.contains(&inside));
5488
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5489
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5490
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5491
}
5492
5493
#[test]
5494
fn receipts_are_kept_with_their_state_and_verified() {
5495
    use crate::receipt::{Receipt, SignedReceipt};
5496
    hermetic();
5497
    let dir = tempfile::tempdir().unwrap();
5498
    let root = dir.path();
5499
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5500
    write(root, "a.txt", b"1\n");
5501
    repo.commit("A", &[]).unwrap();
5502
    let heads = repo.bookmark_heads().unwrap();
5503
    let state = repo
5504
        .store()
5505
        .put_state(&StateObject::new(heads.clone()))
5506
        .unwrap();
5507
    let out = repo.store_blob(b"built\n").unwrap();
5508
    let receipt = Receipt {
5509
        job_name: "build".into(),
5510
        pipeline_hash: ObjectRef([1; 32]),
5511
        scope_tree_hash: ObjectRef([2; 32]),
5512
        inputs: vec![],
5513
        environment: ObjectRef([3; 32]),
5514
        outputs: vec![out],
5515
        exit_code: 0,
5516
        duration_ms: 42,
5517
    };
5518
    let sk = SecretKey::generate();
5519
    let runner = sk.identity("earth-1", "runner@earth", 1);
5520
    let sr = SignedReceipt::sign(
5521
        receipt.clone(),
5522
        repo.id().unwrap(),
5523
        state,
5524
        "demo#1",
5525
        &runner,
5526
        &sk,
5527
    );
5528
5529
    let r = repo.add_receipt(&sr).unwrap();
5530
    let found = repo.receipts(&heads).unwrap();
5531
    assert_eq!(found.len(), 1);
5532
    assert_eq!(found[0].attest, r);
5533
    assert_eq!(found[0].signed, sr);
5534
    assert!(found[0].problem.is_none() && !found[0].revoked);
5535
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5536
5537
    // Another repository's receipt, or a forged one, is refused.
5538
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5539
    assert!(repo
5540
        .add_receipt(&elsewhere)
5541
        .unwrap_err()
5542
        .to_string()
5543
        .contains("another repository"));
5544
    let mut forged = sr.clone();
5545
    forged.receipt.exit_code = 1;
5546
    assert!(repo
5547
        .add_receipt(&forged)
5548
        .unwrap_err()
5549
        .to_string()
5550
        .contains("does not verify"));
5551
5552
    // gc keeps the receipt, its runner and its output while the state lives.
5553
    repo.gc(true).unwrap();
5554
    assert_eq!(repo.receipts(&heads).unwrap().len(), 1);
5555
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5556
    assert!(repo.fsck().unwrap().problems.is_empty());
5557
}
5558
5559
#[test]
5560
fn status_leaves_an_unchanged_manifest_alone() {
5561
    hermetic();
5562
    let dir = tempfile::tempdir().unwrap();
5563
    let root = dir.path();
5564
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5565
    write(root, "a.txt", b"1\n");
5566
    write(root, "b.txt", b"2\n");
5567
    repo.commit("A", &[]).unwrap();
5568
    // Files last touched well outside the racy window.
5569
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5570
    for f in ["a.txt", "b.txt"] {
5571
        fs::File::options()
5572
            .write(true)
5573
            .open(root.join(f))
5574
            .unwrap()
5575
            .set_modified(old)
5576
            .unwrap();
5577
    }
5578
    repo.snapshot_status("status").unwrap();
5579
    let path = repo.manifest_path();
5580
    let first = fs::read(&path).unwrap();
5581
    repo.snapshot_status("status").unwrap();
5582
    assert_eq!(
5583
        fs::read(&path).unwrap(),
5584
        first,
5585
        "an unchanged tree does not rewrite the manifest"
5586
    );
5587
    // A change rewrites it.
5588
    write(root, "a.txt", b"1\n2\n");
5589
    repo.snapshot_status("status").unwrap();
5590
    assert_ne!(fs::read(&path).unwrap(), first);
5591
}
5592
5593
#[test]
5594
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5595
    hermetic();
5596
    let dir = tempfile::tempdir().unwrap();
5597
    let root = dir.path();
5598
    let origin_path = root.join("origin");
5599
    Repo::init(&origin_path).unwrap();
5600
    let origin_url = origin_path.to_string_lossy().to_string();
5601
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5602
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5603
    write(&root.join("a"), "big.txt", big.as_bytes());
5604
    write(&root.join("a"), "small.txt", b"small\n");
5605
    let h1 = a.commit("large", &[]).unwrap();
5606
    let (_, body) = a.store().get(&h1).unwrap();
5607
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5608
    assert!(a.push("origin", false).unwrap()[0].ok);
5609
5610
    // A clone reads the text from the blobs that came with the change.
5611
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5612
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5613
    // An edit in the middle of the stored insert is an ordinary change.
5614
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5615
    write(&root.join("b"), "big.txt", edited.as_bytes());
5616
    let h2 = b.commit("edit", &[]).unwrap();
5617
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5618
    assert!(b.push("origin", false).unwrap()[0].ok);
5619
    assert!(a.pull("origin").unwrap().checked_out);
5620
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5621
    assert_eq!(
5622
        a.fsck().unwrap().errors(),
5623
        0,
5624
        "{:?}",
5625
        a.fsck().unwrap().problems
5626
    );
5627
5628
    // With zero retention gc keeps the text blobs of every kept change.
5629
    let mut a = Repo::open(&root.join("a")).unwrap();
5630
    a.config.set("core.op-retention", "0").unwrap();
5631
    a.save_config().unwrap();
5632
    let a = Repo::open(&root.join("a")).unwrap();
5633
    a.gc(true).unwrap();
5634
    let a = Repo::open(&root.join("a")).unwrap();
5635
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5636
    assert_eq!(
5637
        a.fsck().unwrap().errors(),
5638
        0,
5639
        "{:?}",
5640
        a.fsck().unwrap().problems
5641
    );
5642
    // And a clone of the packed repository reads them from its packs.
5643
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5644
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5645
    drop(c);
5646
}
5647
5648
#[test]
5649
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5650
    hermetic();
5651
    let dir = tempfile::tempdir().unwrap();
5652
    let root = dir.path();
5653
    let repo = Repo::init(root).unwrap();
5654
    write(root, "a.txt", b"a\n");
5655
    let a = repo.commit("a", &[]).unwrap();
5656
    write(root, "b.txt", b"b\n");
5657
    repo.commit("b", &[]).unwrap();
5658
    let (x, op) = repo.head_op().unwrap();
5659
    let ws = *op.view.workspaces.keys().next().unwrap();
5660
    let mut one = op.view.clone();
5661
    one.workspaces.insert(ws, a);
5662
    let mut two = op.view.clone();
5663
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5664
    let first = repo.record_op(&[x], "one", one).unwrap();
5665
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5666
    assert!(
5667
        e.to_string()
5668
            .contains("changed this working copy at the same time"),
5669
        "{e}"
5670
    );
5671
    assert_eq!(
5672
        repo.head_op().unwrap().0,
5673
        first,
5674
        "the second is not recorded"
5675
    );
5676
}
5677
5678
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5679
/// rewrote the working copy recorded the half-written files as edits, and
5680
/// its view replaced the switch's.
5681
#[test]
5682
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5683
    hermetic();
5684
    let dir = tempfile::tempdir().unwrap();
5685
    let root = dir.path().to_path_buf();
5686
    let mut repo = Repo::init(&root).unwrap();
5687
    write(&root, "keep.txt", b"keep\n");
5688
    repo.commit("base", &[]).unwrap();
5689
    repo.bookmark_create("small", None).unwrap();
5690
    for i in 0..300 {
5691
        write(
5692
            &root,
5693
            &format!("many/f{i}.txt"),
5694
            format!("file {i}\n").as_bytes(),
5695
        );
5696
    }
5697
    repo.commit("many", &[]).unwrap();
5698
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5699
    let watcher = {
5700
        let (root, stop) = (root.clone(), stop.clone());
5701
        std::thread::spawn(move || {
5702
            let r = Repo::open(&root).unwrap();
5703
            let mut ran = 0;
5704
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
5705
                if r.snapshot_status("oxy status").is_ok() {
5706
                    ran += 1;
5707
                }
5708
            }
5709
            ran
5710
        })
5711
    };
5712
    for i in 0..20 {
5713
        let to = if i % 2 == 0 { "small" } else { "main" };
5714
        repo.bookmark_switch(to, false).unwrap();
5715
    }
5716
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
5717
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
5718
    // Back on main, clean, with every file where main has it.
5719
    let repo = Repo::open(&root).unwrap();
5720
    let s = repo.snapshot_status("oxy status").unwrap();
5721
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
5722
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
5723
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
5724
    assert!(root.join("many/f299.txt").exists());
5725
}
5726
5727
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
5728
/// put a subrepo that was ahead of its pin back at the pin and moved the
5729
/// subrepo's own bookmark backwards.
5730
#[test]
5731
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
5732
    hermetic();
5733
    let dir = tempfile::tempdir().unwrap();
5734
    let root = dir.path();
5735
    Repo::init(&root.join("lib-origin")).unwrap();
5736
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5737
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
5738
    write(&root.join("lib"), "lib.txt", b"v1\n");
5739
    lib.commit("lib v1", &[]).unwrap();
5740
    assert!(lib.push("origin", false).unwrap()[0].ok);
5741
5742
    let app_dir = root.join("app");
5743
    let mut app = Repo::init(&app_dir).unwrap();
5744
    write(&app_dir, "main.txt", b"app\n");
5745
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5746
    app.commit("app with lib", &[]).unwrap();
5747
    app.bookmark_create("feature", None).unwrap();
5748
5749
    // New work in the subrepo, not yet pinned by the parent.
5750
    let nested_dir = app_dir.join("libs/lib");
5751
    let nested = Repo::open(&nested_dir).unwrap();
5752
    write(&nested_dir, "new.txt", b"new\n");
5753
    let l2 = nested.commit("lib: new file", &[]).unwrap();
5754
    drop(nested);
5755
5756
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
5757
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
5758
    let nested = Repo::open(&nested_dir).unwrap();
5759
    assert!(
5760
        nested.bookmark_heads().unwrap().contains(&l2),
5761
        "its bookmark kept its work"
5762
    );
5763
    assert!(nested_dir.join("new.txt").exists(), "and its files");
5764
    let s = app.snapshot("status").unwrap();
5765
    assert_eq!(
5766
        statuses(&s),
5767
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
5768
    );
5769
}
5770
5771
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
5772
/// moving `main` to a change this clone had pushed on another bookmark,
5773
/// the first `pull` said "Already up to date" while `main` was behind.
5774
#[test]
5775
fn pull_takes_a_remote_move_to_changes_already_here() {
5776
    hermetic();
5777
    let dir = tempfile::tempdir().unwrap();
5778
    let root = dir.path();
5779
    let origin_path = root.join("origin");
5780
    let origin = Repo::init(&origin_path).unwrap();
5781
    let url = origin_path.to_string_lossy().to_string();
5782
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
5783
    write(&root.join("b"), "base.txt", b"base\n");
5784
    b.commit("base", &[]).unwrap();
5785
    assert!(b.push("origin", false).unwrap()[0].ok);
5786
5787
    // A feature bookmark with one change, pushed.
5788
    b.bookmark_create("feat", None).unwrap();
5789
    b.bookmark_switch("feat", false).unwrap();
5790
    write(&root.join("b"), "x.txt", b"x\n");
5791
    let x = b.commit("x", &[]).unwrap();
5792
    assert!(b.push("origin", false).unwrap()[0].ok);
5793
    b.bookmark_switch("main", false).unwrap();
5794
5795
    // The remote lands it: its main moves to the feature's state.
5796
    let feat = origin
5797
        .store()
5798
        .get_state(&origin.view().unwrap().bookmarks["feat"])
5799
        .unwrap()
5800
        .heads;
5801
    origin.bookmark_set("main", &feat).unwrap();
5802
5803
    let r = b.pull("origin").unwrap();
5804
    assert!(r.changed, "{r:?}");
5805
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
5806
    let main = b
5807
        .bookmarks()
5808
        .unwrap()
5809
        .into_iter()
5810
        .find(|m| m.name == "main")
5811
        .unwrap();
5812
    assert_eq!(main.behind, Some(0), "{main:?}");
5813
}
5814
5815
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
5816
/// to one only the remote has makes a local bookmark from it; a pull moves
5817
/// every local bookmark the remote has too; a clone checks out the remote's
5818
/// default bookmark.
5819
#[test]
5820
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
5821
    hermetic();
5822
    let dir = tempfile::tempdir().unwrap();
5823
    let root = dir.path();
5824
    let origin_path = root.join("origin");
5825
    let mut origin = Repo::init(&origin_path).unwrap();
5826
    let url = origin_path.to_string_lossy().to_string();
5827
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
5828
    write(&root.join("a"), "base.txt", b"base\n");
5829
    a.commit("base", &[]).unwrap();
5830
    assert!(a.push("origin", false).unwrap()[0].ok);
5831
    a.bookmark_create("develop", None).unwrap();
5832
    a.bookmark_switch("develop", false).unwrap();
5833
    write(&root.join("a"), "base.txt", b"base\nd1\n");
5834
    let d1 = a.commit("d1", &[]).unwrap();
5835
    assert!(a.push("origin", false).unwrap()[0].ok);
5836
5837
    // A clone has main only; origin/develop is a name all the same.
5838
    let c_root = root.join("c");
5839
    let mut c = Repo::clone(&url, &c_root).unwrap();
5840
    assert_eq!(c.config.bookmark, "main");
5841
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
5842
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
5843
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
5844
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
5845
5846
    // Switching makes the local bookmark from origin's.
5847
    c.bookmark_switch("develop", false).unwrap();
5848
    assert_eq!(c.config.bookmark, "develop");
5849
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
5850
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
5851
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
5852
    assert!(c.bookmark_switch("nowhere", false).is_err());
5853
5854
    // Both bookmarks move on the remote; one pull takes both.
5855
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
5856
    let d2 = a.commit("d2", &[]).unwrap();
5857
    assert!(a.push("origin", false).unwrap()[0].ok);
5858
    a.bookmark_switch("main", false).unwrap();
5859
    write(&root.join("a"), "m.txt", b"m\n");
5860
    let m = a.commit("m", &[]).unwrap();
5861
    assert!(a.push("origin", false).unwrap()[0].ok);
5862
    let r = c.pull("origin").unwrap();
5863
    assert!(r.changed && r.checked_out, "{r:?}");
5864
    assert_eq!(r.heads, vec![d2]);
5865
    assert_eq!(r.others, vec!["main".to_string()]);
5866
    assert!(c.resolve_heads("main").unwrap().contains(&m));
5867
    assert_eq!(
5868
        fs::read(c_root.join("base.txt")).unwrap(),
5869
        b"base\nd1\nd2\n"
5870
    );
5871
    let again = c.pull("origin").unwrap();
5872
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
5873
5874
    // A clone checks out the remote's default bookmark.
5875
    origin.config.set("workspace.bookmark", "develop").unwrap();
5876
    origin.save_config().unwrap();
5877
    let e = Repo::clone(&url, &root.join("e")).unwrap();
5878
    assert_eq!(e.config.bookmark, "develop");
5879
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
5880
    let reopened = Repo::open(&root.join("e")).unwrap();
5881
    assert_eq!(reopened.config.bookmark, "develop");
5882
    // REMOTE/NAME names the remote's bookmark to switch to.
5883
    let mut e = reopened;
5884
    e.bookmark_switch("origin/main", false).unwrap();
5885
    assert_eq!(e.config.bookmark, "main");
5886
    assert!(e.bookmark_heads().unwrap().contains(&m));
5887
}
5888
5889
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
5890
/// op restore goes back to an operation, files included, and undo takes
5891
/// the restore back whole; op revert undoes one operation alone; each
5892
/// operation's changes are described from the views.
5893
#[test]
5894
fn operations_can_be_read_restored_and_reverted() {
5895
    hermetic();
5896
    let dir = tempfile::tempdir().unwrap();
5897
    let root = dir.path();
5898
    let repo = Repo::init(root).unwrap();
5899
    write(root, "a.txt", b"a\n");
5900
    let first = repo.commit("first", &[]).unwrap();
5901
    write(root, "a.txt", b"a\nb\n");
5902
    let second = repo.commit("second", &[]).unwrap();
5903
    let at_second = repo.head_op().unwrap().0.to_hex();
5904
    repo.bookmark_create("keep", None).unwrap();
5905
    let created = repo.head_op().unwrap().0.to_hex();
5906
    write(root, "n.txt", b"n\n");
5907
    let third = repo.commit("third", &[]).unwrap();
5908
5909
    // What each operation changed.
5910
    let ops = repo.op_log().unwrap();
5911
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
5912
    assert!(
5913
        changes
5914
            .iter()
5915
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
5916
        "{changes:?}"
5917
    );
5918
    assert!(changes
5919
        .iter()
5920
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
5921
5922
    // Reading at an earlier operation.
5923
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
5924
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
5925
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
5926
    write(root, "z.txt", b"z\n");
5927
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
5928
    fs::remove_file(root.join("z.txt")).unwrap();
5929
    assert!(repo.resolve_op("zz").is_err());
5930
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
5931
5932
    // Restore goes back, files and all; undo takes it back whole.
5933
    repo.op_restore(&at_second, false).unwrap();
5934
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
5935
    assert!(!root.join("n.txt").exists());
5936
    repo.undo().unwrap();
5937
    let mut heads = repo.bookmark_heads().unwrap();
5938
    heads.sort();
5939
    let mut want = vec![second, third];
5940
    want.sort();
5941
    assert_eq!(heads, want);
5942
    assert!(
5943
        root.join("n.txt").exists(),
5944
        "the files came back with the undo"
5945
    );
5946
5947
    // Revert the bookmark's creation alone: the commit after it stays.
5948
    let r = repo.op_revert(&created).unwrap();
5949
    assert_eq!(r.reverted, vec!["keep".to_string()]);
5950
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
5951
    assert!(repo
5952
        .load_state(&repo.bookmark_heads().unwrap())
5953
        .unwrap()
5954
        .contains(&third));
5955
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
5956
    let _ = first;
5957
}
5958
5959
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
5960
/// from the status cache while every file is as the snapshot left it, and
5961
/// from a snapshot again as soon as one is not.
5962
#[test]
5963
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
5964
    hermetic();
5965
    let dir = tempfile::tempdir().unwrap();
5966
    let root = dir.path();
5967
    let repo = Repo::init(root).unwrap();
5968
    write(root, "a.txt", b"a\n");
5969
    write(root, "b.txt", b"b\n");
5970
    repo.commit("base", &[]).unwrap();
5971
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
5972
5973
    write(root, "a.txt", b"a\nmore\n");
5974
    assert_eq!(
5975
        repo.status_by_manifest().unwrap(),
5976
        None,
5977
        "no snapshot of the edit yet"
5978
    );
5979
    let snap = repo.snapshot_status("oxy status").unwrap();
5980
    assert_eq!(snap.statuses.len(), 1);
5981
    let cached = repo
5982
        .status_by_manifest()
5983
        .unwrap()
5984
        .expect("answered from the cache");
5985
    assert_eq!(cached.len(), 1);
5986
    assert_eq!(
5987
        (cached[0].path.as_str(), cached[0].status),
5988
        ("a.txt", ChangeStatus::Modified)
5989
    );
5990
5991
    // Any further change sends status back to a snapshot.
5992
    write(root, "a.txt", b"a\nmore\nand more\n");
5993
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
5994
    repo.snapshot_status("oxy status").unwrap();
5995
    assert!(repo.status_by_manifest().unwrap().is_some());
5996
    write(root, "new.txt", b"n\n");
5997
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
5998
    fs::remove_file(root.join("new.txt")).unwrap();
5999
    assert!(
6000
        repo.status_by_manifest().unwrap().is_some(),
6001
        "back as it was"
6002
    );
6003
    fs::remove_file(root.join("b.txt")).unwrap();
6004
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6005
    write(root, "b.txt", b"b\n");
6006
6007
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6008
    repo.snapshot_status("oxy status").unwrap();
6009
    repo.commit("more", &[]).unwrap();
6010
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6011
}
6012
6013
/// oxygen#41: while the status cache holds, the working copy's diff is
6014
/// rendered from the stored working-copy change, and says exactly what a
6015
/// snapshot's diff says.
6016
#[test]
6017
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6018
    hermetic();
6019
    let dir = tempfile::tempdir().unwrap();
6020
    let root = dir.path();
6021
    let repo = Repo::init(root).unwrap();
6022
    write(root, "a.txt", b"one\ntwo\nthree\n");
6023
    write(root, "gone.txt", b"bye\n");
6024
    repo.commit("base", &[]).unwrap();
6025
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6026
    write(root, "new.txt", b"hello\n");
6027
    fs::remove_file(root.join("gone.txt")).unwrap();
6028
    let snap = repo.snapshot_status("oxy status").unwrap();
6029
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6030
    assert!(
6031
        repo.status_by_manifest().unwrap().is_some(),
6032
        "the cache holds"
6033
    );
6034
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6035
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6036
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6037
}
6038
6039
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6040
/// while none has moved, the check stats the tracked files without listing
6041
/// the tree, and a file added or removed anywhere moves its directory's
6042
/// time, so the tree is listed again.
6043
#[test]
6044
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6045
    hermetic();
6046
    let dir = tempfile::tempdir().unwrap();
6047
    let root = dir.path();
6048
    let repo = Repo::init(root).unwrap();
6049
    write(root, "a.txt", b"a\n");
6050
    write(root, "sub/deep/b.txt", b"b\n");
6051
    repo.commit("base", &[]).unwrap();
6052
    // Out of the racy window: every file and directory a minute old.
6053
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6054
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6055
        fs::File::open(root.join(p))
6056
            .unwrap()
6057
            .set_modified(old)
6058
            .unwrap();
6059
    }
6060
    repo.snapshot_status("oxy status").unwrap();
6061
    repo.write_manifest(false, false).unwrap();
6062
    let m = repo.read_manifest().unwrap().unwrap().2;
6063
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6064
    assert_eq!(
6065
        repo.disk_differs_by_dirs(&m),
6066
        Some(false),
6067
        "no listing needed"
6068
    );
6069
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6070
6071
    // A same-size edit with a new time: found by its stat.
6072
    write(root, "sub/deep/b.txt", b"c\n");
6073
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6074
    write(root, "sub/deep/b.txt", b"b\n");
6075
    fs::File::open(root.join("sub/deep/b.txt"))
6076
        .unwrap()
6077
        .set_modified(old)
6078
        .unwrap();
6079
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6080
6081
    // A new file moves its directory's time: the tree must be listed.
6082
    write(root, "sub/deep/new.txt", b"n\n");
6083
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6084
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6085
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6086
    // A removed one too.
6087
    fs::remove_file(root.join("a.txt")).unwrap();
6088
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6089
}
6090
6091
/// oxygen#41: a commit right after a status takes the snapshot the status
6092
/// left (the status cache holds) rather than walking again, and commits
6093
/// exactly what a snapshot would have.
6094
#[test]
6095
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6096
    hermetic();
6097
    let dir = tempfile::tempdir().unwrap();
6098
    let root = dir.path();
6099
    let repo = Repo::init(root).unwrap();
6100
    write(root, "a.txt", b"a\nb\n");
6101
    write(root, ".oxyattributes", b"*.bin binary\n");
6102
    repo.commit("base", &[]).unwrap();
6103
    write(root, "a.txt", b"a\nB\n");
6104
    write(root, "new.txt", b"new\n");
6105
    let snap = repo.snapshot_status("oxy status").unwrap();
6106
    let cached = repo
6107
        .snapshot_from_cache()
6108
        .unwrap()
6109
        .expect("the cache holds");
6110
    assert_eq!(cached.wc_hash, snap.wc_hash);
6111
    assert_eq!(cached.statuses, snap.statuses);
6112
    assert!(
6113
        !cached.attributes.is_empty(),
6114
        "the .oxyattributes file was read"
6115
    );
6116
    let h = repo.commit("edit", &[]).unwrap();
6117
    let c = repo.store().get_change(&h).unwrap();
6118
    assert_eq!(
6119
        c.tree_ops.len() + c.edits.len(),
6120
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6121
    );
6122
    assert_eq!(
6123
        repo.status_by_manifest().unwrap(),
6124
        Some(vec![]),
6125
        "clean after the commit"
6126
    );
6127
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6128
}
6129
6130
/// oxygen#41: a clean check that verified racy entries restamps the
6131
/// manifest, so later checks can trust them, and a same-size rewrite
6132
/// straight afterwards is still found: entries within two seconds of the
6133
/// new time stay racy.
6134
#[test]
6135
fn a_verified_clean_check_restamps_the_manifest_safely() {
6136
    hermetic();
6137
    let dir = tempfile::tempdir().unwrap();
6138
    let root = dir.path();
6139
    let repo = Repo::init(root).unwrap();
6140
    write(root, "a.txt", b"one\n");
6141
    repo.commit("one", &[]).unwrap();
6142
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6143
    assert!(repo.clean_by_manifest().unwrap());
6144
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6145
    assert!(after > before, "restamped");
6146
    write(root, "a.txt", b"two\n");
6147
    assert!(
6148
        !repo.clean_by_manifest().unwrap(),
6149
        "a same-size rewrite is still seen"
6150
    );
6151
}
6152
6153
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6154
/// stored insert's text blob only when it builds that file's graph, and
6155
/// builds the same graph a full load does.
6156
#[test]
6157
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6158
    hermetic();
6159
    let dir = tempfile::tempdir().unwrap();
6160
    let root = dir.path();
6161
    let repo = Repo::init(root).unwrap();
6162
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6163
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6164
    write(root, "big.txt", big.as_bytes());
6165
    write(root, "other.txt", other.as_bytes());
6166
    let h = repo.commit("two large files", &[]).unwrap();
6167
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6168
    let h2 = repo.commit("append", &[]).unwrap();
6169
6170
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6171
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6172
        FileContent::Text { bytes, .. } => bytes.clone(),
6173
        other => panic!("{other:?}"),
6174
    };
6175
    // Built on demand, every graph renders as the full load's.
6176
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6177
    let big_node = full.files["big.txt"].node;
6178
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6179
    repo.load_all_graphs(&mut hist).unwrap();
6180
    let rendered = hist.materialize();
6181
    for p in ["big.txt", "other.txt"] {
6182
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6183
    }
6184
6185
    // Without other.txt's text blob, history still loads and big.txt still
6186
    // builds: nothing read the other text.
6187
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6188
    assert_eq!(texts.len(), 2);
6189
    let content = |r: &ObjectRef| -> Vec<u8> {
6190
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6191
        blob.chunks
6192
            .iter()
6193
            .flat_map(|c| repo.store().get(c).unwrap().1)
6194
            .collect()
6195
    };
6196
    let other_text = texts
6197
        .iter()
6198
        .filter_map(|t| match t {
6199
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6200
            _ => None,
6201
        })
6202
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6203
        .unwrap();
6204
    repo.store().remove_loose_for_test(&other_text).unwrap();
6205
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6206
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6207
    assert!(repo
6208
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6209
        .is_err());
6210
}
6211
6212
/// oxygen#35: the first status after a commit read and rendered every
6213
/// file (79 s and more than 14 GB on the Linux tree), because the
6214
/// manifest had no graph keys for files the commit added.
6215
#[test]
6216
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6217
    use std::os::unix::fs::PermissionsExt;
6218
    hermetic();
6219
    let dir = tempfile::tempdir().unwrap();
6220
    let root = dir.path();
6221
    let repo = Repo::init(root).unwrap();
6222
    let files = ["a.txt", "b.txt", "d/c.txt"];
6223
    for p in files {
6224
        write(root, p, format!("{p}\n").as_bytes());
6225
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6226
        fs::File::options()
6227
            .write(true)
6228
            .open(root.join(p))
6229
            .unwrap()
6230
            .set_modified(old)
6231
            .unwrap();
6232
    }
6233
    repo.commit("added", &[]).unwrap();
6234
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6235
    assert!(
6236
        m.entries.values().all(|e| e.graph.is_some()),
6237
        "keys recorded at commit"
6238
    );
6239
    // Unreadable files prove the next status reads none of them.
6240
    for p in files {
6241
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6242
    }
6243
    let snap = repo.snapshot_status("status").unwrap();
6244
    for p in files {
6245
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6246
    }
6247
    assert!(!snap.changed && snap.statuses.is_empty());
6248
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6249
}
6250
6251
/// oxygen#35: a checkout reads, renders and writes only the files whose
6252
/// graphs differ, and renders the rest a batch at a time.
6253
#[test]
6254
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6255
    use std::os::unix::fs::PermissionsExt;
6256
    hermetic();
6257
    let dir = tempfile::tempdir().unwrap();
6258
    let root = dir.path();
6259
    let origin = root.join("origin");
6260
    let mut repo = Repo::init(&origin).unwrap();
6261
    // More files than one batch holds.
6262
    let n = 2100;
6263
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6264
    for i in 0..n {
6265
        let p = format!("f/{i:04}.txt");
6266
        write(&origin, &p, format!("file {i}\n").as_bytes());
6267
        fs::File::options()
6268
            .write(true)
6269
            .open(origin.join(&p))
6270
            .unwrap()
6271
            .set_modified(old)
6272
            .unwrap();
6273
    }
6274
    repo.commit("many", &[]).unwrap();
6275
    repo.bookmark_create("feature", None).unwrap();
6276
    repo.bookmark_switch("feature", false).unwrap();
6277
    write(&origin, "f/0007.txt", b"changed\n");
6278
    repo.commit("one change", &[]).unwrap();
6279
6280
    // Switching back to main must not read the unchanged files.
6281
    for i in 0..n {
6282
        if i != 7 {
6283
            let p = origin.join(format!("f/{i:04}.txt"));
6284
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6285
        }
6286
    }
6287
    let r = repo.bookmark_switch("main", false).unwrap();
6288
    for i in 0..n {
6289
        let p = origin.join(format!("f/{i:04}.txt"));
6290
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6291
    }
6292
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6293
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6294
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6295
6296
    // A clone renders every file, across batches.
6297
    let c = root.join("clone");
6298
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6299
    for i in [0, 2047, 2048, n - 1] {
6300
        assert_eq!(
6301
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6302
            format!("file {i}\n").as_bytes()
6303
        );
6304
    }
6305
    let cloned = Repo::open(&c).unwrap();
6306
    assert!(cloned
6307
        .snapshot_status("status")
6308
        .unwrap()
6309
        .statuses
6310
        .is_empty());
6311
}
6312
6313
/// A file written just before the manifest (inside the racy window) is
6314
/// checked by its hash: trusted when equal, caught when edited in place
6315
/// with the same size and time.
6316
#[test]
6317
fn a_racy_manifest_entry_is_checked_by_hash() {
6318
    hermetic();
6319
    let dir = tempfile::tempdir().unwrap();
6320
    let root = dir.path();
6321
    let repo = Repo::init(root).unwrap();
6322
    write(root, "a.txt", b"one\n");
6323
    repo.commit("fresh", &[]).unwrap();
6324
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6325
    let t = fs::metadata(root.join("a.txt"))
6326
        .unwrap()
6327
        .modified()
6328
        .unwrap();
6329
    write(root, "a.txt", b"two\n");
6330
    fs::File::options()
6331
        .write(true)
6332
        .open(root.join("a.txt"))
6333
        .unwrap()
6334
        .set_modified(t)
6335
        .unwrap();
6336
    assert!(
6337
        !repo.clean_by_manifest().unwrap(),
6338
        "same size and time, other bytes"
6339
    );
6340
    assert_eq!(
6341
        statuses(&repo.snapshot_status("status").unwrap()),
6342
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6343
    );
6344
}
6345
6346
/// A fetch on one machine moves changes as stored, text blobs among the
6347
/// objects; a change whose text blob did not come is refused, not stored.
6348
#[test]
6349
fn a_raw_bundle_without_a_changes_text_is_refused() {
6350
    hermetic();
6351
    let dir = tempfile::tempdir().unwrap();
6352
    let root = dir.path();
6353
    let a = Repo::init(&root.join("a")).unwrap();
6354
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6355
    write(&root.join("a"), "big.txt", big.as_bytes());
6356
    let h = a.commit("big", &[]).unwrap();
6357
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6358
    assert_eq!(bundle.raw_changes.len(), 1);
6359
    assert!(bundle.changes.is_empty());
6360
    let b = Repo::init(&root.join("b")).unwrap();
6361
    let mut without = bundle.clone();
6362
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6363
    let e = b.import_bundle(&without, false).unwrap_err();
6364
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6365
    assert!(!b.store().has(&h));
6366
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6367
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6368
}
6369
6370
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6371
/// again was a second node for one Git path, so a file moved into it on
6372
/// another line, where the first node still stood, ended up in two places.
6373
/// An import now brings the directory back rather than make a new one.
6374
#[test]
6375
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6376
    hermetic();
6377
    if std::process::Command::new("git")
6378
        .arg("--version")
6379
        .output()
6380
        .is_err()
6381
    {
6382
        eprintln!("git not installed; skipping");
6383
        return;
6384
    }
6385
    let dir = tempfile::tempdir().unwrap();
6386
    let root = dir.path();
6387
    let g = root.join("src.git");
6388
    fs::create_dir_all(&g).unwrap();
6389
    let git = |args: &[&str]| -> String {
6390
        let out = std::process::Command::new("git")
6391
            .arg("-C")
6392
            .arg(&g)
6393
            .args([
6394
                "-c",
6395
                "user.name=Grace",
6396
                "-c",
6397
                "[email protected]",
6398
                "-c",
6399
                "commit.gpgsign=false",
6400
            ])
6401
            .args(args)
6402
            .output()
6403
            .unwrap();
6404
        assert!(
6405
            out.status.success(),
6406
            "git {args:?}: {}",
6407
            String::from_utf8_lossy(&out.stderr)
6408
        );
6409
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6410
    };
6411
    git(&["init", "-q", "-b", "main"]);
6412
    write(&g, "d/a.txt", b"a\n");
6413
    write(&g, "c/x.txt", b"x\n");
6414
    git(&["add", "."]);
6415
    git(&["commit", "-qm", "base"]);
6416
    // One line: move x into d while d still stands.
6417
    git(&["checkout", "-qb", "side"]);
6418
    git(&["mv", "c/x.txt", "d/x.txt"]);
6419
    git(&["commit", "-qm", "x into d"]);
6420
    // The other: d goes, comes back, and x moves into it too.
6421
    git(&["checkout", "-q", "main"]);
6422
    git(&["rm", "-q", "d/a.txt"]);
6423
    git(&["commit", "-qm", "d goes"]);
6424
    write(&g, "d/b.txt", b"b\n");
6425
    git(&["add", "."]);
6426
    git(&["commit", "-qm", "d comes back"]);
6427
    git(&["mv", "c/x.txt", "d/x.txt"]);
6428
    git(&["commit", "-qm", "x into d again"]);
6429
    git(&["merge", "-q", "--no-edit", "side"]);
6430
6431
    let repo = Repo::init(&root.join("o")).unwrap();
6432
    repo.import_git(&g, "main").unwrap();
6433
    let v = repo.verify_git_import(&g, "main").unwrap();
6434
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6435
    let st = repo
6436
        .load_state_history(&repo.bookmark_heads().unwrap())
6437
        .unwrap();
6438
    let view = st.tree().view();
6439
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6440
    // The directory is the one the first commit made.
6441
    // Commits made in one second tie on time: find the first by its message.
6442
    let first = repo
6443
        .log()
6444
        .unwrap()
6445
        .into_iter()
6446
        .find(|e| e.change.message.starts_with("base"))
6447
        .unwrap();
6448
    let base = repo
6449
        .load_state_history(&[first.hash])
6450
        .unwrap()
6451
        .tree()
6452
        .view();
6453
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6454
}
6455
6456
/// oxygen#30, the rest: a placement left under a directory another line
6457
/// removed is out of sight, so no diff reaches it; the merge that settles
6458
/// where the file is retires it.
6459
#[test]
6460
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6461
    hermetic();
6462
    if std::process::Command::new("git")
6463
        .arg("--version")
6464
        .output()
6465
        .is_err()
6466
    {
6467
        eprintln!("git not installed; skipping");
6468
        return;
6469
    }
6470
    let dir = tempfile::tempdir().unwrap();
6471
    let root = dir.path();
6472
    let g = root.join("src.git");
6473
    fs::create_dir_all(&g).unwrap();
6474
    let run = |args: &[&str]| {
6475
        std::process::Command::new("git")
6476
            .arg("-C")
6477
            .arg(&g)
6478
            .args([
6479
                "-c",
6480
                "user.name=Grace",
6481
                "-c",
6482
                "[email protected]",
6483
                "-c",
6484
                "commit.gpgsign=false",
6485
            ])
6486
            .args(args)
6487
            .output()
6488
            .unwrap()
6489
    };
6490
    let git = |args: &[&str]| {
6491
        let out = run(args);
6492
        assert!(
6493
            out.status.success(),
6494
            "git {args:?}: {}",
6495
            String::from_utf8_lossy(&out.stderr)
6496
        );
6497
    };
6498
    git(&["init", "-q", "-b", "main"]);
6499
    write(&g, "c/x.txt", b"x\n");
6500
    write(&g, "keep.txt", b"k\n");
6501
    git(&["add", "."]);
6502
    git(&["commit", "-qm", "base"]);
6503
    // One line renames the file within c; the other moves it out of c,
6504
    // which goes.
6505
    git(&["checkout", "-qb", "side"]);
6506
    git(&["mv", "c/x.txt", "c/y.txt"]);
6507
    git(&["commit", "-qm", "rename within c"]);
6508
    git(&["checkout", "-q", "main"]);
6509
    fs::create_dir_all(g.join("n")).unwrap();
6510
    git(&["mv", "c/x.txt", "n/x.txt"]);
6511
    git(&["commit", "-qm", "move out of c"]);
6512
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6513
    let _ = run(&["merge", "-q", "side"]);
6514
    let _ = run(&[
6515
        "rm",
6516
        "-q",
6517
        "--cached",
6518
        "--ignore-unmatch",
6519
        "c/y.txt",
6520
        "c/x.txt",
6521
    ]);
6522
    let _ = std::fs::remove_dir_all(g.join("c"));
6523
    write(&g, "n/x.txt", b"x\n");
6524
    git(&["add", "-A"]);
6525
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6526
6527
    let repo = Repo::init(&root.join("o")).unwrap();
6528
    repo.import_git(&g, "main").unwrap();
6529
    let v = repo.verify_git_import(&g, "main").unwrap();
6530
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6531
    let st = repo
6532
        .load_state_history(&repo.bookmark_heads().unwrap())
6533
        .unwrap();
6534
    let view = st.tree().view();
6535
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6536
    assert!(view.entries.contains_key("n/x.txt"));
6537
}
6538
6539
/// oxygen#30, orphans: a file added on one line into a directory the other
6540
/// line removed is placed where the tree cannot show it; Git's merge keeps
6541
/// the file, and the import's merge leaves exactly one of it.
6542
#[test]
6543
fn git_import_merge_leaves_no_orphan_behind() {
6544
    hermetic();
6545
    if std::process::Command::new("git")
6546
        .arg("--version")
6547
        .output()
6548
        .is_err()
6549
    {
6550
        eprintln!("git not installed; skipping");
6551
        return;
6552
    }
6553
    let dir = tempfile::tempdir().unwrap();
6554
    let root = dir.path();
6555
    let g = root.join("src.git");
6556
    fs::create_dir_all(&g).unwrap();
6557
    let git = |args: &[&str]| {
6558
        let out = std::process::Command::new("git")
6559
            .arg("-C")
6560
            .arg(&g)
6561
            .args([
6562
                "-c",
6563
                "user.name=Grace",
6564
                "-c",
6565
                "[email protected]",
6566
                "-c",
6567
                "commit.gpgsign=false",
6568
            ])
6569
            .args(args)
6570
            .output()
6571
            .unwrap();
6572
        assert!(
6573
            out.status.success(),
6574
            "git {args:?}: {}",
6575
            String::from_utf8_lossy(&out.stderr)
6576
        );
6577
    };
6578
    git(&["init", "-q", "-b", "main"]);
6579
    write(&g, "d/f.txt", b"f\n");
6580
    write(&g, "keep.txt", b"k\n");
6581
    git(&["add", "."]);
6582
    git(&["commit", "-qm", "base"]);
6583
    git(&["checkout", "-qb", "side"]);
6584
    write(&g, "d/new.txt", b"new\n");
6585
    git(&["add", "."]);
6586
    git(&["commit", "-qm", "add into d"]);
6587
    git(&["checkout", "-q", "main"]);
6588
    git(&["rm", "-q", "d/f.txt"]);
6589
    git(&["commit", "-qm", "d goes"]);
6590
    git(&["merge", "-q", "--no-edit", "side"]);
6591
6592
    let repo = Repo::init(&root.join("o")).unwrap();
6593
    repo.import_git(&g, "main").unwrap();
6594
    let v = repo.verify_git_import(&g, "main").unwrap();
6595
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6596
    let st = repo
6597
        .load_state_history(&repo.bookmark_heads().unwrap())
6598
        .unwrap();
6599
    let view = st.tree().view();
6600
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6601
    assert!(view.entries.contains_key("d/new.txt"));
6602
}
6603
6604
/// fsck checks a change's text as the blobs it is stored in, without
6605
/// decoding it: a missing text blob is an error named for the change.
6606
#[test]
6607
fn fsck_names_a_missing_text_blob() {
6608
    hermetic();
6609
    let dir = tempfile::tempdir().unwrap();
6610
    let root = dir.path();
6611
    let repo = Repo::init(root).unwrap();
6612
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6613
    write(root, "big.txt", big.as_bytes());
6614
    let h = repo.commit("big", &[]).unwrap();
6615
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6616
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6617
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6618
        panic!("a stored text")
6619
    };
6620
    repo.store().remove_loose_for_test(&b).unwrap();
6621
    let rep = repo.fsck().unwrap();
6622
    assert!(rep.errors() > 0);
6623
    assert!(
6624
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6625
        "{:?}",
6626
        rep.problems
6627
    );
6628
}
6629
6630
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6631
/// reached with that remote's token and CA (a private subrepo then clones
6632
/// for anyone who can read the parent); another hub gets none of them.
6633
#[test]
6634
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6635
    hermetic();
6636
    let dir = tempfile::tempdir().unwrap();
6637
    let mut repo = Repo::init(dir.path()).unwrap();
6638
    repo.config
6639
        .set(
6640
            "remote.origin.url",
6641
            "https://Hub.example:7343/doomsdayone/metalgear",
6642
        )
6643
        .unwrap();
6644
    repo.config.set("remote.origin.token", "secret").unwrap();
6645
    repo.config
6646
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6647
        .unwrap();
6648
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6649
    assert_eq!(same.token.as_deref(), Some("secret"));
6650
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6651
    for other in [
6652
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6653
        "https://hub.example/doomsdayone/rstar-api",
6654
        "http://hub.example:7343/doomsdayone/rstar-api",
6655
    ] {
6656
        let o = repo.credentials_for(other);
6657
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6658
    }
6659
}
6660
6661
/// oxygen#47: a remote with no token of its own uses the user's credential
6662
/// store for its hub, and a nested checkout finds its parent's remote
6663
/// token there instead of keeping a copy.
6664
#[test]
6665
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
6666
    hermetic();
6667
    let home = tempfile::tempdir().unwrap();
6668
    let dir = tempfile::tempdir().unwrap();
6669
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
6670
    parent
6671
        .config
6672
        .set("remote.origin.url", "https://hub.example/o/parent")
6673
        .unwrap();
6674
    parent.save_config().unwrap();
6675
    assert_eq!(parent.remote_options("origin").token, None);
6676
    crate::credentials::Credentials::at(home.path())
6677
        .save("https://hub.example", "stored", Some("andy"), None)
6678
        .unwrap();
6679
    assert_eq!(
6680
        parent.remote_options("origin").token.as_deref(),
6681
        Some("stored")
6682
    );
6683
6684
    let empty_home = tempfile::tempdir().unwrap();
6685
    let nested = dir.path().join("deps").join("child");
6686
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
6687
    child
6688
        .config
6689
        .set("remote.origin.url", "https://hub.example/o/child")
6690
        .unwrap();
6691
    child.save_config().unwrap();
6692
    assert_eq!(child.remote_options("origin").token, None);
6693
    parent
6694
        .config
6695
        .set("remote.origin.token", "checkout")
6696
        .unwrap();
6697
    parent.save_config().unwrap();
6698
    assert_eq!(
6699
        child.remote_options("origin").token.as_deref(),
6700
        Some("checkout")
6701
    );
6702
    // Another hub's checkout token is not borrowed.
6703
    child
6704
        .config
6705
        .set("remote.origin.url", "https://other.example/o/child")
6706
        .unwrap();
6707
    assert_eq!(child.remote_options("origin").token, None);
6708
}
6709
6710
#[test]
6711
fn the_metadata_cache_survives_a_torn_tail() {
6712
    hermetic();
6713
    let dir = tempfile::tempdir().unwrap();
6714
    let root = dir.path();
6715
    let repo = Repo::init(root).unwrap();
6716
    write(root, "a.txt", b"1\n");
6717
    let h = repo.commit("first", &[]).unwrap();
6718
    let meta = repo.store().get_change_meta(&h).unwrap();
6719
    let cache = repo.store().dir().join("metas");
6720
    let len = fs::metadata(&cache).unwrap().len();
6721
    assert!(len > 0, "a change read is cached");
6722
    // A torn record at the end: the cache reads up to it and cuts it off.
6723
    fs::OpenOptions::new()
6724
        .append(true)
6725
        .open(&cache)
6726
        .unwrap()
6727
        .write_all(&[7; 20])
6728
        .unwrap();
6729
    let again = Repo::open(root).unwrap();
6730
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
6731
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
6732
}
6733
6734
#[test]
6735
fn a_manifest_that_does_not_check_reads_as_none() {
6736
    hermetic();
6737
    let dir = tempfile::tempdir().unwrap();
6738
    let root = dir.path();
6739
    let repo = Repo::init(root).unwrap();
6740
    write(root, "a.txt", b"1\n");
6741
    repo.commit("first", &[]).unwrap();
6742
    let path = repo.manifest_path();
6743
    let mut bytes = fs::read(&path).unwrap();
6744
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
6745
    let last = bytes.len() - 1;
6746
    bytes[last] ^= 1;
6747
    fs::write(&path, &bytes).unwrap();
6748
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
6749
    // The next status reads the files and writes it again.
6750
    let again = Repo::open(root).unwrap();
6751
    assert!(!again.snapshot("status").unwrap().changed);
6752
    assert!(again.read_manifest().unwrap().is_some());
6753
}
6754
6755
#[test]
6756
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
6757
    hermetic();
6758
    let dir = tempfile::tempdir().unwrap();
6759
    let root = dir.path();
6760
    let repo = Repo::init(root).unwrap();
6761
    write(root, "a.txt", b"1\n");
6762
    write(root, "b.txt", b"2\n");
6763
    // b.txt outside the racy window, so snapshots take it as unchanged.
6764
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6765
    fs::File::options()
6766
        .write(true)
6767
        .open(root.join("b.txt"))
6768
        .unwrap()
6769
        .set_modified(old)
6770
        .unwrap();
6771
    repo.commit("first", &[]).unwrap();
6772
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
6773
    repo.snapshot_status("status").unwrap();
6774
    write(root, "a.txt", b"1\n2\n");
6775
    repo.commit("second", &[]).unwrap();
6776
    assert!(
6777
        repo.clean_by_manifest().unwrap(),
6778
        "after a commit of one file"
6779
    );
6780
    // Edited, seen by a status, edited again, then committed: the status
6781
    // left the first edit's stat, which the commit must not keep.
6782
    write(root, "a.txt", b"1\n2\n3\n");
6783
    repo.snapshot_status("status").unwrap();
6784
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
6785
    repo.commit("third", &[]).unwrap();
6786
    assert!(
6787
        repo.clean_by_manifest().unwrap(),
6788
        "after an edit a status saw"
6789
    );
6790
}
6791
6792
#[test]
6793
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
6794
    hermetic();
6795
    let dir = tempfile::tempdir().unwrap();
6796
    let root = dir.path();
6797
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6798
    write(root, "a.txt", b"1\n2\n");
6799
    let a = repo.commit("A", &[]).unwrap();
6800
    repo.bookmark_create("develop", Some(&[a])).unwrap();
6801
    write(root, "a.txt", b"1\nX\n");
6802
    let c = repo.commit("C: 2 to X", &[]).unwrap();
6803
    repo.bookmark_switch("develop", false).unwrap();
6804
    write(root, "a.txt", b"1\nY\n");
6805
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
6806
    repo.bookmark_switch("main", false).unwrap();
6807
6808
    let err = repo.rebase(&c, &[d]).unwrap_err();
6809
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
6810
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
6811
    assert!(r.changed && r.checked_out);
6812
    let snap = repo.snapshot_status("status").unwrap();
6813
    assert!(
6814
        snap.base_snapshot.is_conflicted(),
6815
        "the conflict is in the working copy"
6816
    );
6817
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
6818
    assert!(text.contains('X') && text.contains('Y'), "{text}");
6819
6820
    write(root, "a.txt", b"1\nXY\n");
6821
    repo.commit("Resolve", &[]).unwrap();
6822
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
6823
    assert!(st.contains(&c) && st.contains(&d));
6824
    let files = st.materialize().files;
6825
    assert!(!files["a.txt"].is_conflicted());
6826
    assert!(
6827
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
6828
    );
6829
6830
    // A change the current bookmark does not hold is refused.
6831
    repo.bookmark_switch("develop", false).unwrap();
6832
    write(root, "b.txt", b"b\n");
6833
    let e = repo.commit("E", &[]).unwrap();
6834
    repo.bookmark_switch("main", false).unwrap();
6835
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
6836
    assert!(
6837
        err.to_string().contains("not on the current bookmark"),
6838
        "{err}"
6839
    );
6840
}
6841
6842
#[test]
6843
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
6844
    hermetic();
6845
    let dir = tempfile::tempdir().unwrap();
6846
    let root = dir.path();
6847
    let repo = Repo::init(root).unwrap();
6848
    write(root, "a.txt", b"a\n");
6849
    write(root, "kept.log", b"tracked\n");
6850
    repo.commit("first", &[]).unwrap();
6851
    write(root, "build.log", b"made\n");
6852
    let snap = repo.snapshot_status("status").unwrap();
6853
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
6854
    // A rule written afterwards leaves the added file out again, while the
6855
    // committed one stays tracked.
6856
    write(root, ".gitignore", b"*.log\n");
6857
    let snap = repo.snapshot_status("status").unwrap();
6858
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
6859
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
6860
    write(root, "kept.log", b"tracked, edited\n");
6861
    let snap = repo.snapshot_status("status").unwrap();
6862
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
6863
}
6864
6865
#[test]
6866
fn shed_graphs_come_back_the_same() {
6867
    hermetic();
6868
    let dir = tempfile::tempdir().unwrap();
6869
    let root = dir.path();
6870
    let repo = Repo::init(root).unwrap();
6871
    write(root, "a.txt", b"1\n2\n3\n");
6872
    write(root, "b.txt", b"x\n");
6873
    repo.commit("first", &[]).unwrap();
6874
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
6875
    repo.commit("second", &[]).unwrap();
6876
    let heads = repo.bookmark_heads().unwrap();
6877
    let mut st = repo.load_state_history(&heads).unwrap();
6878
    let view = st.tree().view();
6879
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
6880
        .iter()
6881
        .map(|p| view.entries[*p].node)
6882
        .collect();
6883
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6884
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6885
    assert_eq!(st.built_count(), 2);
6886
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
6887
    assert_eq!((shed, st.built_count()), (2, 0));
6888
    // A later change applies on top of the shed history.
6889
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
6890
    let h3 = repo.commit("third", &[]).unwrap();
6891
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
6892
    st.add_known(h3, skeleton, texts);
6893
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6894
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6895
    assert_eq!(after[1], before[1]);
6896
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
6897
}
6898
6899
#[test]
6900
fn many_edited_files_diff_in_parallel() {
6901
    // Enough edited files that the builder diffs them in parallel; the
6902
    // commit must hold exactly what is on disk, and a second snapshot
6903
    // must find nothing left to commit.
6904
    hermetic();
6905
    let dir = tempfile::tempdir().unwrap();
6906
    let root = dir.path();
6907
    let repo = Repo::init(root).unwrap();
6908
    let text = |i: usize, round: usize| {
6909
        let mut s = String::new();
6910
        for line in 0..50 {
6911
            if round > 0 && line % 7 == i % 7 {
6912
                s.push_str(&format!("edited {round} {i} {line}\n"));
6913
            } else {
6914
                s.push_str(&format!("file {i} line {line}\n"));
6915
            }
6916
        }
6917
        if round > 0 && i.is_multiple_of(3) {
6918
            s.push_str("appended\n");
6919
        }
6920
        s
6921
    };
6922
    for i in 0..40 {
6923
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
6924
    }
6925
    repo.commit("first", &[]).unwrap();
6926
    for i in 0..40 {
6927
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
6928
    }
6929
    let h = repo.commit("edit every file", &[]).unwrap();
6930
    let snap = repo.load_state(&[h]).unwrap().materialize();
6931
    for i in 0..40 {
6932
        let want = text(i, 1);
6933
        assert!(
6934
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
6935
            "d/f{i}.txt as committed"
6936
        );
6937
    }
6938
    assert!(
6939
        repo.commit("nothing", &[]).is_err(),
6940
        "nothing left to commit"
6941
    );
6942
}
6943
6944
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
6945
/// is known (fetch printed "up to date" while main was behind), a change
6946
/// only fetched resolves and says where it is, and a checkout whose only
6947
/// remote is not `origin` uses that one.
6948
#[test]
6949
fn a_fetched_change_shows_as_behind_and_resolves() {
6950
    hermetic();
6951
    let dir = tempfile::tempdir().unwrap();
6952
    let root = dir.path();
6953
    let origin = Repo::init(&root.join("origin")).unwrap();
6954
    drop(origin);
6955
    let url = root.join("origin").to_string_lossy().to_string();
6956
    let a = Repo::clone(&url, &root.join("a"))
6957
        .unwrap()
6958
        .with_home(root.join("home-a"));
6959
    write(&root.join("a"), "f.txt", b"one\n");
6960
    a.commit("one", &[]).unwrap();
6961
    a.push("origin", false).unwrap();
6962
    let b = Repo::clone(&url, &root.join("b"))
6963
        .unwrap()
6964
        .with_home(root.join("home-b"));
6965
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
6966
6967
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
6968
    let h2 = a.commit("two", &[]).unwrap();
6969
    a.push("origin", false).unwrap();
6970
    b.fetch("origin").unwrap();
6971
    // Fetched, not pulled: one behind, the change found and placed.
6972
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
6973
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
6974
    assert_eq!(
6975
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
6976
            .unwrap(),
6977
        h2
6978
    );
6979
    assert_eq!(
6980
        b.remote_only_location(&h2).unwrap().as_deref(),
6981
        Some("origin/main")
6982
    );
6983
    // Fetching again changes nothing: still behind, which is what the
6984
    // CLI now says rather than "up to date".
6985
    b.fetch("origin").unwrap();
6986
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
6987
    b.pull("origin").unwrap();
6988
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
6989
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
6990
6991
    // One remote, not called origin: it is the default.
6992
    let mut c = Repo::init(&root.join("c")).unwrap();
6993
    assert_eq!(c.default_remote(), "origin");
6994
    c.config.set("remote.earth.url", &url).unwrap();
6995
    assert_eq!(c.default_remote(), "earth");
6996
    c.config.set("remote.origin.url", &url).unwrap();
6997
    assert_eq!(c.default_remote(), "origin");
6998
}
6999
7000
/// oxygen#57: a clone from a relative local path records the remote as an
7001
/// absolute path, so fetch still finds it from inside the clone.
7002
#[test]
7003
fn a_clone_from_a_relative_path_records_it_absolute() {
7004
    hermetic();
7005
    let dir = tempfile::tempdir().unwrap();
7006
    let root = dir.path();
7007
    Repo::init(&root.join("origin")).unwrap();
7008
    let rel = crate::protocol::stored_url("relative/repo");
7009
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7010
    assert_eq!(
7011
        crate::protocol::stored_url("https://hub.example/o/n"),
7012
        "https://hub.example/o/n"
7013
    );
7014
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7015
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7016
    // A bucket is kept as written: it is not a path.
7017
    assert_eq!(
7018
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7019
        "s3://bucket/prefix?profile=p"
7020
    );
7021
    let url = root.join("origin").to_string_lossy().to_string();
7022
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7023
    assert_eq!(b.config.remotes["origin"], url);
7024
    b.fetch("origin").unwrap();
7025
}
7026
7027
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7028
/// and gets its subrepos at their pins from this workspace's copies, with
7029
/// their remotes pointing where the subrepos come from.
7030
#[test]
7031
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7032
    hermetic();
7033
    let dir = tempfile::tempdir().unwrap();
7034
    let root = dir.path();
7035
    Repo::init(&root.join("lib-origin")).unwrap();
7036
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7037
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7038
        .unwrap()
7039
        .with_home(root.join("home"));
7040
    write(&root.join("lib"), "lib.txt", b"v1\n");
7041
    let l1 = lib.commit("lib v1", &[]).unwrap();
7042
    assert!(lib.push("origin", false).unwrap()[0].ok);
7043
7044
    let app_dir = root.join("app");
7045
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7046
    write(&app_dir, "main.txt", b"app\n");
7047
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7048
    app.commit("app with lib", &[]).unwrap();
7049
    // A second bookmark, and the main workspace on another.
7050
    app.bookmark_create("develop", None).unwrap();
7051
    app.bookmark_create("feature", None).unwrap();
7052
    let mut app = app;
7053
    app.bookmark_switch("feature", false).unwrap();
7054
    assert_eq!(app.config.bookmark, "feature");
7055
7056
    // The library's origin goes away: the subrepo must come from here.
7057
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7058
    let heads = app.resolve_heads("develop").unwrap();
7059
    let ws = app
7060
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7061
        .unwrap();
7062
    assert_eq!(
7063
        ws.config.bookmark, "develop",
7064
        "the new workspace is on develop"
7065
    );
7066
    assert_eq!(
7067
        app.config.bookmark, "feature",
7068
        "and this one stays on its own"
7069
    );
7070
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7071
    assert_eq!(
7072
        sub.config.remotes["origin"], lib_url,
7073
        "its origin is the subrepo's URL"
7074
    );
7075
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7076
    assert_eq!(
7077
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7078
        b"v1\n"
7079
    );
7080
}
7081
7082
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7083
/// operators and the predicates, over a small graph with two heads and
7084
/// a rename.
7085
#[test]
7086
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7087
    hermetic();
7088
    let dir = tempfile::tempdir().unwrap();
7089
    let root = dir.path();
7090
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7091
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7092
        .unwrap();
7093
    write(root, "src/a.rs", b"one\n");
7094
    let a = repo.commit("first: add a", &[]).unwrap();
7095
    write(root, "src/a.rs", b"one\ntwo\n");
7096
    let b = repo.commit("second: grow a", &[]).unwrap();
7097
    // A second head, independent of b: a new file on top of a.
7098
    repo.checkout(&[a], false, "checkout a").unwrap();
7099
    write(root, "docs/notes.md", b"notes\n");
7100
    let c = repo.commit("third: notes", &[]).unwrap();
7101
    // Back to both heads, then rename a.rs: the node keeps its identity.
7102
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7103
        .unwrap();
7104
    fs::remove_file(root.join("src/a.rs")).unwrap();
7105
    write(root, "src/z.rs", b"one\ntwo\n");
7106
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7107
    let wc = repo.working_copy().unwrap().0;
7108
    // A saved revset is checked when set.
7109
    repo.set_user_config("revset.mine", "author(me) & ::main")
7110
        .unwrap();
7111
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7112
    let set = |src: &str| -> Vec<ChangeHash> {
7113
        let mut v = repo.revset(src).unwrap().hashes;
7114
        v.sort();
7115
        v
7116
    };
7117
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7118
        let mut v = hs.to_vec();
7119
        v.sort();
7120
        v
7121
    };
7122
7123
    // Changes commute: a new file depends on nothing and the rename on the
7124
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7125
    // copy on the three heads b, c, d.
7126
    let heads = sorted(&repo.bookmark_heads().unwrap());
7127
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7128
    assert!(heads.contains(&d) && heads.contains(&c));
7129
    // Symbols and closures.
7130
    assert_eq!(set("main"), heads);
7131
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7132
    assert_eq!(set("@"), vec![wc]);
7133
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7134
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7135
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7136
    assert_eq!(
7137
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7138
        sorted(&[a, b])
7139
    );
7140
    // Ranges: what main has beyond b, and `..` forms.
7141
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7142
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7143
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7144
    // Operators and precedence: ~ binds tighter than &, & than |.
7145
    assert_eq!(
7146
        set(&format!("::main ~ #{}", d.short(12))),
7147
        sorted(&[a, b, c])
7148
    );
7149
    assert_eq!(
7150
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7151
        sorted(&[b, c])
7152
    );
7153
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7154
    // Relations.
7155
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7156
    head_deps.sort();
7157
    head_deps.dedup();
7158
    assert_eq!(set("deps(main)"), head_deps);
7159
    let on_a: Vec<ChangeHash> = [b, c, d]
7160
        .into_iter()
7161
        .filter(|h| meta(h).deps.contains(&a))
7162
        .collect();
7163
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7164
    assert_eq!(set("heads(::main)"), heads);
7165
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7166
    assert_eq!(
7167
        set(&format!(
7168
            "heads(#{} | #{} | #{})",
7169
            a.short(12),
7170
            b.short(12),
7171
            c.short(12)
7172
        )),
7173
        sorted(&[b, c])
7174
    );
7175
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7176
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7177
    assert_eq!(set("none()"), vec![]);
7178
    // Predicates: author by name, email, key prefix and `me`.
7179
    let key = repo.config.author_key.unwrap();
7180
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7181
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7182
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7183
    assert_eq!(set("author(me) & ::main").len(), 4);
7184
    assert_eq!(set("author(nobody)"), vec![]);
7185
    assert_eq!(set("description(notes)"), vec![c]);
7186
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7187
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7188
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7189
    // touches follows the node through the rename, in the current state.
7190
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7191
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7192
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7193
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7194
    // Newest first in the result order.
7195
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7196
    // The saved revset, and errors that say what is wrong.
7197
    assert_eq!(set("mine()").len(), 4);
7198
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7199
    assert!(e.contains("unknown function nosuch()"), "{e}");
7200
    let e = repo.revset("main &").unwrap_err().to_string();
7201
    assert!(e.contains("at character"), "{e}");
7202
    let e = repo.revset("zzzz").unwrap_err().to_string();
7203
    assert!(e.contains("no change matches"), "{e}");
7204
    let e = repo
7205
        .revset_with_budget("::main", std::time::Duration::ZERO)
7206
        .unwrap_err()
7207
        .to_string();
7208
    assert!(e.contains("budget"), "{e}");
7209
    // The log entries carry the bookmark's heads and the working copy.
7210
    let entries = repo.log_revset("::@").unwrap();
7211
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7212
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7213
    // push); then a signed change, a tag, and a revocation.
7214
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7215
    assert_eq!(set("signed_by(me)"), vec![]);
7216
    repo.sign_change(&d).unwrap();
7217
    assert_eq!(set("signed_by(me)"), vec![d]);
7218
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7219
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7220
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7221
    assert_eq!(set("delegated()"), vec![]);
7222
    assert_eq!(set("revoked()"), vec![]);
7223
    assert_eq!(set("attested(tag)"), vec![]);
7224
    repo.tag_create("v1", &[b], "first").unwrap();
7225
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7226
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7227
    assert_eq!(set("attested(receipt)"), vec![]);
7228
    assert_eq!(set("built(test)"), vec![]);
7229
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7230
    assert!(e.contains("tag, receipt or ref"), "{e}");
7231
    repo.revoke_identity(&key, "test").unwrap();
7232
    assert_eq!(set("revoked()"), vec![d]);
7233
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7234
}
7235
7236
#[test]
7237
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7238
    let dir = tempfile::tempdir().unwrap();
7239
    let root = dir.path();
7240
    let home = root.join("home");
7241
    // Ada's identity lives in the user file; repository `a` pins the same
7242
    // key in its own file, repository `b` names none.
7243
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7244
    let (key, _) = a
7245
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7246
        .unwrap();
7247
    a.config.set("author.key", &key.to_hex()).unwrap();
7248
    a.save_config().unwrap();
7249
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7250
    let r = a
7251
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7252
        .unwrap();
7253
    assert_eq!(
7254
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7255
        r.new.to_hex(),
7256
        "the user file follows"
7257
    );
7258
    assert_eq!(
7259
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7260
        r.new.to_hex(),
7261
        "the pinning repository follows"
7262
    );
7263
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7264
    assert_eq!(
7265
        b.config.author_key,
7266
        Some(r.new),
7267
        "a checkout without a pin follows the user file"
7268
    );
7269
    // A repository-scoped identity leaves the user file alone.
7270
    let other_home = root.join("home2");
7271
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7272
    let (ck, _) = c
7273
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7274
        .unwrap();
7275
    assert!(!other_home.join("config.toml").exists());
7276
    let r2 = c.rotate_identity().unwrap();
7277
    assert_ne!(r2.new, ck);
7278
    assert_eq!(
7279
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7280
        r2.new.to_hex()
7281
    );
7282
    assert!(
7283
        !other_home.join("config.toml").exists(),
7284
        "a repository-scoped identity stays repository-scoped"
7285
    );
7286
    // Several delegates in one rotation; a repeat is refused.
7287
    let (d1, d2) = (
7288
        SecretKey::generate().identity("D1", "d1@x", 1),
7289
        SecretKey::generate().identity("D2", "d2@x", 1),
7290
    );
7291
    let r3 = c
7292
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7293
        .unwrap();
7294
    assert_eq!(r3.identity.delegates.len(), 2);
7295
    assert!(c
7296
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7297
        .is_err());
7298
}
7299
7300
/// Two unrelated histories that both add the same file, joined by two
7301
/// independent merges on two branches, then those branches merged: Git
7302
/// merges identical additions cleanly, and the import must too (#71,
7303
/// found in VS Code's history).
7304
#[test]
7305
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7306
    // Batches of one: every merge renders apart from the state, where a
7307
    // file whose graph the state had built came out empty (#71).
7308
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7309
    hermetic();
7310
    if std::process::Command::new("git")
7311
        .arg("--version")
7312
        .output()
7313
        .is_err()
7314
    {
7315
        eprintln!("git not installed; skipping");
7316
        return;
7317
    }
7318
    let dir = tempfile::tempdir().unwrap();
7319
    let root = dir.path();
7320
    let g = root.join("src.git");
7321
    fs::create_dir_all(&g).unwrap();
7322
    let git = |args: &[&str]| -> String {
7323
        let out = std::process::Command::new("git")
7324
            .arg("-C")
7325
            .arg(&g)
7326
            .args([
7327
                "-c",
7328
                "user.name=Grace",
7329
                "-c",
7330
                "[email protected]",
7331
                "-c",
7332
                "commit.gpgsign=false",
7333
            ])
7334
            .args(args)
7335
            .output()
7336
            .unwrap();
7337
        assert!(
7338
            out.status.success(),
7339
            "git {args:?}: {}",
7340
            String::from_utf8_lossy(&out.stderr)
7341
        );
7342
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7343
    };
7344
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7345
    // History A: main.
7346
    git(&["init", "-q", "-b", "main"]);
7347
    write(&g, "gulpfile.js", text);
7348
    write(&g, "a.txt", b"a\n");
7349
    git(&["add", "."]);
7350
    git(&["commit", "-q", "-m", "A root"]);
7351
    // History B: an unrelated root adding the same file, identical.
7352
    git(&["checkout", "-q", "--orphan", "fork"]);
7353
    git(&["rm", "-q", "-r", "--cached", "."]);
7354
    for f in ["gulpfile.js", "a.txt"] {
7355
        let _ = fs::remove_file(g.join(f));
7356
    }
7357
    write(&g, "gulpfile.js", text);
7358
    write(&g, "b.txt", b"b\n");
7359
    git(&["add", "."]);
7360
    git(&["commit", "-q", "-m", "B root"]);
7361
    // Two branches from main, each joining B on its own.
7362
    git(&["checkout", "-q", "-b", "one", "main"]);
7363
    git(&[
7364
        "merge",
7365
        "-q",
7366
        "--no-ff",
7367
        "--allow-unrelated-histories",
7368
        "-m",
7369
        "join on one",
7370
        "fork",
7371
    ]);
7372
    git(&["checkout", "-q", "-b", "two", "main"]);
7373
    write(&g, "a.txt", b"a\ntwo\n");
7374
    git(&["commit", "-q", "-am", "work on two"]);
7375
    git(&[
7376
        "merge",
7377
        "-q",
7378
        "--no-ff",
7379
        "--allow-unrelated-histories",
7380
        "-m",
7381
        "join on two",
7382
        "fork",
7383
    ]);
7384
    // Then the two joins meet, and the file is reformatted after.
7385
    git(&["checkout", "-q", "main"]);
7386
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7387
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7388
    write(
7389
        &g,
7390
        "gulpfile.js",
7391
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7392
    );
7393
    git(&["commit", "-q", "-am", "after"]);
7394
7395
    let dest = root.join("dest");
7396
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7397
    repo.import_git(&g, "main").unwrap();
7398
    let v = repo.verify_git_import(&g, "main").unwrap();
7399
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7400
    assert_eq!(
7401
        fs::read(dest.join("gulpfile.js")).unwrap(),
7402
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7403
    );
7404
}
7405
7406
/// As above, but the two joins keep different copies (each branch had a
7407
/// different version when it joined), and later work edits each copy:
7408
/// the shape of VS Code's c67ef57cda90 (#71).
7409
#[test]
7410
fn git_import_joins_where_each_join_kept_a_different_copy() {
7411
    // Batches of one: every merge renders apart from the state, where a
7412
    // file whose graph the state had built came out empty (#71).
7413
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7414
    hermetic();
7415
    if std::process::Command::new("git")
7416
        .arg("--version")
7417
        .output()
7418
        .is_err()
7419
    {
7420
        eprintln!("git not installed; skipping");
7421
        return;
7422
    }
7423
    let dir = tempfile::tempdir().unwrap();
7424
    let root = dir.path();
7425
    let g = root.join("src.git");
7426
    fs::create_dir_all(&g).unwrap();
7427
    let run = |args: &[&str]| {
7428
        std::process::Command::new("git")
7429
            .arg("-C")
7430
            .arg(&g)
7431
            .args([
7432
                "-c",
7433
                "user.name=Grace",
7434
                "-c",
7435
                "[email protected]",
7436
                "-c",
7437
                "commit.gpgsign=false",
7438
            ])
7439
            .args(args)
7440
            .output()
7441
            .unwrap()
7442
    };
7443
    let git = |args: &[&str]| -> String {
7444
        let out = run(args);
7445
        assert!(
7446
            out.status.success(),
7447
            "git {args:?}: {}",
7448
            String::from_utf8_lossy(&out.stderr)
7449
        );
7450
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7451
    };
7452
    git(&["init", "-q", "-b", "main"]);
7453
    write(
7454
        &g,
7455
        "gulpfile.js",
7456
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7457
    );
7458
    git(&["add", "."]);
7459
    git(&["commit", "-q", "-m", "A root"]);
7460
    write(
7461
        &g,
7462
        "gulpfile.js",
7463
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7464
    );
7465
    git(&["commit", "-q", "-am", "whitespace"]);
7466
    git(&["checkout", "-q", "--orphan", "fork"]);
7467
    git(&["rm", "-q", "-r", "--cached", "."]);
7468
    let _ = fs::remove_file(g.join("gulpfile.js"));
7469
    write(
7470
        &g,
7471
        "gulpfile.js",
7472
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7473
    );
7474
    git(&["add", "."]);
7475
    git(&["commit", "-q", "-m", "B root"]);
7476
    // Branch one joins B keeping main's copy; branch two keeps B's.
7477
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7478
        git(&["checkout", "-q", "-b", branch, "main"]);
7479
        let _ = run(&[
7480
            "merge",
7481
            "-q",
7482
            "--no-ff",
7483
            "--allow-unrelated-histories",
7484
            "-m",
7485
            "join",
7486
            "fork",
7487
        ]);
7488
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7489
        git(&["add", "gulpfile.js"]);
7490
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7491
    }
7492
    // Each branch then edits its copy.
7493
    git(&["checkout", "-q", "one"]);
7494
    write(
7495
        &g,
7496
        "gulpfile.js",
7497
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7498
    );
7499
    git(&["commit", "-q", "-am", "tslint on one"]);
7500
    git(&["checkout", "-q", "two"]);
7501
    write(
7502
        &g,
7503
        "gulpfile.js",
7504
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7505
    );
7506
    write(&g, "extra.txt", b"x\n");
7507
    write(&g, "more.txt", b"m\n");
7508
    git(&["add", "."]);
7509
    git(&["commit", "-q", "-am", "fmt on two"]);
7510
    // They meet: resolved by hand.
7511
    git(&["checkout", "-q", "one"]);
7512
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7513
    write(
7514
        &g,
7515
        "gulpfile.js",
7516
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7517
    );
7518
    git(&["add", "gulpfile.js"]);
7519
    git(&["commit", "-q", "-m", "merge two into one"]);
7520
7521
    let dest = root.join("dest");
7522
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7523
    repo.import_git(&g, "one").unwrap();
7524
    let v = repo.verify_git_import(&g, "one").unwrap();
7525
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7526
}
7527
7528
/// oxygen#68: on a store that is not this disk's directory, the operation
7529
/// head is the store's reference record, moved by compare-and-swap. Two
7530
/// handles recording from the same head both get through, merged; a swap
7531
/// from a stale version is refused; a second repository cannot start on a
7532
/// store that already holds one.
7533
#[test]
7534
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
7535
    use crate::strata::{MemoryStore, Store as _};
7536
    let backend = std::sync::Arc::new(MemoryStore::new());
7537
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
7538
    let dir = tempfile::tempdir().unwrap();
7539
    let a = Repo::init(dir.path()).unwrap();
7540
    assert!(
7541
        !dir.path().join(".oxy/ops/head").exists(),
7542
        "the head is not a file"
7543
    );
7544
    let (h0, op0) = a.head_op().unwrap();
7545
    let record = backend
7546
        .read_ref(HEAD_RECORD)
7547
        .unwrap()
7548
        .expect("the head is the store's record");
7549
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
7550
7551
    let b = Repo::open(dir.path()).unwrap();
7552
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
7553
    let mut va = op0.view.clone();
7554
    va.bookmarks.insert("from-a".into(), state);
7555
    let mut vb = op0.view.clone();
7556
    vb.bookmarks.insert("from-b".into(), state);
7557
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
7558
    assert_eq!(b.head_ref().unwrap(), rb);
7559
    // a recorded from h0 too: the head moved, so the two are merged.
7560
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
7561
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
7562
    assert_eq!(head, ra);
7563
    assert!(
7564
        op.command.ends_with("(merged with a concurrent operation)"),
7565
        "{}",
7566
        op.command
7567
    );
7568
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
7569
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
7570
7571
    // A swap from a version that is no longer current moves nothing.
7572
    let (h, v) = a.read_head().unwrap();
7573
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
7574
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
7575
    assert_eq!(a.head_ref().unwrap(), rb);
7576
7577
    let other = tempfile::tempdir().unwrap();
7578
    let err = Repo::init(other.path())
7579
        .err()
7580
        .expect("the store already holds a log")
7581
        .to_string();
7582
    assert!(
7583
        err.contains("already holds a repository's operation log"),
7584
        "{err}"
7585
    );
7586
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
7587
}
7588
7589
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
7590
/// objects and operation head there, with `.oxy/cache` in front: it works
7591
/// as one on disk does, reopens, and survives losing its cache.
7592
#[test]
7593
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
7594
    hermetic();
7595
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
7596
        return;
7597
    }
7598
    let dir = tempfile::tempdir().unwrap();
7599
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
7600
    let url = format!("dir://{}", bucket.display());
7601
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
7602
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
7603
    write(&root, "a.txt", b"one\n");
7604
    let h1 = repo.commit("First", &[]).unwrap();
7605
    write(&root, "a.txt", b"one\ntwo\n");
7606
    let h2 = repo.commit("Second", &[]).unwrap();
7607
    assert!(
7608
        !root.join(".oxy/ops/head").exists(),
7609
        "the head is in the store"
7610
    );
7611
    assert!(bucket.join("ops/head").is_file());
7612
    assert!(root.join(".oxy/cache").is_dir());
7613
    drop(repo);
7614
7615
    // Reopened, and again with no cache at all: everything comes from the store.
7616
    for drop_cache in [false, true] {
7617
        if drop_cache {
7618
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
7619
        }
7620
        let repo = Repo::open(&root).unwrap();
7621
        let log: Vec<String> = repo
7622
            .op_log()
7623
            .unwrap()
7624
            .into_iter()
7625
            .map(|(_, op)| op.command)
7626
            .collect();
7627
        assert!(log.len() >= 3, "{log:?}");
7628
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
7629
        let heads = repo
7630
            .store()
7631
            .get_state(&repo.view().unwrap().bookmarks["main"])
7632
            .unwrap()
7633
            .heads;
7634
        assert_eq!(heads, vec![h2]);
7635
        assert_eq!(
7636
            repo.load_state(&heads).unwrap().materialize().files.len(),
7637
            1
7638
        );
7639
    }
7640
7641
    // A second repository cannot start on the same store.
7642
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
7643
        .err()
7644
        .unwrap()
7645
        .to_string();
7646
    assert!(
7647
        err.contains("already holds a repository's operation log"),
7648
        "{err}"
7649
    );
7650
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
7651
        .err()
7652
        .unwrap()
7653
        .to_string();
7654
    assert!(err.contains("cannot open that kind of store"), "{err}");
7655
}
7656
7657
/// oxygen#75: the prompt's quick check agrees with status in a repository
7658
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
7659
/// another state, clean again once that pin is committed. (It compared the
7660
/// subrepo's directory as if it were a file, so it was always dirty.)
7661
#[test]
7662
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
7663
    hermetic();
7664
    let dir = tempfile::tempdir().unwrap();
7665
    let root = dir.path();
7666
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7667
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7668
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7669
        .unwrap()
7670
        .with_home(root.join("home"));
7671
    write(&root.join("lib"), "lib.txt", b"v1\n");
7672
    lib.commit("lib v1", &[]).unwrap();
7673
    assert!(lib.push("origin", false).unwrap()[0].ok);
7674
    let app_dir = root.join("app");
7675
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7676
    write(&app_dir, "main.txt", b"app\n");
7677
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7678
    app.commit("app with lib", &[]).unwrap();
7679
    // Out of the racy window, so the stat-only path decides.
7680
    std::thread::sleep(std::time::Duration::from_millis(2100));
7681
    let reopen = || Repo::open(&app_dir).unwrap();
7682
    assert_eq!(
7683
        reopen().quick_dirty().unwrap(),
7684
        Some(false),
7685
        "clean, as status says"
7686
    );
7687
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
7688
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
7689
    nested.commit("lib v2", &[]).unwrap();
7690
    assert_eq!(
7691
        reopen().quick_dirty().unwrap(),
7692
        Some(true),
7693
        "the subrepo moved"
7694
    );
7695
    reopen().commit("pin lib v2", &[]).unwrap();
7696
    std::thread::sleep(std::time::Duration::from_millis(2100));
7697
    assert_eq!(
7698
        reopen().quick_dirty().unwrap(),
7699
        Some(false),
7700
        "the new pin is committed"
7701
    );
7702
}
7703
7704
#[test]
7705
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
7706
    // oxygen#72: a .oxymodules section with no subrepo behind it.
7707
    hermetic();
7708
    let dir = tempfile::tempdir().unwrap();
7709
    let root = dir.path();
7710
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7711
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7712
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7713
        .unwrap()
7714
        .with_home(root.join("home"));
7715
    write(&root.join("lib"), "lib.txt", b"v1\n");
7716
    lib.commit("lib v1", &[]).unwrap();
7717
    assert!(lib.push("origin", false).unwrap()[0].ok);
7718
    let app_dir = root.join("app");
7719
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7720
    write(
7721
        &app_dir,
7722
        ".oxymodules",
7723
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
7724
    );
7725
    let unpinned = app.unpinned_modules().unwrap();
7726
    assert_eq!(unpinned.len(), 1);
7727
    assert_eq!(unpinned[0].0, "libs/lib");
7728
    assert_eq!(unpinned[0].1.url, lib_url);
7729
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
7730
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7731
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
7732
}
7733
7734
#[test]
7735
fn the_bookmark_revset_function_names_only_bookmarks() {
7736
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
7737
    hermetic();
7738
    let dir = tempfile::tempdir().unwrap();
7739
    let repo = Repo::init(dir.path()).unwrap();
7740
    write(dir.path(), "a.txt", b"a\n");
7741
    let a = repo.commit("A", &[]).unwrap();
7742
    write(dir.path(), "b.txt", b"b\n");
7743
    let b = repo.commit("B", &[]).unwrap();
7744
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
7745
    heads.sort();
7746
    let mut want = repo.bookmark_heads().unwrap();
7747
    want.sort();
7748
    assert_eq!(heads, want);
7749
    assert!(heads.contains(&b));
7750
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
7751
    // A change prefix is a symbol, not a bookmark.
7752
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
7753
    assert!(repo.revset(&prefix).is_ok());
7754
    let e = repo
7755
        .revset(&format!("bookmark({prefix})"))
7756
        .unwrap_err()
7757
        .to_string();
7758
    assert!(e.contains("no such bookmark"), "{e}");
7759
}
7760
7761
#[test]
7762
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
7763
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
7764
    // pinning the subrepo, and the nested repository on disk at that pin.
7765
    hermetic();
7766
    let dir = tempfile::tempdir().unwrap();
7767
    let root = dir.path();
7768
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7769
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7770
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7771
        .unwrap()
7772
        .with_home(root.join("home"));
7773
    write(&root.join("lib"), "lib.txt", b"v1\n");
7774
    lib.commit("lib v1", &[]).unwrap();
7775
    assert!(lib.push("origin", false).unwrap()[0].ok);
7776
    let app_dir = root.join("app");
7777
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7778
    write(&app_dir, "main.txt", b"app\n");
7779
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7780
    // The stale state: registered in .oxymodules, never pinned.
7781
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
7782
    app.commit("initial", &[]).unwrap();
7783
    let stale = app.bookmark_heads().unwrap();
7784
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
7785
    app.commit("pin lib", &[]).unwrap();
7786
    let newer = app.bookmark_heads().unwrap();
7787
    app.checkout(&stale, false, "test").unwrap();
7788
    write(&app_dir, "notes.txt", b"mine\n");
7789
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
7790
    assert_eq!(carried, vec!["notes.txt".to_string()]);
7791
    assert!(app_dir.join("notes.txt").exists());
7792
}
7793
7794
#[test]
7795
fn a_bookmark_only_behind_its_remote_catches_up() {
7796
    // oxygen#74: switch takes the remote's state rather than a stale one.
7797
    hermetic();
7798
    let dir = tempfile::tempdir().unwrap();
7799
    let root = dir.path();
7800
    let _origin = Repo::init(&root.join("origin")).unwrap();
7801
    let url = root.join("origin").to_string_lossy().to_string();
7802
    let one = Repo::clone(&url, &root.join("one"))
7803
        .unwrap()
7804
        .with_home(root.join("home"));
7805
    write(&root.join("one"), "a.txt", b"a\n");
7806
    one.commit("A", &[]).unwrap();
7807
    assert!(one.push("origin", false).unwrap()[0].ok);
7808
    let two = Repo::clone(&url, &root.join("two"))
7809
        .unwrap()
7810
        .with_home(root.join("home"));
7811
    write(&root.join("two"), "b.txt", b"b\n");
7812
    two.commit("B", &[]).unwrap();
7813
    assert!(two.push("origin", false).unwrap()[0].ok);
7814
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
7815
    one.fetch("origin").unwrap();
7816
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
7817
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
7818
    // Local work the remote lacks: left alone.
7819
    write(&root.join("one"), "c.txt", b"c\n");
7820
    one.commit("C", &[]).unwrap();
7821
    write(&root.join("two"), "d.txt", b"d\n");
7822
    two.commit("D", &[]).unwrap();
7823
    assert!(two.push("origin", false).unwrap()[0].ok);
7824
    one.fetch("origin").unwrap();
7825
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
7826
}
7827
7828
#[test]
7829
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
7830
    // oxygen#83: remotes earth and gcs, origin removed.
7831
    hermetic();
7832
    let dir = tempfile::tempdir().unwrap();
7833
    let root = dir.path();
7834
    let _up = Repo::init(&root.join("up")).unwrap();
7835
    let url = root.join("up").to_string_lossy().to_string();
7836
    let other = Repo::clone(&url, &root.join("other"))
7837
        .unwrap()
7838
        .with_home(root.join("home"));
7839
    write(&root.join("other"), "a.txt", b"a\n");
7840
    other.commit("a", &[]).unwrap();
7841
    assert!(other.push("origin", false).unwrap()[0].ok);
7842
    let mut one = Repo::clone(&url, &root.join("one"))
7843
        .unwrap()
7844
        .with_home(root.join("home"));
7845
    one.config.set("remote.earth.url", &url).unwrap();
7846
    one.config.set("remote.gcs.url", &url).unwrap();
7847
    one.config.set("remote.origin.url", "").unwrap();
7848
    one.save_config().unwrap();
7849
    write(&root.join("other"), "b.txt", b"b\n");
7850
    other.commit("b", &[]).unwrap();
7851
    assert!(other.push("origin", false).unwrap()[0].ok);
7852
    one.fetch("earth").unwrap();
7853
    let b = one
7854
        .bookmarks()
7855
        .unwrap()
7856
        .into_iter()
7857
        .find(|b| b.name == "main")
7858
        .unwrap();
7859
    assert_eq!(
7860
        (b.remote.as_deref(), b.behind),
7861
        (Some("earth"), Some(1)),
7862
        "a stale origin copy is not used"
7863
    );
7864
    assert_eq!(
7865
        one.default_remote(),
7866
        "origin",
7867
        "no default chosen among several"
7868
    );
7869
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
7870
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
7871
    one.config.set("core.remote", "earth").unwrap();
7872
    assert_eq!(one.default_remote(), "earth");
7873
}
7874
7875
#[test]
7876
fn a_missing_author_identity_says_how_to_fix_it() {
7877
    // oxygen#82: an agent home's author.key naming an identity the
7878
    // repository does not hold.
7879
    hermetic();
7880
    let dir = tempfile::tempdir().unwrap();
7881
    let mut repo = Repo::init(dir.path()).unwrap();
7882
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
7883
    repo.config.set("author.key", &missing.to_hex()).unwrap();
7884
    let e = repo.identity(&missing).unwrap_err().to_string();
7885
    assert!(
7886
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
7887
        "{e}"
7888
    );
7889
    assert!(e.contains("this repository's config"), "{e}");
7890
}
7891
7892
#[test]
7893
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
7894
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
7895
    // the working copy, a pull with nothing new left it there, and status
7896
    // said "clean".
7897
    hermetic();
7898
    let dir = tempfile::tempdir().unwrap();
7899
    let root = dir.path();
7900
    let _up = Repo::init(&root.join("up")).unwrap();
7901
    let url = root.join("up").to_string_lossy().to_string();
7902
    let other = Repo::clone(&url, &root.join("other"))
7903
        .unwrap()
7904
        .with_home(root.join("home"));
7905
    write(&root.join("other"), "a.txt", b"a\n");
7906
    other.commit("a", &[]).unwrap();
7907
    assert!(other.push("origin", false).unwrap()[0].ok);
7908
    let one = Repo::clone(&url, &root.join("one"))
7909
        .unwrap()
7910
        .with_home(root.join("home"));
7911
    write(&root.join("other"), "b.txt", b"b\n");
7912
    other.commit("b", &[]).unwrap();
7913
    assert!(other.push("origin", false).unwrap()[0].ok);
7914
    one.fetch("origin").unwrap();
7915
    // The bookmark moves; the working copy does not.
7916
    let theirs = one.resolve_heads("origin/main").unwrap();
7917
    one.bookmark_set("main", &theirs).unwrap();
7918
    assert!(!root.join("one/b.txt").exists());
7919
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
7920
    let r = one.pull("origin").unwrap();
7921
    assert!(
7922
        !r.changed && r.checked_out,
7923
        "nothing new, but the working copy caught up"
7924
    );
7925
    assert!(root.join("one/b.txt").exists());
7926
    assert_eq!(one.working_copy_behind().unwrap(), None);
7927
}
7928
7929
#[test]
7930
fn touched_nodes_cache_answers_as_the_changes_do() {
7931
    hermetic();
7932
    let dir = tempfile::tempdir().unwrap();
7933
    let repo = Repo::init(dir.path()).unwrap();
7934
    write(dir.path(), "a.txt", b"one\n");
7935
    write(dir.path(), "b.txt", b"x\n");
7936
    repo.snapshot("t").unwrap();
7937
    let c1 = repo.commit("first", &[]).unwrap();
7938
    write(dir.path(), "b.txt", b"y\n");
7939
    repo.snapshot("t").unwrap();
7940
    repo.commit("b only", &[]).unwrap();
7941
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
7942
    write(dir.path(), "c.txt", b"one\ntwo\n");
7943
    repo.snapshot("t").unwrap();
7944
    let c3 = repo.commit("rename and edit", &[]).unwrap();
7945
    // Uncommitted work, so the working copy touches a file too.
7946
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
7947
    repo.snapshot("t").unwrap();
7948
7949
    let path = dir.path().join(".oxy/index/touched");
7950
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
7951
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
7952
    assert!(path.exists(), "the first query writes the cache");
7953
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
7954
    assert_eq!(cold, warm, "the cache answers as the changes do");
7955
    let (wc, _) = repo.working_copy().unwrap();
7956
    assert_eq!(
7957
        cold,
7958
        vec![wc, c3, c1],
7959
        "renames followed, the working copy included"
7960
    );
7961
7962
    // Working-copy changes are not kept: they are replaced by every snapshot.
7963
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
7964
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
7965
    assert!(cached.contains(&c1) && cached.contains(&c3));
7966
7967
    // A damaged cache is ignored, not trusted.
7968
    let mut bytes = fs::read(&path).unwrap();
7969
    let last = bytes.len() - 40;
7970
    bytes[last] ^= 1;
7971
    fs::write(&path, &bytes).unwrap();
7972
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
7973
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
7974
    assert_eq!(hashes(touches), vec![c3, c1]);
7975
}
7976
7977
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
7978
/// file back where it was leave two placements at one place, which the
7979
/// tree shows as one file. Removing it, and then its directory, retires
7980
/// both, so no copy is left under a directory that is gone.
7981
#[test]
7982
fn git_import_removes_every_copy_of_a_file_at_one_place() {
7983
    hermetic();
7984
    if std::process::Command::new("git")
7985
        .arg("--version")
7986
        .output()
7987
        .is_err()
7988
    {
7989
        eprintln!("git not installed; skipping");
7990
        return;
7991
    }
7992
    let dir = tempfile::tempdir().unwrap();
7993
    let root = dir.path();
7994
    let g = root.join("src.git");
7995
    fs::create_dir_all(&g).unwrap();
7996
    let git = |args: &[&str]| {
7997
        let out = std::process::Command::new("git")
7998
            .arg("-C")
7999
            .arg(&g)
8000
            .args([
8001
                "-c",
8002
                "user.name=Grace",
8003
                "-c",
8004
                "[email protected]",
8005
                "-c",
8006
                "commit.gpgsign=false",
8007
            ])
8008
            .args(args)
8009
            .output()
8010
            .unwrap();
8011
        assert!(
8012
            out.status.success(),
8013
            "git {args:?}: {}",
8014
            String::from_utf8_lossy(&out.stderr)
8015
        );
8016
    };
8017
    git(&["init", "-q", "-b", "main"]);
8018
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8019
    write(&g, "keep.txt", b"k\n");
8020
    git(&["add", "."]);
8021
    git(&["commit", "-qm", "base"]);
8022
    fs::create_dir_all(g.join("d/sub")).unwrap();
8023
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8024
    git(&["commit", "-qm", "into sub"]);
8025
    git(&["checkout", "-qb", "side"]);
8026
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8027
    git(&["commit", "-qm", "back, on side"]);
8028
    git(&["checkout", "-q", "main"]);
8029
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8030
    git(&["commit", "-qm", "back, on main"]);
8031
    git(&["merge", "-q", "--no-edit", "side"]);
8032
    git(&["rm", "-rq", "d"]);
8033
    git(&["commit", "-qm", "d goes"]);
8034
8035
    let repo = Repo::init(&root.join("o")).unwrap();
8036
    repo.import_git(&g, "main").unwrap();
8037
    let v = repo.verify_git_import(&g, "main").unwrap();
8038
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8039
    let st = repo
8040
        .load_state_history(&repo.bookmark_heads().unwrap())
8041
        .unwrap();
8042
    let view = st.tree().view();
8043
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8044
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8045
}
8046
8047
/// oxygen#94: a state index's file histories are read, and checked by
8048
/// their own hashes, only when a file is built. One found damaged is an
8049
/// error that says so, the index is removed, and the next read rebuilds it.
8050
#[test]
8051
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8052
    hermetic();
8053
    let dir = tempfile::tempdir().unwrap();
8054
    let repo = Repo::init(dir.path()).unwrap();
8055
    for i in 0..6 {
8056
        write(
8057
            dir.path(),
8058
            &format!("f{i}.txt"),
8059
            format!("one {i}\n").as_bytes(),
8060
        );
8061
    }
8062
    repo.snapshot("t").unwrap();
8063
    repo.commit("first", &[]).unwrap();
8064
    for i in 0..6 {
8065
        write(
8066
            dir.path(),
8067
            &format!("f{i}.txt"),
8068
            format!("one {i}\ntwo\n").as_bytes(),
8069
        );
8070
    }
8071
    repo.snapshot("t").unwrap();
8072
    repo.commit("second", &[]).unwrap();
8073
    let want: Vec<Vec<u8>> = (0..6)
8074
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8075
        .collect();
8076
    // The index of the working copy's base, holding every file's history
8077
    // (a few changes behind, an index is replayed onto, not rewritten).
8078
    let (_, wc) = repo.working_copy().unwrap();
8079
    let base = repo.load_state_history(&wc.deps).unwrap();
8080
    repo.write_state_index(&wc.deps, &base);
8081
    for (i, w) in want.iter().enumerate() {
8082
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8083
    }
8084
    let index = repo.state_indexes();
8085
    assert!(!index.is_empty(), "a state index was written");
8086
    // The histories are last in the file: damage the last of them.
8087
    let mut bytes = fs::read(&index[0]).unwrap();
8088
    let last = bytes.len() - 1;
8089
    bytes[last] ^= 0x40;
8090
    fs::write(&index[0], &bytes).unwrap();
8091
8092
    let reads: Vec<_> = (0..6)
8093
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8094
        .collect();
8095
    let damaged: Vec<String> = reads
8096
        .iter()
8097
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8098
        .collect();
8099
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8100
    assert!(
8101
        damaged[0].contains("state index was damaged")
8102
            && damaged[0].contains("run the command again"),
8103
        "{}",
8104
        damaged[0]
8105
    );
8106
    // Every file reads right again, from an index rebuilt from history.
8107
    for (i, w) in want.iter().enumerate() {
8108
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8109
    }
8110
}
8111
8112
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8113
/// objects alone and in dependency order, and the last moves the bookmark.
8114
/// The remote ends with every change and the same state, and says how each
8115
/// part went.
8116
#[test]
8117
fn a_long_push_goes_in_parts() {
8118
    hermetic();
8119
    let dir = tempfile::tempdir().unwrap();
8120
    let root = dir.path();
8121
    let origin = root.join("origin");
8122
    Repo::init_bare_unbound(&origin).unwrap();
8123
    let main = root.join("main");
8124
    let mut repo = Repo::init(&main).unwrap();
8125
    repo.config
8126
        .set("remote.origin.url", &origin.to_string_lossy())
8127
        .unwrap();
8128
    // One byte: every change is a part of its own.
8129
    repo.config.set("push.batch-bytes", "1").unwrap();
8130
    repo.save_config().unwrap();
8131
    for i in 0..6 {
8132
        write(
8133
            &main,
8134
            &format!("f{i}.txt"),
8135
            format!("file {i}\n").as_bytes(),
8136
        );
8137
        repo.commit(&format!("c{i}"), &[]).unwrap();
8138
    }
8139
    let mut parts = Vec::new();
8140
    let results = repo
8141
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8142
        .unwrap();
8143
    assert!(
8144
        results.iter().any(|r| r.ok && r.name == "main"),
8145
        "{results:?}"
8146
    );
8147
    assert_eq!(parts.len(), 6, "{parts:?}");
8148
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8149
8150
    let remote = Repo::open(&origin).unwrap();
8151
    let heads = repo.bookmark_heads().unwrap();
8152
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8153
    assert_eq!(
8154
        remote.log_state(&heads).unwrap().len(),
8155
        repo.log_state(&heads).unwrap().len()
8156
    );
8157
    // A push of objects alone reports how it went, as `objects`.
8158
    let got = remote
8159
        .receive_push(Bundle::default(), vec![], None, vec![])
8160
        .unwrap();
8161
    assert_eq!(got.len(), 1);
8162
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8163
}
8164
8165
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8166
/// own commits (Git author email = its email, any case) with its key, and
8167
/// leaves anyone else's with the zero key; the history verifies as before.
8168
#[test]
8169
fn git_import_claims_your_own_commits() {
8170
    hermetic();
8171
    if std::process::Command::new("git")
8172
        .arg("--version")
8173
        .output()
8174
        .is_err()
8175
    {
8176
        eprintln!("git not installed; skipping");
8177
        return;
8178
    }
8179
    let dir = tempfile::tempdir().unwrap();
8180
    let root = dir.path();
8181
    let g = root.join("src.git");
8182
    fs::create_dir_all(&g).unwrap();
8183
    let git = |who: &str, args: &[&str]| {
8184
        let (name, email) = who.split_once(' ').unwrap();
8185
        let out = std::process::Command::new("git")
8186
            .arg("-C")
8187
            .arg(&g)
8188
            .args([
8189
                "-c",
8190
                &format!("user.name={name}"),
8191
                "-c",
8192
                &format!("user.email={email}"),
8193
                "-c",
8194
                "commit.gpgsign=false",
8195
            ])
8196
            .args(args)
8197
            .output()
8198
            .unwrap();
8199
        assert!(
8200
            out.status.success(),
8201
            "git {args:?}: {}",
8202
            String::from_utf8_lossy(&out.stderr)
8203
        );
8204
    };
8205
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8206
    write(&g, "a.txt", b"a\n");
8207
    git("Grace [email protected]", &["add", "."]);
8208
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8209
    write(&g, "b.txt", b"b\n");
8210
    git("Ada [email protected]", &["add", "."]);
8211
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8212
8213
    let mut repo = Repo::init(&root.join("o")).unwrap();
8214
    let (key, _) = repo
8215
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8216
        .unwrap();
8217
    repo.config.set("git.claim", "true").unwrap();
8218
    repo.save_config().unwrap();
8219
    let repo = Repo::open(&root.join("o")).unwrap();
8220
    repo.import_git(&g, "main").unwrap();
8221
    let v = repo.verify_git_import(&g, "main").unwrap();
8222
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8223
    let heads = repo.bookmark_heads().unwrap();
8224
    let by_message: std::collections::HashMap<String, KeyId> = repo
8225
        .log_state(&heads)
8226
        .unwrap()
8227
        .into_iter()
8228
        .map(|e| {
8229
            (
8230
                e.change.message.lines().next().unwrap_or("").to_string(),
8231
                e.change.author,
8232
            )
8233
        })
8234
        .collect();
8235
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8236
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8237
}
8238
8239
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8240
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8241
#[test]
8242
fn removing_a_remote_leaves_nothing_of_it() {
8243
    hermetic();
8244
    let dir = tempfile::tempdir().unwrap();
8245
    let origin = dir.path().join("origin");
8246
    Repo::init_bare_unbound(&origin).unwrap();
8247
    let main = dir.path().join("main");
8248
    let mut repo = Repo::init(&main).unwrap();
8249
    repo.config
8250
        .set("remote.origin.url", &origin.to_string_lossy())
8251
        .unwrap();
8252
    repo.config
8253
        .set("remote.origin.token", "secret-ish")
8254
        .unwrap();
8255
    repo.config
8256
        .set("remote.keep.url", &origin.to_string_lossy())
8257
        .unwrap();
8258
    repo.save_config().unwrap();
8259
    write(&main, "a.txt", b"a\n");
8260
    repo.commit("a", &[]).unwrap();
8261
    assert!(repo.push("origin", false).unwrap()[0].ok);
8262
    assert!(
8263
        repo.view().unwrap().remotes.contains_key("origin"),
8264
        "a tracking bookmark"
8265
    );
8266
8267
    repo.remove_remote("origin").unwrap();
8268
    let again = Repo::open(&main).unwrap();
8269
    assert!(
8270
        !again
8271
            .config
8272
            .repo_layer()
8273
            .keys()
8274
            .any(|k| k.starts_with("remote.origin.")),
8275
        "{:?}",
8276
        again.config.repo_layer()
8277
    );
8278
    assert!(!again.config.remotes.contains_key("origin"));
8279
    assert!(
8280
        !again.view().unwrap().remotes.contains_key("origin"),
8281
        "its tracking bookmarks go"
8282
    );
8283
    assert!(
8284
        again.config.remotes.contains_key("keep"),
8285
        "another remote stays"
8286
    );
8287
    let mut again = again;
8288
    assert!(
8289
        again.remove_remote("origin").is_err(),
8290
        "a second removal is refused"
8291
    );
8292
}
8293
8294
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
8295
/// unreachable from history, so gc prunes it, unless the host names it:
8296
/// then it and its chunks stay, and it reads back whole.
8297
#[test]
8298
fn gc_keeps_the_blobs_a_host_names() {
8299
    hermetic();
8300
    let dir = tempfile::tempdir().unwrap();
8301
    let repo = Repo::init(dir.path()).unwrap();
8302
    write(dir.path(), "a.txt", b"a\n");
8303
    repo.commit("a", &[]).unwrap();
8304
    // Large enough to be several chunks.
8305
    let body: Vec<u8> = (0..400_000u32)
8306
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
8307
        .collect();
8308
    let kept = repo.store_blob(&body).unwrap();
8309
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
8310
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
8311
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
8312
    assert!(!repo.store().has(&lost), "not named: pruned");
8313
    repo.gc(true).unwrap();
8314
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
8315
}
8316
8317
/// oxygen#99: undo in one workspace undoes that workspace's last command,
8318
/// never another workspace's, says what it undid, and goes further back
8319
/// when run again.
8320
#[test]
8321
fn undo_is_scoped_to_its_workspace() {
8322
    hermetic();
8323
    let dir = tempfile::tempdir().unwrap();
8324
    let root = dir.path().join("main");
8325
    let a = Repo::init(&root).unwrap();
8326
    write(&root, "base.txt", b"base\n");
8327
    let base = a.commit("base", &[]).unwrap();
8328
    a.bookmark_create("feature", None).unwrap();
8329
    let ws_dir = dir.path().join("ws");
8330
    let heads = a.resolve_heads("feature").unwrap();
8331
    let b = a
8332
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
8333
        .unwrap();
8334
8335
    // A commits on main, then B commits on feature: B's is the newest.
8336
    write(&root, "a.txt", b"a\n");
8337
    let ca = a.commit("from a", &[]).unwrap();
8338
    write(&ws_dir, "b.txt", b"b\n");
8339
    let cb = b.commit("from b", &[]).unwrap();
8340
8341
    // A's undo undoes A's commit and leaves B's.
8342
    let u = a.undo().unwrap();
8343
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8344
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
8345
    assert!(!u.changes.is_empty());
8346
    let view = a.view().unwrap();
8347
    // (Independent changes commute, so a bookmark's heads may hold base too.)
8348
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
8349
    assert!(
8350
        a.heads_of(&view, "feature").unwrap().contains(&cb),
8351
        "B's commit stands"
8352
    );
8353
    assert!(
8354
        a.store().get_change(&ca).is_ok(),
8355
        "the change itself is still in the store"
8356
    );
8357
    // A's working copy was clean, so its files followed; B's are untouched.
8358
    assert!(!root.join("a.txt").exists());
8359
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
8360
    assert!(ws_dir.join("b.txt").exists());
8361
8362
    // B's undo still finds B's own commit, under A's undo.
8363
    let u = b.undo().unwrap();
8364
    assert_eq!(u.command, "oxy commit -m \"from b\"");
8365
    assert!(!b
8366
        .heads_of(&b.view().unwrap(), "feature")
8367
        .unwrap()
8368
        .contains(&cb));
8369
    assert_eq!(
8370
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
8371
        vec![base],
8372
        "A's undo stands"
8373
    );
8374
8375
    // A's next undo goes past the commit it already undid, to adding B's
8376
    // workspace: refused, since B has worked there since.
8377
    let e = a.undo().unwrap_err().to_string();
8378
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
8379
}
8380
8381
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
8382
/// own commit's head, and the other workspace's head stays.
8383
#[test]
8384
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
8385
    hermetic();
8386
    let dir = tempfile::tempdir().unwrap();
8387
    let root = dir.path().join("main");
8388
    let a = Repo::init(&root).unwrap();
8389
    write(&root, "base.txt", b"base\n");
8390
    a.commit("base", &[]).unwrap();
8391
    let ws_dir = dir.path().join("ws");
8392
    let b = a.workspace_add(&ws_dir, None).unwrap();
8393
    write(&root, "a.txt", b"a\n");
8394
    let ca = a.commit("from a", &[]).unwrap();
8395
    write(&ws_dir, "b.txt", b"b\n");
8396
    let cb = b.commit("from b", &[]).unwrap();
8397
    let u = a.undo().unwrap();
8398
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8399
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
8400
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
8401
}
8402
8403
/// oxygen#99: an undo that would also take back what another workspace
8404
/// did since to the same bookmark is refused, naming it.
8405
#[test]
8406
fn undo_refuses_to_take_back_another_workspaces_work() {
8407
    hermetic();
8408
    let dir = tempfile::tempdir().unwrap();
8409
    let root = dir.path().join("main");
8410
    let a = Repo::init(&root).unwrap();
8411
    write(&root, "base.txt", b"base\n");
8412
    a.commit("base", &[]).unwrap();
8413
    let ws_dir = dir.path().join("ws");
8414
    let b = a.workspace_add(&ws_dir, None).unwrap();
8415
    // Both on main: A commits, then B builds on it, editing A's file.
8416
    write(&root, "a.txt", b"a\n");
8417
    a.commit("from a", &[]).unwrap();
8418
    let heads = b.resolve_heads("main").unwrap();
8419
    b.checkout(&heads, false, "oxy checkout").unwrap();
8420
    write(&ws_dir, "a.txt", b"a, then b\n");
8421
    b.commit("from b", &[]).unwrap();
8422
    let e = a.undo().unwrap_err().to_string();
8423
    assert!(
8424
        e.contains("bookmark main") && e.contains("builds on"),
8425
        "{e}"
8426
    );
8427
    assert!(e.contains("oxy op restore"), "{e}");
8428
}
8429
8430
/// oxygen#99: undoing a commit that was already pushed says so: the remote
8431
/// still has it.
8432
#[test]
8433
fn undo_says_when_the_commit_was_pushed() {
8434
    hermetic();
8435
    let dir = tempfile::tempdir().unwrap();
8436
    let root = dir.path();
8437
    Repo::init(&root.join("origin")).unwrap();
8438
    let url = root.join("origin").to_string_lossy().to_string();
8439
    let repo = Repo::clone(&url, &root.join("work"))
8440
        .unwrap()
8441
        .with_home(root.join("home"));
8442
    write(&root.join("work"), "a.txt", b"a\n");
8443
    repo.commit("a", &[]).unwrap();
8444
    assert!(repo.push("origin", false).unwrap()[0].ok);
8445
    // The push itself is passed over: the remote keeps what it was sent.
8446
    let u = repo.undo().unwrap();
8447
    assert_eq!(u.command, "oxy commit -m \"a\"");
8448
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
8449
}
8450
8451
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
8452
/// out of the snapshot and named; tracked files and files already in the
8453
/// working copy are not.
8454
#[test]
8455
fn large_new_files_are_left_out_of_snapshots() {
8456
    hermetic();
8457
    let dir = tempfile::tempdir().unwrap();
8458
    let root = dir.path();
8459
    let mut repo = Repo::init(root).unwrap();
8460
    repo.config.max_new_file = 1024;
8461
    write(root, "small.txt", b"small\n");
8462
    write(root, "big.bin", &vec![0u8; 4096]);
8463
    let s = repo.snapshot("oxy status").unwrap();
8464
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8465
    assert_eq!(paths, ["small.txt"]);
8466
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
8467
    repo.commit("small", &[]).unwrap();
8468
8469
    // A tracked file may grow past the limit.
8470
    write(root, "small.txt", &vec![b'x'; 4096]);
8471
    let s = repo.snapshot("oxy status").unwrap();
8472
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
8473
    // With no limit the big file is taken in, and stays once it is.
8474
    repo.config.max_new_file = 0;
8475
    let s = repo.snapshot("oxy status").unwrap();
8476
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
8477
    repo.config.max_new_file = 1024;
8478
    let s = repo.snapshot("oxy status").unwrap();
8479
    assert!(
8480
        s.statuses.iter().any(|p| p.path == "big.bin"),
8481
        "already in the working copy"
8482
    );
8483
    assert!(repo.skipped_large().is_empty());
8484
}
8485
8486
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
8487
/// snapshots expire, and kept while they have not.
8488
#[test]
8489
fn gc_prunes_what_only_expired_snapshots_held() {
8490
    hermetic();
8491
    let dir = tempfile::tempdir().unwrap();
8492
    let root = dir.path();
8493
    let mut repo = Repo::init(root).unwrap();
8494
    repo.config.gc_grace_days = 0;
8495
    write(root, "a.txt", b"a\n");
8496
    repo.commit("a", &[]).unwrap();
8497
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
8498
    write(root, "image.tar", &image);
8499
    repo.snapshot("oxy status").unwrap();
8500
    std::fs::remove_file(root.join("image.tar")).unwrap();
8501
    repo.snapshot("oxy status").unwrap();
8502
    let blob = Repo::blob_ref(&image);
8503
    assert!(repo.store().has(&blob));
8504
    repo.gc(true).unwrap();
8505
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
8506
    repo.config.snapshot_retention_days = 0;
8507
    repo.gc(true).unwrap();
8508
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
8509
    assert_eq!(
8510
        repo.file_at("a.txt", None).unwrap(),
8511
        b"a\n",
8512
        "committed files stay"
8513
    );
8514
}
8515
8516
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
8517
/// already has is no conflict: the switch goes through, nothing is lost,
8518
/// and other carried work still comes along.
8519
#[test]
8520
fn carrying_work_the_target_already_has_is_no_conflict() {
8521
    hermetic();
8522
    let dir = tempfile::tempdir().unwrap();
8523
    let root = dir.path();
8524
    let mut repo = Repo::init(root).unwrap();
8525
    write(root, "a.txt", b"one\n");
8526
    write(root, "b.txt", b"b\n");
8527
    repo.commit("one", &[]).unwrap();
8528
    repo.bookmark_create("landed", None).unwrap();
8529
    // On landed, a.txt becomes "two" (as a proposal landing would).
8530
    repo.bookmark_switch("landed", false).unwrap();
8531
    write(root, "a.txt", b"two\n");
8532
    repo.commit("two", &[]).unwrap();
8533
    repo.bookmark_switch("main", false).unwrap();
8534
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
8535
    // The same edit, uncommitted, on main; and another edit besides.
8536
    write(root, "a.txt", b"two\n");
8537
    write(root, "b.txt", b"b, edited\n");
8538
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
8539
    assert_eq!(
8540
        carried,
8541
        vec!["b.txt".to_string()],
8542
        "only the work landed lacks is carried"
8543
    );
8544
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
8545
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
8546
    let s = repo.snapshot("oxy status").unwrap();
8547
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8548
    assert_eq!(paths, ["b.txt"]);
8549
8550
    // A real difference is still refused.
8551
    repo.bookmark_switch("main", true).unwrap();
8552
    write(root, "a.txt", b"three\n");
8553
    let e = repo
8554
        .bookmark_switch_carry("landed")
8555
        .unwrap_err()
8556
        .to_string();
8557
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
8558
}
8559
8560
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
8561
/// resolves, so JSON output feeds back into commands.
8562
#[test]
8563
fn a_full_hash_resolves_without_its_hash_sign() {
8564
    hermetic();
8565
    let dir = tempfile::tempdir().unwrap();
8566
    let root = dir.path();
8567
    let repo = Repo::init(root).unwrap();
8568
    write(root, "a.txt", b"a\n");
8569
    let h = repo.commit("a", &[]).unwrap();
8570
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
8571
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
8572
    assert!(repo
8573
        .resolve_change(&"0".repeat(64))
8574
        .unwrap_err()
8575
        .to_string()
8576
        .contains("no change matches"));
8577
}