OXYGENHUB
# d82e44097323 oxygen / crates / oxy-core / src / repo / tests.rs
142.4 KiB · Rust · last changed Seals adopt anonymous changes; oxy seal command 1 month ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
use crate::protocol::SignedPolicy;
5
use crate::repo::{BisectStep, Selection};
6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
137
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
138
    assert!(d.contains("-fn main() {}"), "{d}");
139
140
    // Resolution by prefix.
141
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
142
    assert_eq!(
143
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
144
        h1
145
    );
146
    assert!(repo.resolve_change("zzzz").is_err());
147
148
    // Undo the commit: bookmark and working copy go back.
149
    repo.undo().unwrap();
150
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
151
    let s = repo.snapshot("oxy status").unwrap();
152
    assert!(
153
        !s.changed,
154
        "files on disk still match the pre-commit working copy"
155
    );
156
    assert_eq!(s.statuses.len(), 3);
157
}
158
159
/// Make `main` conflicted: two commits on the same base that edit the same line.
160
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
161
    let dir = tempfile::tempdir().unwrap();
162
    let root = dir.path();
163
    let repo = Repo::init(root).unwrap();
164
    write(root, "f.txt", b"a\nb\nc\n");
165
    let h1 = repo.commit("base", &[]).unwrap();
166
    write(root, "f.txt", b"a\nB\nc\n");
167
    let h2 = repo.commit("upper", &[]).unwrap();
168
    repo.checkout(&[h1], false, "checkout").unwrap();
169
    write(root, "f.txt", b"a\nX\nc\n");
170
    let h3 = repo.commit("ex", &[]).unwrap();
171
    (dir, repo, h1, h2, h3)
172
}
173
174
#[test]
175
fn concurrent_edits_conflict_and_can_be_resolved() {
176
    hermetic();
177
    let (dir, repo, h1, h2, h3) = conflicted_repo();
178
    let root = dir.path();
179
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
180
    assert_eq!(heads, [h2, h3].into_iter().collect());
181
    let st = repo.load_state(&[h2, h3]).unwrap();
182
    assert!(st.materialize().is_conflicted());
183
184
    // Checking out main writes markers.
185
    let r = repo
186
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
187
        .unwrap();
188
    assert!(r.conflicted);
189
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
190
    assert!(
191
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
192
        "{marked}"
193
    );
194
    assert!(
195
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
196
        "{marked}"
197
    );
198
    assert!(has_conflict_markers(marked.as_bytes()));
199
    // Untouched markers: clean working copy; commit has nothing to do.
200
    let s = repo.snapshot("status").unwrap();
201
    assert!(s.statuses.is_empty());
202
    assert!(!s.resolves);
203
204
    // Partially edited file that still has markers cannot be committed.
205
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
206
    let s = repo.snapshot("status").unwrap();
207
    assert_eq!(
208
        statuses(&s),
209
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
210
    );
211
    assert!(repo.commit("no", &[]).is_err());
212
213
    // Resolve by keeping one side and adding a line elsewhere.
214
    write(root, "f.txt", b"a\nX\nc\nd\n");
215
    let s = repo.snapshot("status").unwrap();
216
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
217
    assert!(s.resolves);
218
    let h4 = repo.commit("resolve", &[]).unwrap();
219
    let c4 = repo.store().get_change(&h4).unwrap();
220
    assert_eq!(c4.kind, ChangeKind::Resolution);
221
    let mut want = vec![h1, h2, h3];
222
    want.sort();
223
    assert_eq!(
224
        c4.deps, want,
225
        "a resolution depends on exactly the contributors and what it references"
226
    );
227
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
228
    let snap = repo.load_state(&[h4]).unwrap().materialize();
229
    assert!(!snap.is_conflicted());
230
    assert!(
231
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
232
    );
233
    assert!(!repo.snapshot("status").unwrap().changed);
234
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
235
    // whatever order the changes arrive in.
236
    let mut st = State::new();
237
    for h in [h4, h3, h1, h2] {
238
        st.add_unchecked(repo.store().get_change(&h).unwrap());
239
    }
240
    st.validate().unwrap();
241
    assert!(
242
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
243
    );
244
}
245
246
#[test]
247
fn resolution_may_keep_both_sides_or_neither() {
248
    hermetic();
249
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
250
    let root = dir.path();
251
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
252
        .unwrap();
253
    // Keep both sides in a chosen order.
254
    write(root, "f.txt", b"a\nX\nB\nc\n");
255
    let h = repo.commit("both", &[]).unwrap();
256
    let snap = repo.load_state(&[h]).unwrap().materialize();
257
    assert!(!snap.is_conflicted());
258
    assert!(
259
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
260
    );
261
    // Undo and instead drop the whole region.
262
    repo.undo().unwrap();
263
    write(root, "f.txt", b"a\nc\n");
264
    let h = repo.commit("neither", &[]).unwrap();
265
    let snap = repo.load_state(&[h]).unwrap().materialize();
266
    assert!(!snap.is_conflicted());
267
    assert!(
268
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
269
    );
270
}
271
272
#[test]
273
fn name_conflict_resolved_by_removing_a_candidate() {
274
    hermetic();
275
    let dir = tempfile::tempdir().unwrap();
276
    let root = dir.path();
277
    let repo = Repo::init(root).unwrap();
278
    write(root, "keep.txt", b"k\n");
279
    let h1 = repo.commit("base", &[]).unwrap();
280
    write(root, "new.txt", b"one\n");
281
    repo.commit("one", &[]).unwrap();
282
    repo.checkout(&[h1], false, "checkout").unwrap();
283
    write(root, "new.txt", b"two\n");
284
    repo.commit("two", &[]).unwrap();
285
    let r = repo
286
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
287
        .unwrap();
288
    assert!(r.conflicted);
289
    assert!(
290
        root.join("new.txt.oxy-conflict-1").exists()
291
            && root.join("new.txt.oxy-conflict-2").exists()
292
    );
293
    assert!(!root.join("new.txt").exists());
294
    // Candidate numbering follows change-hash order, so pick by content:
295
    // keep the "two" candidate under the real name and drop the other.
296
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
297
        (1, 2)
298
    } else {
299
        (2, 1)
300
    };
301
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
302
    fs::rename(
303
        root.join(format!("new.txt.oxy-conflict-{keep}")),
304
        root.join("new.txt"),
305
    )
306
    .unwrap();
307
    let h = repo.commit("pick two", &[]).unwrap();
308
    assert_eq!(
309
        repo.store().get_change(&h).unwrap().kind,
310
        ChangeKind::Resolution
311
    );
312
    // The resolution does not touch keep.txt, so it does not depend on h1;
313
    // the bookmark keeps both as heads and their union is the state.
314
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
315
    assert_eq!(heads, [h1, h].into_iter().collect());
316
    let snap = repo
317
        .load_state(&repo.bookmark_heads().unwrap())
318
        .unwrap()
319
        .materialize();
320
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
321
    assert_eq!(
322
        snap.files.keys().cloned().collect::<Vec<_>>(),
323
        ["keep.txt", "new.txt"]
324
    );
325
    assert!(
326
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
327
    );
