OXYGENHUB
# 4dee277c327a oxygen / crates / oxy-core / src / repo / tests.rs
117.5 KiB · Rust · last changed Subrepositories: subrepo node kind with Oxygen and Git pins, .oxymodules, nested repositories skipped by the walker and moved by checkout, oxy submodule add|update|status|remove, Git gitlink import and export (spec 0.8 section 7.8) 1 month ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
use crate::protocol::SignedPolicy;
5
6
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
7
/// test reads or writes the developer's real user configuration or keys.
8
fn hermetic() {
9
    static ONCE: std::sync::Once = std::sync::Once::new();
10
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
11
    ONCE.call_once(|| {
12
        let d = tempfile::tempdir().unwrap();
13
        std::env::set_var("OXY_HOME", d.path());
14
        DIR.set(d).ok();
15
    });
16
}
17
18
fn write(root: &Path, rel: &str, content: &[u8]) {
19
    let p = root.join(rel);
20
    fs::create_dir_all(p.parent().unwrap()).unwrap();
21
    fs::write(p, content).unwrap();
22
}
23
24
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
25
    s.statuses.iter().map(|p| (p.path.clone(), p.status)).collect()
26
}
27
28
#[test]
29
fn init_snapshot_commit_log_undo() {
30
    hermetic();
31
    let dir = tempfile::tempdir().unwrap();
32
    let root = dir.path();
33
    let repo = Repo::init(root).unwrap();
34
    assert!(Repo::init(root).is_err());
35
    let ops = repo.op_log().unwrap();
36
    assert_eq!(ops.len(), 1);
37
    assert_eq!(ops[0].1.command, "oxy init");
38
39
    // Empty working copy: snapshot records no operation (spec §12.3).
40
    let s = repo.snapshot("oxy status").unwrap();
41
    assert!(!s.changed);
42
    assert_eq!(repo.op_log().unwrap().len(), 1);
43
44
    write(root, "src/main.rs", b"fn main() {}\n");
45
    write(root, "README.md", b"# Hello\n");
46
    write(root, ".oxyignore", b"/target\n");
47
    write(root, "target/junk.o", b"\0\0\0");
48
    let s = repo.snapshot("oxy status").unwrap();
49
    assert!(s.changed);
50
    assert_eq!(
51
        statuses(&s),
52
        vec![
53
            (".oxyignore".into(), ChangeStatus::Added),
54
            ("README.md".into(), ChangeStatus::Added),
55
            ("src/main.rs".into(), ChangeStatus::Added),
56
        ]
57
    );
58
    assert_eq!(repo.op_log().unwrap().len(), 2);
59
    // Snapshotting again with nothing changed records no op.
60
    let s2 = repo.snapshot("oxy status").unwrap();
61
    assert!(!s2.changed);
62
    assert_eq!(s2.wc_hash, s.wc_hash);
63
    assert_eq!(repo.op_log().unwrap().len(), 2);
64
65
    let h1 = repo.commit("Initial import", &[]).unwrap();
66
    let c1 = repo.store().get_change(&h1).unwrap();
67
    assert_eq!(c1.kind, ChangeKind::Normal);
68
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
69
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
70
    let (wc_hash, wc) = repo.working_copy().unwrap();
71
    assert_eq!(wc.deps, vec![h1]);
72
    assert!(wc.edits.is_empty());
73
    assert!(repo.commit("nothing", &[]).is_err());
74
75
    // Modify one file, remove another, add a binary file.
76
    write(root, "src/main.rs", b"fn main() {\n    println!(\"hi\");\n}\n");
77
    fs::remove_file(root.join("README.md")).unwrap();
78
    write(root, "logo.png", b"\x89PNG\0\0\x01");
79
    let s = repo.snapshot("oxy status").unwrap();
80
    assert_eq!(
81
        statuses(&s),
82
        vec![
83
            ("README.md".into(), ChangeStatus::Removed),
84
            ("logo.png".into(), ChangeStatus::Added),
85
            ("src/main.rs".into(), ChangeStatus::Modified),
86
        ]
87
    );
88
    assert_ne!(s.wc_hash, wc_hash);
89
    // The rewritten working copy keeps its ChangeId and depends on h1.
90
    assert_eq!(s.wc.change_id, wc.change_id);
91
    assert!(s.wc.deps.contains(&h1));
92
93
    let h2 = repo.commit("Second", &[]).unwrap();
94
    let c2 = repo.store().get_change(&h2).unwrap();
95
    assert_eq!(c2.deps, vec![h1], "everything it touches was introduced by h1");
96
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
97
98
    // The materialized head state matches the working copy.
99
    let st = repo.load_state(&[h2]).unwrap();
100
    let snap = st.materialize();
101
    assert!(!snap.is_conflicted());
102
    assert_eq!(snap.files.keys().cloned().collect::<Vec<_>>(), [".oxyignore", "logo.png", "src", "src/main.rs"]);
103
    assert!(matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n"));
104
    assert!(snap.files["logo.png"].mode.opaque);
105
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
106
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
107
    } else {
108
        panic!("logo should be opaque");
109
    }
110
111
    // Log: newest first, working copy included.
112
    let log = repo.log().unwrap();
113
    assert_eq!(log.len(), 3);
114
    assert!(log[0].is_working_copy);
115
    assert_eq!(log[1].hash, h2);
116
    assert!(log[1].is_head);
117
    assert_eq!(log[2].hash, h1);
118
    let d = repo.describe_change(&h2).unwrap();
119
    assert!(d.contains("D README.md"), "{d}");
120
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
121
    assert!(d.contains("-fn main() {}"), "{d}");
122
123
    // Resolution by prefix.
124
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
125
    assert_eq!(repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(), h1);
126
    assert!(repo.resolve_change("zzzz").is_err());
127
128
    // Undo the commit: bookmark and working copy go back.
129
    repo.undo().unwrap();
130
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
131
    let s = repo.snapshot("oxy status").unwrap();
132
    assert!(!s.changed, "files on disk still match the pre-commit working copy");
133
    assert_eq!(s.statuses.len(), 3);
134
}
135
136
/// Make `main` conflicted: two commits on the same base that edit the same line.
137
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
138
    let dir = tempfile::tempdir().unwrap();
139
    let root = dir.path();
140
    let repo = Repo::init(root).unwrap();
141
    write(root, "f.txt", b"a\nb\nc\n");
142
    let h1 = repo.commit("base", &[]).unwrap();
143
    write(root, "f.txt", b"a\nB\nc\n");
144
    let h2 = repo.commit("upper", &[]).unwrap();
145
    repo.checkout(&[h1], false, "checkout").unwrap();
146
    write(root, "f.txt", b"a\nX\nc\n");
147
    let h3 = repo.commit("ex", &[]).unwrap();
148
    (dir, repo, h1, h2, h3)
149
}
150
151
#[test]
152
fn concurrent_edits_conflict_and_can_be_resolved() {
153
    hermetic();
154
    let (dir, repo, h1, h2, h3) = conflicted_repo();
155
    let root = dir.path();
156
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
157
    assert_eq!(heads, [h2, h3].into_iter().collect());
158
    let st = repo.load_state(&[h2, h3]).unwrap();
159
    assert!(st.materialize().is_conflicted());
160
161
    // Checking out main writes markers.
162
    let r = repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main").unwrap();
163
    assert!(r.conflicted);
164
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
165
    assert!(marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"), "{marked}");
166
    assert!(marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"), "{marked}");
167
    assert!(has_conflict_markers(marked.as_bytes()));
168
    // Untouched markers: clean working copy; commit has nothing to do.
169
    let s = repo.snapshot("status").unwrap();
170
    assert!(s.statuses.is_empty());
171
    assert!(!s.resolves);
172
173
    // Partially edited file that still has markers cannot be committed.
174
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
175
    let s = repo.snapshot("status").unwrap();
176
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::ConflictEdited)]);
177
    assert!(repo.commit("no", &[]).is_err());
178
179
    // Resolve by keeping one side and adding a line elsewhere.
180
    write(root, "f.txt", b"a\nX\nc\nd\n");
181
    let s = repo.snapshot("status").unwrap();
182
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
183
    assert!(s.resolves);
184
    let h4 = repo.commit("resolve", &[]).unwrap();
185
    let c4 = repo.store().get_change(&h4).unwrap();
186
    assert_eq!(c4.kind, ChangeKind::Resolution);
187
    let mut want = vec![h1, h2, h3];
188
    want.sort();
189
    assert_eq!(c4.deps, want, "a resolution depends on exactly the contributors and what it references");
190
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
191
    let snap = repo.load_state(&[h4]).unwrap().materialize();
192
    assert!(!snap.is_conflicted());
