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