328
}
329
330
#[test]
331
fn identities_and_signed_commits() {
332
    hermetic();
333
    let dir = tempfile::tempdir().unwrap();
334
    let root = dir.path();
335
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
336
    write(root, "a.txt", b"a\n");
337
    let h0 = repo.commit("unsigned", &[]).unwrap();
338
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
339
    assert_eq!(
340
        repo.store().get_change(&h0).unwrap().author,
341
        ObjectRef::ZERO
342
    );
343
344
    let (key, id) = repo
345
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
346
        .unwrap();
347
    assert_eq!(id.hash(), key);
348
    assert_eq!(repo.config.author_key, Some(key));
349
    // Config survives reopen; the secret key is found again.
350
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
351
    assert_eq!(reopened.config.author_key, Some(key));
352
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
353
354
    // Default core.sign = seal: commits carry the author but no signature.
355
    write(root, "a.txt", b"a\nb\n");
356
    let h1 = repo.commit("authored", &[]).unwrap();
357
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
358
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
359
    // Signing later works too.
360
    repo.sign_change(&h1).unwrap();
361
    assert!(
362
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
363
    );
364
365
    repo.config.set("core.sign", "change").unwrap();
366
    repo.save_config().unwrap();
367
    write(root, "a.txt", b"a\nb\nc\n");
368
    let h2 = repo.commit("signed", &[]).unwrap();
369
    assert_eq!(
370
        repo.verify_change(&h2).unwrap(),
371
        SignatureStatus::Valid {
372
            key,
373
            name: "Ada".into(),
374
            email: "[email protected]".into(),
375
            sealed: false,
376
            revoked: false
377
        }
378
    );
379
380
    // A signature by a key that is not the author or a delegate is rejected
381
    // when the change names an author; an anonymous change (made before any
382
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
383
    let other = SecretKey::generate();
384
    let other_id = other.identity("Mallory", "[email protected]", 0);
385
    let other_key = repo.store().put_identity(&other_id).unwrap();
386
    write(root, "a.txt", b"a\nb\nc\nd\n");
387
    repo.config.set("core.sign", "seal").unwrap();
388
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
389
    let forged = other.sign(Domain::Change, &other_key, &h3);
390
    repo.store().put_signature(&h3, &forged).unwrap();
391
    assert!(
392
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
393
    );
394
    let adopted = other.sign(Domain::Change, &other_key, &h0);
395
    repo.store().put_signature(&h0, &adopted).unwrap();
396
    assert!(
397
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
398
    );
399
400
    // Tampering with the stored signature invalidates it.
401
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
402
    sig.ed[0] ^= 1;
403
    repo.store().put_signature(&h2, &sig).unwrap();
404
    assert!(matches!(
405
        repo.verify_change(&h2).unwrap(),
406
        SignatureStatus::Invalid(_)
407
    ));
408
409
    // Without the secret key, signing at commit fails cleanly.
410
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
411
    write(root, "a.txt", b"z\n");
412
    assert!(no_keys.commit("cannot sign", &[]).is_err());
413
}
414
415
#[test]
416
fn checkout_moves_the_working_copy() {
417
    hermetic();
418
    let dir = tempfile::tempdir().unwrap();
419
    let root = dir.path();
420
    let repo = Repo::init(root).unwrap();
421
    write(root, "a.txt", b"one\n");
422
    write(root, "sub/deep/b.txt", b"b\n");
423
    let h1 = repo.commit("first", &[]).unwrap();
424
    write(root, "a.txt", b"two\n");
425
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
426
    write(root, "bin.dat", &[0, 1, 2, 3]);
427
    let h2 = repo.commit("second", &[]).unwrap();
428
429
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
430
    assert_eq!(
431
        r,
432
        CheckoutReport {
433
            written: 2,
434
            removed: 1,
435
            conflicted: false,
436
            notes: vec![]
437
        }
438
    );
439
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
440
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
441
    assert!(!root.join("bin.dat").exists());
442
    let (_, wc) = repo.working_copy().unwrap();
443
    assert_eq!(wc.deps, vec![h1]);
444
    assert!(
445
        !repo.snapshot("status").unwrap().changed,
446
        "checkout leaves a clean working copy"
447
    );
448
    // The bookmark still points at h2.
449
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
450
451
    // Dirty working copy refuses without --discard.
452
    write(root, "a.txt", b"dirty\n");
453
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
454
    let r = repo
455
        .checkout(&[h2], true, "oxy checkout --discard")
456
        .unwrap();
457
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
458
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
459
    assert!(!root.join("sub").exists(), "empty directories are pruned");
460
    assert_eq!(r.removed, 1);
461
    assert!(!repo.snapshot("status").unwrap().changed);
462
463
    // Refuses to write through a symlinked directory.
464
    #[cfg(unix)]
465
    {
466
        fs::remove_dir_all(root.join("sub")).ok();
467
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
468
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
469
    }
470
}
471
472
#[test]
473
fn large_files_are_chunked_and_read_back() {
474
    hermetic();
475
    let dir = tempfile::tempdir().unwrap();
476
    let repo = Repo::init(dir.path()).unwrap();
477
    let mut big = vec![0u8; 700 * 1024];
478
    for (i, b) in big.iter_mut().enumerate() {
479
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
480
    }
481
    let r = repo.store_blob(&big).unwrap();
482
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
483
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
484
    assert_eq!(repo.read_blob(&r).unwrap(), big);
485
    assert_eq!(Repo::blob_ref(&big), r);
486
}
487
488
#[test]
489
fn clone_push_pull_with_seals_and_attestations() {
490
    hermetic();
491
    let dir = tempfile::tempdir().unwrap();
492
    let root = dir.path();
493
    let origin_path = root.join("origin");
494
    let origin = Repo::init(&origin_path).unwrap();
495
    let origin_url = origin_path.to_string_lossy().to_string();
496
497
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
498
    let mut a = Repo::clone(&origin_url, &root.join("a"))
499
        .unwrap()
500
        .with_home(root.join("home-a"));
501
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
502
    let (key_a, _) = a
503
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
504
        .unwrap();
505
    write(&root.join("a"), "f.txt", b"a\n");
506
    let h1 = a.commit("first", &[]).unwrap();
507
    let results = a.push("origin", false).unwrap();
508
    assert!(results[0].ok, "{}", results[0].reason);
509
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
510
    // The change was sealed at push and the reference attested.
511
    assert!(
512
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
513
    );
514
    assert_eq!(
515
        origin.verify_change(&h1).unwrap(),
516
        SignatureStatus::Unsigned
517
    );
518
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
519
    assert!(matches!(att.attest.body, AttestBody::Ref { serial: 1, .. }));
520
    let again = a.push("origin", false).unwrap();
521
    assert!(again[0].ok && again[0].reason.contains("up to date"));
522
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
523
    assert!(
524
        matches!(att.attest.body, AttestBody::Ref { serial: 1, .. }),
525
        "a no-op push does not attest again"
526
    );
527
528
    // B clones and sees the file and the seal.
529
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
530
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
531
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
532
    assert!(matches!(
533
        b.authenticate_change(&h1).unwrap(),
534
        SignatureStatus::Valid { sealed: true, .. }
535
    ));
536
537
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
538
    write(&root.join("b"), "f.txt", b"a\nb\n");
539
    let h2 = b.commit("second", &[]).unwrap();
540
    assert!(b.push("origin", false).unwrap()[0].ok);
541
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
542
543
    // A commits an independent change; push is refused until A pulls.
544
    write(&root.join("a"), "g.txt", b"g\n");
545
    let h3 = a.commit("third", &[]).unwrap();
546
    assert!(a.push("origin", false).is_err());
547
    let pr = a.pull("origin").unwrap();
548
    assert!(pr.changed && pr.checked_out);
549
    let mut want = vec![h2, h3];
550
    want.sort();
551
    assert_eq!(pr.heads, want);
552
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
553
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
554
    let results = a.push("origin", false).unwrap();
555
    assert!(results[0].ok, "{}", results[0].reason);
556
    let mut origin_heads = origin.bookmark_heads().unwrap();
557
    origin_heads.sort();
558
    assert_eq!(origin_heads, want);
559
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
560
    assert!(matches!(att.attest.body, AttestBody::Ref { serial: 2, .. }));
561
562
    // B pulls and ends up identical.
563
    let pr = b.pull("origin").unwrap();
564
    assert_eq!(pr.heads, want);
565
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
566
    assert!(!b.snapshot("status").unwrap().changed);
567
568
    // Concurrent edits of the same line: the union is a reified conflict.
569
    write(&root.join("a"), "f.txt", b"a\nA\n");
570
    a.commit("a-edit", &[]).unwrap();
571
    a.push("origin", false).unwrap();
572
    write(&root.join("b"), "f.txt", b"a\nB\n");
573
    b.commit("b-edit", &[]).unwrap();
574
    let pr = b.pull("origin").unwrap();
575
    assert!(pr.changed && pr.checked_out);
576
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
577
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
578
    write(&root.join("b"), "f.txt", b"a\nAB\n");
579
    let hr = b.commit("resolve", &[]).unwrap();
580
    assert_eq!(
581
        b.store().get_change(&hr).unwrap().kind,
582
        ChangeKind::Resolution
583
    );
584
    assert!(b.push("origin", false).unwrap()[0].ok);
585
    a.pull("origin").unwrap();
586
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
587
    // The resolution depends on the conflicting edits, but nothing depends
588
    // on "third" (it only added g.txt), so it stays a head beside it.
589
    let mut want = vec![hr, h3];
590
    want.sort();
591
    assert_eq!(a.bookmark_heads().unwrap(), want);
592
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
593
}
594
595
#[test]
596
fn receive_push_rejects_bad_updates() {
597
    hermetic();
598
    let dir = tempfile::tempdir().unwrap();
599
    let root = dir.path();
600
    let origin = Repo::init(&root.join("origin")).unwrap();
601
    let url = root.join("origin").to_string_lossy().to_string();
602
    let mut a = Repo::clone(&url, &root.join("a"))
603
        .unwrap()
604
        .with_home(root.join("home"));
605
    let (key, _) = a
606
        .create_identity("Ada", "a@b", IdentityScope::Repo)
607
        .unwrap();
608
    write(&root.join("a"), "f.txt", b"x\n");
609
    let h1 = a.commit("one", &[]).unwrap();
610
    assert!(a.push("origin", false).unwrap()[0].ok);
611
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
612
    let s1 = origin
613
        .store()
614
        .put_state(&StateObject::new(vec![h1]))
615
        .unwrap();
616
617
    // Missing head.
618
    let ghost = origin
619
        .store()
620
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
621
        .unwrap();
622
    let r = origin
623
        .receive_push(
624
            Bundle::default(),
625
            vec![RefUpdate {
626
                name: "main".into(),
627
                old_state: s1,
628
                new_state: ghost,
629
                force: false,
630
                attestation: None,
631
            }],
632
            None,
633
            vec![],
634
        )
635
        .unwrap();
636
    assert!(
637
        !r[0].ok && r[0].reason.contains("missing"),
638
        "{}",
639
        r[0].reason
640
    );
641
642
    // Stale old_state.
643
    let r = origin
644
        .receive_push(
645
            Bundle::default(),
646
            vec![RefUpdate {
647
                name: "main".into(),
648
                old_state: empty,
649
                new_state: s1,
650
                force: false,
651
                attestation: None,
652
            }],
653
            None,
654
            vec![],
655
        )
656
        .unwrap();
657
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
658
659
    // Non-fast-forward without force is refused; with force it passes.
660
    let r = origin
661
        .receive_push(
662
            Bundle::default(),
663
            vec![RefUpdate {
664
                name: "main".into(),
665
                old_state: s1,
666
                new_state: empty,
667
                force: false,
668
                attestation: None,
669
            }],
670
            None,
671
            vec![],
672
        )
673
        .unwrap();
674
    assert!(
675
        !r[0].ok && r[0].reason.contains("fast-forward"),
676
        "{}",
677
        r[0].reason
678
    );
679
    let r = origin
680
        .receive_push(
681
            Bundle::default(),
682
            vec![RefUpdate {
683
                name: "main".into(),
684
                old_state: s1,
685
                new_state: empty,
686
                force: true,
687
                attestation: None,
688
            }],
689
            None,
690
            vec![],
691
        )
692
        .unwrap();
693
    assert!(r[0].ok);
694
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
695
696
    // Attestation with a stale serial is a rollback and is refused.
697
    let sa = a
698
        .sign_attest(&Attest {
699
            repo: a.id().unwrap(),
700
            hlc: Hlc::now(),
701
            body: AttestBody::Ref {
702
                name: "main".into(),
703
                old_state: empty,
704
                new_state: s1,
705
                serial: 1,
706
            },
707
        })
708
        .unwrap();
709
    let r = origin
710
        .receive_push(
711
            Bundle::default(),
712
            vec![RefUpdate {
713
                name: "main".into(),
714
                old_state: empty,
715
                new_state: s1,
716
                force: false,
717
                attestation: Some(sa.clone()),
718
            }],
719
            None,
720
            vec![],
721
        )
722
        .unwrap();
723
    assert!(
724
        !r[0].ok && r[0].reason.contains("serial"),
725
        "{}",
726
        r[0].reason
727
    );
728
    // An attestation for a different update is refused too.
729
    let sa2 = a
730
        .sign_attest(&Attest {
731
            repo: a.id().unwrap(),
732
            hlc: Hlc::now(),
733
            body: AttestBody::Ref {
734
                name: "main".into(),
735
                old_state: s1,
736
                new_state: empty,
737
                serial: 5,
738
            },
739
        })
740
        .unwrap();
741
    let r = origin
742
        .receive_push(
743
            Bundle::default(),
744
            vec![RefUpdate {
745
                name: "main".into(),
746
                old_state: empty,
747
                new_state: s1,
748
                force: false,
749
                attestation: Some(sa2),
750
            }],
751
            None,
752
            vec![],
753
        )
754
        .unwrap();
755
    assert!(
756
        !r[0].ok && r[0].reason.contains("describe"),
757
        "{}",
758
        r[0].reason
759
    );
760
    let _ = key;
761
}
762
763
#[test]
764
fn user_config_supplies_defaults_and_clones_sign() {
765
    hermetic();
766
    let dir = tempfile::tempdir().unwrap();
767
    let root = dir.path();
768
    let home = root.join("home");
769
    let origin = Repo::init(&root.join("origin")).unwrap();
770
    let url = root.join("origin").to_string_lossy().to_string();
771
772
    // Identity at user scope: the repository file stays free of author keys.
773
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
774
    let (key, _) = a
775
        .create_identity("Ada", "[email protected]", IdentityScope::User)
776
        .unwrap();
777
    assert!(!a.config.repo_layer().contains_key("author.key"));
778
    assert_eq!(a.config.author_key, Some(key));
779
    assert!(home.join("config.toml").exists());
780
    a.set_user_config("core.sign", "change").unwrap();
781
    assert!(a.config.sign_changes);
782
783
    // Repository settings override user settings and are the only ones saved.
784
    a.config.set("core.sign", "seal").unwrap();
785
    a.save_config().unwrap();
786
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
787
    assert!(!again.config.sign_changes);
788
    assert_eq!(again.config.author_key, Some(key));
789
    assert_eq!(
790
        read_config_file(&root.join("a/.oxy/config"))
791
            .unwrap()
792
            .get("core.sign")
793
            .map(String::as_str),
794
        Some("seal")
795
    );
796
797
    // A fresh clone made by this user signs with the user-level identity,
798
    // even though the clone's store has never seen the identity object.
799
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
800
    assert!(b.config.sign_changes);
801
    write(&root.join("b"), "f.txt", b"f\n");
802
    let h = b.commit("signed from a clone", &[]).unwrap();
803
    assert!(
804
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
805
    );
806
    assert!(b.push("origin", false).unwrap()[0].ok);
807
    assert!(matches!(
808
        origin.verify_change(&h).unwrap(),
809
        SignatureStatus::Valid { .. }
810
    ));
811
}
812
813
#[test]
814
fn format1_repositories_are_migrated_on_open() {
815
    hermetic();
816
    use crate::oplog::{Format1Op, Format1View};
817
    let dir = tempfile::tempdir().unwrap();
818
    let root = dir.path();
819
    let repo = Repo::init(root).unwrap();
820
    write(root, "a.txt", b"a\n");
821
    let h1 = repo.commit("one", &[]).unwrap();
822
    let (wc_hash, _) = repo.working_copy().unwrap();
823
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
824
    let mut v1 = Format1View::default();
825
    v1.bookmarks.insert("main".into(), vec![]);
826
    v1.workspaces.insert(repo.workspace(), wc_hash);
827
    let init = Format1Op {
828
        parents: vec![],
829
        hlc: Hlc::default(),
830
        command: "oxy init".into(),
831
        view: v1.clone(),
832
    };
833
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
834
    v1.bookmarks.insert("main".into(), vec![h1]);
835
    let commit = Format1Op {
836
        parents: vec![init_ref],
837
        hlc: Hlc::default(),
838
        command: "oxy commit".into(),
839
        view: v1,
840
    };
841
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
842
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
843
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
844
    drop(repo);
845
846
    let repo = Repo::open(root).unwrap();
847
    assert_eq!(
848
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
849
        FORMAT_LINE
850
    );
851
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
852
    let ops = repo.op_log().unwrap();
853
    assert_eq!(
854
        ops.iter()
855
            .map(|(_, o)| o.command.as_str())
856
            .collect::<Vec<_>>(),
857
        ["oxy commit", "oxy init"]
858
    );
859
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
860
    assert!(!repo.snapshot("status").unwrap().changed);
861
    // Reopening again is a no-op.
862
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
863
}
864
865
#[test]
866
fn undo_skips_snapshot_operations() {
867
    hermetic();
868
    let dir = tempfile::tempdir().unwrap();
869
    let root = dir.path();
870
    let repo = Repo::init(root).unwrap();
871
    write(root, "a.txt", b"a\n");
872
    let h1 = repo.commit("a", &[]).unwrap();
873
    // A later command snapshots new edits on top of the commit.
874
    write(root, "b.txt", b"b\n");
875
    let s = repo.snapshot("oxy status").unwrap();
876
    assert!(s.changed);
877
    assert!(repo.head_op().unwrap().1.is_snapshot());
878
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
879
    // Undo must undo the commit, not the snapshot.
880
    repo.undo().unwrap();
881
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
882
    let s = repo.snapshot("oxy status").unwrap();
883
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
884
    assert_eq!(
885
        paths,
886
        ["a.txt", "b.txt"],
887
        "both files are back in the working copy"
888
    );
889
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
890
    // Only snapshots remain above `init`, so there is nothing left to undo.
891
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
892
    assert!(repo.undo().is_err());
893
}
894
895
#[test]
896
fn independent_changes_commute_and_make_multiple_heads() {
897
    hermetic();
898
    let dir = tempfile::tempdir().unwrap();
899
    let root = dir.path();
900
    let repo = Repo::init(root).unwrap();
901
    write(root, "a.txt", b"a\n");
902
    let h1 = repo.commit("a", &[]).unwrap();
903
    write(root, "b.txt", b"b\n");
904
    let h2 = repo.commit("b", &[]).unwrap();
905
    let c2 = repo.store().get_change(&h2).unwrap();
906
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
907
    let mut heads = repo.bookmark_heads().unwrap();
908
    heads.sort();
909
    let mut want = vec![h1, h2];
910
    want.sort();
911
    assert_eq!(heads, want);
912
    // Editing a.txt depends on h1 only.
913
    write(root, "a.txt", b"a\na2\n");
914
    let h3 = repo.commit("a2", &[]).unwrap();
915
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
916
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
917
    assert_eq!(heads, [h2, h3].into_iter().collect());
918
    // Explicit dependency.
919
    write(root, "c.txt", b"c\n");
920
    let h4 = repo.commit("c", &[h2]).unwrap();
921
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
922
}
923
924
#[test]
925
fn mode_change_and_text_binary_switch() {
926
    hermetic();
927
    let dir = tempfile::tempdir().unwrap();
928
    let root = dir.path();
929
    let repo = Repo::init(root).unwrap();
930
    write(root, "run.sh", b"#!/bin/sh\n");
931
    repo.commit("add script", &[]).unwrap();
932
    #[cfg(unix)]
933
    {
934
        use std::os::unix::fs::PermissionsExt;
935
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
936
        let s = repo.snapshot("status").unwrap();
937
        assert_eq!(
938
            statuses(&s),
939
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
940
        );
941
        let h = repo.commit("exec", &[]).unwrap();
942
        let snap = repo.load_state(&[h]).unwrap().materialize();
943
        assert!(snap.files["run.sh"].mode.exec);
944
    }
945
    // Text → binary → text.
946
    write(root, "run.sh", b"\0binary");
947
    let h = repo.commit("binary", &[]).unwrap();
948
    let snap = repo.load_state(&[h]).unwrap().materialize();
949
    assert!(snap.files["run.sh"].mode.opaque);
950
    write(root, "run.sh", b"text again\n");
951
    let h = repo.commit("text", &[]).unwrap();
952
    let snap = repo.load_state(&[h]).unwrap().materialize();
953
    assert!(!snap.files["run.sh"].mode.opaque);
954
    assert!(
955
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
956
    );
957
    assert!(!snap.is_conflicted());
958
}
959
960
#[test]
961
fn trust_policy_governs_pushes_and_fetches() {
962
    hermetic();
963
    let dir = tempfile::tempdir().unwrap();
964
    let root = dir.path();
965
    let origin = Repo::init(&root.join("origin")).unwrap();
966
    let url = root.join("origin").to_string_lossy().to_string();
967
968
    // A is the root. Before the policy, an unsigned push from B is fine.
969
    let mut a = Repo::clone(&url, &root.join("a"))
970
        .unwrap()
971
        .with_home(root.join("home-a"));
972
    let (key_a, _) = a
973
        .create_identity("Ada", "[email protected]", IdentityScope::User)
974
        .unwrap();
975
    let mut b = Repo::clone(&url, &root.join("b"))
976
        .unwrap()
977
        .with_home(root.join("home-b"));
978
    write(&root.join("b"), "b.txt", b"b\n");
979
    b.commit("unsigned before policy", &[]).unwrap();
980
    assert!(b.push("origin", false).unwrap()[0].ok);
981
982
    // A creates the policy and pushes it; origin now enforces it.
983
    write(&root.join("a"), "a.txt", b"a\n");
984
    a.commit("a", &[]).unwrap();
985
    let sp = a.policy_init().unwrap();
986
    assert_eq!(sp.policy.serial, 1);
987
    a.pull("origin").unwrap();
988
    let results = a.push("origin", false).unwrap();
989
    assert!(results.iter().all(|r| r.ok), "{results:?}");
990
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
991
992
    // B pulls the policy. Without an identity B cannot push at all.
993
    b.pull("origin").unwrap();
994
    assert!(
995
        b.current_policy().unwrap().is_some(),
996
        "the policy arrived with the fetch"
997
    );
998
    assert!(b.push("origin", false).is_err());
999
    // With an identity the policy does not list, the push is rejected by origin.
1000
    let (key_b, id_b) = b
1001
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1002
        .unwrap();
1003
    write(&root.join("b"), "b.txt", b"b2\n");
1004
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1005
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1006
    let r = b.push("origin", false).unwrap();
1007
    assert!(
1008
        !r[0].ok && r[0].reason.contains("may not update"),
1009
        "{:?}",
1010
        r
1011
    );
1012
1013
    // A grants B (identity handed over as a file) and publishes the policy.
1014
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1015
    assert_eq!(sp.policy.serial, 2);
1016
    let r = a.push("origin", false).unwrap();
1017
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1018
    // B must fetch the new policy before pushing.
1019
    assert!(b
1020
        .push("origin", false)
1021
        .unwrap_or_else(|e| vec![RefResult {
1022
            name: "main".into(),
1023
            ok: false,
1024
            reason: e.to_string()
1025
        }])
1026
        .iter()
1027
        .all(|x| !x.ok));
1028
    b.pull("origin").unwrap();
1029
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1030
    let r = b.push("origin", false).unwrap();
1031
    assert!(r[0].ok, "{:?}", r);
1032
    // Origin verified B's change under the policy.
1033
    let heads = origin.bookmark_heads().unwrap();
1034
    for h in &heads {
1035
        let c = origin.store().get_change(h).unwrap();
1036
        if c.author == key_b {
1037
            origin
1038
                .change_allowed(
1039
                    h,
1040
                    &origin.current_policy().unwrap().unwrap().1.policy,
1041
                    "main",
1042
                )
1043
                .unwrap();
1044
        }
1045
    }
1046
1047
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1048
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1049
    forged.serial = 3;
1050
    forged.roots = vec![key_b];
1051
    let fh = forged.hash();
1052
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1053
    let forged = SignedPolicy {
1054
        policy: forged,
1055
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1056
    };
1057
    let r = origin
1058
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1059
        .unwrap();
1060
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1061
    let stale = a.current_policy().unwrap().unwrap().1;
1062
    let mut old = stale.clone();
1063
    old.policy.serial = 1;
1064
    let r = origin
1065
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1066
        .unwrap();
1067
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1068
1069
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1070
    a.pull("origin").unwrap();
1071
    a.policy_revoke(&key_b).unwrap();
1072
    let r = a.push("origin", false).unwrap();
1073
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1074
    b.pull("origin").unwrap();
1075
    write(&root.join("b"), "b.txt", b"b3\n");
1076
    b.commit("b3", &[]).unwrap();
1077
    let r = b.push("origin", false).unwrap();
1078
    assert!(!r[0].ok, "{:?}", r);
1079
1080
    // A clone by a third party receives and verifies everything.
1081
    let c = Repo::clone(&url, &root.join("c"))
1082
        .unwrap()
1083
        .with_home(root.join("home-c"));
1084
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1085
    assert!(c
1086
        .current_policy()
1087
        .unwrap()
1088
        .unwrap()
1089
        .1
1090
        .policy
1091
        .roots
1092
        .contains(&key_a));
1093
    assert!(!c.snapshot("status").unwrap().changed);
1094
}
1095
1096
#[test]
1097
fn gc_packs_objects_and_history_still_works() {
1098
    hermetic();
1099
    let dir = tempfile::tempdir().unwrap();
1100
    let root = dir.path();
1101
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1102
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1103
        .unwrap();
1104
    repo.set_user_config("core.sign", "change").unwrap();
1105
    write(root, "a.txt", b"one\n");
1106
    let h1 = repo.commit("one", &[]).unwrap();
1107
    write(root, "a.txt", b"two\n");
1108
    write(root, "big.bin", &vec![0u8; 100_000]);
1109
    let h2 = repo.commit("two", &[]).unwrap();
1110
    // Several snapshots leave superseded working-copy versions behind.
1111
    for i in 0..5 {
1112
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1113
        repo.snapshot("status").unwrap();
1114
    }
1115
    write(root, "a.txt", b"two\n");
1116
    repo.snapshot("status").unwrap();
1117
    let before = repo.store().list().unwrap();
1118
    assert!(repo.store().loose_count().unwrap() > 0);
1119
1120
    // With the default retention every operation's view is a root: nothing prunes.
1121
    let r = repo.gc(true).unwrap();
1122
    assert_eq!(r.packed.objects, before.len());
1123
    assert_eq!(r.pruned.objects, 0);
1124
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1125
    assert_eq!(repo.store().list().unwrap(), before);
1126
1127
    // With zero retention only the current view is a root: superseded
1128
    // working copies go, everything reachable stays.
1129
    repo.config.set("core.op-retention", "0").unwrap();
1130
    repo.save_config().unwrap();
1131
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1132
    let r = repo.gc(true).unwrap();
1133
    assert!(r.pruned.objects >= 5, "{r:?}");
1134
    let after = repo.store().list().unwrap();
1135
    assert!(after.len() < before.len());
1136
    assert!(after.contains(&h1) && after.contains(&h2));
1137
    for (_, op) in repo.op_log().unwrap() {
1138
        assert!(!op.command.is_empty(), "operation objects are all kept");
1139
    }
1140
    // Everything still works from the pruned, packed store.
1141
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1142
    assert!(matches!(
1143
        repo.verify_change(&h2).unwrap(),
1144
        SignatureStatus::Valid { .. }
1145
    ));
1146
    assert_eq!(repo.log().unwrap().len(), 3);
1147
    repo.checkout(&[h1], false, "checkout").unwrap();
1148
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1149
    repo.checkout(&[h2], false, "checkout").unwrap();
1150
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1151
    assert!(!repo.snapshot("status").unwrap().changed);
1152
    // Grace period defers pruning of young garbage.
1153
    write(root, "a.txt", b"three\n");
1154
    repo.commit("three", &[]).unwrap();
1155
    let r = repo.gc(false).unwrap();
1156
    assert_eq!(r.pruned.objects, 0);
1157
    assert!(r.pruned.deferred > 0);
1158
    let r = repo.gc(true).unwrap();
1159
    assert!(r.pruned.objects > 0);
1160
    assert_eq!(repo.log().unwrap().len(), 4);
1161
}
1162
1163
#[test]
1164
fn describe_amend_abandon_heads() {
1165
    hermetic();
1166
    let dir = tempfile::tempdir().unwrap();
1167
    let root = dir.path();
1168
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1169
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1170
        .unwrap();
1171
    repo.set_user_config("core.sign", "change").unwrap();
1172
    write(root, "a.txt", b"one\n");
1173
    let h1 = repo.commit("first", &[]).unwrap();
1174
    write(root, "a.txt", b"one\ntwo\n");
1175
    let h2 = repo.commit("secnod", &[]).unwrap();
1176
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1177
1178
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1179
    let h2b = repo.describe(&h2, "second").unwrap();
1180
    assert_ne!(h2b, h2);
1181
    let c = repo.store().get_change(&h2b).unwrap();
1182
    assert_eq!(
1183
        (c.change_id, c.message.as_str(), c.deps.clone()),
1184
        (id2, "second", vec![h1])
1185
    );
1186
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1187
    assert!(matches!(
1188
        repo.verify_change(&h2b).unwrap(),
1189
        SignatureStatus::Valid { .. }
1190
    ));
1191
    let s = repo.snapshot("status").unwrap();
1192
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1193
    assert_eq!(
1194
        repo.resolve_change(&id2.short(8)).unwrap(),
1195
        h2b,
1196
        "the old object is no longer reachable from the log"
1197
    );
1198
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1199
    let h1b = repo.describe(&h1, "first, described").unwrap();
1200
    assert_ne!(h1b, h1);
1201
    let heads = repo.bookmark_heads().unwrap();
1202
    assert_eq!(heads.len(), 1);
1203
    let top = repo.store().get_change(&heads[0]).unwrap();
1204
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1205
    assert!(
1206
        matches!(
1207
            repo.verify_change(&heads[0]).unwrap(),
1208
            SignatureStatus::Valid { .. }
1209
        ),
1210
        "rewritten own change is re-signed"
1211
    );
1212
    let (_, wc) = repo.working_copy().unwrap();
1213
    assert_eq!(
1214
        wc.deps,
1215
        vec![heads[0]],
1216
        "the working copy follows the rewrite"
1217
    );
1218
    assert!(!repo.snapshot("status").unwrap().changed);
1219
    let snap = repo.load_state(&heads).unwrap().materialize();
1220
    assert!(
1221
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1222
    );
1223
1224
    // amend: fold an edit into the head; the result is one change from h1.
1225
    write(root, "a.txt", b"one\ntwo\nthree\n");
1226
    write(root, "b.txt", b"b\n");
1227
    let h2c = repo.amend(None).unwrap();
1228
    let c = repo.store().get_change(&h2c).unwrap();
1229
    assert_eq!(c.change_id, id2);
1230
    assert_eq!(c.message, "second");
1231
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1232
    assert_eq!(
1233
        repo.log().unwrap().len(),
1234
        3,
1235
        "working copy, amended head, first"
1236
    );
1237
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1238
    assert!(
1239
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1240
    );
1241
    assert!(snap.files.contains_key("b.txt"));
1242
    assert!(!repo.snapshot("status").unwrap().changed);
1243
    assert!(
1244
        repo.amend(None).is_err(),
1245
        "clean working copy and no message"
1246
    );
1247
    let h2d = repo.amend(Some("second, amended")).unwrap();
1248
    assert_eq!(
1249
        repo.store().get_change(&h2d).unwrap().message,
1250
        "second, amended"
1251
    );
1252
1253
    // abandon: the head goes, its content stays as uncommitted work.
1254
    repo.abandon(&h2d).unwrap();
1255
    assert_eq!(
1256
        repo.bookmark_heads().unwrap(),
1257
        vec![h1b],
1258
        "the described first change is the head again"
1259
    );
1260
    let s = repo.snapshot("status").unwrap();
1261
    let paths: Vec<_> = s
1262
        .statuses
1263
        .iter()
1264
        .map(|p| (p.path.as_str(), p.status))
1265
        .collect();
1266
    assert_eq!(
1267
        paths,
1268
        vec![
1269
            ("a.txt", ChangeStatus::Modified),
1270
            ("b.txt", ChangeStatus::Added)
1271
        ]
1272
    );
1273
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1274
    let h3 = repo.commit("recommitted", &[]).unwrap();
1275
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1276
    // undo brings the abandoned head back.
1277
    repo.undo().unwrap();
1278
    repo.undo().unwrap();
1279
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1280
1281
    // Abandoning a non-head whose dependent references its atoms reifies
1282
    // the references (here: a.txt vanishes with it, so the dependent's edit
1283
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1284
    let base = repo.bookmark_heads().unwrap()[0];
1285
    let base_change = repo.store().get_change(&base).unwrap();
1286
    let h1_now = base_change.deps[0];
1287
    let notes = repo.abandon(&h1_now).unwrap();
1288
    assert!(
1289
        !notes.is_empty(),
1290
        "the dependent's edit of a.txt was reified"
1291
    );
1292
    let heads = repo.bookmark_heads().unwrap();
1293
    let after = repo.load_state(&heads).unwrap().materialize();
1294
    assert!(
1295
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1296
        "{:?}",
1297
        after.files.keys()
1298
    );
1299
    repo.undo().unwrap();
1300
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1301
    write(root, "c.txt", b"c\n");
1302
    let hc = repo.commit("c", &[]).unwrap();
1303
    write(root, "d.txt", b"d\n");
1304
    let hd = repo.commit("d", &[hc]).unwrap();
1305
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1306
    repo.abandon(&hc).unwrap();
1307
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1308
    assert!(!heads.contains(&hc));
1309
    let d_now = heads
1310
        .iter()
1311
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1312
        .copied()
1313
        .unwrap();
1314
    assert!(
1315
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1316
        "d inherited c's (empty) dependencies"
1317
    );
1318
    let s = repo.snapshot("status").unwrap();
1319
    assert_eq!(
1320
        s.statuses
1321
            .iter()
1322
            .map(|p| p.path.as_str())
1323
            .collect::<Vec<_>>(),
1324
        vec!["c.txt"],
1325
        "c's content is now uncommitted work"
1326
    );
1327
}
1328
1329
#[test]
1330
fn git_export_mirrors_history() {
1331
    hermetic();
1332
    if std::process::Command::new("git")
1333
        .arg("--version")
1334
        .output()
1335
        .is_err()
1336
    {
1337
        eprintln!("git not installed; skipping");
1338
        return;
1339
    }
1340
    let dir = tempfile::tempdir().unwrap();
1341
    let root = dir.path();
1342
    let mut repo = Repo::init(&root.join("r"))
1343
        .unwrap()
1344
        .with_home(root.join("home"));
1345
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1346
        .unwrap();
1347
    let r = root.join("r");
1348
    write(&r, "README.md", b"hello\n");
1349
    write(&r, "src/main.rs", b"fn main() {}\n");
1350
    let h1 = repo.commit("first", &[]).unwrap();
1351
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1352
    write(&r, "logo.png", b"\x89PNG\0\0");
1353
    let h2 = repo.commit("second", &[]).unwrap();
1354
1355
    let git_dir = root.join("mirror.git");
1356
    let rep = repo.git_export(&git_dir).unwrap();
1357
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1358
    let git = |args: &[&str]| -> String {
1359
        let out = std::process::Command::new("git")
1360
            .arg("-C")
1361
            .arg(&git_dir)
1362
            .args(args)
1363
            .output()
1364
            .unwrap();
1365
        assert!(
1366
            out.status.success(),
1367
            "{}",
1368
            String::from_utf8_lossy(&out.stderr)
1369
        );
1370
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1371
    };
1372
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1373
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1374
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1375
    let body = git(&["log", "-1", "--format=%B", "main"]);
1376
    assert!(
1377
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1378
        "{body}"
1379
    );
1380
    assert!(body.contains("Change-Id: "), "{body}");
1381
    assert_eq!(
1382
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1383
        "Ada Lovelace <[email protected]>"
1384
    );
1385
    assert_eq!(
1386
        git(&["ls-tree", "--name-only", "main"]),
1387
        "README.md\nlogo.png\nsrc"
1388
    );
1389
1390
    // Re-export is incremental.
1391
    let rep = repo.git_export(&git_dir).unwrap();
1392
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1393
1394
    // An independent change makes two heads; the next state is one more
1395
    // commit on the linear branch whose tree is the union.
1396
    repo.checkout(&[h1], false, "checkout").unwrap();
1397
    write(&r, "other.txt", b"o\n");
1398
    let h3 = repo.commit("third", &[]).unwrap();
1399
    let rep = repo.git_export(&git_dir).unwrap();
1400
    assert_eq!((rep.exported, rep.heads), (1, 2));
1401
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1402
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1403
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1404
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1405
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1406
    assert_eq!(
1407
        git(&["ls-tree", "--name-only", "main"]),
1408
        "README.md\nlogo.png\nother.txt\nsrc"
1409
    );
1410
    let body = git(&["log", "-1", "--format=%B", "main"]);
1411
    assert!(
1412
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1413
        "{body}"
1414
    );
1415
    // A rewrite is a new state whose one new change is the rewritten one.
1416
    repo.describe(&h3, "third, described").unwrap();
1417
    let rep = repo.git_export(&git_dir).unwrap();
1418
    assert_eq!(rep.exported, 1);
1419
    assert_eq!(
1420
        git(&["log", "-1", "--format=%s", "main"]),
1421
        "third, described"
1422
    );
1423
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1424
    let _ = h2;
1425
}
1426
1427
#[test]
1428
fn git_import_reproduces_trees() {
1429
    hermetic();
1430
    if std::process::Command::new("git")
1431
        .arg("--version")
1432
        .output()
1433
        .is_err()
1434
    {
1435
        eprintln!("git not installed; skipping");
1436
        return;
1437
    }
1438
    let dir = tempfile::tempdir().unwrap();
1439
    let root = dir.path();
1440
    let g = root.join("src.git");
1441
    fs::create_dir_all(&g).unwrap();
1442
    let git = |args: &[&str]| -> String {
1443
        let out = std::process::Command::new("git")
1444
            .arg("-C")
1445
            .arg(&g)
1446
            .args([
1447
                "-c",
1448
                "user.name=Grace",
1449
                "-c",
1450
                "[email protected]",
1451
                "-c",
1452
                "commit.gpgsign=false",
1453
            ])
1454
            .args(args)
1455
            .output()
1456
            .unwrap();
1457
        assert!(
1458
            out.status.success(),
1459
            "git {args:?}: {}",
1460
            String::from_utf8_lossy(&out.stderr)
1461
        );
1462
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1463
    };
1464
    git(&["init", "-q", "-b", "main"]);
1465
    write(&g, "README.md", b"# Hi\n");
1466
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1467
    git(&["add", "."]);
1468
    git(&["commit", "-q", "-m", "initial"]);
1469
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1470
    write(&g, "run.sh", b"#!/bin/sh\n");
1471
    #[cfg(unix)]
1472
    {
1473
        use std::os::unix::fs::PermissionsExt;
1474
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1475
    }
1476
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1477
    git(&["add", "."]);
1478
    git(&[
1479
        "commit",
1480
        "-q",
1481
        "-m",
1482
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1483
    ]);
1484
    // A branch that edits README, merged back with a conflict-free merge.
1485
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1486
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1487
    git(&["commit", "-q", "-am", "readme"]);
1488
    git(&["checkout", "-q", "main"]);
1489
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1490
    // A branch from the initial commit inserting at the same place as
1491
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1492
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1493
    git(&["checkout", "-q", "-b", "clash", &initial]);
1494
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1495
    git(&["commit", "-q", "-am", "clash"]);
1496
    git(&["checkout", "-q", "main"]);
1497
    let _ = std::process::Command::new("git")
1498
        .arg("-C")
1499
        .arg(&g)
1500
        .args(["merge", "-q", "clash"])
1501
        .output();
1502
    write(
1503
        &g,
1504
        "src/lib.rs",
1505
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1506
    );
1507
    git(&["add", "."]);
1508
    git(&["commit", "-q", "-m", "resolve clash"]);
1509
    git(&["rm", "-q", "logo.png"]);
1510
    git(&["commit", "-q", "-m", "drop logo"]);
1511
    // A rename with a small edit is imported as a move of the same node.
1512
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1513
    write(
1514
        &g,
1515
        "src/lib2.rs",
1516
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1517
    );
1518
    git(&["add", "."]);
1519
    git(&["commit", "-q", "-m", "rename lib"]);
1520
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1521
1522
    let dest = root.join("oxy");
1523
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1524
    let rep = repo.import_git(&g, "main").unwrap();
1525
    assert_eq!(rep.commits, expected_count);
1526
    assert_eq!(rep.merges, 2);
1527
    // The working copy equals the Git tree at main.
1528
    assert_eq!(
1529
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1530
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1531
    );
1532
    assert!(!dest.join("src/lib.rs").exists());
1533
    assert_eq!(
1534
        fs::read(dest.join("README.md")).unwrap(),
1535
        b"# Hi\n\nMore.\n"
1536
    );
1537
    assert!(!dest.join("logo.png").exists());
1538
    #[cfg(unix)]
1539
    {
1540
        use std::os::unix::fs::PermissionsExt;
1541
        assert!(
1542
            fs::metadata(dest.join("run.sh"))
1543
                .unwrap()
1544
                .permissions()
1545
                .mode()
1546
                & 0o111
1547
                != 0
1548
        );
1549
    }
1550
    assert!(
1551
        !repo.snapshot("status").unwrap().changed,
1552
        "clean after import"
1553
    );
1554
    let heads = repo.bookmark_heads().unwrap();
1555
    let st = repo.load_state(&heads).unwrap();
1556
    assert!(!st.materialize().is_conflicted());
1557
    assert_eq!(st.len(), expected_count);
1558
    let tip = repo
1559
        .log()
1560
        .unwrap()
1561
        .into_iter()
1562
        .find(|e| e.change.message.starts_with("rename lib"))
1563
        .unwrap();
1564
    let c = repo.store().get_change(&tip.hash).unwrap();
1565
    assert!(
1566
        c.tree_ops
1567
            .iter()
1568
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1569
        "{:?}",
1570
        c.tree_ops
1571
    );
1572
    assert!(!c
1573
        .tree_ops
1574
        .iter()
1575
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1576
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1577
    let log = repo.log().unwrap();
1578
    let second = log
1579
        .iter()
1580
        .find(|e| e.change.message.starts_with("second"))
1581
        .unwrap();
1582
    assert_eq!(
1583
        second.change.change_id,
1584
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1585
    );
1586
    assert!(second
1587
        .change
1588
        .message
1589
        .contains("Git-Author: Grace <[email protected]>"));
1590
    let resolve = log
1591
        .iter()
1592
        .find(|e| e.change.message.starts_with("resolve clash"))
1593
        .unwrap();
1594
    assert_eq!(
1595
        resolve.change.kind,
1596
        ChangeKind::Resolution,
1597
        "a conflicting Git merge becomes a resolution"
1598
    );
1599
    // Re-importing into another fresh repository gives the same ChangeIds.
1600
    let repo2 = Repo::init(&root.join("oxy2"))
1601
        .unwrap()
1602
        .with_home(root.join("home"));
1603
    repo2.import_git(&g, "main").unwrap();
1604
    let ids: BTreeSet<ChangeId> = repo
1605
        .log()
1606
        .unwrap()
1607
        .iter()
1608
        .filter(|e| !e.is_working_copy)
1609
        .map(|e| e.change.change_id)
1610
        .collect();
1611
    let ids2: BTreeSet<ChangeId> = repo2
1612
        .log()
1613
        .unwrap()
1614
        .iter()
1615
        .filter(|e| !e.is_working_copy)
1616
        .map(|e| e.change.change_id)
1617
        .collect();
1618
    assert_eq!(ids, ids2);
1619
    // Round trip back out to Git reproduces the tip tree.
1620
    let mirror = root.join("mirror.git");
1621
    repo.git_export(&mirror).unwrap();
1622
    let out = std::process::Command::new("git")
1623
        .arg("-C")
1624
        .arg(&mirror)
1625
        .args(["show", "main:src/lib2.rs"])
1626
        .output()
1627
        .unwrap();
1628
    assert_eq!(
1629
        String::from_utf8_lossy(&out.stdout),
1630
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1631
    );
1632
    let out = std::process::Command::new("git")
1633
        .arg("-C")
1634
        .arg(&mirror)
1635
        .args(["show", "main:src/lib.rs"])
1636
        .output()
1637
        .unwrap();
1638
    assert!(
1639
        !out.status.success(),
1640
        "the old path is gone from the export"
1641
    );
1642
}
1643
1644
#[test]
1645
fn checkpoints_accelerate_loading_and_stay_correct() {
1646
    hermetic();
1647
    let dir = tempfile::tempdir().unwrap();
1648
    let root = dir.path();
1649
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1650
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1651
    repo.save_config().unwrap();
1652
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1653
    let mut hashes = Vec::new();
1654
    for i in 0..12 {
1655
        write(
1656
            root,
1657
            "a.txt",
1658
            format!(
1659
                "{}\n",
1660
                (0..=i)
1661
                    .map(|k| k.to_string())
1662
                    .collect::<Vec<_>>()
1663
                    .join("\n")
1664
            )
1665
            .as_bytes(),
1666
        );
1667
        write(root, &format!("f{i}.txt"), b"x\n");
1668
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1669
    }
1670
    let (_, cp) = repo
1671
        .latest_checkpoint("main")
1672
        .unwrap()
1673
        .expect("automatic checkpoint");
1674
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1675
    // Loading through the checkpoint equals loading everything.
1676
    let heads = repo.bookmark_heads().unwrap();
1677
    let fast = repo.load_state(&heads).unwrap();
1678
    let full = repo.load_state_full(&heads).unwrap();
1679
    assert_eq!(fast.len(), full.len());
1680
    assert_eq!(fast.heads(), full.heads());
1681
    let (a, b) = (fast.materialize(), full.materialize());
1682
    assert_eq!(
1683
        a.files.keys().collect::<Vec<_>>(),
1684
        b.files.keys().collect::<Vec<_>>()
1685
    );
1686
    for (p, f) in &a.files {
1687
        assert_eq!(f.content, b.files[p].content, "{p}");
1688
    }
1689
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1690
    // A head set that does not contain the checkpoint's heads falls back.
1691
    assert!(repo
1692
        .load_state_checkpointed(&[hashes[0]])
1693
        .unwrap()
1694
        .is_none());
1695
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1696
    // Everything else keeps working on top of the checkpoint.
1697
    assert!(!repo.snapshot("status").unwrap().changed);
1698
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1699
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1700
    let (r, n, bytes) = repo.checkpoint().unwrap();
1701
    assert!(n >= 12 && bytes > 0);
1702
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1703
    write(root, "a.txt", b"after\n");
1704
    let h_after = repo.commit("after", &[]).unwrap();
1705
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1706
    assert!(st.contains(&h_after));
1707
    assert!(
1708
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1709
    );
1710
    assert_eq!(repo.log().unwrap().len(), 14);
1711
    // Checkpoints survive gc.
1712
    repo.gc(true).unwrap();
1713
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1714
    assert!(repo
1715
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1716
        .unwrap()
1717
        .is_some());
1718
}
1719
1720
#[test]
1721
fn quick_status_for_prompts() {
1722
    hermetic();
1723
    let dir = tempfile::tempdir().unwrap();
1724
    let root = dir.path();
1725
    let origin = Repo::init(&root.join("origin")).unwrap();
1726
    let url = root.join("origin").to_string_lossy().to_string();
1727
    let a = Repo::clone(&url, &root.join("a"))
1728
        .unwrap()
1729
        .with_home(root.join("home"));
1730
    let ops_before = a.op_log().unwrap().len();
1731
    let info = a.quick_status().unwrap();
1732
    assert_eq!(
1733
        (
1734
            info.bookmark.as_str(),
1735
            info.heads,
1736
            info.dirty,
1737
            info.conflicted,
1738
            info.ahead,
1739
            info.behind
1740
        ),
1741
        ("main", 0, false, false, Some(0), Some(0))
1742
    );
1743
    write(&root.join("a"), "f.txt", b"f\n");
1744
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1745
    assert_eq!(
1746
        a.op_log().unwrap().len(),
1747
        ops_before,
1748
        "quick_status records nothing"
1749
    );
1750
    // A snapshotted but uncommitted change is still dirty.
1751
    a.snapshot("status").unwrap();
1752
    assert!(a.quick_status().unwrap().dirty);
1753
    a.commit("f", &[]).unwrap();
1754
    let info = a.quick_status().unwrap();
1755
    assert!(!info.dirty, "clean right after a commit");
1756
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
1757
    assert_eq!(
1758
        info.format("%b %c%d%x%A%D"),
1759
        format!("main {}+1", info.change_id)
1760
    );
1761
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1762
    // Touching a file without changing it is not dirty; changing content of
1763
    // the same size is.
1764
    let p = root.join("a/f.txt");
1765
    let content = fs::read(&p).unwrap();
1766
    fs::write(&p, &content).unwrap();
1767
    assert!(!a.quick_status().unwrap().dirty);
1768
    fs::write(&p, b"g\n").unwrap();
1769
    assert!(a.quick_status().unwrap().dirty);
1770
    fs::write(&p, b"f\n").unwrap();
1771
    // Push, then a second clone commits and pushes: we are behind.
1772
    assert!(a.push("origin", false).unwrap()[0].ok);
1773
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
1774
    let b = Repo::clone(&url, &root.join("b"))
1775
        .unwrap()
1776
        .with_home(root.join("home-b"));
1777
    write(&root.join("b"), "g.txt", b"g\n");
1778
    b.commit("g", &[]).unwrap();
1779
    b.push("origin", false).unwrap();
1780
    a.fetch("origin").unwrap();
1781
    let info = a.quick_status().unwrap();
1782
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1783
    assert_eq!(info.format("%A%D"), "-1");
1784
    let _ = origin;
1785
}
1786
1787
#[test]
1788
fn lazy_blobs_are_fetched_on_first_read() {
1789
    hermetic();
1790
    let dir = tempfile::tempdir().unwrap();
1791
    let root = dir.path();
1792
    let origin_dir = root.join("origin");
1793
    let origin = Repo::init(&origin_dir)
1794
        .unwrap()
1795
        .with_home(root.join("home"));
1796
    let url = origin_dir.to_string_lossy().to_string();
1797
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1798
    write(&origin_dir, "big.bin", &big);
1799
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1800
    write(&origin_dir, "t.txt", b"t\n");
1801
    let h = origin.commit("blobs", &[]).unwrap();
1802
    let big_ref = Repo::blob_ref(&big);
1803
1804
    // Fetch only (no checkout) with a filter: the big blob stays absent.
1805
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1806
        .unwrap()
1807
        .with_home(root.join("home"));
1808
    let a = {
1809
        let mut a = a;
1810
        a.config.set("remote.origin.url", &url).unwrap();
1811
        a.config.set("filter.max-blob", "100K").unwrap();
1812
        a.save_config().unwrap();
1813
        a
1814
    };
1815
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1816
    a.fetch("origin").unwrap();
1817
    assert!(a.store().has(&h));
1818
    assert!(!a.store().has(&big_ref), "withheld");
1819
    assert!(
1820
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1821
        "small blob came along"
1822
    );
1823
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1824
1825
    // status and commit do not need it: adopt the state, edit a text file, commit.
1826
    let (op_ref, op) = a.head_op().unwrap();
1827
    let mut view = op.view.clone();
1828
    view.bookmarks.insert(
1829
        "main".into(),
1830
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1831
    );
1832
    a.record_op(&[op_ref], "adopt", view).unwrap();
1833
    // Checkout reads the blob lazily, which fetches it.
1834
    a.checkout(&[h], true, "checkout").unwrap();
1835
    assert!(a.store().has(&big_ref), "fetched on first read");
1836
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1837
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1838
    write(&root.join("a"), "t.txt", b"t2\n");
1839
    a.commit("text edit", &[]).unwrap();
1840
1841
    // clone --max-blob records the filter; the checkout fetches lazily.
1842
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
1843
    assert_eq!(b.config.max_blob, Some(1024));
1844
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1845
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1846
    assert!(parse_size("lots").is_err());
1847
}
1848
1849
#[test]
1850
fn sparse_checkout_materializes_only_chosen_paths() {
1851
    hermetic();
1852
    let dir = tempfile::tempdir().unwrap();
1853
    let root = dir.path();
1854
    let origin_dir = root.join("origin");
1855
    let origin = Repo::init(&origin_dir)
1856
        .unwrap()
1857
        .with_home(root.join("home"));
1858
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1859
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1860
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1861
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1862
    write(&origin_dir, "docs/logo.png", &logo);
1863
    write(&origin_dir, "README.md", b"# top\n");
1864
    let h1 = origin.commit("tree", &[]).unwrap();
1865
    let url = origin_dir.to_string_lossy().to_string();
1866
1867
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
1868
        .unwrap()
1869
        .with_home(root.join("home"));
1870
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1871
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1872
    assert!(root.join("a/src/main.rs").exists());
1873
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
1874
    assert!(
1875
        !a.store().has(&Repo::blob_ref(&logo)),
1876
        "out-of-scope blob never fetched"
1877
    );
1878
    assert!(
1879
        !a.snapshot("status").unwrap().changed,
1880
        "out-of-scope files are not removals"
1881
    );
1882
    assert!(!a.quick_status().unwrap().dirty);
1883
1884
    // Edits in scope commit normally and keep the rest of the tree intact.
1885
    write(
1886
        &root.join("a"),
1887
        "src/lib.rs",
1888
        b"pub fn a() {}\npub fn b() {}\n",
1889
    );
1890
    let h2 = a.commit("edit lib", &[]).unwrap();
1891
    let st = a.load_state(&[h2]).unwrap().materialize();
1892
    assert!(
1893
        st.files.contains_key("docs/guide.md"),
1894
        "the state still has everything"
1895
    );
1896
    assert!(a.push("origin", false).unwrap()[0].ok);
1897
    // Files created outside the scope are ignored by status.
1898
    write(&root.join("a"), "docs/new.md", b"ignored\n");
1899
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
1900
1901
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
1902
    let mut a = a;
1903
    a.config.set("filter.paths", "src,docs").unwrap();
1904
    a.save_config().unwrap();
1905
    let r = a
1906
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
1907
        .unwrap();
1908
    assert!(r.written >= 2);
1909
    assert_eq!(
1910
        fs::read(root.join("a/docs/logo.png")).unwrap(),
1911
        logo,
1912
        "now fetched lazily"
1913
    );
1914
    assert!(!root.join("a/README.md").exists());
1915
    // Origin sees the change made under a sparse checkout with the full tree intact.
1916
    origin.pull("origin").err();
1917
    let full = origin
1918
        .load_state(&origin.bookmark_heads().unwrap())
1919
        .unwrap()
1920
        .materialize();
1921
    assert!(
1922
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
1923
    );
1924
    assert!(full.files.contains_key("README.md"));
1925
    let _ = h1;
1926
}
1927
1928
#[test]
1929
fn shallow_clone_and_deepen() {
1930
    hermetic();
1931
    let dir = tempfile::tempdir().unwrap();
1932
    let root = dir.path();
1933
    let origin_dir = root.join("origin");
1934
    let origin = Repo::init(&origin_dir)
1935
        .unwrap()
1936
        .with_home(root.join("home"));
1937
    let mut hashes = Vec::new();
1938
    for i in 0..8 {
1939
        write(
1940
            &origin_dir,
1941
            "a.txt",
1942
            format!(
1943
                "{}\n",
1944
                (0..=i)
1945
                    .map(|k| k.to_string())
1946
                    .collect::<Vec<_>>()
1947
                    .join("\n")
1948
            )
1949
            .as_bytes(),
1950
        );
1951
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
1952
    }
1953
    let url = origin_dir.to_string_lossy().to_string();
1954
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
1955
        .unwrap()
1956
        .with_home(root.join("home"));
1957
    assert!(a.is_shallow());
1958
    assert_eq!(
1959
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
1960
        "0\n1\n2\n3\n4\n5\n6\n7\n"
1961
    );
1962
    assert!(
1963
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
1964
        "three levels present"
1965
    );
1966
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
1967
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
1968
    assert_eq!(
1969
        a.log().unwrap().len(),
1970
        9,
1971
        "the log shows every change from the checkpoint's metadata"
1972
    );
1973
    assert!(!a.snapshot("status").unwrap().changed);
1974
    assert_eq!(a.quick_status().unwrap().heads, 1);
1975
1976
    // Work continues on top of the shallow history and pushes back.
1977
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
1978
    let h_new = a.commit("c8", &[]).unwrap();
1979
    assert!(a.push("origin", false).unwrap()[0].ok);
1980
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
1981
    // Fetching new work from origin into the shallow clone works too.
1982
    write(&origin_dir, "b.txt", b"b\n");
1983
    origin.pull("origin").err();
1984
    let (_, wc) = origin.working_copy().unwrap();
1985
    let _ = wc;
1986
    origin
1987
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
1988
        .unwrap();
1989
    write(&origin_dir, "b.txt", b"b\n");
1990
    let h_b = origin.commit("b", &[]).unwrap();
1991
    let pr = a.pull("origin").unwrap();
1992
    assert!(pr.changed);
1993
    assert!(a.store().has(&h_b));
1994
    assert!(root.join("a/b.txt").exists());
1995
1996
    // Deepening fetches older history until the boundary is gone.
1997
    // Every commit also depends on the change that created the file, so two
1998
    // levels below the boundary hold h4, h3, and the root.
1999
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2000
    assert!(a.store().has(&hashes[3]));
2001
    assert!(a.is_shallow());
2002
    a.deepen("origin", 100).unwrap();
2003
    assert!(!a.is_shallow(), "boundary reached the root");
2004
    assert!(a.store().has(&hashes[0]));
2005
    assert_eq!(
2006
        a.load_state_full(&a.bookmark_heads().unwrap())
2007
            .unwrap()
2008
            .len(),
2009
        10
2010
    );
2011
}
2012
2013
#[test]
2014
fn tags_are_immutable_named_states_and_travel() {
2015
    hermetic();
2016
    let dir = tempfile::tempdir().unwrap();
2017
    let root = dir.path();
2018
    let origin = Repo::init(&root.join("origin")).unwrap();
2019
    let url = root.join("origin").to_string_lossy().to_string();
2020
    let mut a = Repo::clone(&url, &root.join("a"))
2021
        .unwrap()
2022
        .with_home(root.join("home-a"));
2023
    let (key_a, _) = a
2024
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2025
        .unwrap();
2026
    write(&root.join("a"), "f.txt", b"1\n");
2027
    let h1 = a.commit("one", &[]).unwrap();
2028
    write(&root.join("a"), "f.txt", b"1\n2\n");
2029
    let h2 = a.commit("two", &[]).unwrap();
2030
2031
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2032
    assert_eq!(
2033
        (t.heads.clone(), t.signer.as_deref()),
2034
        (vec![h1], Some("Ada"))
2035
    );
2036
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2037
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2038
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2039
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2040
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2041
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2042
    assert_eq!(sa.sigs[0].key, key_a);
2043
    // Checkout by tag.
2044
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2045
        .unwrap();
2046
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2047
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2048
        .unwrap();
2049
2050
    // Push carries the tag; a second attestation for the name is refused.
2051
    let r = a.push("origin", false).unwrap();
2052
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2053
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2054
    let mut forged = a
2055
        .tag_refs()
2056
        .unwrap()
2057
        .into_iter()
2058
        .find(|t| t.name == "v1")
2059
        .unwrap();
2060
    forged.state = origin
2061
        .store()
2062
        .put_state(&StateObject::new(vec![h2]))
2063
        .unwrap();
2064
    forged.heads = vec![h2];
2065
    forged.attestation = None;
2066
    let r = origin
2067
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2068
        .unwrap();
2069
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2070
2071
    // A clone gets the tag; a later tag arrives on fetch.
2072
    let b = Repo::clone(&url, &root.join("b"))
2073
        .unwrap()
2074
        .with_home(root.join("home-b"));
2075
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2076
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2077
    a.tag_create("v2", &[h2], "second").unwrap();
2078
    a.push("origin", false).unwrap();
2079
    let rep = b.fetch("origin").unwrap();
2080
    assert_eq!(rep.new_tags, 1);
2081
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2082
2083
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2084
    a.policy_init().unwrap();
2085
    a.push("origin", false).unwrap();
2086
    let unattested = crate::protocol::TagRef {
2087
        name: "v3".into(),
2088
        state: origin
2089
            .store()
2090
            .put_state(&StateObject::new(vec![h2]))
2091
            .unwrap(),
2092
        heads: vec![h2],
2093
        attestation: None,
2094
    };
2095
    let r = origin
2096
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2097
        .unwrap();
2098
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2099
    a.tag_create("v3", &[h2], "").unwrap();
2100
    let r = a.push("origin", false).unwrap();
2101
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2102
    assert!(a.gc(true).is_ok());
2103
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2104
}
2105
2106
#[test]
2107
fn multiple_workspaces_share_a_repository() {
2108
    hermetic();
2109
    let dir = tempfile::tempdir().unwrap();
2110
    let root = dir.path();
2111
    let main_dir = root.join("main");
2112
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2113
    write(&main_dir, "a.txt", b"a\n");
2114
    let h1 = repo.commit("a", &[]).unwrap();
2115
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2116
2117
    // A second workspace elsewhere, checked out on the bookmark.
2118
    let ws_dir = root.join("ws2");
2119
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2120
    assert!(ws_dir.join(".oxy").is_file());
2121
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2122
    assert_ne!(ws.workspace(), repo.workspace());
2123
    let list = repo.workspaces().unwrap();
2124
    assert_eq!(list.len(), 2);
2125
    assert!(list
2126
        .iter()
2127
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2128
    assert!(!ws.snapshot("status").unwrap().changed);
2129
2130
    // Work in the second workspace: its own working copy, shared bookmark.
2131
    write(&ws_dir, "b.txt", b"b\n");
2132
    let s = ws.snapshot("status").unwrap();
2133
    assert_eq!(s.statuses.len(), 1);
2134
    assert!(
2135
        !repo.snapshot("status").unwrap().changed,
2136
        "the first workspace is untouched"
2137
    );
2138
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2139
    let mut heads = repo.bookmark_heads().unwrap();
2140
    heads.sort();
2141
    let mut want = vec![h1, h2];
2142
    want.sort();
2143
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2144
    assert!(!main_dir.join("b.txt").exists());
2145
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2146
        .unwrap();
2147
    assert!(main_dir.join("b.txt").exists());
2148
2149
    // Reopening from inside the second workspace finds the shared repository.
2150
    let reopened = Repo::open(&ws_dir).unwrap();
2151
    assert_eq!(reopened.workspace(), ws.workspace());
2152
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2153
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2154
2155
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2156
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2157
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2158
    repo.workspace_forget(&ws.workspace()).unwrap();
2159
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2160
    assert!(ws_dir.join("b.txt").exists());
2161
    assert!(
2162
        ws.snapshot("status").is_err(),
2163
        "a forgotten workspace is no longer in the view"
2164
    );
2165
2166
    // The snapshot lock: a fresh lock blocks a second, a stale one is taken over.
2167
    let lock = repo.lock_snapshot().unwrap();
2168
    drop(lock);
2169
    let lock_path = main_dir
2170
        .join(".oxy/workspaces")
2171
        .join(repo.workspace().to_hex())
2172
        .join("lock");
2173
    fs::write(&lock_path, "1").unwrap();
2174
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2175
    fs::File::open(&lock_path)
2176
        .unwrap()
2177
        .set_modified(old)
2178
        .unwrap();
2179
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2180
}
2181
2182
#[test]
2183
fn attributes_binary_eol_nocompress_lockable() {
2184
    hermetic();
2185
    let dir = tempfile::tempdir().unwrap();
2186
    let root = dir.path();
2187
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2188
    write(
2189
        root,
2190
        ".oxyattributes",
2191
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2192
    );
2193
    write(root, "plain.dat", b"no nul bytes here\n");
2194
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2195
    write(root, "assets/model.bin", b"\0model");
2196
    let h = repo.commit("attrs", &[]).unwrap();
2197
    let snap = repo.load_state(&[h]).unwrap().materialize();
2198
    assert!(
2199
        snap.files["plain.dat"].mode.opaque,
2200
        "binary attribute forces opaque without NUL bytes"
2201
    );
2202
    assert!(
2203
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2204
        "stored with LF"
2205
    );
2206
    assert!(
2207
        !repo.snapshot("status").unwrap().changed,
2208
        "CRLF on disk equals LF in the state"
2209
    );
2210
    // nocompress chunks pack raw.
2211
    let r = repo.gc(true).unwrap();
2212
    assert!(r.packed.objects > 0);
2213
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2214
    fs::remove_file(root.join("notes.txt")).unwrap();
2215
    repo.checkout(&[h], true, "co").unwrap();
2216
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2217
    assert!(fs::metadata(root.join("assets/model.bin"))
2218
        .unwrap()
2219
        .permissions()
2220
        .readonly());
2221
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2222
    repo.lock_path("assets/model.bin").unwrap();
2223
    assert!(!fs::metadata(root.join("assets/model.bin"))
2224
        .unwrap()
2225
        .permissions()
2226
        .readonly());
2227
    assert!(repo.is_locked("assets/model.bin"));
2228
    write(root, "assets/model.bin", b"\0model2");
2229
    repo.commit("edit model", &[]).unwrap();
2230
    repo.unlock_path("assets/model.bin").unwrap();
2231
    assert!(fs::metadata(root.join("assets/model.bin"))
2232
        .unwrap()
2233
        .permissions()
2234
        .readonly());
2235
    // A later checkout can still overwrite a read-only lockable file.
2236
    repo.checkout(&[h], true, "co").unwrap();
2237
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2238
}
2239
2240
#[cfg(unix)]
2241
#[test]
2242
fn hooks_can_veto_observe_and_add_dependencies() {
2243
    use std::os::unix::fs::PermissionsExt;
2244
    hermetic();
2245
    let dir = tempfile::tempdir().unwrap();
2246
    let root = dir.path();
2247
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2248
    let hooks = root.join(".oxy/hooks");
2249
    fs::create_dir_all(&hooks).unwrap();
2250
    let hook = |name: &str, body: &str| {
2251
        let p = hooks.join(name);
2252
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2253
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2254
    };
2255
    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");
2256
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2257
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2258
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2259
    write(root, ".oxyignore", b".last-*\n");
2260
    write(root, "a.txt", b"a\n");
2261
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2262
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2263
    let h1 = repo.commit("first", &[]).unwrap();
2264
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2265
    assert!(
2266
        pre.contains("\"event\":\"pre-commit\"")
2267
            && pre.contains("\"path\":\"a.txt\"")
2268
            && pre.contains("\"message\":\"first\""),
2269
        "{pre}"
2270
    );
2271
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2272
    assert!(post.contains(&h1.to_hex()), "{post}");
2273
    repo.checkout(&[h1], false, "co").unwrap();
2274
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2275
        .unwrap()
2276
        .contains("post-checkout"));
2277
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2278
    repo.save_config().unwrap();
2279
    let err = repo.push("origin", false).unwrap_err().to_string();
2280
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2281
2282
    // semantic-deps: only when enabled; adds an explicit dependency.
2283
    write(root, "b.txt", b"b\n");
2284
    hook(
2285
        "semantic-deps",
2286
        &format!(
2287
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2288
            h1.to_hex()
2289
        ),
2290
    );
2291
    let h2 = repo.commit("b without hook", &[]).unwrap();
2292
    assert!(
2293
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2294
        "hook disabled by default"
2295
    );
2296
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2297
    repo.save_config().unwrap();
2298
    write(root, "c.txt", b"c\n");
2299
    let h3 = repo.commit("c with hook", &[]).unwrap();
2300
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2301
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2302
    assert!(
2303
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2304
        "{sem}"
2305
    );
2306
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2307
}
2308
2309
#[test]
2310
fn amend_into_older_change_and_split() {
2311
    hermetic();
2312
    let dir = tempfile::tempdir().unwrap();
2313
    let root = dir.path();
2314
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2315
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2316
        .unwrap();
2317
    repo.set_user_config("core.sign", "change").unwrap();
2318
    write(root, "a.txt", b"one\ntwo\n");
2319
    let h0 = repo.commit("base", &[]).unwrap();
2320
    write(root, "a.txt", b"one\nTWO\n");
2321
    let h1 = repo.commit("edit two", &[]).unwrap();
2322
    write(root, "a.txt", b"one\nTWO\nthree\n");
2323
    let h2 = repo.commit("add three", &[]).unwrap();
2324
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2325
2326
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2327
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2328
    let h1b = repo.amend_into(&h1, None).unwrap();
2329
    assert_ne!(h1b, h1);
2330
    let c1b = repo.store().get_change(&h1b).unwrap();
2331
    assert_eq!(c1b.change_id, id1);
2332
    assert_eq!(c1b.deps, vec![h0]);
2333
    assert!(matches!(
2334
        repo.verify_change(&h1b).unwrap(),
2335
        SignatureStatus::Valid { .. }
2336
    ));
2337
    let heads = repo.bookmark_heads().unwrap();
2338
    assert_eq!(heads.len(), 1);
2339
    let top = repo.store().get_change(&heads[0]).unwrap();
2340
    assert_eq!(top.message, "add three");
2341
    assert_eq!(
2342
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2343
        [h0, h1b].into_iter().collect(),
2344
        "depends on the file's creator and the rewritten line"
2345
    );
2346
    let snap = repo.load_state(&heads).unwrap().materialize();
2347
    assert!(
2348
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2349
    );
2350
    assert!(
2351
        !repo.snapshot("status").unwrap().changed,
2352
        "the working copy is clean after folding"
2353
    );
2354
    // Only h1b's own state shows the fix without "three".
2355
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2356
    assert!(
2357
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2358
    );
2359
    assert_eq!(repo.log().unwrap().len(), 4);
2360
2361
    // An edit to a line introduced by h2 cannot fold into h1.
2362
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2363
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2364
    assert!(err.contains("introduced after"), "{err}");
2365
    assert!(
2366
        repo.snapshot("status").unwrap().statuses.len() == 1,
2367
        "nothing was changed by the refusal"
2368
    );
2369
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2370
2371
    // Split the head that touches two files.
2372
    write(root, "b.txt", b"b\n");
2373
    write(root, "c.txt", b"c\n");
2374
    let h3 = repo.commit("b and c", &[]).unwrap();
2375
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2376
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2377
    let c_1 = repo.store().get_change(&p1).unwrap();
2378
    let c_2 = repo.store().get_change(&p2).unwrap();
2379
    assert!(c_1.message.contains("part 1: b.txt"));
2380
    assert_eq!(c_2.change_id, id3);
2381
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2382
    assert!(
2383
        heads.contains(&p1) && heads.contains(&p2),
2384
        "independent parts are both heads"
2385
    );
2386
    let snap = repo
2387
        .load_state(&repo.bookmark_heads().unwrap())
2388
        .unwrap()
2389
        .materialize();
2390
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2391
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2392
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2393
    assert!(!repo.snapshot("status").unwrap().changed);
2394
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2395
    let _ = h2;
2396
}
2397
2398
#[test]
2399
fn identity_lifecycle() {
2400
    hermetic();
2401
    let dir = tempfile::tempdir().unwrap();
2402
    let root = dir.path();
2403
    let origin = Repo::init(&root.join("origin")).unwrap();
2404
    let url = root.join("origin").to_string_lossy().to_string();
2405
    let mut a = Repo::clone(&url, &root.join("a"))
2406
        .unwrap()
2407
        .with_home(root.join("home-a"));
2408
    a.set_user_config("core.sign", "change").unwrap();
2409
    let (key_a, _) = a
2410
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2411
        .unwrap();
2412
    write(&root.join("a"), "a.txt", b"a\n");
2413
    let h1 = a.commit("one", &[]).unwrap();
2414
    assert!(a.policy_init().unwrap().applied);
2415
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2416
2417
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2418
    let mut e = Repo::init(&root.join("e"))
2419
        .unwrap()
2420
        .with_home(root.join("home-e"));
2421
    e.set_user_config("core.sign", "change").unwrap();
2422
    e.create_identity_with(
2423
        "Eve",
2424
        "[email protected]",
2425
        IdentityScope::User,
2426
        Some(Hlc::now().wall_ms - 1),
2427
    )
2428
    .unwrap();
2429
    write(&root.join("e"), "e.txt", b"e\n");
2430
    let he = e.commit("late", &[]).unwrap();
2431
    assert!(
2432
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2433
    );
2434
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2435
    let r = e
2436
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2437
        .unwrap();
2438
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2439
    write(&root.join("e"), "e.txt", b"e2\n");
2440
    let he2 = e.commit("in time", &[]).unwrap();
2441
    assert!(
2442
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2443
    );
2444
2445
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2446
    let r = a.rotate_identity().unwrap();
2447
    assert_eq!(r.old, key_a);
2448
    assert_eq!(a.config.author_key, Some(r.new));
2449
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2450
    assert!(r.policy.as_ref().unwrap().applied);
2451
    let (_, sp) = a.current_policy().unwrap().unwrap();
2452
    assert_eq!(
2453
        (sp.policy.serial, sp.policy.roots.clone()),
2454
        (2, vec![r.new])
2455
    );
2456
    assert!(
2457
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2458
        "superseded, not revoked"
2459
    );
2460
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2461
    assert!(
2462
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2463
    );
2464
    write(&root.join("a"), "a.txt", b"a2\n");
2465
    let h2 = a.commit("two", &[]).unwrap();
2466
    assert!(
2467
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2468
    );
2469
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2470
    let res = a.push("origin", false).unwrap();
2471
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2472
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2473
    let key_a = r.new;
2474
2475
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2476
    // identity object, so Ada's KeyId changes while her keys stay the same.
2477
    let mut b = Repo::clone(&url, &root.join("b"))
2478
        .unwrap()
2479
        .with_home(root.join("home-b"));
2480
    let (key_b, id_b) = b
2481
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2482
        .unwrap();
2483
    let r = a.delegate_add(id_b.clone()).unwrap();
2484
    assert_eq!(r.old, key_a);
2485
    let key_a2 = r.new;
2486
    assert_eq!(a.identity(&key_a2).unwrap().delegates, vec![key_b]);
2487
    assert_eq!(
2488
        a.identity(&key_a2).unwrap().ed25519_pk,
2489
        a.identity(&key_a).unwrap().ed25519_pk
2490
    );
2491
    assert!(a.delegate_add(id_b.clone()).is_err(), "already a delegate");
2492
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2493
    write(&root.join("a"), "a.txt", b"a3\n");
2494
    let h3 = a.commit("three", &[]).unwrap();
2495
    assert!(
2496
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2497
        "the same secret signs under the new KeyId"
2498
    );
2499
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2500
    a.set_user_config("core.sign", "seal").unwrap();
2501
    write(&root.join("a"), "a.txt", b"a4\n");
2502
    let h4 = a.commit("four", &[]).unwrap();
2503
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2504
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2505
    a.store()
2506
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2507
        .unwrap();
2508
    assert!(
2509
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2510
    );
2511
    a.set_user_config("core.sign", "change").unwrap();
2512
    // Withdrawing the delegation re-issues the identity again.
2513
    let r = a.delegate_remove(&key_b).unwrap();
2514
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2515
    assert!(a.delegate_remove(&key_b).is_err());
2516
    let key_a3 = r.new;
2517
    let res = a.push("origin", false).unwrap();
2518
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2519
2520
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2521
    // both applied under the old threshold of 1. A grant then needs Bob too.
2522
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2523
    assert!(a.policy_root_add(id_b.clone()).is_err());
2524
    assert!(a.policy_set_threshold(3).is_err());
2525
    assert!(a.policy_set_threshold(2).unwrap().applied);
2526
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2527
    b.pull("origin").unwrap();
2528
    assert_eq!(
2529
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2530
        2
2531
    );
2532
    let mut c = Repo::init(&root.join("c"))
2533
        .unwrap()
2534
        .with_home(root.join("home-c"));
2535
    let (key_c, id_c) = c
2536
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2537
        .unwrap();
2538
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2539
    let proposal = a.policy_grant(id_c, None).unwrap();
2540
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2541
    assert_eq!(proposal.policy.serial, serial_before + 1);
2542
    assert_eq!(
2543
        a.current_policy().unwrap().unwrap().1.policy.serial,
2544
        serial_before,
2545
        "a proposal changes nothing yet"
2546
    );
2547
    // Bob signs the proposal, handed over as a file, and it applies for him.
2548
    let bytes = proposal.signed().encode();
2549
    let signed = b
2550
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2551
        .unwrap();
2552
    assert!(signed.applied && signed.sigs.len() == 2);
2553
    assert!(b
2554
        .current_policy()
2555
        .unwrap()
2556
        .unwrap()
2557
        .1
2558
        .policy
2559
        .authorizes(&key_c, "main"));
2560
    assert!(
2561
        b.policy_sign(signed.signed()).is_err(),
2562
        "a stale proposal is refused"
2563
    );
2564
    // Bob publishes it and Ada picks it up.
2565
    assert!(b
2566
        .push("origin", false)
2567
        .unwrap()
2568
        .iter()
2569
        .any(|x| x.name == "policy" && x.ok));
2570
    a.pull("origin").unwrap();
2571
    assert_eq!(
2572
        a.current_policy().unwrap().unwrap().1.policy.serial,
2573
        serial_before + 1
2574
    );
2575
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2576
    assert!(a.policy_revoke(&key_a3).is_err());
2577
    let u = a
2578
        .revoke_identity(&key_c, "left the project")
2579
        .unwrap()
2580
        .unwrap();
2581
    assert!(!u.applied);
2582
    assert!(a.is_revoked(&key_c).unwrap());
2583
    assert!(!b.is_revoked(&key_c).unwrap());
2584
    let u = b.policy_sign(u.signed()).unwrap();
2585
    assert!(u.applied && u.policy.is_revoked(&key_c));
2586
    assert!(b.is_revoked(&key_c).unwrap());
2587
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2588
    assert!(
2589
        b.policy_revoke(&key_a3).is_err(),
2590
        "would leave one root for a threshold of 2"
2591
    );
2592
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2593
    let key_c_own = c.config.author_key.unwrap();
2594
    assert!(c
2595
        .revoke_identity(&key_c_own, "lost laptop")
2596
        .unwrap()
2597
        .is_none());
2598
    assert!(c.is_revoked(&key_c_own).unwrap());
2599
    assert_eq!(key_c_own, key_c);
2600
}
2601
2602
#[test]
2603
fn renames_are_detected_and_tracked_as_moves() {
2604
    hermetic();
2605
    let dir = tempfile::tempdir().unwrap();
2606
    let root = dir.path();
2607
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2608
    write(
2609
        root,
2610
        "src/old.rs",
2611
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2612
    );
2613
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2614
    write(root, "tiny.txt", b"x\n");
2615
    let h1 = repo.commit("base", &[]).unwrap();
2616
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2617
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2618
2619
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2620
    // that shares nothing with the removed file.
2621
    fs::remove_file(root.join("src/old.rs")).unwrap();
2622
    write(
2623
        root,
2624
        "lib/new.rs",
2625
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2626
    );
2627
    fs::remove_file(root.join("img.bin")).unwrap();
2628
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2629
    fs::remove_file(root.join("tiny.txt")).unwrap();
2630
    write(root, "other.txt", b"completely different\n");
2631
    let snap = repo.snapshot("status").unwrap();
2632
    let statuses: Vec<(&str, ChangeStatus)> = snap
2633
        .statuses
2634
        .iter()
2635
        .map(|s| (s.path.as_str(), s.status))
2636
        .collect();
2637
    assert_eq!(
2638
        statuses,
2639
        vec![
2640
            ("assets/img.bin", ChangeStatus::Renamed),
2641
            ("lib/new.rs", ChangeStatus::Renamed),
2642
            ("other.txt", ChangeStatus::Added),
2643
            ("src", ChangeStatus::Removed),
2644
            ("tiny.txt", ChangeStatus::Removed)
2645
        ]
2646
    );
2647
    let h2 = repo.commit("move things", &[]).unwrap();
2648
    let c = repo.store().get_change(&h2).unwrap();
2649
    let moves: Vec<_> = c
2650
        .tree_ops
2651
        .iter()
2652
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2653
        .collect();
2654
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
2655
    assert!(c.tree_ops.iter().any(
2656
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2657
    ));
2658
    assert!(c.tree_ops.iter().any(
2659
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2660
    ));
2661
    let snap = repo.load_state(&[h2]).unwrap().materialize();
2662
    assert_eq!(
2663
        snap.files["lib/new.rs"].node, node_old,
2664
        "the node survives the rename"
2665
    );
2666
    assert!(
2667
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2668
    );
2669
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
2670
    assert!(render_change(
2671
        &c,
2672
        &repo.load_state(&[h1]).unwrap(),
2673
        &repo.load_state(&[h1]).unwrap().materialize()
2674
    )
2675
    .contains("R "));
2676
    // A fresh checkout reproduces the tree.
2677
    let other = tempfile::tempdir().unwrap();
2678
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
2679
    assert_eq!(
2680
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2681
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2682
    );
2683
    assert!(!other.path().join("src").exists());
2684
    assert!(!clone.snapshot("status").unwrap().changed);
2685
    // Similarity is line based, byte weighted.
2686
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2687
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2688
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2689
    assert_eq!(similarity(b"", b"x\n"), 0);
2690
}
2691
2692
#[test]
2693
fn git_fetch_and_push_round_trip() {
2694
    hermetic();
2695
    if std::process::Command::new("git")
2696
        .arg("--version")
2697
        .output()
2698
        .is_err()
2699
    {
2700
        eprintln!("git not installed; skipping");
2701
        return;
2702
    }
2703
    let dir = tempfile::tempdir().unwrap();
2704
    let root = dir.path();
2705
    let git_in = |d: &Path, args: &[&str]| -> String {
2706
        let out = std::process::Command::new("git")
2707
            .arg("-C")
2708
            .arg(d)
2709
            .args([
2710
                "-c",
2711
                "user.name=Grace",
2712
                "-c",
2713
                "[email protected]",
2714
                "-c",
2715
                "commit.gpgsign=false",
2716
            ])
2717
            .args(args)
2718
            .output()
2719
            .unwrap();
2720
        assert!(
2721
            out.status.success(),
2722
            "git {args:?}: {}",
2723
            String::from_utf8_lossy(&out.stderr)
2724
        );
2725
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2726
    };
2727
    // A bare "remote" and a work tree that pushes to it.
2728
    let remote = root.join("remote.git");
2729
    fs::create_dir_all(&remote).unwrap();
2730
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2731
    let work = root.join("work");
2732
    git_in(
2733
        root,
2734
        &[
2735
            "clone",
2736
            "-q",
2737
            remote.to_str().unwrap(),
2738
            work.to_str().unwrap(),
2739
        ],
2740
    );
2741
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2742
    write(&work, "README.md", b"# Project\n");
2743
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2744
    git_in(&work, &["add", "."]);
2745
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2746
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2747
    git_in(&work, &["commit", "-q", "-am", "second"]);
2748
    git_in(&work, &["push", "-q", "origin", "main"]);
2749
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2750
2751
    // Fetch into a fresh oxy repository.
2752
    let o = root.join("oxy");
2753
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
2754
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2755
        .unwrap();
2756
    let url = remote.to_string_lossy().to_string();
2757
    let r = repo.git_fetch(&url, "main").unwrap();
2758
    assert_eq!((r.commits, r.heads), (2, 1));
2759
    assert_eq!(
2760
        fs::read(o.join("src/lib.rs")).unwrap(),
2761
        b"pub fn a() {}\npub fn b() {}\n"
2762
    );
2763
    assert!(!repo.snapshot("status").unwrap().changed);
2764
    assert_eq!(
2765
        repo.git_fetch(&url, "main").unwrap().commits,
2766
        0,
2767
        "nothing new"
2768
    );
2769
2770
    // An oxy change, pushed back: one commit on top of the Git tip.
2771
    write(
2772
        &o,
2773
        "src/lib.rs",
2774
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2775
    );
2776
    write(&o, "NOTES.md", b"from oxy\n");
2777
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2778
    let r = repo.git_push(&url, "main").unwrap();
2779
    assert_eq!(r.exported, 1, "{r:?}");
2780
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2781
    assert_eq!(
2782
        git_in(&work, &["log", "--format=%s", "main"]),
2783
        "add c and notes\nsecond\ninitial"
2784
    );
2785
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2786
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2787
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
2788
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2789
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2790
    assert_eq!(
2791
        repo.git_push(&url, "main").unwrap().exported,
2792
        0,
2793
        "already pushed"
2794
    );
2795
2796
    // Git moves on; pushing without fetching is refused, fetching brings
2797
    // the commit in and the working copy follows.
2798
    write(&work, "README.md", b"# Project\n\nMore.\n");
2799
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2800
    git_in(&work, &["push", "-q", "origin", "main"]);
2801
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
2802
    assert!(repo
2803
        .git_push(&url, "main")
2804
        .unwrap_err()
2805
        .to_string()
2806
        .contains("fetch"));
2807
    let r = repo.git_fetch(&url, "main").unwrap();
2808
    assert_eq!(
2809
        (r.commits, r.heads),
2810
        (1, 2),
2811
        "the Git change and the oxy change commute"
2812
    );
2813
    assert_eq!(
2814
        fs::read(o.join("README.md")).unwrap(),
2815
        b"# Project\n\nMore.\n"
2816
    );
2817
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2818
    assert!(!repo.snapshot("status").unwrap().changed);
2819
    // Another oxy change pushes on top of Git's newest commit.
2820
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2821
    repo.commit("notes again", &[]).unwrap();
2822
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2823
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2824
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
2825
    assert_eq!(
2826
        fs::read(work.join("NOTES.md")).unwrap(),
2827
        b"from oxy\nagain\n"
2828
    );
2829
    assert_eq!(
2830
        git_in(&work, &["log", "--format=%s", "main"])
2831
            .lines()
2832
            .count(),
2833
        5
2834
    );
2835
}
2836
2837
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2838
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2839
#[test]
2840
#[ignore]
2841
fn bench_one_gibibyte_file() {
2842
    hermetic();
2843
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2844
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2845
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2846
        None => tempfile::tempdir().unwrap(),
2847
    };
2848
    let root = dir.path();
2849
    let repo = Repo::init(&root.join("r"))
2850
        .unwrap()
2851
        .with_home(root.join("home"));
2852
    let size = 1usize << 30;
2853
    let mut data = vec![0u8; size];
2854
    let mut x = 0x9e3779b97f4a7c15u64;
2855
    for chunk in data.chunks_mut(8) {
2856
        x ^= x << 13;
2857
        x ^= x >> 7;
2858
        x ^= x << 17;
2859
        let b = x.to_le_bytes();
2860
        chunk.copy_from_slice(&b[..chunk.len()]);
2861
    }
2862
    let t = std::time::Instant::now();
2863
    write(&root.join("r"), "big.bin", &data);
2864
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
2865
    let t = std::time::Instant::now();
2866
    let h = repo.commit("big", &[]).unwrap();
2867
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
2868
    let t = std::time::Instant::now();
2869
    assert!(!repo.snapshot("status").unwrap().changed);
2870
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
2871
    let t = std::time::Instant::now();
2872
    let objects = repo.store().list().unwrap().len();
2873
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
2874
    let t = std::time::Instant::now();
2875
    let g = repo.gc(true).unwrap();
2876
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
2877
    let t = std::time::Instant::now();
2878
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
2879
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
2880
    let t = std::time::Instant::now();
2881
    let back = fs::read(root.join("c/big.bin")).unwrap();
2882
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
2883
    eprintln!("read back and verify: {:.2?}", t.elapsed());
2884
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
2885
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
2886
    eprintln!(
2887
        "store size: {:.1} MiB for 1 GiB of data",
2888
        store_bytes as f64 / (1024.0 * 1024.0)
2889
    );
2890
}
2891
2892
fn walkdir_size(p: &Path) -> u64 {
2893
    let mut total = 0;
2894
    if let Ok(rd) = fs::read_dir(p) {
2895
        for e in rd.flatten() {
2896
            let path = e.path();
2897
            if path.is_dir() {
2898
                total += walkdir_size(&path);
2899
            } else if let Ok(m) = fs::metadata(&path) {
2900
                total += m.len();
2901
            }
2902
        }
2903
    }
2904
    total
2905
}
2906
2907
/// An opaque file whose size and mtime match the manifest is not read on
2908
/// the next snapshot: its blob comes from the manifest's stat cache.
2909
#[cfg(unix)]
2910
#[test]
2911
fn stat_cache_skips_reading_unchanged_opaque_files() {
2912
    use std::os::unix::fs::PermissionsExt;
2913
    hermetic();
2914
    let dir = tempfile::tempdir().unwrap();
2915
    let root = dir.path();
2916
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2917
    let mut big = vec![0u8; 300 * 1024];
2918
    for (i, b) in big.iter_mut().enumerate() {
2919
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
2920
    }
2921
    big[0] = 0;
2922
    write(root, "big.bin", &big);
2923
    write(root, "a.txt", b"text\n");
2924
    let h1 = repo.commit("base", &[]).unwrap();
2925
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
2926
    assert!(
2927
        m.entries["big.bin"].blob.is_some(),
2928
        "opaque files record their blob"
2929
    );
2930
    assert!(m.entries["a.txt"].blob.is_none());
2931
    let blob = m.entries["big.bin"].blob.unwrap();
2932
    assert!(repo.store().has(&blob));
2933
2934
    // Files modified within two seconds of the manifest are racy and still
2935
    // read; age the file so the cache applies, then snapshot to record it.
2936
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
2937
    fs::File::options()
2938
        .write(true)
2939
        .open(root.join("big.bin"))
2940
        .unwrap()
2941
        .set_modified(old)
2942
        .unwrap();
2943
    assert!(!repo.snapshot("status").unwrap().changed);
2944
    // Now the file cannot be read at all; the snapshot succeeds without it.
2945
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
2946
    let snap = repo.snapshot("status").unwrap();
2947
    assert!(
2948
        !snap.changed && snap.statuses.is_empty(),
2949
        "{:?}",
2950
        snap.statuses
2951
    );
2952
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
2953
    // A real change (new mtime, new content) is seen and committed correctly.
2954
    let mut big2 = big.clone();
2955
    big2[10] ^= 0xff;
2956
    write(root, "big.bin", &big2);
2957
    let snap = repo.snapshot("status").unwrap();
2958
    assert_eq!(
2959
        snap.statuses
2960
            .iter()
2961
            .map(|s| (s.path.as_str(), s.status))
2962
            .collect::<Vec<_>>(),
2963
        vec![("big.bin", ChangeStatus::Modified)]
2964
    );
2965
    let h2 = repo.commit("edit", &[]).unwrap();
2966
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
2967
    assert_eq!(
2968
        files["big.bin"].content,
2969
        FileContent::Opaque {
2970
            blobs: vec![Repo::blob_ref(&big2)]
2971
        }
2972
    );
2973
    // Checkout writes a manifest with blobs too, so the next status is cached.
2974
    repo.checkout(&[h1], false, "checkout").unwrap();
2975
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
2976
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
2977
    assert!(!repo.snapshot("status").unwrap().changed);
2978
}
2979
2980
#[test]
2981
fn status_json_lists_conflicts_with_contributors() {
2982
    hermetic();
2983
    let dir = tempfile::tempdir().unwrap();
2984
    let root = dir.path();
2985
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2986
    write(root, "a.txt", b"one\n");
2987
    let h1 = repo.commit("base", &[]).unwrap();
2988
    write(root, "a.txt", b"one\nleft\n");
2989
    let ha = repo.commit("left", &[]).unwrap();
2990
    repo.checkout(&[h1], true, "checkout").unwrap();
2991
    write(root, "a.txt", b"one\nright\n");
2992
    let hb = repo.commit("right", &[]).unwrap();
2993
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
2994
    let snap = repo.snapshot("status").unwrap();
2995
    assert!(snap.base_snapshot.is_conflicted());
2996
    let json = repo.status_json(&snap).unwrap();
2997
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
2998
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
2999
    assert!(json.contains("\"conflicted\":true"), "{json}");
3000
    assert!(
3001
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3002
        "{json}"
3003
    );
3004
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3005
    assert!(json.contains("\"resolved\":false"), "{json}");
3006
    assert!(json.starts_with('{') && json.ends_with('}'));
3007
    // Resolve and the report says so; a clean copy has no conflicts.
3008
    write(root, "a.txt", b"one\nleft\nright\n");
3009
    let snap = repo.snapshot("status").unwrap();
3010
    let json = repo.status_json(&snap).unwrap();
3011
    assert!(json.contains("\"resolved\":true"), "{json}");
3012
    repo.commit("resolve", &[]).unwrap();
3013
    let snap = repo.snapshot("status").unwrap();
3014
    let json = repo.status_json(&snap).unwrap();
3015
    assert!(
3016
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3017
        "{json}"
3018
    );
3019
}
3020
3021
#[test]
3022
fn ignore_rules_do_not_untrack_files() {
3023
    hermetic();
3024
    let dir = tempfile::tempdir().unwrap();
3025
    let root = dir.path();
3026
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3027
    write(root, "src.c", b"int x;\n");
3028
    write(root, "build/out.o", b"\0obj");
3029
    write(root, "sub/keep.log", b"keep\n");
3030
    write(root, "sub/junk.log", b"junk\n");
3031
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3032
    let snap = repo.snapshot("status").unwrap();
3033
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3034
    assert_eq!(
3035
        added,
3036
        vec![".oxyignore", "src.c", "sub/keep.log"],
3037
        "anchored, glob, and negated rules"
3038
    );
3039
    let h1 = repo.commit("base", &[]).unwrap();
3040
    // Ignoring a tracked file changes nothing about it.
3041
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3042
    let snap = repo.snapshot("status").unwrap();
3043
    assert_eq!(
3044
        snap.statuses
3045
            .iter()
3046
            .map(|s| s.path.as_str())
3047
            .collect::<Vec<_>>(),
3048
        vec![".oxyignore"]
3049
    );
3050
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3051
    assert!(repo
3052
        .load_state(&[h2])
3053
        .unwrap()
3054
        .materialize()
3055
        .files
3056
        .contains_key("src.c"));
3057
    // Its edits are still seen, by status and by the prompt.
3058
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3059
    write(root, "src.c", b"int x, y;\n");
3060
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3061
    let snap = repo.snapshot("status").unwrap();
3062
    assert_eq!(
3063
        snap.statuses
3064
            .iter()
3065
            .map(|s| (s.path.as_str(), s.status))
3066
            .collect::<Vec<_>>(),
3067
        vec![("src.c", ChangeStatus::Modified)]
3068
    );
3069
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3070
    assert!(
3071
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3072
    );
3073
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3074
    fs::remove_file(root.join("src.c")).unwrap();
3075
    let snap = repo.snapshot("status").unwrap();
3076
    assert_eq!(
3077
        snap.statuses
3078
            .iter()
3079
            .map(|s| (s.path.as_str(), s.status))
3080
            .collect::<Vec<_>>(),
3081
        vec![("src.c", ChangeStatus::Removed)]
3082
    );
3083
    repo.checkout(&[h3], true, "checkout").unwrap();
3084
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3085
    assert!(!repo.snapshot("status").unwrap().changed);
3086
    let _ = h1;
3087
}
3088
3089
#[test]
3090
fn split_works_on_non_heads_by_node() {
3091
    hermetic();
3092
    let dir = tempfile::tempdir().unwrap();
3093
    let root = dir.path();
3094
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3095
    write(root, "a.txt", b"one\n");
3096
    write(root, "junk/x.lock", b"lock\n");
3097
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3098
    write(root, "a.txt", b"one\ntwo\n");
3099
    let h2 = repo.commit("more work", &[]).unwrap();
3100
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3101
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3102
    // h1 is not a head: split it by node.
3103
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3104
    assert_ne!(h1b, h1);
3105
    assert_eq!(
3106
        repo.store().get_change(&h1b).unwrap().change_id,
3107
        id1,
3108
        "the rest keeps the ChangeId"
3109
    );
3110
    let junk = repo.store().get_change(&hj).unwrap();
3111
    assert!(junk.tree_ops.iter().all(
3112
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3113
    ));
3114
    let heads = repo.bookmark_heads().unwrap();
3115
    assert!(
3116
        heads.contains(&hj),
3117
        "the split-off part is a head of its own"
3118
    );
3119
    let snap = repo.load_state(&heads).unwrap().materialize();
3120
    assert!(
3121
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3122
        "the dependent was rewritten onto the new hash"
3123
    );
3124
    assert!(snap.files.contains_key("junk/x.lock"));
3125
    let h2b = heads
3126
        .iter()
3127
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3128
        .copied()
3129
        .unwrap();
3130
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3131
    assert!(!repo.snapshot("status").unwrap().changed);
3132
    // Abandoning the split-off head removes the junk from history.
3133
    repo.abandon(&hj).unwrap();
3134
    let heads = repo.bookmark_heads().unwrap();
3135
    let snap = repo.load_state(&heads).unwrap().materialize();
3136
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3137
    assert!(snap.files.contains_key("a.txt"));
3138
    // A dependent that touches the split-off paths blocks the split.
3139
    write(root, "junk/y.lock", b"y\n");
3140
    let hb = repo.commit("junk base", &[]).unwrap();
3141
    write(root, "junk/y.lock", b"yy\n");
3142
    write(root, "b.txt", b"b\n");
3143
    repo.commit("touches junk", &[]).unwrap();
3144
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3145
    assert!(err.contains("depends on the split-off paths"), "{err}");
3146
}
3147
3148
#[test]
3149
fn bookmarks_switch_merge_and_push() {
3150
    hermetic();
3151
    let dir = tempfile::tempdir().unwrap();
3152
    let root = dir.path();
3153
    let origin = Repo::init(&root.join("origin")).unwrap();
3154
    let url = root.join("origin").to_string_lossy().to_string();
3155
    let mut repo = Repo::clone(&url, &root.join("r"))
3156
        .unwrap()
3157
        .with_home(root.join("home"));
3158
    let r = root.join("r");
3159
    write(&r, "a.txt", b"a\n");
3160
    let h_a = repo.commit("a", &[]).unwrap();
3161
    assert!(repo.push("origin", false).unwrap()[0].ok);
3162
3163
    // A bookmark at the working copy's base, then work on it.
3164
    assert!(repo.bookmark_create("bad name..", None).is_err());
3165
    assert!(repo.bookmark_create("-x", None).is_err());
3166
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3167
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3168
    repo.bookmark_switch("feature", false).unwrap();
3169
    assert_eq!(repo.config.bookmark, "feature");
3170
    write(&r, "a.txt", b"a\nb\n");
3171
    write(&r, "b.txt", b"b\n");
3172
    let h_b = repo.commit("b on feature", &[]).unwrap();
3173
    assert_eq!(
3174
        repo.bookmark_heads().unwrap(),
3175
        vec![h_b],
3176
        "b edits a.txt, so it depends on a"
3177
    );
3178
    assert_eq!(
3179
        repo.resolve_heads("main").unwrap(),
3180
        vec![h_a],
3181
        "main is untouched"
3182
    );
3183
    assert_eq!(
3184
        repo.resolve_change("feature").unwrap(),
3185
        h_b,
3186
        "a one-head bookmark names its change"
3187
    );
3188
    // Reopening keeps the workspace's bookmark.
3189
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3190
    assert_eq!(reopened.config.bookmark, "feature");
3191
    // Back to main: b.txt goes away; work there.
3192
    repo.bookmark_switch("main", false).unwrap();
3193
    assert!(!r.join("b.txt").exists());
3194
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3195
    write(&r, "c.txt", b"c\n");
3196
    let h_c = repo.commit("c on main", &[]).unwrap();
3197
    let list = repo.bookmarks().unwrap();
3198
    assert_eq!(
3199
        list.iter()
3200
            .map(|b| (b.name.as_str(), b.current))
3201
            .collect::<Vec<_>>(),
3202
        vec![("feature", false), ("main", true)]
3203
    );
3204
    assert_eq!(
3205
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3206
        Some(1),
3207
        "c is not on origin yet"
3208
    );
3209
    // Merge feature into main: the union, both heads, no merge change.
3210
    let m = repo.merge("feature").unwrap();
3211
    assert!(m.changed && m.checked_out);
3212
    let mut want = vec![h_b, h_c];
3213
    want.sort();
3214
    assert_eq!(m.heads, want);
3215
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3216
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3217
    assert!(repo.merge("main").is_err());
3218
    // The other bookmark can be pushed by name and appears at origin.
3219
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3220
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3221
    assert!(repo.push("origin", false).unwrap()[0].ok);
3222
    assert_eq!(
3223
        repo.bookmarks()
3224
            .unwrap()
3225
            .iter()
3226
            .find(|b| b.name == "main")
3227
            .unwrap()
3228
            .ahead,
3229
        Some(0)
3230
    );
3231
    // A second workspace inherits the current bookmark and can switch independently.
3232
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3233
    assert_eq!(ws.config.bookmark, "main");
3234
    let mut ws = ws;
3235
    ws.bookmark_switch("feature", false).unwrap();
3236
    assert_eq!(
3237
        Repo::open(&r).unwrap().config.bookmark,
3238
        "main",
3239
        "the first workspace is unaffected"
3240
    );
3241
    assert!(
3242
        repo.bookmark_delete("feature").is_err(),
3243
        "current bookmark of another workspace"
3244
    );
3245
    ws.bookmark_switch("main", false).unwrap();
3246
    // Set and delete.
3247
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3248
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3249
    repo.bookmark_delete("feature").unwrap();
3250
    assert!(repo.resolve_heads("feature").is_err());
3251
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3252
    assert!(
3253
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3254
        "changes of a deleted bookmark remain"
3255
    );
3256
}
3257
3258
#[test]
3259
fn oxygen_subrepos_pin_follow_and_update() {
3260
    hermetic();
3261
    let dir = tempfile::tempdir().unwrap();
3262
    let root = dir.path();
3263
    // A library repository with two commits, and a bare-ish origin for it.
3264
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3265
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3266
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3267
        .unwrap()
3268
        .with_home(root.join("home"));
3269
    write(&root.join("lib"), "lib.txt", b"v1\n");
3270
    let l1 = lib.commit("lib v1", &[]).unwrap();
3271
    assert!(lib.push("origin", false).unwrap()[0].ok);
3272
    let _ = lib_origin;
3273
3274
    // The application (a clone of its own origin) adds it as a subrepo.
3275
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3276
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3277
    let _ = app_origin;
3278
    let app_dir = root.join("app");
3279
    let app = Repo::clone(&app_url, &app_dir)
3280
        .unwrap()
3281
        .with_home(root.join("home"));
3282
    write(&app_dir, "main.txt", b"app\n");
3283
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3284
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3285
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3286
    let snap = app.snapshot("status").unwrap();
3287
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3288
    assert_eq!(
3289
        paths,
3290
        vec![".oxymodules", "libs/lib", "main.txt"],
3291
        "the nested files are not walked"
3292
    );
3293
    let a1 = app.commit("app with lib", &[]).unwrap();
3294
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3295
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3296
    assert!(!files.contains_key("libs/lib/lib.txt"));
3297
    assert!(!app.snapshot("status").unwrap().changed);
3298
    let subs = app.subrepos().unwrap();
3299
    assert_eq!(subs.len(), 1);
3300
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3301
3302
    // Advance the nested repository: the parent sees a modified pin.
3303
    let nested = Repo::open(&app_dir.join("libs/lib"))
3304
        .unwrap()
3305
        .with_home(root.join("home"));
3306
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3307
    let l2 = nested.commit("lib v2", &[]).unwrap();
3308
    assert!(nested.push("origin", false).unwrap()[0].ok);
3309
    let snap = app.snapshot("status").unwrap();
3310
    assert_eq!(
3311
        snap.statuses
3312
            .iter()
3313
            .map(|s| (s.path.as_str(), s.status))
3314
            .collect::<Vec<_>>(),
3315
        vec![("libs/lib", ChangeStatus::Modified)]
3316
    );
3317
    let a2 = app.commit("bump lib", &[]).unwrap();
3318
    // Checking out the older app state moves the nested repository back.
3319
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3320
    assert!(r.notes.is_empty(), "{:?}", r.notes);
3321
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3322
    assert_eq!(
3323
        Repo::open(&app_dir.join("libs/lib"))
3324
            .unwrap()
3325
            .bookmark_heads()
3326
            .unwrap(),
3327
        vec![l1]
3328
    );
3329
    assert!(!app.snapshot("status").unwrap().changed);
3330
    // A dirty nested repository is left alone and reported.
3331
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3332
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3333
    assert!(
3334
        r.notes.iter().any(|n| n.contains("uncommitted")),
3335
        "{:?}",
3336
        r.notes
3337
    );
3338
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3339
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3340
    let r = app.submodule_update(false, &[]).unwrap();
3341
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3342
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3343
    let _ = l2;
3344
3345
    // A fresh clone of the app has the pin but no nested repository until update --init.
3346
    assert!(app.push("origin", false).unwrap()[0].ok);
3347
    let clone_dir = root.join("app-clone");
3348
    let clone = Repo::clone(&app_url, &clone_dir)
3349
        .unwrap()
3350
        .with_home(root.join("home"));
3351
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3352
    assert_eq!(
3353
        clone.submodule_update(false, &[]).unwrap(),
3354
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3355
    );
3356
    assert_eq!(
3357
        clone.submodule_update(true, &[]).unwrap(),
3358
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3359
    );
3360
    assert_eq!(
3361
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3362
        b"v2\n"
3363
    );
3364
    assert!(!clone.snapshot("status").unwrap().changed);
3365
    // Removing the subrepo leaves the directory and drops the node.
3366
    clone.submodule_remove("libs/lib").unwrap();
3367
    let snap = clone.snapshot("status").unwrap();
3368
    assert!(
3369
        snap.statuses
3370
            .iter()
3371
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3372
        "{:?}",
3373
        snap.statuses
3374
    );
3375
    let c = clone.commit("drop lib", &[]).unwrap();
3376
    assert!(!clone
3377
        .load_state(&[c])
3378
        .unwrap()
3379
        .materialize()
3380
        .files
3381
        .contains_key("libs/lib"));
3382
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3383
    assert!(
3384
        !clone.snapshot("status").unwrap().changed,
3385
        "an unregistered nested repository is ignored"
3386
    );
3387
}
3388
3389
#[test]
3390
fn git_submodules_import_and_export_as_gitlinks() {
3391
    hermetic();
3392
    if std::process::Command::new("git")
3393
        .arg("--version")
3394
        .output()
3395
        .is_err()
3396
    {
3397
        eprintln!("git not installed; skipping");
3398
        return;
3399
    }
3400
    let dir = tempfile::tempdir().unwrap();
3401
    let root = dir.path();
3402
    let git_in = |d: &Path, args: &[&str]| -> String {
3403
        let out = std::process::Command::new("git")
3404
            .arg("-C")
3405
            .arg(d)
3406
            .args([
3407
                "-c",
3408
                "user.name=Grace",
3409
                "-c",
3410
                "[email protected]",
3411
                "-c",
3412
                "commit.gpgsign=false",
3413
                "-c",
3414
                "protocol.file.allow=always",
3415
            ])
3416
            .args(args)
3417
            .output()
3418
            .unwrap();
3419
        assert!(
3420
            out.status.success(),
3421
            "git {args:?}: {}",
3422
            String::from_utf8_lossy(&out.stderr)
3423
        );
3424
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3425
    };
3426
    let sub = root.join("sub");
3427
    fs::create_dir_all(&sub).unwrap();
3428
    git_in(&sub, &["init", "-q", "-b", "main"]);
3429
    write(&sub, "s.txt", b"sub\n");
3430
    git_in(&sub, &["add", "."]);
3431
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3432
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3433
    let g = root.join("main.git");
3434
    fs::create_dir_all(&g).unwrap();
3435
    git_in(&g, &["init", "-q", "-b", "main"]);
3436
    write(&g, "README.md", b"# app\n");
3437
    git_in(&g, &["add", "."]);
3438
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3439
    git_in(
3440
        &g,
3441
        &[
3442
            "submodule",
3443
            "add",
3444
            "-q",
3445
            sub.to_str().unwrap(),
3446
            "vendor/sub",
3447
        ],
3448
    );
3449
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3450
3451
    let dest = root.join("oxy");
3452
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3453
    let rep = repo.import_git(&g, "main").unwrap();
3454
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3455
    let files = repo
3456
        .load_state(&repo.bookmark_heads().unwrap())
3457
        .unwrap()
3458
        .materialize()
3459
        .files;
3460
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3461
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3462
        panic!()
3463
    };