193
    assert!(matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n"));
194
    assert!(!repo.snapshot("status").unwrap().changed);
195
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
196
    // whatever order the changes arrive in.
197
    let mut st = State::new();
198
    for h in [h4, h3, h1, h2] {
199
        st.add_unchecked(repo.store().get_change(&h).unwrap());
200
    }
201
    st.validate().unwrap();
202
    assert!(matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n"));
203
}
204
205
#[test]
206
fn resolution_may_keep_both_sides_or_neither() {
207
    hermetic();
208
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
209
    let root = dir.path();
210
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main").unwrap();
211
    // Keep both sides in a chosen order.
212
    write(root, "f.txt", b"a\nX\nB\nc\n");
213
    let h = repo.commit("both", &[]).unwrap();
214
    let snap = repo.load_state(&[h]).unwrap().materialize();
215
    assert!(!snap.is_conflicted());
216
    assert!(matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n"));
217
    // Undo and instead drop the whole region.
218
    repo.undo().unwrap();
219
    write(root, "f.txt", b"a\nc\n");
220
    let h = repo.commit("neither", &[]).unwrap();
221
    let snap = repo.load_state(&[h]).unwrap().materialize();
222
    assert!(!snap.is_conflicted());
223
    assert!(matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n"));
224
}
225
226
#[test]
227
fn name_conflict_resolved_by_removing_a_candidate() {
228
    hermetic();
229
    let dir = tempfile::tempdir().unwrap();
230
    let root = dir.path();
231
    let repo = Repo::init(root).unwrap();
232
    write(root, "keep.txt", b"k\n");
233
    let h1 = repo.commit("base", &[]).unwrap();
234
    write(root, "new.txt", b"one\n");
235
    repo.commit("one", &[]).unwrap();
236
    repo.checkout(&[h1], false, "checkout").unwrap();
237
    write(root, "new.txt", b"two\n");
238
    repo.commit("two", &[]).unwrap();
239
    let r = repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main").unwrap();
240
    assert!(r.conflicted);
241
    assert!(root.join("new.txt.oxy-conflict-1").exists() && root.join("new.txt.oxy-conflict-2").exists());
242
    assert!(!root.join("new.txt").exists());
243
    // Candidate numbering follows change-hash order, so pick by content:
244
    // keep the "two" candidate under the real name and drop the other.
245
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" { (1, 2) } else { (2, 1) };
246
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
247
    fs::rename(root.join(format!("new.txt.oxy-conflict-{keep}")), root.join("new.txt")).unwrap();
248
    let h = repo.commit("pick two", &[]).unwrap();
249
    assert_eq!(repo.store().get_change(&h).unwrap().kind, ChangeKind::Resolution);
250
    // The resolution does not touch keep.txt, so it does not depend on h1;
251
    // the bookmark keeps both as heads and their union is the state.
252
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
253
    assert_eq!(heads, [h1, h].into_iter().collect());
254
    let snap = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap().materialize();
255
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
256
    assert_eq!(snap.files.keys().cloned().collect::<Vec<_>>(), ["keep.txt", "new.txt"]);
257
    assert!(matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n"));
258
}
259
260
#[test]
261
fn identities_and_signed_commits() {
262
    hermetic();
263
    let dir = tempfile::tempdir().unwrap();
264
    let root = dir.path();
265
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
266
    write(root, "a.txt", b"a\n");
267
    let h0 = repo.commit("unsigned", &[]).unwrap();
268
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
269
    assert_eq!(repo.store().get_change(&h0).unwrap().author, ObjectRef::ZERO);
270
271
    let (key, id) = repo.create_identity("Ada", "[email protected]", IdentityScope::Repo).unwrap();
272
    assert_eq!(id.hash(), key);
273
    assert_eq!(repo.config.author_key, Some(key));
274
    // Config survives reopen; the secret key is found again.
275
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
276
    assert_eq!(reopened.config.author_key, Some(key));
277
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
278
279
    // Default core.sign = seal: commits carry the author but no signature.
280
    write(root, "a.txt", b"a\nb\n");
281
    let h1 = repo.commit("authored", &[]).unwrap();
282
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
283
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
284
    // Signing later works too.
285
    repo.sign_change(&h1).unwrap();
286
    assert!(matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key));
287
288
    repo.config.set("core.sign", "change").unwrap();
289
    repo.save_config().unwrap();
290
    write(root, "a.txt", b"a\nb\nc\n");
291
    let h2 = repo.commit("signed", &[]).unwrap();
292
    assert_eq!(repo.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, name: "Ada".into(), email: "[email protected]".into(), sealed: false, revoked: false });
293
294
    // A signature by a key that is not the author or a delegate is rejected.
295
    let other = SecretKey::generate();
296
    let other_id = other.identity("Mallory", "[email protected]", 0);
297
    let other_key = repo.store().put_identity(&other_id).unwrap();
298
    let forged = other.sign(Domain::Change, &other_key, &h0);
299
    repo.store().put_signature(&h0, &forged).unwrap();
300
    assert!(matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author")));
301
302
    // Tampering with the stored signature invalidates it.
303
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
304
    sig.ed[0] ^= 1;
305
    repo.store().put_signature(&h2, &sig).unwrap();
306
    assert!(matches!(repo.verify_change(&h2).unwrap(), SignatureStatus::Invalid(_)));
307
308
    // Without the secret key, signing at commit fails cleanly.
309
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
310
    write(root, "a.txt", b"z\n");
311
    assert!(no_keys.commit("cannot sign", &[]).is_err());
312
}
313
314
#[test]
315
fn checkout_moves_the_working_copy() {
316
    hermetic();
317
    let dir = tempfile::tempdir().unwrap();
318
    let root = dir.path();
319
    let repo = Repo::init(root).unwrap();
320
    write(root, "a.txt", b"one\n");
321
    write(root, "sub/deep/b.txt", b"b\n");
322
    let h1 = repo.commit("first", &[]).unwrap();
323
    write(root, "a.txt", b"two\n");
324
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
325
    write(root, "bin.dat", &[0, 1, 2, 3]);
326
    let h2 = repo.commit("second", &[]).unwrap();
327
328
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
329
    assert_eq!(r, CheckoutReport { written: 2, removed: 1, conflicted: false, notes: vec![] });
330
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
331
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
332
    assert!(!root.join("bin.dat").exists());
333
    let (_, wc) = repo.working_copy().unwrap();
334
    assert_eq!(wc.deps, vec![h1]);
335
    assert!(!repo.snapshot("status").unwrap().changed, "checkout leaves a clean working copy");
336
    // The bookmark still points at h2.
337
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
338
339
    // Dirty working copy refuses without --discard.
340
    write(root, "a.txt", b"dirty\n");
341
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
342
    let r = repo.checkout(&[h2], true, "oxy checkout --discard").unwrap();
343
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
344
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
345
    assert!(!root.join("sub").exists(), "empty directories are pruned");
346
    assert_eq!(r.removed, 1);
347
    assert!(!repo.snapshot("status").unwrap().changed);
348
349
    // Refuses to write through a symlinked directory.
350
    #[cfg(unix)]
351
    {
352
        fs::remove_dir_all(root.join("sub")).ok();
353
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
354
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
355
    }
356
}
357
358
#[test]
359
fn large_files_are_chunked_and_read_back() {
360
    hermetic();
361
    let dir = tempfile::tempdir().unwrap();
362
    let repo = Repo::init(dir.path()).unwrap();
363
    let mut big = vec![0u8; 700 * 1024];
364
    for (i, b) in big.iter_mut().enumerate() {
365
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
366
    }
367
    let r = repo.store_blob(&big).unwrap();
368
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
369
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
370
    assert_eq!(repo.read_blob(&r).unwrap(), big);
371
    assert_eq!(Repo::blob_ref(&big), r);
372
}
373
374
#[test]
375
fn clone_push_pull_with_seals_and_attestations() {
376
    hermetic();
377
    let dir = tempfile::tempdir().unwrap();
378
    let root = dir.path();
379
    let origin_path = root.join("origin");
380
    let origin = Repo::init(&origin_path).unwrap();
381
    let origin_url = origin_path.to_string_lossy().to_string();
382
383
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
384
    let mut a = Repo::clone(&origin_url, &root.join("a")).unwrap().with_home(root.join("home-a"));
385
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
386
    let (key_a, _) = a.create_identity("Ada", "[email protected]", IdentityScope::Repo).unwrap();
387
    write(&root.join("a"), "f.txt", b"a\n");
388
    let h1 = a.commit("first", &[]).unwrap();
389
    let results = a.push("origin", false).unwrap();
390
    assert!(results[0].ok, "{}", results[0].reason);
391
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
392
    // The change was sealed at push and the reference attested.
393
    assert!(matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a));
394
    assert_eq!(origin.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
395
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
396
    assert!(matches!(att.attest.body, AttestBody::Ref { serial: 1, .. }));
397
    let again = a.push("origin", false).unwrap();
398
    assert!(again[0].ok && again[0].reason.contains("up to date"));
399
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
400
    assert!(matches!(att.attest.body, AttestBody::Ref { serial: 1, .. }), "a no-op push does not attest again");
401
402
    // B clones and sees the file and the seal.
403
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
404
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
405
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
406
    assert!(matches!(b.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { sealed: true, .. }));
407
408
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
409
    write(&root.join("b"), "f.txt", b"a\nb\n");
410
    let h2 = b.commit("second", &[]).unwrap();
411
    assert!(b.push("origin", false).unwrap()[0].ok);
412
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
413
414
    // A commits an independent change; push is refused until A pulls.
415
    write(&root.join("a"), "g.txt", b"g\n");
416
    let h3 = a.commit("third", &[]).unwrap();
417
    assert!(a.push("origin", false).is_err());
418
    let pr = a.pull("origin").unwrap();
419
    assert!(pr.changed && pr.checked_out);
420
    let mut want = vec![h2, h3];
421
    want.sort();
422
    assert_eq!(pr.heads, want);
423
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
424
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
425
    let results = a.push("origin", false).unwrap();
426
    assert!(results[0].ok, "{}", results[0].reason);
427
    let mut origin_heads = origin.bookmark_heads().unwrap();
428
    origin_heads.sort();
429
    assert_eq!(origin_heads, want);
430
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
431
    assert!(matches!(att.attest.body, AttestBody::Ref { serial: 2, .. }));
432
433
    // B pulls and ends up identical.
434
    let pr = b.pull("origin").unwrap();
435
    assert_eq!(pr.heads, want);
436
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
437
    assert!(!b.snapshot("status").unwrap().changed);
438
439
    // Concurrent edits of the same line: the union is a reified conflict.
440
    write(&root.join("a"), "f.txt", b"a\nA\n");
441
    a.commit("a-edit", &[]).unwrap();
442
    a.push("origin", false).unwrap();
443
    write(&root.join("b"), "f.txt", b"a\nB\n");
444
    b.commit("b-edit", &[]).unwrap();
445
    let pr = b.pull("origin").unwrap();
446
    assert!(pr.changed && pr.checked_out);
447
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
448
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
449
    write(&root.join("b"), "f.txt", b"a\nAB\n");
450
    let hr = b.commit("resolve", &[]).unwrap();
451
    assert_eq!(b.store().get_change(&hr).unwrap().kind, ChangeKind::Resolution);
452
    assert!(b.push("origin", false).unwrap()[0].ok);
453
    a.pull("origin").unwrap();
454
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
455
    // The resolution depends on the conflicting edits, but nothing depends
456
    // on "third" (it only added g.txt), so it stays a head beside it.
457
    let mut want = vec![hr, h3];
458
    want.sort();
459
    assert_eq!(a.bookmark_heads().unwrap(), want);
460
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
461
}
462
463
#[test]
464
fn receive_push_rejects_bad_updates() {
465
    hermetic();
466
    let dir = tempfile::tempdir().unwrap();
467
    let root = dir.path();
468
    let origin = Repo::init(&root.join("origin")).unwrap();
469
    let url = root.join("origin").to_string_lossy().to_string();
470
    let mut a = Repo::clone(&url, &root.join("a")).unwrap().with_home(root.join("home"));
471
    let (key, _) = a.create_identity("Ada", "a@b", IdentityScope::Repo).unwrap();
472
    write(&root.join("a"), "f.txt", b"x\n");
473
    let h1 = a.commit("one", &[]).unwrap();
474
    assert!(a.push("origin", false).unwrap()[0].ok);
475
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
476
    let s1 = origin.store().put_state(&StateObject::new(vec![h1])).unwrap();
477
478
    // Missing head.
479
    let ghost = origin.store().put_state(&StateObject::new(vec![ObjectRef([9; 32])])).unwrap();
480
    let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: s1, new_state: ghost, force: false, attestation: None }], None, vec![]).unwrap();
481
    assert!(!r[0].ok && r[0].reason.contains("missing"), "{}", r[0].reason);
482
483
    // Stale old_state.
484
    let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: empty, new_state: s1, force: false, attestation: None }], None, vec![]).unwrap();
485
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
486
487
    // Non-fast-forward without force is refused; with force it passes.
488
    let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: s1, new_state: empty, force: false, attestation: None }], None, vec![]).unwrap();
489
    assert!(!r[0].ok && r[0].reason.contains("fast-forward"), "{}", r[0].reason);
490
    let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: s1, new_state: empty, force: true, attestation: None }], None, vec![]).unwrap();
491
    assert!(r[0].ok);
492
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
493
494
    // Attestation with a stale serial is a rollback and is refused.
495
    let sa = a.sign_attest(&Attest { repo: a.id().unwrap(), hlc: Hlc::now(), body: AttestBody::Ref { name: "main".into(), old_state: empty, new_state: s1, serial: 1 } }).unwrap();
496
    let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: empty, new_state: s1, force: false, attestation: Some(sa.clone()) }], None, vec![]).unwrap();
497
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{}", r[0].reason);
498
    // An attestation for a different update is refused too.
499
    let sa2 = a.sign_attest(&Attest { repo: a.id().unwrap(), hlc: Hlc::now(), body: AttestBody::Ref { name: "main".into(), old_state: s1, new_state: empty, serial: 5 } }).unwrap();
500
    let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: empty, new_state: s1, force: false, attestation: Some(sa2) }], None, vec![]).unwrap();
501
    assert!(!r[0].ok && r[0].reason.contains("describe"), "{}", r[0].reason);
502
    let _ = key;
503
}
504
505
#[test]
506
fn user_config_supplies_defaults_and_clones_sign() {
507
    hermetic();
508
    let dir = tempfile::tempdir().unwrap();
509
    let root = dir.path();
510
    let home = root.join("home");
511
    let origin = Repo::init(&root.join("origin")).unwrap();
512
    let url = root.join("origin").to_string_lossy().to_string();
513
514
    // Identity at user scope: the repository file stays free of author keys.
515
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
516
    let (key, _) = a.create_identity("Ada", "[email protected]", IdentityScope::User).unwrap();
517
    assert!(!a.config.repo_layer().contains_key("author.key"));
518
    assert_eq!(a.config.author_key, Some(key));
519
    assert!(home.join("config.toml").exists());
520
    a.set_user_config("core.sign", "change").unwrap();
521
    assert!(a.config.sign_changes);
522
523
    // Repository settings override user settings and are the only ones saved.
524
    a.config.set("core.sign", "seal").unwrap();
525
    a.save_config().unwrap();
526
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
527
    assert!(!again.config.sign_changes);
528
    assert_eq!(again.config.author_key, Some(key));
529
    assert_eq!(read_config_file(&root.join("a/.oxy/config")).unwrap().get("core.sign").map(String::as_str), Some("seal"));
530
531
    // A fresh clone made by this user signs with the user-level identity,
532
    // even though the clone's store has never seen the identity object.
533
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
534
    assert!(b.config.sign_changes);
535
    write(&root.join("b"), "f.txt", b"f\n");
536
    let h = b.commit("signed from a clone", &[]).unwrap();
537
    assert!(matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key));
538
    assert!(b.push("origin", false).unwrap()[0].ok);
539
    assert!(matches!(origin.verify_change(&h).unwrap(), SignatureStatus::Valid { .. }));
