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