3464
    assert_eq!(
3465
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3466
        crate::subrepo::Pin::Git {
3467
            sha: sub_sha.clone(),
3468
            branch: "HEAD".into()
3469
        }
3470
    );
3471
    let modules =
3472
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3473
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3474
    assert!(modules.entries["vendor/sub"].git);
3475
    assert!(
3476
        files.contains_key(".gitmodules"),
3477
        "the Git file is kept for round trips"
3478
    );
3479
    assert!(
3480
        !dest.join("vendor/sub/.git").exists(),
3481
        "not cloned until update --init"
3482
    );
3483
    assert!(!repo.snapshot("status").unwrap().changed);
3484
    // update --init clones it at the pinned commit; status is unchanged.
3485
    assert_eq!(
3486
        repo.submodule_update(true, &[]).unwrap(),
3487
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3488
    );
3489
    assert_eq!(
3490
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3491
        sub_sha
3492
    );
3493
    assert!(!repo.snapshot("status").unwrap().changed);
3494
    // Export writes the gitlink and .gitmodules back.
3495
    let mirror = root.join("mirror.git");
3496
    let rep = repo.git_export(&mirror).unwrap();
3497
    assert_eq!(rep.skipped_subrepos, 0);
3498
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3499
    assert!(
3500
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3501
        "{ls}"
3502
    );