540
}
541
542
#[test]
543
fn format1_repositories_are_migrated_on_open() {
544
    hermetic();
545
    use crate::oplog::{Format1Op, Format1View};
546
    let dir = tempfile::tempdir().unwrap();
547
    let root = dir.path();
548
    let repo = Repo::init(root).unwrap();
549
    write(root, "a.txt", b"a\n");
550
    let h1 = repo.commit("one", &[]).unwrap();
551
    let (wc_hash, _) = repo.working_copy().unwrap();
552
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
553
    let mut v1 = Format1View::default();
554
    v1.bookmarks.insert("main".into(), vec![]);
555
    v1.workspaces.insert(repo.workspace(), wc_hash);
556
    let init = Format1Op { parents: vec![], hlc: Hlc::default(), command: "oxy init".into(), view: v1.clone() };
557
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
558
    v1.bookmarks.insert("main".into(), vec![h1]);
559
    let commit = Format1Op { parents: vec![init_ref], hlc: Hlc::default(), command: "oxy commit".into(), view: v1 };
560
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
561
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
562
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
563
    drop(repo);
564
565
    let repo = Repo::open(root).unwrap();
566
    assert_eq!(fs::read_to_string(root.join(".oxy/format")).unwrap(), FORMAT_LINE);
567
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
568
    let ops = repo.op_log().unwrap();
569
    assert_eq!(ops.iter().map(|(_, o)| o.command.as_str()).collect::<Vec<_>>(), ["oxy commit", "oxy init"]);
570
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
571
    assert!(!repo.snapshot("status").unwrap().changed);
572
    // Reopening again is a no-op.
573
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
574
}
575
576
#[test]
577
fn undo_skips_snapshot_operations() {
578
    hermetic();
579
    let dir = tempfile::tempdir().unwrap();
580
    let root = dir.path();
581
    let repo = Repo::init(root).unwrap();
582
    write(root, "a.txt", b"a\n");
583
    let h1 = repo.commit("a", &[]).unwrap();
584
    // A later command snapshots new edits on top of the commit.
585
    write(root, "b.txt", b"b\n");
586
    let s = repo.snapshot("oxy status").unwrap();
587
    assert!(s.changed);
588
    assert!(repo.head_op().unwrap().1.is_snapshot());
589
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
590
    // Undo must undo the commit, not the snapshot.
591
    repo.undo().unwrap();
592
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
593
    let s = repo.snapshot("oxy status").unwrap();
594
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
595
    assert_eq!(paths, ["a.txt", "b.txt"], "both files are back in the working copy");
596
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
597
    // Only snapshots remain above `init`, so there is nothing left to undo.
598
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
599
    assert!(repo.undo().is_err());
600
}
601
602
#[test]
603
fn independent_changes_commute_and_make_multiple_heads() {
604
    hermetic();
605
    let dir = tempfile::tempdir().unwrap();
606
    let root = dir.path();
607
    let repo = Repo::init(root).unwrap();
608
    write(root, "a.txt", b"a\n");
609
    let h1 = repo.commit("a", &[]).unwrap();
610
    write(root, "b.txt", b"b\n");
611
    let h2 = repo.commit("b", &[]).unwrap();
612
    let c2 = repo.store().get_change(&h2).unwrap();
613
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
614
    let mut heads = repo.bookmark_heads().unwrap();
615
    heads.sort();
616
    let mut want = vec![h1, h2];
617
    want.sort();
618
    assert_eq!(heads, want);
619
    // Editing a.txt depends on h1 only.
620
    write(root, "a.txt", b"a\na2\n");
621
    let h3 = repo.commit("a2", &[]).unwrap();
622
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
623
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
624
    assert_eq!(heads, [h2, h3].into_iter().collect());
625
    // Explicit dependency.
626
    write(root, "c.txt", b"c\n");
627
    let h4 = repo.commit("c", &[h2]).unwrap();
628
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
629
}
630
631
#[test]
632
fn mode_change_and_text_binary_switch() {
633
    hermetic();
634
    let dir = tempfile::tempdir().unwrap();
635
    let root = dir.path();
636
    let repo = Repo::init(root).unwrap();
637
    write(root, "run.sh", b"#!/bin/sh\n");
638
    repo.commit("add script", &[]).unwrap();
639
    #[cfg(unix)]
640
    {
641
        use std::os::unix::fs::PermissionsExt;
642
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
643
        let s = repo.snapshot("status").unwrap();
644
        assert_eq!(statuses(&s), vec![("run.sh".into(), ChangeStatus::ModeChanged)]);
645
        let h = repo.commit("exec", &[]).unwrap();
646
        let snap = repo.load_state(&[h]).unwrap().materialize();
647
        assert!(snap.files["run.sh"].mode.exec);
648
    }
649
    // Text → binary → text.
650
    write(root, "run.sh", b"\0binary");
651
    let h = repo.commit("binary", &[]).unwrap();
652
    let snap = repo.load_state(&[h]).unwrap().materialize();
653
    assert!(snap.files["run.sh"].mode.opaque);
654
    write(root, "run.sh", b"text again\n");
655
    let h = repo.commit("text", &[]).unwrap();
656
    let snap = repo.load_state(&[h]).unwrap().materialize();
657
    assert!(!snap.files["run.sh"].mode.opaque);
658
    assert!(matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n"));
659
    assert!(!snap.is_conflicted());
660
}
661
662
#[test]
663
fn trust_policy_governs_pushes_and_fetches() {
664
    hermetic();
665
    let dir = tempfile::tempdir().unwrap();
666
    let root = dir.path();
667
    let origin = Repo::init(&root.join("origin")).unwrap();
668
    let url = root.join("origin").to_string_lossy().to_string();
669
670
    // A is the root. Before the policy, an unsigned push from B is fine.
671
    let mut a = Repo::clone(&url, &root.join("a")).unwrap().with_home(root.join("home-a"));
672
    let (key_a, _) = a.create_identity("Ada", "[email protected]", IdentityScope::User).unwrap();
673
    let mut b = Repo::clone(&url, &root.join("b")).unwrap().with_home(root.join("home-b"));
674
    write(&root.join("b"), "b.txt", b"b\n");
675
    b.commit("unsigned before policy", &[]).unwrap();
676
    assert!(b.push("origin", false).unwrap()[0].ok);
677
678
    // A creates the policy and pushes it; origin now enforces it.
679
    write(&root.join("a"), "a.txt", b"a\n");
680
    a.commit("a", &[]).unwrap();
681
    let sp = a.policy_init().unwrap();
682
    assert_eq!(sp.policy.serial, 1);
683
    a.pull("origin").unwrap();
684
    let results = a.push("origin", false).unwrap();
685
    assert!(results.iter().all(|r| r.ok), "{results:?}");
686
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
687
688
    // B pulls the policy. Without an identity B cannot push at all.
689
    b.pull("origin").unwrap();
690
    assert!(b.current_policy().unwrap().is_some(), "the policy arrived with the fetch");
691
    assert!(b.push("origin", false).is_err());
692
    // With an identity the policy does not list, the push is rejected by origin.
693
    let (key_b, id_b) = b.create_identity("Bob", "[email protected]", IdentityScope::User).unwrap();
694
    write(&root.join("b"), "b.txt", b"b2\n");
695
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
696
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
697
    let r = b.push("origin", false).unwrap();
698
    assert!(!r[0].ok && r[0].reason.contains("may not update"), "{:?}", r);
699
700
    // A grants B (identity handed over as a file) and publishes the policy.
701
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
702
    assert_eq!(sp.policy.serial, 2);
703
    let r = a.push("origin", false).unwrap();
704
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
705
    // B must fetch the new policy before pushing.
706
    assert!(b.push("origin", false).unwrap_or_else(|e| vec![RefResult { name: "main".into(), ok: false, reason: e.to_string() }]).iter().all(|x| !x.ok));
707
    b.pull("origin").unwrap();
708
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
709
    let r = b.push("origin", false).unwrap();
710
    assert!(r[0].ok, "{:?}", r);
711
    // Origin verified B's change under the policy.
712
    let heads = origin.bookmark_heads().unwrap();
713
    for h in &heads {
714
        let c = origin.store().get_change(h).unwrap();
715
        if c.author == key_b {
716
            origin.change_allowed(h, &origin.current_policy().unwrap().unwrap().1.policy, "main").unwrap();
717
        }
718
    }
719
720
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
721
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
722
    forged.serial = 3;
723
    forged.roots = vec![key_b];
724
    let fh = forged.hash();
725
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
726
    let forged = SignedPolicy { policy: forged, sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)] };
727
    let r = origin.receive_push(Bundle::default(), vec![], Some(forged), vec![]).unwrap();
728
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
729
    let stale = a.current_policy().unwrap().unwrap().1;
730
    let mut old = stale.clone();
731
    old.policy.serial = 1;
732
    let r = origin.receive_push(Bundle::default(), vec![], Some(old), vec![]).unwrap();
733
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
734
735
    // A revokes B; after B pulls the policy, B's pushes are refused again.
736
    a.pull("origin").unwrap();
737
    a.policy_revoke(&key_b).unwrap();
738
    let r = a.push("origin", false).unwrap();
739
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
740
    b.pull("origin").unwrap();
741
    write(&root.join("b"), "b.txt", b"b3\n");
742
    b.commit("b3", &[]).unwrap();
743
    let r = b.push("origin", false).unwrap();
744
    assert!(!r[0].ok, "{:?}", r);
745
746
    // A clone by a third party receives and verifies everything.
747
    let c = Repo::clone(&url, &root.join("c")).unwrap().with_home(root.join("home-c"));
748
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
749
    assert!(c.current_policy().unwrap().unwrap().1.policy.roots.contains(&key_a));
750
    assert!(!c.snapshot("status").unwrap().changed);
751
}
752
753
#[test]
754
fn gc_packs_objects_and_history_still_works() {
755
    hermetic();
756
    let dir = tempfile::tempdir().unwrap();
757
    let root = dir.path();
758
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
759
    repo.create_identity("Ada", "a@b", IdentityScope::User).unwrap();
760
    repo.set_user_config("core.sign", "change").unwrap();
761
    write(root, "a.txt", b"one\n");
762
    let h1 = repo.commit("one", &[]).unwrap();
763
    write(root, "a.txt", b"two\n");
764
    write(root, "big.bin", &vec![0u8; 100_000]);
765
    let h2 = repo.commit("two", &[]).unwrap();
766
    // Several snapshots leave superseded working-copy versions behind.
767
    for i in 0..5 {
768
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
769
        repo.snapshot("status").unwrap();
770
    }
771
    write(root, "a.txt", b"two\n");
772
    repo.snapshot("status").unwrap();
773
    let before = repo.store().list().unwrap();
774
    assert!(repo.store().loose_count().unwrap() > 0);
775
776
    // With the default retention every operation's view is a root: nothing prunes.
777
    let r = repo.gc(true).unwrap();
778
    assert_eq!(r.packed.objects, before.len());
779
    assert_eq!(r.pruned.objects, 0);
780
    assert_eq!(repo.store().loose_count().unwrap(), 0);
781
    assert_eq!(repo.store().list().unwrap(), before);
782
783
    // With zero retention only the current view is a root: superseded
784
    // working copies go, everything reachable stays.
785
    repo.config.set("core.op-retention", "0").unwrap();
786
    repo.save_config().unwrap();
787
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
788
    let r = repo.gc(true).unwrap();
789
    assert!(r.pruned.objects >= 5, "{r:?}");
790
    let after = repo.store().list().unwrap();
791
    assert!(after.len() < before.len());
792
    assert!(after.contains(&h1) && after.contains(&h2));
793
    for (_, op) in repo.op_log().unwrap() {
794
        assert!(!op.command.is_empty(), "operation objects are all kept");
795
    }
796
    // Everything still works from the pruned, packed store.
797
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
798
    assert!(matches!(repo.verify_change(&h2).unwrap(), SignatureStatus::Valid { .. }));
799
    assert_eq!(repo.log().unwrap().len(), 3);
800
    repo.checkout(&[h1], false, "checkout").unwrap();
801
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
802
    repo.checkout(&[h2], false, "checkout").unwrap();
803
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
804
    assert!(!repo.snapshot("status").unwrap().changed);
805
    // Grace period defers pruning of young garbage.
806
    write(root, "a.txt", b"three\n");
807
    repo.commit("three", &[]).unwrap();
808
    let r = repo.gc(false).unwrap();
809
    assert_eq!(r.pruned.objects, 0);
810
    assert!(r.pruned.deferred > 0);
811
    let r = repo.gc(true).unwrap();
812
    assert!(r.pruned.objects > 0);
813
    assert_eq!(repo.log().unwrap().len(), 4);
814
}
815
816
#[test]
817
fn describe_amend_abandon_heads() {
818
    hermetic();
819
    let dir = tempfile::tempdir().unwrap();
820
    let root = dir.path();
821
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
822
    repo.create_identity("Ada", "a@b", IdentityScope::User).unwrap();
823
    repo.set_user_config("core.sign", "change").unwrap();
824
    write(root, "a.txt", b"one\n");
825
    let h1 = repo.commit("first", &[]).unwrap();
826
    write(root, "a.txt", b"one\ntwo\n");
827
    let h2 = repo.commit("secnod", &[]).unwrap();
828
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
829
830
    // describe: same ChangeId, new hash, bookmark and working copy follow.
831
    let h2b = repo.describe(&h2, "second").unwrap();
832
    assert_ne!(h2b, h2);
833
    let c = repo.store().get_change(&h2b).unwrap();
834
    assert_eq!((c.change_id, c.message.as_str(), c.deps.clone()), (id2, "second", vec![h1]));
835
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
836
    assert!(matches!(repo.verify_change(&h2b).unwrap(), SignatureStatus::Valid { .. }));
837
    let s = repo.snapshot("status").unwrap();
838
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
839
    assert_eq!(repo.resolve_change(&id2.short(8)).unwrap(), h2b, "the old object is no longer reachable from the log");
840
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
841
    let h1b = repo.describe(&h1, "first, described").unwrap();
842
    assert_ne!(h1b, h1);
843
    let heads = repo.bookmark_heads().unwrap();
844
    assert_eq!(heads.len(), 1);
845
    let top = repo.store().get_change(&heads[0]).unwrap();
846
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
847
    assert!(matches!(repo.verify_change(&heads[0]).unwrap(), SignatureStatus::Valid { .. }), "rewritten own change is re-signed");
848
    let (_, wc) = repo.working_copy().unwrap();
849
    assert_eq!(wc.deps, vec![heads[0]], "the working copy follows the rewrite");
850
    assert!(!repo.snapshot("status").unwrap().changed);
851
    let snap = repo.load_state(&heads).unwrap().materialize();
852
    assert!(matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"));
853
854
    // amend: fold an edit into the head; the result is one change from h1.
855
    write(root, "a.txt", b"one\ntwo\nthree\n");
856
    write(root, "b.txt", b"b\n");
857
    let h2c = repo.amend(None).unwrap();
858
    let c = repo.store().get_change(&h2c).unwrap();
859
    assert_eq!(c.change_id, id2);
860
    assert_eq!(c.message, "second");
861
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
862
    assert_eq!(repo.log().unwrap().len(), 3, "working copy, amended head, first");
863
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
864
    assert!(matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n"));
865
    assert!(snap.files.contains_key("b.txt"));
866
    assert!(!repo.snapshot("status").unwrap().changed);
867
    assert!(repo.amend(None).is_err(), "clean working copy and no message");
868
    let h2d = repo.amend(Some("second, amended")).unwrap();
869
    assert_eq!(repo.store().get_change(&h2d).unwrap().message, "second, amended");
870
871
    // abandon: the head goes, its content stays as uncommitted work.
872
    repo.abandon(&h2d).unwrap();
873
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1b], "the described first change is the head again");
874
    let s = repo.snapshot("status").unwrap();
875
    let paths: Vec<_> = s.statuses.iter().map(|p| (p.path.as_str(), p.status)).collect();
876
    assert_eq!(paths, vec![("a.txt", ChangeStatus::Modified), ("b.txt", ChangeStatus::Added)]);
877
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
878
    let h3 = repo.commit("recommitted", &[]).unwrap();
879
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
880
    // undo brings the abandoned head back.
881
    repo.undo().unwrap();
882
    repo.undo().unwrap();
883
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
884
885
    // Abandoning a non-head whose dependent references its atoms reifies
886
    // the references (here: a.txt vanishes with it, so the dependent's edit
887
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
888
    let base = repo.bookmark_heads().unwrap()[0];
889
    let base_change = repo.store().get_change(&base).unwrap();
890
    let h1_now = base_change.deps[0];
891
    let notes = repo.abandon(&h1_now).unwrap();
892
    assert!(!notes.is_empty(), "the dependent's edit of a.txt was reified");
893
    let heads = repo.bookmark_heads().unwrap();
894
    let after = repo.load_state(&heads).unwrap().materialize();
895
    assert!(!after.files.contains_key("a.txt") && after.files.contains_key("b.txt"), "{:?}", after.files.keys());
896
    repo.undo().unwrap();
897
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
898
    write(root, "c.txt", b"c\n");
899
    let hc = repo.commit("c", &[]).unwrap();
900
    write(root, "d.txt", b"d\n");
901
    let hd = repo.commit("d", &[hc]).unwrap();
902
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
903
    repo.abandon(&hc).unwrap();
904
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
905
    assert!(!heads.contains(&hc));
906
    let d_now = heads.iter().find(|h| repo.store().get_change(h).unwrap().message == "d").copied().unwrap();
907
    assert!(repo.store().get_change(&d_now).unwrap().deps.is_empty(), "d inherited c's (empty) dependencies");
908
    let s = repo.snapshot("status").unwrap();
909
    assert_eq!(s.statuses.iter().map(|p| p.path.as_str()).collect::<Vec<_>>(), vec!["c.txt"], "c's content is now uncommitted work");
910
}
911
912
#[test]
913
fn git_export_mirrors_history() {
914
    hermetic();
915
    if std::process::Command::new("git").arg("--version").output().is_err() {
916
        eprintln!("git not installed; skipping");
917
        return;
918
    }
919
    let dir = tempfile::tempdir().unwrap();
920
    let root = dir.path();
921
    let mut repo = Repo::init(&root.join("r")).unwrap().with_home(root.join("home"));
922
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User).unwrap();
923
    let r = root.join("r");
924
    write(&r, "README.md", b"hello\n");
925
    write(&r, "src/main.rs", b"fn main() {}\n");
926
    let h1 = repo.commit("first", &[]).unwrap();
927
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
928
    write(&r, "logo.png", b"\x89PNG\0\0");
929
    let h2 = repo.commit("second", &[]).unwrap();
930
931
    let git_dir = root.join("mirror.git");
932
    let rep = repo.git_export(&git_dir).unwrap();
933
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
934
    let git = |args: &[&str]| -> String {
935
        let out = std::process::Command::new("git").arg("-C").arg(&git_dir).args(args).output().unwrap();
936
        assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
937
        String::from_utf8_lossy(&out.stdout).trim().to_string()
938
    };
939
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
940
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
941
    assert_eq!(git(&["show", "main:README.md"]), "hello");
942
    let body = git(&["log", "-1", "--format=%B", "main"]);
943
    assert!(body.contains(&format!("Oxy-Hash: {}", h2.to_hex())), "{body}");
944
    assert!(body.contains("Change-Id: "), "{body}");
945
    assert_eq!(git(&["log", "-1", "--format=%an <%ae>", "main"]), "Ada Lovelace <[email protected]>");
946
    assert_eq!(git(&["ls-tree", "--name-only", "main"]), "README.md\nlogo.png\nsrc");
947
948
    // Re-export is incremental.
949
    let rep = repo.git_export(&git_dir).unwrap();
950
    assert_eq!((rep.exported, rep.skipped), (0, 2));
951
952
    // An independent change makes two heads; the next state is one more
953
    // commit on the linear branch whose tree is the union.
954
    repo.checkout(&[h1], false, "checkout").unwrap();
955
    write(&r, "other.txt", b"o\n");
956
    let h3 = repo.commit("third", &[]).unwrap();
957
    let rep = repo.git_export(&git_dir).unwrap();
958
    assert_eq!((rep.exported, rep.heads), (1, 2));
959
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
960
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
961
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
962
    assert_eq!(git(&["show", "main:other.txt"]), "o");
963
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
964
    assert_eq!(git(&["ls-tree", "--name-only", "main"]), "README.md\nlogo.png\nother.txt\nsrc");
965
    let body = git(&["log", "-1", "--format=%B", "main"]);