3503
    assert_eq!(
3504
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3505
        ".gitmodules\nREADME.md\nvendor"
3506
    );
3507
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3508
    assert_eq!(
3509
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3510
        orig_tree,
3511
        "tree round trip"
3512
    );
3513
}
3514
3515
#[test]
3516
fn partial_commits_by_path_and_by_hunk() {
3517
    hermetic();
3518
    let dir = tempfile::tempdir().unwrap();
3519
    let root = dir.path();
3520
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3521
    write(root, "a.txt", b"1\n2\n3\n");
3522
    write(root, "b.txt", b"b\n");
3523
    let h0 = repo.commit("base", &[]).unwrap();
3524
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3525
    write(root, "b.txt", b"b\nbb\n");
3526
    write(root, "c.txt", b"c\n");
3527
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3528
    let h1 = repo
3529
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3530
        .unwrap();
3531
    let c1 = repo.store().get_change(&h1).unwrap();
3532
    assert!(
3533
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3534
        "{:?}",
3535
        c1.tree_ops
3536
    );
3537
    assert_eq!(c1.deps, vec![h0]);
3538
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3539
    assert!(
3540
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3541
    );
3542
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3543
    assert!(!files.contains_key("c.txt"));
3544
    let snap = repo.snapshot("status").unwrap();
3545
    assert_eq!(
3546
        snap.statuses
3547
            .iter()
3548
            .map(|s| (s.path.as_str(), s.status))
3549
            .collect::<Vec<_>>(),
3550
        vec![
3551
            ("b.txt", ChangeStatus::Modified),
3552
            ("c.txt", ChangeStatus::Added)
3553
        ]
3554
    );
3555
    assert_eq!(
3556
        fs::read(root.join("b.txt")).unwrap(),
3557
        b"b\nbb\n",
3558
        "disk untouched"
3559
    );
3560
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3561
    let (_, hunks) = repo.hunks().unwrap();
3562
    let b_hunk = hunks
3563
        .iter()
3564
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3565
        .unwrap()
3566
        .index;
3567
    let h2 = repo
3568
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3569
        .unwrap();
3570
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3571
    assert!(
3572
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3573
    );
3574
    assert!(!files.contains_key("c.txt"));
3575
    let snap = repo.snapshot("status").unwrap();
3576
    assert_eq!(
3577
        snap.statuses
3578
            .iter()
3579
            .map(|s| s.path.as_str())
3580
            .collect::<Vec<_>>(),
3581
        vec!["c.txt"]
3582
    );
3583
    // Choosing only the content hunk of a file in a new directory pulls in
3584
    // the directory and file additions it needs.
3585
    write(root, "d/e.txt", b"e\n");
3586
    let (_, hunks) = repo.hunks().unwrap();
3587
    let e_insert = hunks
3588
        .iter()
3589
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3590
        .unwrap()
3591
        .index;
3592
    let h3 = repo
3593
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3594
        .unwrap();
3595
    let c3 = repo.store().get_change(&h3).unwrap();
3596
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3597
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3598
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3599
    // Choosing a new file's addition hunk brings its content along.
3600
    write(root, "f/g.txt", b"g\n");
3601
    let (_, hunks) = repo.hunks().unwrap();
3602
    let g_add = hunks
3603
        .iter()
3604
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3605
        .unwrap()
3606
        .index;
3607
    let h4 = repo
3608
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3609
        .unwrap();
3610
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
3611
    assert!(
3612
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3613
    );
3614
    assert!(!repo
3615
        .snapshot("status")
3616
        .unwrap()
3617
        .statuses
3618
        .iter()
3619
        .any(|s| s.path == "f/g.txt"));
3620
    // Everything left commits normally; the working copy is then clean.
3621
    repo.commit("the rest", &[]).unwrap();
3622
    assert!(!repo.snapshot("status").unwrap().changed);
3623
    let files = repo
3624
        .load_state(&repo.bookmark_heads().unwrap())
3625
        .unwrap()
3626
        .materialize()
3627
        .files;
3628
    assert!(files.contains_key("c.txt"));
3629
}
3630
3631
#[test]
3632
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3633
    hermetic();