966
    assert!(body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "), "{body}");
967
    // A rewrite is a new state whose one new change is the rewritten one.
968
    repo.describe(&h3, "third, described").unwrap();
969
    let rep = repo.git_export(&git_dir).unwrap();
970
    assert_eq!(rep.exported, 1);
971
    assert_eq!(git(&["log", "-1", "--format=%s", "main"]), "third, described");
972
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
973
    let _ = h2;
974
}
975
976
#[test]
977
fn git_import_reproduces_trees() {
978
    hermetic();
979
    if std::process::Command::new("git").arg("--version").output().is_err() {
980
        eprintln!("git not installed; skipping");
981
        return;
982
    }
983
    let dir = tempfile::tempdir().unwrap();
984
    let root = dir.path();
985
    let g = root.join("src.git");
986
    fs::create_dir_all(&g).unwrap();
987
    let git = |args: &[&str]| -> String {
988
        let out = std::process::Command::new("git")
989
            .arg("-C")
990
            .arg(&g)
991
            .args(["-c", "user.name=Grace", "-c", "[email protected]", "-c", "commit.gpgsign=false"])
992
            .args(args)
993
            .output()
994
            .unwrap();
995
        assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
996
        String::from_utf8_lossy(&out.stdout).trim().to_string()
997
    };
998
    git(&["init", "-q", "-b", "main"]);
999
    write(&g, "README.md", b"# Hi\n");
1000
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1001
    git(&["add", "."]);
1002
    git(&["commit", "-q", "-m", "initial"]);
1003
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1004
    write(&g, "run.sh", b"#!/bin/sh\n");
1005
    #[cfg(unix)]
1006
    {
1007
        use std::os::unix::fs::PermissionsExt;
1008
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1009
    }
1010
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1011
    git(&["add", "."]);
1012
    git(&["commit", "-q", "-m", "second\n\nChange-Id: 0123456789abcdef0123456789abcdef"]);
1013
    // A branch that edits README, merged back with a conflict-free merge.
1014
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1015
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1016
    git(&["commit", "-q", "-am", "readme"]);
1017
    git(&["checkout", "-q", "main"]);
1018
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1019
    // A branch from the initial commit inserting at the same place as
1020
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1021
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1022
    git(&["checkout", "-q", "-b", "clash", &initial]);
1023
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1024
    git(&["commit", "-q", "-am", "clash"]);
1025
    git(&["checkout", "-q", "main"]);
1026
    let _ = std::process::Command::new("git").arg("-C").arg(&g).args(["merge", "-q", "clash"]).output();
1027
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n");
1028
    git(&["add", "."]);
1029
    git(&["commit", "-q", "-m", "resolve clash"]);
1030
    git(&["rm", "-q", "logo.png"]);
1031
    git(&["commit", "-q", "-m", "drop logo"]);
1032
    // A rename with a small edit is imported as a move of the same node.
1033
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1034
    write(&g, "src/lib2.rs", b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n");
1035
    git(&["add", "."]);
1036
    git(&["commit", "-q", "-m", "rename lib"]);
1037
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1038
1039
    let dest = root.join("oxy");
1040
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1041
    let rep = repo.import_git(&g, "main").unwrap();
1042
    assert_eq!(rep.commits, expected_count);
1043
    assert_eq!(rep.merges, 2);
1044
    // The working copy equals the Git tree at main.
1045
    assert_eq!(fs::read(dest.join("src/lib2.rs")).unwrap(), b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n");
1046
    assert!(!dest.join("src/lib.rs").exists());
1047
    assert_eq!(fs::read(dest.join("README.md")).unwrap(), b"# Hi\n\nMore.\n");
1048
    assert!(!dest.join("logo.png").exists());
1049
    #[cfg(unix)]
1050
    {
1051
        use std::os::unix::fs::PermissionsExt;
1052
        assert!(fs::metadata(dest.join("run.sh")).unwrap().permissions().mode() & 0o111 != 0);
1053
    }
1054
    assert!(!repo.snapshot("status").unwrap().changed, "clean after import");
1055
    let heads = repo.bookmark_heads().unwrap();
1056
    let st = repo.load_state(&heads).unwrap();
1057
    assert!(!st.materialize().is_conflicted());
1058
    assert_eq!(st.len(), expected_count);
1059
    let tip = repo.log().unwrap().into_iter().find(|e| e.change.message.starts_with("rename lib")).unwrap();
1060
    let c = repo.store().get_change(&tip.hash).unwrap();
1061
    assert!(c.tree_ops.iter().any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")), "{:?}", c.tree_ops);
1062
    assert!(!c.tree_ops.iter().any(|op| matches!(op, TreeOp::AddNode { .. })));
1063
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1064
    let log = repo.log().unwrap();
1065
    let second = log.iter().find(|e| e.change.message.starts_with("second")).unwrap();
1066
    assert_eq!(second.change.change_id, ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap());
1067
    assert!(second.change.message.contains("Git-Author: Grace <[email protected]>"));
1068
    let resolve = log.iter().find(|e| e.change.message.starts_with("resolve clash")).unwrap();
1069
    assert_eq!(resolve.change.kind, ChangeKind::Resolution, "a conflicting Git merge becomes a resolution");
1070
    // Re-importing into another fresh repository gives the same ChangeIds.
1071
    let repo2 = Repo::init(&root.join("oxy2")).unwrap().with_home(root.join("home"));
1072
    repo2.import_git(&g, "main").unwrap();
1073
    let ids: BTreeSet<ChangeId> = repo.log().unwrap().iter().filter(|e| !e.is_working_copy).map(|e| e.change.change_id).collect();
1074
    let ids2: BTreeSet<ChangeId> = repo2.log().unwrap().iter().filter(|e| !e.is_working_copy).map(|e| e.change.change_id).collect();
1075
    assert_eq!(ids, ids2);
1076
    // Round trip back out to Git reproduces the tip tree.
1077
    let mirror = root.join("mirror.git");
1078
    repo.git_export(&mirror).unwrap();
1079
    let out = std::process::Command::new("git").arg("-C").arg(&mirror).args(["show", "main:src/lib2.rs"]).output().unwrap();
1080
    assert_eq!(String::from_utf8_lossy(&out.stdout), "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n");
1081
    let out = std::process::Command::new("git").arg("-C").arg(&mirror).args(["show", "main:src/lib.rs"]).output().unwrap();
1082
    assert!(!out.status.success(), "the old path is gone from the export");
1083
}
1084
1085
#[test]
1086
fn checkpoints_accelerate_loading_and_stay_correct() {
1087
    hermetic();
1088
    let dir = tempfile::tempdir().unwrap();
1089
    let root = dir.path();
1090
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1091
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1092
    repo.save_config().unwrap();
1093
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1094
    let mut hashes = Vec::new();
1095
    for i in 0..12 {
1096
        write(root, "a.txt", format!("{}\n", (0..=i).map(|k| k.to_string()).collect::<Vec<_>>().join("\n")).as_bytes());
1097
        write(root, &format!("f{i}.txt"), b"x\n");
1098
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1099
    }
1100
    let (_, cp) = repo.latest_checkpoint("main").unwrap().expect("automatic checkpoint");
1101
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1102
    // Loading through the checkpoint equals loading everything.
1103
    let heads = repo.bookmark_heads().unwrap();
1104
    let fast = repo.load_state(&heads).unwrap();
1105
    let full = repo.load_state_full(&heads).unwrap();
1106
    assert_eq!(fast.len(), full.len());
1107
    assert_eq!(fast.heads(), full.heads());
1108
    let (a, b) = (fast.materialize(), full.materialize());
1109
    assert_eq!(a.files.keys().collect::<Vec<_>>(), b.files.keys().collect::<Vec<_>>());
1110
    for (p, f) in &a.files {
1111
        assert_eq!(f.content, b.files[p].content, "{p}");
1112
    }
1113
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1114
    // A head set that does not contain the checkpoint's heads falls back.
1115
    assert!(repo.load_state_checkpointed(&[hashes[0]]).unwrap().is_none());
1116
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1117
    // Everything else keeps working on top of the checkpoint.
1118
    assert!(!repo.snapshot("status").unwrap().changed);
1119
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1120
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1121
    let (r, n, bytes) = repo.checkpoint().unwrap();
1122
    assert!(n >= 12 && bytes > 0);
1123
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1124
    write(root, "a.txt", b"after\n");
1125
    let h_after = repo.commit("after", &[]).unwrap();
1126
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1127
    assert!(st.contains(&h_after));
1128
    assert!(matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n"));
1129
    assert_eq!(repo.log().unwrap().len(), 14);
1130
    // Checkpoints survive gc.
1131
    repo.gc(true).unwrap();
1132
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1133
    assert!(repo.load_state_checkpointed(&repo.bookmark_heads().unwrap()).unwrap().is_some());
1134
}
1135
1136
#[test]
1137
fn quick_status_for_prompts() {
1138
    hermetic();
1139
    let dir = tempfile::tempdir().unwrap();
1140
    let root = dir.path();
1141
    let origin = Repo::init(&root.join("origin")).unwrap();
1142
    let url = root.join("origin").to_string_lossy().to_string();
1143
    let a = Repo::clone(&url, &root.join("a")).unwrap().with_home(root.join("home"));
1144
    let ops_before = a.op_log().unwrap().len();
1145
    let info = a.quick_status().unwrap();
1146
    assert_eq!((info.bookmark.as_str(), info.heads, info.dirty, info.conflicted, info.ahead, info.behind), ("main", 0, false, false, Some(0), Some(0)));
1147
    write(&root.join("a"), "f.txt", b"f\n");
1148
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1149
    assert_eq!(a.op_log().unwrap().len(), ops_before, "quick_status records nothing");
1150
    // A snapshotted but uncommitted change is still dirty.
1151
    a.snapshot("status").unwrap();
1152
    assert!(a.quick_status().unwrap().dirty);
1153
    a.commit("f", &[]).unwrap();
1154
    let info = a.quick_status().unwrap();
1155
    assert!(!info.dirty, "clean right after a commit");
1156
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
1157
    assert_eq!(info.format("%b %c%d%x%A%D"), format!("main {}+1", info.change_id));
1158
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1159
    // Touching a file without changing it is not dirty; changing content of
1160
    // the same size is.
1161
    let p = root.join("a/f.txt");
1162
    let content = fs::read(&p).unwrap();
1163
    fs::write(&p, &content).unwrap();
1164
    assert!(!a.quick_status().unwrap().dirty);
1165
    fs::write(&p, b"g\n").unwrap();
1166
    assert!(a.quick_status().unwrap().dirty);
1167
    fs::write(&p, b"f\n").unwrap();
1168
    // Push, then a second clone commits and pushes: we are behind.
1169
    assert!(a.push("origin", false).unwrap()[0].ok);
1170
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
1171
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(root.join("home-b"));
1172
    write(&root.join("b"), "g.txt", b"g\n");
1173
    b.commit("g", &[]).unwrap();
1174
    b.push("origin", false).unwrap();
1175
    a.fetch("origin").unwrap();
1176
    let info = a.quick_status().unwrap();
1177
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1178
    assert_eq!(info.format("%A%D"), "-1");
1179
    let _ = origin;
1180
}
1181
1182
#[test]
1183
fn lazy_blobs_are_fetched_on_first_read() {
1184
    hermetic();
1185
    let dir = tempfile::tempdir().unwrap();
1186
    let root = dir.path();
1187
    let origin_dir = root.join("origin");
1188
    let origin = Repo::init(&origin_dir).unwrap().with_home(root.join("home"));
1189
    let url = origin_dir.to_string_lossy().to_string();
1190
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1191
    write(&origin_dir, "big.bin", &big);
1192
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1193
    write(&origin_dir, "t.txt", b"t\n");
1194
    let h = origin.commit("blobs", &[]).unwrap();
1195
    let big_ref = Repo::blob_ref(&big);
1196
1197
    // Fetch only (no checkout) with a filter: the big blob stays absent.
1198
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap()).unwrap().with_home(root.join("home"));
1199
    let a = {
1200
        let mut a = a;
1201
        a.config.set("remote.origin.url", &url).unwrap();
1202
        a.config.set("filter.max-blob", "100K").unwrap();
1203
        a.save_config().unwrap();
1204
        a
1205
    };
1206
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1207
    a.fetch("origin").unwrap();
1208
    assert!(a.store().has(&h));
1209
    assert!(!a.store().has(&big_ref), "withheld");
1210
    assert!(a.store().has(&Repo::blob_ref(&[0u8, 1, 2])), "small blob came along");
1211
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1212
1213
    // status and commit do not need it: adopt the state, edit a text file, commit.
1214
    let (op_ref, op) = a.head_op().unwrap();
1215
    let mut view = op.view.clone();
1216
    view.bookmarks.insert("main".into(), a.store().put_state(&StateObject::new(vec![h])).unwrap());
1217
    a.record_op(&[op_ref], "adopt", view).unwrap();
1218
    // Checkout reads the blob lazily, which fetches it.
1219
    a.checkout(&[h], true, "checkout").unwrap();
1220
    assert!(a.store().has(&big_ref), "fetched on first read");
1221
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1222
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1223
    write(&root.join("a"), "t.txt", b"t2\n");
1224
    a.commit("text edit", &[]).unwrap();
1225
1226
    // clone --max-blob records the filter; the checkout fetches lazily.
1227
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
1228
    assert_eq!(b.config.max_blob, Some(1024));
1229
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1230
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1231
    assert!(parse_size("lots").is_err());
1232
}
1233
1234
#[test]
1235
fn sparse_checkout_materializes_only_chosen_paths() {
1236
    hermetic();
1237
    let dir = tempfile::tempdir().unwrap();
1238
    let root = dir.path();
1239
    let origin_dir = root.join("origin");
1240
    let origin = Repo::init(&origin_dir).unwrap().with_home(root.join("home"));
1241
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1242
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1243
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1244
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1245
    write(&origin_dir, "docs/logo.png", &logo);
1246
    write(&origin_dir, "README.md", b"# top\n");
1247
    let h1 = origin.commit("tree", &[]).unwrap();
1248
    let url = origin_dir.to_string_lossy().to_string();
1249
1250
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()]).unwrap().with_home(root.join("home"));
1251
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1252
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1253
    assert!(root.join("a/src/main.rs").exists());
1254
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
1255
    assert!(!a.store().has(&Repo::blob_ref(&logo)), "out-of-scope blob never fetched");
1256
    assert!(!a.snapshot("status").unwrap().changed, "out-of-scope files are not removals");
1257
    assert_eq!(a.quick_status().unwrap().dirty, false);
1258
1259
    // Edits in scope commit normally and keep the rest of the tree intact.
1260
    write(&root.join("a"), "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1261
    let h2 = a.commit("edit lib", &[]).unwrap();
1262
    let st = a.load_state(&[h2]).unwrap().materialize();
1263
    assert!(st.files.contains_key("docs/guide.md"), "the state still has everything");
1264
    assert!(a.push("origin", false).unwrap()[0].ok);
1265
    // Files created outside the scope are ignored by status.
1266
    write(&root.join("a"), "docs/new.md", b"ignored\n");
1267
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
1268
1269
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
1270
    let mut a = a;
1271
    a.config.set("filter.paths", "src,docs").unwrap();
1272
    a.save_config().unwrap();
1273
    let r = a.checkout(&a.bookmark_heads().unwrap(), true, "widen").unwrap();
1274
    assert!(r.written >= 2);
1275
    assert_eq!(fs::read(root.join("a/docs/logo.png")).unwrap(), logo, "now fetched lazily");
1276
    assert!(!root.join("a/README.md").exists());
1277
    // Origin sees the change made under a sparse checkout with the full tree intact.
1278
    origin.pull("origin").err();
1279
    let full = origin.load_state(&origin.bookmark_heads().unwrap()).unwrap().materialize();
1280
    assert!(matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n"));
1281
    assert!(full.files.contains_key("README.md"));
1282
    let _ = h1;
1283
}
1284
1285
#[test]
1286
fn shallow_clone_and_deepen() {
1287
    hermetic();
1288
    let dir = tempfile::tempdir().unwrap();
1289
    let root = dir.path();
1290
    let origin_dir = root.join("origin");
1291
    let origin = Repo::init(&origin_dir).unwrap().with_home(root.join("home"));
1292
    let mut hashes = Vec::new();
1293
    for i in 0..8 {
1294
        write(&origin_dir, "a.txt", format!("{}\n", (0..=i).map(|k| k.to_string()).collect::<Vec<_>>().join("\n")).as_bytes());
1295
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
1296
    }
1297
    let url = origin_dir.to_string_lossy().to_string();
1298
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[]).unwrap().with_home(root.join("home"));
1299
    assert!(a.is_shallow());
1300
    assert_eq!(fs::read_to_string(root.join("a/a.txt")).unwrap(), "0\n1\n2\n3\n4\n5\n6\n7\n");
1301
    assert!(a.store().has(&hashes[7]) && a.store().has(&hashes[5]), "three levels present");
1302
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
1303
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
1304
    assert_eq!(a.log().unwrap().len(), 9, "the log shows every change from the checkpoint's metadata");
1305
    assert!(!a.snapshot("status").unwrap().changed);
1306
    assert_eq!(a.quick_status().unwrap().heads, 1);
1307
1308
    // Work continues on top of the shallow history and pushes back.
1309
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
1310
    let h_new = a.commit("c8", &[]).unwrap();
1311
    assert!(a.push("origin", false).unwrap()[0].ok);
1312
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
1313
    // Fetching new work from origin into the shallow clone works too.
1314
    write(&origin_dir, "b.txt", b"b\n");
1315
    origin.pull("origin").err();
1316
    let (_, wc) = origin.working_copy().unwrap();
1317
    let _ = wc;
1318
    origin.checkout(&origin.bookmark_heads().unwrap(), true, "co").unwrap();
1319
    write(&origin_dir, "b.txt", b"b\n");
1320
    let h_b = origin.commit("b", &[]).unwrap();
1321
    let pr = a.pull("origin").unwrap();
1322
    assert!(pr.changed);
1323
    assert!(a.store().has(&h_b));
1324
    assert!(root.join("a/b.txt").exists());
1325
1326
    // Deepening fetches older history until the boundary is gone.
1327
    // Every commit also depends on the change that created the file, so two
1328
    // levels below the boundary hold h4, h3, and the root.
1329
    assert!(a.deepen("origin", 2).unwrap() >= 2);
1330
    assert!(a.store().has(&hashes[3]));
1331
    assert!(a.is_shallow());
1332
    a.deepen("origin", 100).unwrap();
1333
    assert!(!a.is_shallow(), "boundary reached the root");
1334
    assert!(a.store().has(&hashes[0]));
1335
    assert_eq!(a.load_state_full(&a.bookmark_heads().unwrap()).unwrap().len(), 10);
1336
}
1337
1338
#[test]
1339
fn tags_are_immutable_named_states_and_travel() {
1340
    hermetic();
1341
    let dir = tempfile::tempdir().unwrap();
1342
    let root = dir.path();
1343
    let origin = Repo::init(&root.join("origin")).unwrap();
1344
    let url = root.join("origin").to_string_lossy().to_string();
1345
    let mut a = Repo::clone(&url, &root.join("a")).unwrap().with_home(root.join("home-a"));
1346
    let (key_a, _) = a.create_identity("Ada", "[email protected]", IdentityScope::User).unwrap();
1347
    write(&root.join("a"), "f.txt", b"1\n");
1348
    let h1 = a.commit("one", &[]).unwrap();
1349
    write(&root.join("a"), "f.txt", b"1\n2\n");
1350
    let h2 = a.commit("two", &[]).unwrap();
1351
1352
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
1353
    assert_eq!((t.heads.clone(), t.signer.as_deref()), (vec![h1], Some("Ada")));
1354
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
1355
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
1356
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
1357
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
1358
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
1359
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
1360
    assert_eq!(sa.sigs[0].key, key_a);
1361
    // Checkout by tag.
1362
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co").unwrap();
1363
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
1364
    a.checkout(&a.bookmark_heads().unwrap(), false, "co").unwrap();
1365
1366
    // Push carries the tag; a second attestation for the name is refused.
1367
    let r = a.push("origin", false).unwrap();
1368
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
1369
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
1370
    let mut forged = a.tag_refs().unwrap().into_iter().find(|t| t.name == "v1").unwrap();
1371
    forged.state = origin.store().put_state(&StateObject::new(vec![h2])).unwrap();
1372
    forged.heads = vec![h2];
1373
    forged.attestation = None;
1374
    let r = origin.receive_push(Bundle::default(), vec![], None, vec![forged]).unwrap();
1375
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
1376
1377
    // A clone gets the tag; a later tag arrives on fetch.
1378
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(root.join("home-b"));
1379
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
1380
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
1381
    a.tag_create("v2", &[h2], "second").unwrap();
1382
    a.push("origin", false).unwrap();
1383
    let rep = b.fetch("origin").unwrap();
1384
    assert_eq!(rep.new_tags, 1);
1385
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
1386
1387
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
1388
    a.policy_init().unwrap();
1389
    a.push("origin", false).unwrap();
1390
    let unattested = crate::protocol::TagRef { name: "v3".into(), state: origin.store().put_state(&StateObject::new(vec![h2])).unwrap(), heads: vec![h2], attestation: None };
1391
    let r = origin.receive_push(Bundle::default(), vec![], None, vec![unattested]).unwrap();
1392
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
1393
    a.tag_create("v3", &[h2], "").unwrap();
1394
    let r = a.push("origin", false).unwrap();
1395
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
1396
    assert!(a.gc(true).is_ok());
1397
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
1398
}
1399
1400
#[test]
1401
fn multiple_workspaces_share_a_repository() {
1402
    hermetic();
1403
    let dir = tempfile::tempdir().unwrap();
1404
    let root = dir.path();
1405
    let main_dir = root.join("main");
1406
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
1407
    write(&main_dir, "a.txt", b"a\n");
1408
    let h1 = repo.commit("a", &[]).unwrap();
1409
    assert_eq!(repo.workspaces().unwrap().len(), 1);
1410
1411
    // A second workspace elsewhere, checked out on the bookmark.
1412
    let ws_dir = root.join("ws2");
1413
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
1414
    assert!(ws_dir.join(".oxy").is_file());
1415
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
1416
    assert_ne!(ws.workspace(), repo.workspace());
1417
    let list = repo.workspaces().unwrap();
1418
    assert_eq!(list.len(), 2);
1419
    assert!(list.iter().any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
1420
    assert!(!ws.snapshot("status").unwrap().changed);
1421
1422
    // Work in the second workspace: its own working copy, shared bookmark.
1423
    write(&ws_dir, "b.txt", b"b\n");
1424
    let s = ws.snapshot("status").unwrap();
1425
    assert_eq!(s.statuses.len(), 1);
1426
    assert!(!repo.snapshot("status").unwrap().changed, "the first workspace is untouched");
1427
    let h2 = ws.commit("b from ws2", &[]).unwrap();
1428
    let mut heads = repo.bookmark_heads().unwrap();
1429
    heads.sort();
1430
    let mut want = vec![h1, h2];
1431
    want.sort();
1432
    assert_eq!(heads, want, "both workspaces see the bookmark move");
1433
    assert!(!main_dir.join("b.txt").exists());
1434
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co").unwrap();
1435
    assert!(main_dir.join("b.txt").exists());
1436
1437
    // Reopening from inside the second workspace finds the shared repository.
1438
    let reopened = Repo::open(&ws_dir).unwrap();
1439
    assert_eq!(reopened.workspace(), ws.workspace());
1440
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
1441
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
1442
1443
    // Workspaces cannot nest; forget drops one from the view but keeps files.
1444
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
1445
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
1446
    repo.workspace_forget(&ws.workspace()).unwrap();
1447
    assert_eq!(repo.workspaces().unwrap().len(), 1);
1448
    assert!(ws_dir.join("b.txt").exists());
1449
    assert!(ws.snapshot("status").is_err(), "a forgotten workspace is no longer in the view");
1450
1451
    // The snapshot lock: a fresh lock blocks a second, a stale one is taken over.
1452
    let lock = repo.lock_snapshot().unwrap();
1453
    drop(lock);
1454
    let lock_path = main_dir.join(".oxy/workspaces").join(repo.workspace().to_hex()).join("lock");
1455
    fs::write(&lock_path, "1").unwrap();
1456
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
1457
    fs::File::open(&lock_path).unwrap().set_modified(old).unwrap();
1458
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
1459
}
1460
1461
#[test]
1462
fn attributes_binary_eol_nocompress_lockable() {
1463
    hermetic();
1464
    let dir = tempfile::tempdir().unwrap();
1465
    let root = dir.path();
1466
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
1467
    write(root, ".oxyattributes", b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n");
1468
    write(root, "plain.dat", b"no nul bytes here\n");
1469
    write(root, "notes.txt", b"one\r\ntwo\r\n");
1470
    write(root, "assets/model.bin", b"\0model");
1471
    let h = repo.commit("attrs", &[]).unwrap();
1472
    let snap = repo.load_state(&[h]).unwrap().materialize();
1473
    assert!(snap.files["plain.dat"].mode.opaque, "binary attribute forces opaque without NUL bytes");
1474
    assert!(matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"), "stored with LF");
1475
    assert!(!repo.snapshot("status").unwrap().changed, "CRLF on disk equals LF in the state");
1476
    // nocompress chunks pack raw.
1477
    let r = repo.gc(true).unwrap();
1478
    assert!(r.packed.objects > 0);
1479
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
1480
    fs::remove_file(root.join("notes.txt")).unwrap();
1481
    repo.checkout(&[h], true, "co").unwrap();
1482
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
1483
    assert!(fs::metadata(root.join("assets/model.bin")).unwrap().permissions().readonly());
1484
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
1485
    repo.lock_path("assets/model.bin").unwrap();
1486
    assert!(!fs::metadata(root.join("assets/model.bin")).unwrap().permissions().readonly());
1487
    assert!(repo.is_locked("assets/model.bin"));
1488
    write(root, "assets/model.bin", b"\0model2");
1489
    repo.commit("edit model", &[]).unwrap();
1490
    repo.unlock_path("assets/model.bin").unwrap();
1491
    assert!(fs::metadata(root.join("assets/model.bin")).unwrap().permissions().readonly());
1492
    // A later checkout can still overwrite a read-only lockable file.
1493
    repo.checkout(&[h], true, "co").unwrap();
1494
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
1495
}
1496
1497
#[cfg(unix)]
1498
#[test]
1499
fn hooks_can_veto_observe_and_add_dependencies() {
1500
    use std::os::unix::fs::PermissionsExt;
1501
    hermetic();
1502
    let dir = tempfile::tempdir().unwrap();
1503
    let root = dir.path();
1504
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1505
    let hooks = root.join(".oxy/hooks");
1506
    fs::create_dir_all(&hooks).unwrap();
1507
    let hook = |name: &str, body: &str| {
1508
        let p = hooks.join(name);
1509
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
1510
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
1511
    };
1512
    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");
1513
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
1514
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
1515
    hook("pre-push", "echo pushing blocked >&2; exit 3");
1516
    write(root, ".oxyignore", b".last-*\n");
1517
    write(root, "a.txt", b"a\n");
1518
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
1519
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
1520
    let h1 = repo.commit("first", &[]).unwrap();
1521
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
1522
    assert!(pre.contains("\"event\":\"pre-commit\"") && pre.contains("\"path\":\"a.txt\"") && pre.contains("\"message\":\"first\""), "{pre}");
1523
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
1524
    assert!(post.contains(&h1.to_hex()), "{post}");
1525
    repo.checkout(&[h1], false, "co").unwrap();
1526
    assert!(fs::read_to_string(root.join(".last-post-checkout")).unwrap().contains("post-checkout"));
1527
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
1528
    repo.save_config().unwrap();
1529
    let err = repo.push("origin", false).unwrap_err().to_string();
1530
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
1531
1532
    // semantic-deps: only when enabled; adds an explicit dependency.
1533
    write(root, "b.txt", b"b\n");
1534
    hook("semantic-deps", &format!("cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'", h1.to_hex()));
1535
    let h2 = repo.commit("b without hook", &[]).unwrap();
1536
    assert!(repo.store().get_change(&h2).unwrap().deps.is_empty(), "hook disabled by default");
1537
    repo.config.set("hooks.semantic-deps", "true").unwrap();
1538
    repo.save_config().unwrap();
1539
    write(root, "c.txt", b"c\n");
1540
    let h3 = repo.commit("c with hook", &[]).unwrap();
1541
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
1542
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
1543
    assert!(sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"), "{sem}");
1544
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
1545
}
1546
1547
#[test]
1548
fn amend_into_older_change_and_split() {
1549
    hermetic();
1550
    let dir = tempfile::tempdir().unwrap();
1551
    let root = dir.path();
1552
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1553
    repo.create_identity("Ada", "a@b", IdentityScope::User).unwrap();
1554
    repo.set_user_config("core.sign", "change").unwrap();
1555
    write(root, "a.txt", b"one\ntwo\n");
1556
    let h0 = repo.commit("base", &[]).unwrap();
1557
    write(root, "a.txt", b"one\nTWO\n");
1558
    let h1 = repo.commit("edit two", &[]).unwrap();
1559
    write(root, "a.txt", b"one\nTWO\nthree\n");
1560
    let h2 = repo.commit("add three", &[]).unwrap();
1561
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
1562
1563
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
1564
    write(root, "a.txt", b"one\nTWO!\nthree\n");
1565
    let h1b = repo.amend_into(&h1, None).unwrap();
1566
    assert_ne!(h1b, h1);
1567
    let c1b = repo.store().get_change(&h1b).unwrap();
1568
    assert_eq!(c1b.change_id, id1);
1569
    assert_eq!(c1b.deps, vec![h0]);
1570
    assert!(matches!(repo.verify_change(&h1b).unwrap(), SignatureStatus::Valid { .. }));
1571
    let heads = repo.bookmark_heads().unwrap();
1572
    assert_eq!(heads.len(), 1);
1573
    let top = repo.store().get_change(&heads[0]).unwrap();
1574
    assert_eq!(top.message, "add three");
1575
    assert_eq!(top.deps.iter().copied().collect::<BTreeSet<_>>(), [h0, h1b].into_iter().collect(), "depends on the file's creator and the rewritten line");
1576
    let snap = repo.load_state(&heads).unwrap().materialize();
1577
    assert!(matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n"));
1578
    assert!(!repo.snapshot("status").unwrap().changed, "the working copy is clean after folding");
1579
    // Only h1b's own state shows the fix without "three".
1580
    let only = repo.load_state(&[h1b]).unwrap().materialize();
1581
    assert!(matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n"));
1582
    assert_eq!(repo.log().unwrap().len(), 4);
1583
1584
    // An edit to a line introduced by h2 cannot fold into h1.
1585
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
1586
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
1587
    assert!(err.contains("introduced after"), "{err}");
1588
    assert!(repo.snapshot("status").unwrap().statuses.len() == 1, "nothing was changed by the refusal");
1589
    write(root, "a.txt", b"one\nTWO!\nthree\n");
1590
1591
    // Split the head that touches two files.
1592
    write(root, "b.txt", b"b\n");
1593
    write(root, "c.txt", b"c\n");
1594
    let h3 = repo.commit("b and c", &[]).unwrap();
1595
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
1596
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
1597
    let c_1 = repo.store().get_change(&p1).unwrap();
1598
    let c_2 = repo.store().get_change(&p2).unwrap();
1599
    assert!(c_1.message.contains("part 1: b.txt"));
1600
    assert_eq!(c_2.change_id, id3);
1601
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1602
    assert!(heads.contains(&p1) && heads.contains(&p2), "independent parts are both heads");
1603
    let snap = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap().materialize();
1604
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
1605
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
1606
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
1607
    assert!(!repo.snapshot("status").unwrap().changed);
1608
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
1609
    let _ = h2;
1610
}
1611
1612
#[test]
1613
fn identity_lifecycle() {
1614
    hermetic();
1615
    let dir = tempfile::tempdir().unwrap();
1616
    let root = dir.path();
1617
    let origin = Repo::init(&root.join("origin")).unwrap();
1618
    let url = root.join("origin").to_string_lossy().to_string();
1619
    let mut a = Repo::clone(&url, &root.join("a")).unwrap().with_home(root.join("home-a"));
1620
    a.set_user_config("core.sign", "change").unwrap();
1621
    let (key_a, _) = a.create_identity("Ada", "[email protected]", IdentityScope::User).unwrap();
1622
    write(&root.join("a"), "a.txt", b"a\n");
1623
    let h1 = a.commit("one", &[]).unwrap();
1624
    assert!(a.policy_init().unwrap().applied);
1625
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1626
1627
    // Expiry: an identity that had expired when the change was made does not authenticate it.
1628
    let mut e = Repo::init(&root.join("e")).unwrap().with_home(root.join("home-e"));
1629
    e.set_user_config("core.sign", "change").unwrap();
1630
    e.create_identity_with("Eve", "[email protected]", IdentityScope::User, Some(Hlc::now().wall_ms - 1)).unwrap();
1631
    write(&root.join("e"), "e.txt", b"e\n");
1632
    let he = e.commit("late", &[]).unwrap();
1633
    assert!(matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired")));
1634
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
1635
    let r = e.renew_identity(Some(Hlc::now().wall_ms + 86_400_000)).unwrap();
1636
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
1637
    write(&root.join("e"), "e.txt", b"e2\n");
1638
    let he2 = e.commit("in time", &[]).unwrap();
1639
    assert!(matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new));
1640
1641
    // Rotation: a fresh key; the old change still verifies; the policy follows.
1642
    let r = a.rotate_identity().unwrap();
1643
    assert_eq!(r.old, key_a);
1644
    assert_eq!(a.config.author_key, Some(r.new));
1645
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
1646
    assert!(r.policy.as_ref().unwrap().applied);
1647
    let (_, sp) = a.current_policy().unwrap().unwrap();
1648
    assert_eq!((sp.policy.serial, sp.policy.roots.clone()), (2, vec![r.new]));
1649
    assert!(!sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"), "superseded, not revoked");
1650
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
1651
    assert!(matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a));
1652
    write(&root.join("a"), "a.txt", b"a2\n");
1653
    let h2 = a.commit("two", &[]).unwrap();
1654
    assert!(matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new));
1655
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
1656
    let res = a.push("origin", false).unwrap();
1657
    assert!(res.iter().all(|x| x.ok), "{res:?}");
1658
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
1659
    let key_a = r.new;
1660
1661
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
1662
    // identity object, so Ada's KeyId changes while her keys stay the same.
1663
    let mut b = Repo::clone(&url, &root.join("b")).unwrap().with_home(root.join("home-b"));
1664
    let (key_b, id_b) = b.create_identity("Bob", "[email protected]", IdentityScope::User).unwrap();
1665
    let r = a.delegate_add(id_b.clone()).unwrap();
1666
    assert_eq!(r.old, key_a);
1667
    let key_a2 = r.new;
1668
    assert_eq!(a.identity(&key_a2).unwrap().delegates, vec![key_b]);
1669
    assert_eq!(a.identity(&key_a2).unwrap().ed25519_pk, a.identity(&key_a).unwrap().ed25519_pk);
1670
    assert!(a.delegate_add(id_b.clone()).is_err(), "already a delegate");
1671
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
1672
    write(&root.join("a"), "a.txt", b"a3\n");
1673
    let h3 = a.commit("three", &[]).unwrap();
1674
    assert!(matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2), "the same secret signs under the new KeyId");
1675
    // A change authored by Ada but signed only by Bob verifies through the delegation.
1676
    a.set_user_config("core.sign", "seal").unwrap();
1677
    write(&root.join("a"), "a.txt", b"a4\n");
1678
    let h4 = a.commit("four", &[]).unwrap();
1679
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
1680
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1681
    a.store().put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4)).unwrap();
1682
    assert!(matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b));
1683
    a.set_user_config("core.sign", "change").unwrap();
1684
    // Withdrawing the delegation re-issues the identity again.
1685
    let r = a.delegate_remove(&key_b).unwrap();
1686
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
1687
    assert!(a.delegate_remove(&key_b).is_err());
1688
    let key_a3 = r.new;
1689
    let res = a.push("origin", false).unwrap();
1690
    assert!(res.iter().all(|x| x.ok), "{res:?}");
1691
1692
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
1693
    // both applied under the old threshold of 1. A grant then needs Bob too.
1694
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
1695
    assert!(a.policy_root_add(id_b.clone()).is_err());
1696
    assert!(a.policy_set_threshold(3).is_err());
1697
    assert!(a.policy_set_threshold(2).unwrap().applied);
1698
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
1699
    b.pull("origin").unwrap();
1700
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.root_threshold, 2);
1701
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(root.join("home-c"));
1702
    let (key_c, id_c) = c.create_identity("Cy", "[email protected]", IdentityScope::User).unwrap();
1703
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
1704
    let proposal = a.policy_grant(id_c, None).unwrap();
1705
    assert!(!proposal.applied && proposal.sigs.len() == 1);
1706
    assert_eq!(proposal.policy.serial, serial_before + 1);
1707
    assert_eq!(a.current_policy().unwrap().unwrap().1.policy.serial, serial_before, "a proposal changes nothing yet");
1708
    // Bob signs the proposal, handed over as a file, and it applies for him.
1709
    let bytes = proposal.signed().encode();
1710
    let signed = b.policy_sign(SignedPolicy::decode(&bytes).unwrap()).unwrap();
1711
    assert!(signed.applied && signed.sigs.len() == 2);
1712
    assert!(b.current_policy().unwrap().unwrap().1.policy.authorizes(&key_c, "main"));
1713
    assert!(b.policy_sign(signed.signed()).is_err(), "a stale proposal is refused");
1714
    // Bob publishes it and Ada picks it up.
1715
    assert!(b.push("origin", false).unwrap().iter().any(|x| x.name == "policy" && x.ok));
1716
    a.pull("origin").unwrap();
1717
    assert_eq!(a.current_policy().unwrap().unwrap().1.policy.serial, serial_before + 1);
1718
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
1719
    assert!(a.policy_revoke(&key_a3).is_err());
1720
    let u = a.revoke_identity(&key_c, "left the project").unwrap().unwrap();
1721
    assert!(!u.applied);
1722
    assert!(a.is_revoked(&key_c).unwrap());
1723
    assert!(!b.is_revoked(&key_c).unwrap());
1724
    let u = b.policy_sign(u.signed()).unwrap();
1725
    assert!(u.applied && u.policy.is_revoked(&key_c));
1726
    assert!(b.is_revoked(&key_c).unwrap());
1727
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
1728
    assert!(b.policy_revoke(&key_a3).is_err(), "would leave one root for a threshold of 2");
1729
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
1730
    let key_c_own = c.config.author_key.unwrap();
1731
    assert!(c.revoke_identity(&key_c_own, "lost laptop").unwrap().is_none());
1732
    assert!(c.is_revoked(&key_c_own).unwrap());
1733
    assert_eq!(key_c_own, key_c);
1734
}
1735
1736
#[test]
1737
fn renames_are_detected_and_tracked_as_moves() {
1738
    hermetic();
1739
    let dir = tempfile::tempdir().unwrap();
1740
    let root = dir.path();
1741
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
1742
    write(root, "src/old.rs", b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n");
1743
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
1744
    write(root, "tiny.txt", b"x\n");
1745
    let h1 = repo.commit("base", &[]).unwrap();
1746
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
1747
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
1748
1749
    // Rename with a small edit, a binary moved unchanged, and a rewrite
1750
    // that shares nothing with the removed file.
1751
    fs::remove_file(root.join("src/old.rs")).unwrap();
1752
    write(root, "lib/new.rs", b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n");
1753
    fs::remove_file(root.join("img.bin")).unwrap();
1754
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
1755
    fs::remove_file(root.join("tiny.txt")).unwrap();
1756
    write(root, "other.txt", b"completely different\n");
1757
    let snap = repo.snapshot("status").unwrap();
1758
    let statuses: Vec<(&str, ChangeStatus)> = snap.statuses.iter().map(|s| (s.path.as_str(), s.status)).collect();
1759
    assert_eq!(
1760
        statuses,
1761
        vec![("assets/img.bin", ChangeStatus::Renamed), ("lib/new.rs", ChangeStatus::Renamed), ("other.txt", ChangeStatus::Added), ("src", ChangeStatus::Removed), ("tiny.txt", ChangeStatus::Removed)]
1762
    );
1763
    let h2 = repo.commit("move things", &[]).unwrap();
1764
    let c = repo.store().get_change(&h2).unwrap();
1765
    let moves: Vec<_> = c.tree_ops.iter().filter(|op| matches!(op, TreeOp::Move { .. })).collect();
1766
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
1767
    assert!(c.tree_ops.iter().any(|op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")));
1768
    assert!(c.tree_ops.iter().any(|op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")));
1769
    let snap = repo.load_state(&[h2]).unwrap().materialize();
1770
    assert_eq!(snap.files["lib/new.rs"].node, node_old, "the node survives the rename");
1771
    assert!(matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"));
1772
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
1773
    assert!(render_change(&c, &repo.load_state(&[h1]).unwrap(), &repo.load_state(&[h1]).unwrap().materialize()).contains("R "));
1774
    // A fresh checkout reproduces the tree.
1775
    let other = tempfile::tempdir().unwrap();
1776
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
1777
    assert_eq!(fs::read(other.path().join("lib/new.rs")).unwrap(), b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n");
1778
    assert!(!other.path().join("src").exists());
1779
    assert!(!clone.snapshot("status").unwrap().changed);
1780
    // Similarity is line based, byte weighted.
1781
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
1782
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
1783
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
1784
    assert_eq!(similarity(b"", b"x\n"), 0);
1785
}
1786
1787
#[test]
1788
fn git_fetch_and_push_round_trip() {
1789
    hermetic();
1790
    if std::process::Command::new("git").arg("--version").output().is_err() {
1791
        eprintln!("git not installed; skipping");
1792
        return;
1793
    }
1794
    let dir = tempfile::tempdir().unwrap();
1795
    let root = dir.path();
1796
    let git_in = |d: &Path, args: &[&str]| -> String {
1797
        let out = std::process::Command::new("git")
1798
            .arg("-C")
1799
            .arg(d)
1800
            .args(["-c", "user.name=Grace", "-c", "[email protected]", "-c", "commit.gpgsign=false"])
1801
            .args(args)
1802
            .output()
1803
            .unwrap();
1804
        assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
1805
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1806
    };
1807
    // A bare "remote" and a work tree that pushes to it.
1808
    let remote = root.join("remote.git");
1809
    fs::create_dir_all(&remote).unwrap();
1810
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
1811
    let work = root.join("work");
1812
    git_in(root, &["clone", "-q", remote.to_str().unwrap(), work.to_str().unwrap()]);
1813
    git_in(&work, &["checkout", "-q", "-b", "main"]);
1814
    write(&work, "README.md", b"# Project\n");
1815
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
1816
    git_in(&work, &["add", "."]);
1817
    git_in(&work, &["commit", "-q", "-m", "initial"]);
1818
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1819
    git_in(&work, &["commit", "-q", "-am", "second"]);
1820
    git_in(&work, &["push", "-q", "origin", "main"]);
1821
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
1822
1823
    // Fetch into a fresh oxy repository.
1824
    let o = root.join("oxy");
1825
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
1826
    repo.create_identity("Ada", "[email protected]", IdentityScope::User).unwrap();
1827
    let url = remote.to_string_lossy().to_string();
1828
    let r = repo.git_fetch(&url, "main").unwrap();
1829
    assert_eq!((r.commits, r.heads), (2, 1));
1830
    assert_eq!(fs::read(o.join("src/lib.rs")).unwrap(), b"pub fn a() {}\npub fn b() {}\n");
1831
    assert!(!repo.snapshot("status").unwrap().changed);
1832
    assert_eq!(repo.git_fetch(&url, "main").unwrap().commits, 0, "nothing new");
1833
1834
    // An oxy change, pushed back: one commit on top of the Git tip.
1835
    write(&o, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n");
1836
    write(&o, "NOTES.md", b"from oxy\n");
1837
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
1838
    let r = repo.git_push(&url, "main").unwrap();
1839
    assert_eq!(r.exported, 1, "{r:?}");
1840
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
1841
    assert_eq!(git_in(&work, &["log", "--format=%s", "main"]), "add c and notes\nsecond\ninitial");
1842
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
1843
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
1844
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
1845
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"]).contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
1846
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 0, "already pushed");
1847
1848
    // Git moves on; pushing without fetching is refused, fetching brings
1849
    // the commit in and the working copy follows.
1850
    write(&work, "README.md", b"# Project\n\nMore.\n");
1851
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
1852
    git_in(&work, &["push", "-q", "origin", "main"]);
1853
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
1854
    assert!(repo.git_push(&url, "main").unwrap_err().to_string().contains("fetch"));
1855
    let r = repo.git_fetch(&url, "main").unwrap();
1856
    assert_eq!((r.commits, r.heads), (1, 2), "the Git change and the oxy change commute");
1857
    assert_eq!(fs::read(o.join("README.md")).unwrap(), b"# Project\n\nMore.\n");
1858
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
1859
    assert!(!repo.snapshot("status").unwrap().changed);
1860
    // Another oxy change pushes on top of Git's newest commit.
1861
    write(&o, "NOTES.md", b"from oxy\nagain\n");
1862
    repo.commit("notes again", &[]).unwrap();
1863
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
1864
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
1865
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
1866
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\nagain\n");
1867
    assert_eq!(git_in(&work, &["log", "--format=%s", "main"]).lines().count(), 5);
1868
}
1869
1870
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
1871
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
1872
#[test]
1873
#[ignore]
1874
fn bench_one_gibibyte_file() {
1875
    hermetic();
1876
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
1877
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
1878
        Some(d) => tempfile::tempdir_in(d).unwrap(),
1879
        None => tempfile::tempdir().unwrap(),
1880
    };
1881
    let root = dir.path();
1882
    let repo = Repo::init(&root.join("r")).unwrap().with_home(root.join("home"));
1883
    let size = 1usize << 30;
1884
    let mut data = vec![0u8; size];
1885
    let mut x = 0x9e3779b97f4a7c15u64;
1886
    for chunk in data.chunks_mut(8) {
1887
        x ^= x << 13;
1888
        x ^= x >> 7;
1889
        x ^= x << 17;
1890
        let b = x.to_le_bytes();
1891
        chunk.copy_from_slice(&b[..chunk.len()]);
1892
    }
1893
    let t = std::time::Instant::now();
1894
    write(&root.join("r"), "big.bin", &data);
1895
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
1896
    let t = std::time::Instant::now();
1897
    let h = repo.commit("big", &[]).unwrap();
1898
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
1899
    let t = std::time::Instant::now();
1900
    assert!(!repo.snapshot("status").unwrap().changed);
1901
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
1902
    let t = std::time::Instant::now();
1903
    let objects = repo.store().list().unwrap().len();
1904
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
1905
    let t = std::time::Instant::now();
1906
    let g = repo.gc(true).unwrap();
1907
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
1908
    let t = std::time::Instant::now();
1909
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
1910
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
1911
    let t = std::time::Instant::now();
1912
    let back = fs::read(root.join("c/big.bin")).unwrap();
1913
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
1914
    eprintln!("read back and verify: {:.2?}", t.elapsed());
1915
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
1916
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
1917
    eprintln!("store size: {:.1} MiB for 1 GiB of data", store_bytes as f64 / (1024.0 * 1024.0));
1918
}
1919
1920
fn walkdir_size(p: &Path) -> u64 {
1921
    let mut total = 0;
1922
    if let Ok(rd) = fs::read_dir(p) {
1923
        for e in rd.flatten() {
1924
            let path = e.path();
1925
            if path.is_dir() {
1926
                total += walkdir_size(&path);
1927
            } else if let Ok(m) = fs::metadata(&path) {
1928
                total += m.len();
1929
            }
1930
        }
1931
    }
1932
    total
1933
}
1934
1935
/// An opaque file whose size and mtime match the manifest is not read on
1936
/// the next snapshot: its blob comes from the manifest's stat cache.
1937
#[cfg(unix)]
1938
#[test]
1939
fn stat_cache_skips_reading_unchanged_opaque_files() {
1940
    use std::os::unix::fs::PermissionsExt;
1941
    hermetic();
1942
    let dir = tempfile::tempdir().unwrap();
1943
    let root = dir.path();
1944
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
1945
    let mut big = vec![0u8; 300 * 1024];
1946
    for (i, b) in big.iter_mut().enumerate() {
1947
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
1948
    }
1949
    big[0] = 0;
1950
    write(root, "big.bin", &big);
1951
    write(root, "a.txt", b"text\n");
1952
    let h1 = repo.commit("base", &[]).unwrap();
1953
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
1954
    assert!(m.entries["big.bin"].blob.is_some(), "opaque files record their blob");
1955
    assert!(m.entries["a.txt"].blob.is_none());
1956
    let blob = m.entries["big.bin"].blob.unwrap();
1957
    assert!(repo.store().has(&blob));
1958
1959
    // Files modified within two seconds of the manifest are racy and still
1960
    // read; age the file so the cache applies, then snapshot to record it.
1961
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
1962
    fs::File::options().write(true).open(root.join("big.bin")).unwrap().set_modified(old).unwrap();
1963
    assert!(!repo.snapshot("status").unwrap().changed);
1964
    // Now the file cannot be read at all; the snapshot succeeds without it.
1965
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
1966
    let snap = repo.snapshot("status").unwrap();
1967
    assert!(!snap.changed && snap.statuses.is_empty(), "{:?}", snap.statuses);
1968
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
1969
    // A real change (new mtime, new content) is seen and committed correctly.
1970
    let mut big2 = big.clone();
1971
    big2[10] ^= 0xff;
1972
    write(root, "big.bin", &big2);
1973
    let snap = repo.snapshot("status").unwrap();
1974
    assert_eq!(snap.statuses.iter().map(|s| (s.path.as_str(), s.status)).collect::<Vec<_>>(), vec![("big.bin", ChangeStatus::Modified)]);
1975
    let h2 = repo.commit("edit", &[]).unwrap();
1976
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
1977
    assert_eq!(files["big.bin"].content, FileContent::Opaque { blobs: vec![Repo::blob_ref(&big2)] });
1978
    // Checkout writes a manifest with blobs too, so the next status is cached.
1979
    repo.checkout(&[h1], false, "checkout").unwrap();
1980
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
1981
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
1982
    assert!(!repo.snapshot("status").unwrap().changed);
1983
}
1984
1985
#[test]
1986
fn status_json_lists_conflicts_with_contributors() {
1987
    hermetic();
1988
    let dir = tempfile::tempdir().unwrap();
1989
    let root = dir.path();
1990
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
1991
    write(root, "a.txt", b"one\n");
1992
    let h1 = repo.commit("base", &[]).unwrap();
1993
    write(root, "a.txt", b"one\nleft\n");
1994
    let ha = repo.commit("left", &[]).unwrap();
1995
    repo.checkout(&[h1], true, "checkout").unwrap();
1996
    write(root, "a.txt", b"one\nright\n");
1997
    let hb = repo.commit("right", &[]).unwrap();
1998
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
1999
    let snap = repo.snapshot("status").unwrap();
2000
    assert!(snap.base_snapshot.is_conflicted());
2001
    let json = repo.status_json(&snap).unwrap();
2002
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
2003
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
2004
    assert!(json.contains("\"conflicted\":true"), "{json}");
2005
    assert!(json.contains("\"kind\":\"text\",\"path\":\"a.txt\""), "{json}");
2006
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
2007
    assert!(json.contains("\"resolved\":false"), "{json}");
2008
    assert!(json.starts_with('{') && json.ends_with('}'));
2009
    // Resolve and the report says so; a clean copy has no conflicts.
2010
    write(root, "a.txt", b"one\nleft\nright\n");
2011
    let snap = repo.snapshot("status").unwrap();
2012
    let json = repo.status_json(&snap).unwrap();
2013
    assert!(json.contains("\"resolved\":true"), "{json}");
2014
    repo.commit("resolve", &[]).unwrap();
2015
    let snap = repo.snapshot("status").unwrap();
2016
    let json = repo.status_json(&snap).unwrap();
2017
    assert!(json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"), "{json}");
2018
}
2019
2020
#[test]
2021
fn ignore_rules_do_not_untrack_files() {
2022
    hermetic();
2023
    let dir = tempfile::tempdir().unwrap();
2024
    let root = dir.path();
2025
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2026
    write(root, "src.c", b"int x;\n");
2027
    write(root, "build/out.o", b"\0obj");
2028
    write(root, "sub/keep.log", b"keep\n");
2029
    write(root, "sub/junk.log", b"junk\n");
2030
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
2031
    let snap = repo.snapshot("status").unwrap();
2032
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
2033
    assert_eq!(added, vec![".oxyignore", "src.c", "sub/keep.log"], "anchored, glob, and negated rules");
2034
    let h1 = repo.commit("base", &[]).unwrap();
2035
    // Ignoring a tracked file changes nothing about it.
2036
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
2037
    let snap = repo.snapshot("status").unwrap();
2038
    assert_eq!(snap.statuses.iter().map(|s| s.path.as_str()).collect::<Vec<_>>(), vec![".oxyignore"]);
2039
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
2040
    assert!(repo.load_state(&[h2]).unwrap().materialize().files.contains_key("src.c"));
2041
    // Its edits are still seen, by status and by the prompt.
2042
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
2043
    write(root, "src.c", b"int x, y;\n");
2044
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
2045
    let snap = repo.snapshot("status").unwrap();
2046
    assert_eq!(snap.statuses.iter().map(|s| (s.path.as_str(), s.status)).collect::<Vec<_>>(), vec![("src.c", ChangeStatus::Modified)]);
2047
    let h3 = repo.commit("edit src.c", &[]).unwrap();
2048
    assert!(matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n"));
2049
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
2050
    fs::remove_file(root.join("src.c")).unwrap();
2051
    let snap = repo.snapshot("status").unwrap();
2052
    assert_eq!(snap.statuses.iter().map(|s| (s.path.as_str(), s.status)).collect::<Vec<_>>(), vec![("src.c", ChangeStatus::Removed)]);
2053
    repo.checkout(&[h3], true, "checkout").unwrap();
2054
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
2055
    assert!(!repo.snapshot("status").unwrap().changed);
2056
    let _ = h1;
2057
}
2058
2059
#[test]
2060
fn split_works_on_non_heads_by_node() {
2061
    hermetic();
2062
    let dir = tempfile::tempdir().unwrap();
2063
    let root = dir.path();
2064
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2065
    write(root, "a.txt", b"one\n");
2066
    write(root, "junk/x.lock", b"lock\n");
2067
    let h1 = repo.commit("work plus junk", &[]).unwrap();
2068
    write(root, "a.txt", b"one\ntwo\n");
2069
    let h2 = repo.commit("more work", &[]).unwrap();
2070
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
2071
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2072
    // h1 is not a head: split it by node.
2073
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
2074
    assert_ne!(h1b, h1);
2075
    assert_eq!(repo.store().get_change(&h1b).unwrap().change_id, id1, "the rest keeps the ChangeId");
2076
    let junk = repo.store().get_change(&hj).unwrap();
2077
    assert!(junk.tree_ops.iter().all(|op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")));
2078
    let heads = repo.bookmark_heads().unwrap();
2079
    assert!(heads.contains(&hj), "the split-off part is a head of its own");
2080
    let snap = repo.load_state(&heads).unwrap().materialize();
2081
    assert!(matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"), "the dependent was rewritten onto the new hash");
2082
    assert!(snap.files.contains_key("junk/x.lock"));
2083
    let h2b = heads.iter().find(|h| repo.store().get_change(h).unwrap().message == "more work").copied().unwrap();
2084
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
2085
    assert!(!repo.snapshot("status").unwrap().changed);
2086
    // Abandoning the split-off head removes the junk from history.
2087
    repo.abandon(&hj).unwrap();
2088
    let heads = repo.bookmark_heads().unwrap();
2089
    let snap = repo.load_state(&heads).unwrap().materialize();
2090
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
2091
    assert!(snap.files.contains_key("a.txt"));
2092
    // A dependent that touches the split-off paths blocks the split.
2093
    write(root, "junk/y.lock", b"y\n");
2094
    let hb = repo.commit("junk base", &[]).unwrap();
2095
    write(root, "junk/y.lock", b"yy\n");
2096
    write(root, "b.txt", b"b\n");
2097
    repo.commit("touches junk", &[]).unwrap();
2098
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
2099
    assert!(err.contains("depends on the split-off paths"), "{err}");
2100
}
2101
2102
#[test]
2103
fn bookmarks_switch_merge_and_push() {
2104
    hermetic();
2105
    let dir = tempfile::tempdir().unwrap();
2106
    let root = dir.path();
2107
    let origin = Repo::init(&root.join("origin")).unwrap();
2108
    let url = root.join("origin").to_string_lossy().to_string();
2109
    let mut repo = Repo::clone(&url, &root.join("r")).unwrap().with_home(root.join("home"));
2110
    let r = root.join("r");
2111
    write(&r, "a.txt", b"a\n");
2112
    let h_a = repo.commit("a", &[]).unwrap();
2113
    assert!(repo.push("origin", false).unwrap()[0].ok);
2114
2115
    // A bookmark at the working copy's base, then work on it.
2116
    assert!(repo.bookmark_create("bad name..", None).is_err());
2117
    assert!(repo.bookmark_create("-x", None).is_err());
2118
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
2119
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
2120
    repo.bookmark_switch("feature", false).unwrap();
2121
    assert_eq!(repo.config.bookmark, "feature");
2122
    write(&r, "a.txt", b"a\nb\n");
2123
    write(&r, "b.txt", b"b\n");
2124
    let h_b = repo.commit("b on feature", &[]).unwrap();
2125
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h_b], "b edits a.txt, so it depends on a");
2126
    assert_eq!(repo.resolve_heads("main").unwrap(), vec![h_a], "main is untouched");
2127
    assert_eq!(repo.resolve_change("feature").unwrap(), h_b, "a one-head bookmark names its change");
2128
    // Reopening keeps the workspace's bookmark.
2129
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
2130
    assert_eq!(reopened.config.bookmark, "feature");
2131
    // Back to main: b.txt goes away; work there.
2132
    repo.bookmark_switch("main", false).unwrap();
2133
    assert!(!r.join("b.txt").exists());
2134
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
2135
    write(&r, "c.txt", b"c\n");
2136
    let h_c = repo.commit("c on main", &[]).unwrap();
2137
    let list = repo.bookmarks().unwrap();
2138
    assert_eq!(list.iter().map(|b| (b.name.as_str(), b.current)).collect::<Vec<_>>(), vec![("feature", false), ("main", true)]);
2139
    assert_eq!(list.iter().find(|b| b.name == "main").unwrap().ahead, Some(1), "c is not on origin yet");
2140
    // Merge feature into main: the union, both heads, no merge change.
2141
    let m = repo.merge("feature").unwrap();
2142
    assert!(m.changed && m.checked_out);
2143
    let mut want = vec![h_b, h_c];
2144
    want.sort();
2145
    assert_eq!(m.heads, want);
2146
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
2147
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
2148
    assert!(repo.merge("main").is_err());
2149
    // The other bookmark can be pushed by name and appears at origin.
2150
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
2151
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
2152
    assert!(repo.push("origin", false).unwrap()[0].ok);
2153
    assert_eq!(repo.bookmarks().unwrap().iter().find(|b| b.name == "main").unwrap().ahead, Some(0));
2154
    // A second workspace inherits the current bookmark and can switch independently.
2155
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
2156
    assert_eq!(ws.config.bookmark, "main");
2157
    let mut ws = ws;
2158
    ws.bookmark_switch("feature", false).unwrap();
2159
    assert_eq!(Repo::open(&r).unwrap().config.bookmark, "main", "the first workspace is unaffected");
2160
    assert!(repo.bookmark_delete("feature").is_err(), "current bookmark of another workspace");
2161
    ws.bookmark_switch("main", false).unwrap();
2162
    // Set and delete.
2163
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
2164
    assert!(repo.bookmark_delete("main").is_err(), "current here");
2165
    repo.bookmark_delete("feature").unwrap();
2166
    assert!(repo.resolve_heads("feature").is_err());
2167
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
2168
    assert!(repo.checkout(&[h_a], false, "checkout").is_ok(), "changes of a deleted bookmark remain");
2169
}
2170
2171
#[test]
2172
fn oxygen_subrepos_pin_follow_and_update() {
2173
    hermetic();
2174
    let dir = tempfile::tempdir().unwrap();
2175
    let root = dir.path();
2176
    // A library repository with two commits, and a bare-ish origin for it.
2177
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
2178
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
2179
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap().with_home(root.join("home"));
2180
    write(&root.join("lib"), "lib.txt", b"v1\n");
2181
    let l1 = lib.commit("lib v1", &[]).unwrap();
2182
    assert!(lib.push("origin", false).unwrap()[0].ok);
2183
    let _ = lib_origin;
2184
2185
    // The application (a clone of its own origin) adds it as a subrepo.
2186
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
2187
    let app_url = root.join("app-origin").to_string_lossy().to_string();
2188
    let _ = app_origin;
2189
    let app_dir = root.join("app");
2190
    let app = Repo::clone(&app_url, &app_dir).unwrap().with_home(root.join("home"));
2191
    write(&app_dir, "main.txt", b"app\n");
2192
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
2193
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
2194
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
2195
    let snap = app.snapshot("status").unwrap();
2196
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
2197
    assert_eq!(paths, vec![".oxymodules", "libs/lib", "main.txt"], "the nested files are not walked");
2198
    let a1 = app.commit("app with lib", &[]).unwrap();
2199
    let files = app.load_state(&[a1]).unwrap().materialize().files;
2200
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
2201
    assert!(!files.contains_key("libs/lib/lib.txt"));
2202
    assert!(!app.snapshot("status").unwrap().changed);
2203
    let subs = app.subrepos().unwrap();
2204
    assert_eq!(subs.len(), 1);
2205
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
2206
2207
    // Advance the nested repository: the parent sees a modified pin.
2208
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap().with_home(root.join("home"));
2209
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
2210
    let l2 = nested.commit("lib v2", &[]).unwrap();
2211
    assert!(nested.push("origin", false).unwrap()[0].ok);
2212
    let snap = app.snapshot("status").unwrap();
2213
    assert_eq!(snap.statuses.iter().map(|s| (s.path.as_str(), s.status)).collect::<Vec<_>>(), vec![("libs/lib", ChangeStatus::Modified)]);
2214
    let a2 = app.commit("bump lib", &[]).unwrap();
2215
    // Checking out the older app state moves the nested repository back.
2216
    let r = app.checkout(&[a1], false, "checkout").unwrap();
2217
    assert!(r.notes.is_empty(), "{:?}", r.notes);
2218
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
2219
    assert_eq!(Repo::open(&app_dir.join("libs/lib")).unwrap().bookmark_heads().unwrap(), vec![l1]);
2220
    assert!(!app.snapshot("status").unwrap().changed);
2221
    // A dirty nested repository is left alone and reported.
2222
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
2223
    let r = app.checkout(&[a2], false, "checkout").unwrap();
2224
    assert!(r.notes.iter().any(|n| n.contains("uncommitted")), "{:?}", r.notes);
2225
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
2226
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
2227
    let r = app.submodule_update(false, &[]).unwrap();
2228
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
2229
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
2230
    let _ = l2;
2231
2232
    // A fresh clone of the app has the pin but no nested repository until update --init.
2233
    assert!(app.push("origin", false).unwrap()[0].ok);
2234
    let clone_dir = root.join("app-clone");
2235
    let clone = Repo::clone(&app_url, &clone_dir).unwrap().with_home(root.join("home"));
2236
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
2237
    assert_eq!(clone.submodule_update(false, &[]).unwrap(), vec![("libs/lib".to_string(), SubrepoSync::Missing)]);
2238
    assert_eq!(clone.submodule_update(true, &[]).unwrap(), vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
2239
    assert_eq!(fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
2240
    assert!(!clone.snapshot("status").unwrap().changed);
2241
    // Removing the subrepo leaves the directory and drops the node.
2242
    clone.submodule_remove("libs/lib").unwrap();
2243
    let snap = clone.snapshot("status").unwrap();
2244
    assert!(snap.statuses.iter().any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed), "{:?}", snap.statuses);
2245
    let c = clone.commit("drop lib", &[]).unwrap();
2246
    assert!(!clone.load_state(&[c]).unwrap().materialize().files.contains_key("libs/lib"));
2247
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
2248
    assert!(!clone.snapshot("status").unwrap().changed, "an unregistered nested repository is ignored");
2249
}
2250
2251
#[test]
2252
fn git_submodules_import_and_export_as_gitlinks() {
2253
    hermetic();
2254
    if std::process::Command::new("git").arg("--version").output().is_err() {
2255
        eprintln!("git not installed; skipping");
2256
        return;
2257
    }
2258
    let dir = tempfile::tempdir().unwrap();
2259
    let root = dir.path();
2260
    let git_in = |d: &Path, args: &[&str]| -> String {
2261
        let out = std::process::Command::new("git")
2262
            .arg("-C")
2263
            .arg(d)
2264
            .args(["-c", "user.name=Grace", "-c", "[email protected]", "-c", "commit.gpgsign=false", "-c", "protocol.file.allow=always"])
2265
            .args(args)
2266
            .output()
2267
            .unwrap();
2268
        assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
2269
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2270
    };
2271
    let sub = root.join("sub");
2272
    fs::create_dir_all(&sub).unwrap();
2273
    git_in(&sub, &["init", "-q", "-b", "main"]);
2274
    write(&sub, "s.txt", b"sub\n");
2275
    git_in(&sub, &["add", "."]);
2276
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
2277
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
2278
    let g = root.join("main.git");
2279
    fs::create_dir_all(&g).unwrap();
2280
    git_in(&g, &["init", "-q", "-b", "main"]);
2281
    write(&g, "README.md", b"# app\n");
2282
    git_in(&g, &["add", "."]);
2283
    git_in(&g, &["commit", "-q", "-m", "initial"]);
2284
    git_in(&g, &["submodule", "add", "-q", sub.to_str().unwrap(), "vendor/sub"]);
2285
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
2286
2287
    let dest = root.join("oxy");
2288
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
2289
    let rep = repo.import_git(&g, "main").unwrap();
2290
    assert_eq!((rep.commits, rep.submodules), (2, 1));
2291
    let files = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap().materialize().files;
2292
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
2293
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else { panic!() };
2294
    assert_eq!(crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(), crate::subrepo::Pin::Git { sha: sub_sha.clone(), branch: "HEAD".into() });
2295
    let modules = crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
2296
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
2297
    assert!(modules.entries["vendor/sub"].git);
2298
    assert!(files.contains_key(".gitmodules"), "the Git file is kept for round trips");
2299
    assert!(!dest.join("vendor/sub/.git").exists(), "not cloned until update --init");
2300
    assert!(!repo.snapshot("status").unwrap().changed);
2301
    // update --init clones it at the pinned commit; status is unchanged.
2302
    assert_eq!(repo.submodule_update(true, &[]).unwrap(), vec![("vendor/sub".to_string(), SubrepoSync::Updated)]);
2303
    assert_eq!(git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]), sub_sha);
2304
    assert!(!repo.snapshot("status").unwrap().changed);
2305
    // Export writes the gitlink and .gitmodules back.
2306
    let mirror = root.join("mirror.git");
2307
    let rep = repo.git_export(&mirror).unwrap();
2308
    assert_eq!(rep.skipped_subrepos, 0);
2309
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
2310
    assert!(ls.starts_with("160000 commit ") && ls.contains(&sub_sha), "{ls}");
2311
    assert_eq!(git_in(&mirror, &["ls-tree", "--name-only", "main"]), ".gitmodules\nREADME.md\nvendor");
2312
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
2313
    assert_eq!(git_in(&mirror, &["rev-parse", "main^{tree}"]), orig_tree, "tree round trip");
2314
}
2315