3634
    let dir = tempfile::tempdir().unwrap();
3635
    let root = dir.path();
3636
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3637
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3638
        .unwrap();
3639
    write(root, "a.txt", b"one\n");
3640
    let h1 = repo.commit("first", &[]).unwrap();
3641
    write(root, "a.txt", b"one\ntwo\n");
3642
    let h2 = repo.commit("second", &[]).unwrap();
3643
    let b = repo.blame("a.txt").unwrap();
3644
    assert_eq!(
3645
        b.iter()
3646
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3647
            .collect::<Vec<_>>(),
3648
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3649
    );
3650
    assert!(b.iter().all(|l| l.author == "Ada"));
3651
    assert_eq!(
3652
        b[0].change_id,
3653
        repo.store().get_change(&h1).unwrap().change_id
3654
    );
3655
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3656
    repo.commit("rename", &[]).unwrap();
3657
    let b = repo.blame("b.txt").unwrap();
3658
    assert_eq!(
3659
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3660
        vec![h1, h2],
3661
        "the node survives the rename"
3662
    );
3663
    assert!(repo.blame("a.txt").is_err());
3664
}
3665
3666
#[test]
3667
fn bisect_finds_the_first_bad_change() {
3668
    hermetic();
3669
    let dir = tempfile::tempdir().unwrap();
3670
    let root = dir.path();
3671
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3672
    let mut content = String::new();
3673
    let mut hashes = Vec::new();
3674
    for i in 1..=8 {
3675
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3676
        write(root, "f.txt", content.as_bytes());
3677
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3678
    }
3679
    // Each step appends after the previous line, so the chain is linear.
3680
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3681
    repo.bisect_start().unwrap();
3682
    assert!(matches!(
3683
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3684
        BisectStep::NeedMarks { good: 1, bad: 0 }
3685
    ));
3686
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3687
    assert!(
3688
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3689
        "{step:?}"
3690
    );
3691
    // Automated: bad when the bug line is present.
3692
    let step = repo
3693
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3694
        .unwrap();
3695
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3696
    assert_eq!(
3697
        repo.bisect_status().unwrap(),
3698
        Some(BisectStep::Found { culprit: hashes[4] })
3699
    );
3700
    repo.bisect_reset().unwrap();
3701
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3702
    assert!(repo.bisect_status().unwrap().is_none());
3703
    assert!(!repo.snapshot("status").unwrap().changed);
3704
    // Manual marks and a skip.
3705
    repo.bisect_start().unwrap();
3706
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3707
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3708
    let mut skipped_once = false;
3709
    let mut guard = 0;
3710
    while let BisectStep::Testing { .. } = step {
3711
        guard += 1;
3712
        assert!(guard < 20);
3713
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3714
        if !skipped_once && text.contains("line 6") {
3715
            // An untestable state away from the boundary: the search routes around it.
3716
            skipped_once = true;
3717
            step = repo.bisect_mark(None, &[]).unwrap();
3718
            continue;
3719
        }
3720
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3721
    }
3722
    assert!(skipped_once);
3723
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3724
    repo.bisect_reset().unwrap();
3725
    // Skipping the culprit itself leaves it among the candidates reported.
3726
    repo.bisect_start().unwrap();
3727
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3728
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3729
    let mut guard = 0;
3730
    while let BisectStep::Testing { heads, .. } = &step {
3731
        guard += 1;
3732
        assert!(guard < 20);
3733
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3734
        let is_culprit_state =
3735
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3736
        step = if is_culprit_state {
3737
            repo.bisect_mark(None, &[]).unwrap()
3738
        } else {
3739
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3740
        };
3741
    }
3742
    match step {
3743
        BisectStep::Inconclusive { candidates } => assert!(
3744
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3745
            "{candidates:?}"
3746
        ),
3747
        other => panic!("{other:?}"),
3748
    }
3749
    repo.bisect_reset().unwrap();
3750
}
3751
3752
#[test]
3753
fn squash_folds_a_change_into_its_dependency() {
3754
    hermetic();
3755
    let dir = tempfile::tempdir().unwrap();
3756
    let root = dir.path();
3757
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3758
    write(root, "a.txt", b"1\n");
3759
    let a = repo.commit("A", &[]).unwrap();
3760
    write(root, "a.txt", b"1\n2\n");
3761
    let c = repo.commit("C", &[]).unwrap();
3762
    write(root, "a.txt", b"1\n2\n3\n");
3763
    let e = repo.commit("E", &[]).unwrap();
3764
    write(root, "b.txt", b"b\n");
3765
    let b = repo.commit("B", &[]).unwrap();
3766
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3767
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3768
    // E depends on C which A lacks: refused, naming it.
3769
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3770
    assert!(err.contains(&c.short(12)), "{err}");
3771
    // C into A: A' has both, C is gone, E follows and still reads the same.
3772
    let a2 = repo.squash(&c, &a).unwrap();
3773
    let a2c = repo.store().get_change(&a2).unwrap();
3774
    assert_eq!(a2c.change_id, id_a);
3775
    assert!(a2c.deps.is_empty());
3776
    let heads = repo.bookmark_heads().unwrap();
3777
    let st = repo.load_state(&heads).unwrap();
3778
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
3779
    let e2 = st
3780
        .changes()
3781
        .find(|(_, m)| m.change_id == id_e)
3782
        .map(|(h, _)| *h)
3783
        .unwrap();
3784
    assert_eq!(
3785
        repo.store().get_change(&e2).unwrap().deps,
3786
        vec![a2],
3787
        "E now depends on A' alone"
3788
    );
3789
    let files = st.materialize().files;
3790
    assert!(
3791
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3792
    );
3793
    assert!(files.contains_key("b.txt"));
3794
    assert!(st.contains(&b));
3795
    assert!(!repo.snapshot("status").unwrap().changed);
3796
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3797
    // Undo restores the three original changes.
3798
    repo.undo().unwrap();
3799
    repo.undo().unwrap();
3800
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3801
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3802
}
3803
3804
#[test]
3805
fn rebase_re_expresses_a_change_against_another_base() {
3806
    hermetic();
3807
    let dir = tempfile::tempdir().unwrap();
3808
    let root = dir.path();
3809
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3810
    write(root, "a.txt", b"1\n2\n");
3811
    let a = repo.commit("A", &[]).unwrap();
3812
    write(root, "a.txt", b"1\n2\n3\n");
3813
    let c = repo.commit("C: append 3", &[]).unwrap();
3814
    write(root, "a.txt", b"1\n2\n3\n4\n");
3815
    let e = repo.commit("E: append 4", &[]).unwrap();
3816
    // A different base: A plus a change that prepends a line.
3817
    repo.checkout(&[a], true, "checkout").unwrap();
3818
    write(root, "a.txt", b"0\n1\n2\n");
3819
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3820
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3821
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3822
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3823
    let c2 = repo.rebase(&c, &[d]).unwrap();
3824
    let c2c = repo.store().get_change(&c2).unwrap();
3825
    assert_eq!(c2c.change_id, id_c);
3826
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3827
    let heads = repo.bookmark_heads().unwrap();
3828
    let st = repo.load_state(&heads).unwrap();
3829
    assert!(!st.contains(&c) && st.contains(&d));
3830
    let e2 = st
3831
        .changes()
3832
        .find(|(_, m)| m.change_id == id_e)
3833
        .map(|(h, _)| *h)
3834
        .unwrap();
3835
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
3836
    assert!(
3837
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3838
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3839
    );
3840
    let files = st.materialize().files;
3841
    assert!(
3842
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3843
        "{:?}",
3844
        files["a.txt"].content
3845
    );
3846
    assert!(!files["a.txt"].is_conflicted());
3847
    // Rebasing onto a state that already contains the change is refused.
3848
    assert!(repo.rebase(&c2, &[c2]).is_err());
3849
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
3850
    assert!(
3851
        err.contains("lacks dependencies"),
3852
        "E needs C, which D's state does not have: {err}"
3853
    );
3854
}
3855
3856
#[test]
3857
fn unsigned_tags_keep_their_message() {
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"a\n");
3863
    repo.commit("a", &[]).unwrap();
3864
    assert!(repo.secret_key().unwrap().is_none());
3865
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
3866
        .unwrap();
3867
    let tags = repo.tags().unwrap();
3868
    assert_eq!(
3869
        (
3870
            tags[0].name.as_str(),
3871
            tags[0].message.as_str(),
3872
            tags[0].signer.as_deref()
3873
        ),
3874
        ("v1", "first release", None)
3875
    );
3876
    assert!(
3877
        repo.tag_refs().unwrap()[0].attestation.is_none(),
3878
        "an unsigned attestation is not advertised"
3879
    );
3880
}