OXYGENHUB
# 982864068a59 oxygen / crates / oxy-core / src / repo / tests.rs
30.7 KiB · Rust · last changed Split repo.rs into repo/{config,snapshot,checkout,identity,sync,tests}; hermetic OXY_HOME in tests; identity recorded in user config 1 month ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
5
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
6
/// test reads or writes the developer's real user configuration or keys.
7
fn hermetic() {
8
    static ONCE: std::sync::Once = std::sync::Once::new();
9
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
10
    ONCE.call_once(|| {
11
        let d = tempfile::tempdir().unwrap();
12
        std::env::set_var("OXY_HOME", d.path());
13
        DIR.set(d).ok();
14
    });
15
}
16
17
fn write(root: &Path, rel: &str, content: &[u8]) {
18
    let p = root.join(rel);
19
    fs::create_dir_all(p.parent().unwrap()).unwrap();
20
    fs::write(p, content).unwrap();
21
}
22
23
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
24
    s.statuses.iter().map(|p| (p.path.clone(), p.status)).collect()
25
}
26
27
#[test]
28
fn init_snapshot_commit_log_undo() {
29
    hermetic();
30
    let dir = tempfile::tempdir().unwrap();
31
    let root = dir.path();
32
    let repo = Repo::init(root).unwrap();
33
    assert!(Repo::init(root).is_err());
34
    let ops = repo.op_log().unwrap();
35
    assert_eq!(ops.len(), 1);
36
    assert_eq!(ops[0].1.command, "oxy init");
37
38
    // Empty working copy: snapshot records no operation (spec §12.3).
39
    let s = repo.snapshot("oxy status").unwrap();
40
    assert!(!s.changed);
41
    assert_eq!(repo.op_log().unwrap().len(), 1);
42
43
    write(root, "src/main.rs", b"fn main() {}\n");
44
    write(root, "README.md", b"# Hello\n");
45
    write(root, ".oxyignore", b"/target\n");
46
    write(root, "target/junk.o", b"\0\0\0");
47
    let s = repo.snapshot("oxy status").unwrap();
48
    assert!(s.changed);
49
    assert_eq!(
50
        statuses(&s),
51
        vec![
52
            (".oxyignore".into(), ChangeStatus::Added),
53
            ("README.md".into(), ChangeStatus::Added),
54
            ("src/main.rs".into(), ChangeStatus::Added),
55
        ]
56
    );
57
    assert_eq!(repo.op_log().unwrap().len(), 2);
58
    // Snapshotting again with nothing changed records no op.
59
    let s2 = repo.snapshot("oxy status").unwrap();
60
    assert!(!s2.changed);
61
    assert_eq!(s2.wc_hash, s.wc_hash);
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
64
    let h1 = repo.commit("Initial import", &[]).unwrap();
65
    let c1 = repo.store().get_change(&h1).unwrap();
66
    assert_eq!(c1.kind, ChangeKind::Normal);
67
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
68
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
69
    let (wc_hash, wc) = repo.working_copy().unwrap();
70
    assert_eq!(wc.deps, vec![h1]);
71
    assert!(wc.edits.is_empty());
72
    assert!(repo.commit("nothing", &[]).is_err());
73
74
    // Modify one file, remove another, add a binary file.
75
    write(root, "src/main.rs", b"fn main() {\n    println!(\"hi\");\n}\n");
76
    fs::remove_file(root.join("README.md")).unwrap();
77
    write(root, "logo.png", b"\x89PNG\0\0\x01");
78
    let s = repo.snapshot("oxy status").unwrap();
79
    assert_eq!(
80
        statuses(&s),
81
        vec![
82
            ("README.md".into(), ChangeStatus::Removed),
83
            ("logo.png".into(), ChangeStatus::Added),
84
            ("src/main.rs".into(), ChangeStatus::Modified),
85
        ]
86
    );
87
    assert_ne!(s.wc_hash, wc_hash);
88
    // The rewritten working copy keeps its ChangeId and depends on h1.
89
    assert_eq!(s.wc.change_id, wc.change_id);
90
    assert!(s.wc.deps.contains(&h1));
91
92
    let h2 = repo.commit("Second", &[]).unwrap();
93
    let c2 = repo.store().get_change(&h2).unwrap();
94
    assert_eq!(c2.deps, vec![h1], "everything it touches was introduced by h1");
95
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
96
97
    // The materialized head state matches the working copy.
98
    let st = repo.load_state(&[h2]).unwrap();
99
    let snap = st.materialize();
100
    assert!(!snap.is_conflicted());
101
    assert_eq!(snap.files.keys().cloned().collect::<Vec<_>>(), [".oxyignore", "logo.png", "src", "src/main.rs"]);
102
    assert!(matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n"));
103
    assert!(snap.files["logo.png"].mode.opaque);
104
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
105
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
106
    } else {
107
        panic!("logo should be opaque");
108
    }
109
110
    // Log: newest first, working copy included.
111
    let log = repo.log().unwrap();
112
    assert_eq!(log.len(), 3);
113
    assert!(log[0].is_working_copy);
114
    assert_eq!(log[1].hash, h2);
115
    assert!(log[1].is_head);
116
    assert_eq!(log[2].hash, h1);
117
    let d = repo.describe_change(&h2).unwrap();
118
    assert!(d.contains("D README.md"), "{d}");
119
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
120
    assert!(d.contains("-fn main() {}"), "{d}");
121
122
    // Resolution by prefix.
123
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
124
    assert_eq!(repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(), h1);
125
    assert!(repo.resolve_change("zzzz").is_err());
126
127
    // Undo the commit: bookmark and working copy go back.
128
    repo.undo().unwrap();
129
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
130
    let s = repo.snapshot("oxy status").unwrap();
131
    assert!(!s.changed, "files on disk still match the pre-commit working copy");
132
    assert_eq!(s.statuses.len(), 3);
133
}
134
135
/// Make `main` conflicted: two commits on the same base that edit the same line.
136
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
137
    let dir = tempfile::tempdir().unwrap();
138
    let root = dir.path();
139
    let repo = Repo::init(root).unwrap();
140
    write(root, "f.txt", b"a\nb\nc\n");
141
    let h1 = repo.commit("base", &[]).unwrap();
142
    write(root, "f.txt", b"a\nB\nc\n");
143
    let h2 = repo.commit("upper", &[]).unwrap();
144
    repo.checkout(&[h1], false, "checkout").unwrap();
145
    write(root, "f.txt", b"a\nX\nc\n");
146
    let h3 = repo.commit("ex", &[]).unwrap();
147
    (dir, repo, h1, h2, h3)
148
}
149
150
#[test]
151
fn concurrent_edits_conflict_and_can_be_resolved() {
152
    hermetic();
153
    let (dir, repo, h1, h2, h3) = conflicted_repo();
154
    let root = dir.path();
155
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
156
    assert_eq!(heads, [h2, h3].into_iter().collect());
157
    let st = repo.load_state(&[h2, h3]).unwrap();
158
    assert!(st.materialize().is_conflicted());
159
160
    // Checking out main writes markers.
161
    let r = repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main").unwrap();
162
    assert!(r.conflicted);
163
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
164
    assert!(marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"), "{marked}");
165
    assert!(marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"), "{marked}");
166
    assert!(has_conflict_markers(marked.as_bytes()));
167
    // Untouched markers: clean working copy; commit has nothing to do.
168
    let s = repo.snapshot("status").unwrap();
169
    assert!(s.statuses.is_empty());
170
    assert!(!s.resolves);
171
172
    // Partially edited file that still has markers cannot be committed.
173
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
174
    let s = repo.snapshot("status").unwrap();
175
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::ConflictEdited)]);
176
    assert!(repo.commit("no", &[]).is_err());
177
178
    // Resolve by keeping one side and adding a line elsewhere.
179
    write(root, "f.txt", b"a\nX\nc\nd\n");
180
    let s = repo.snapshot("status").unwrap();
181
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
182
    assert!(s.resolves);
183
    let h4 = repo.commit("resolve", &[]).unwrap();
184
    let c4 = repo.store().get_change(&h4).unwrap();
185
    assert_eq!(c4.kind, ChangeKind::Resolution);
186
    let mut want = vec![h1, h2, h3];
187
    want.sort();
188
    assert_eq!(c4.deps, want, "a resolution depends on exactly the contributors and what it references");
189
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
190
    let snap = repo.load_state(&[h4]).unwrap().materialize();
191
    assert!(!snap.is_conflicted());
192
    assert!(matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n"));
193
    assert!(!repo.snapshot("status").unwrap().changed);
194
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
195
    // whatever order the changes arrive in.
196
    let mut st = State::new();
197
    for h in [h4, h3, h1, h2] {
198
        st.add_unchecked(repo.store().get_change(&h).unwrap());
199
    }
200
    st.validate().unwrap();
201
    assert!(matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n"));
202
}
203
204
#[test]
205
fn resolution_may_keep_both_sides_or_neither() {
206
    hermetic();
207
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
208
    let root = dir.path();
209
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main").unwrap();
210
    // Keep both sides in a chosen order.
211
    write(root, "f.txt", b"a\nX\nB\nc\n");
212
    let h = repo.commit("both", &[]).unwrap();
213
    let snap = repo.load_state(&[h]).unwrap().materialize();
214
    assert!(!snap.is_conflicted());
215
    assert!(matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n"));
216
    // Undo and instead drop the whole region.
217
    repo.undo().unwrap();
218
    write(root, "f.txt", b"a\nc\n");
219
    let h = repo.commit("neither", &[]).unwrap();
220
    let snap = repo.load_state(&[h]).unwrap().materialize();
221
    assert!(!snap.is_conflicted());
222
    assert!(matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n"));
223
}
224
225
#[test]
226
fn name_conflict_resolved_by_removing_a_candidate() {
227
    hermetic();
228
    let dir = tempfile::tempdir().unwrap();
229
    let root = dir.path();
230
    let repo = Repo::init(root).unwrap();
231
    write(root, "keep.txt", b"k\n");
232
    let h1 = repo.commit("base", &[]).unwrap();
233
    write(root, "new.txt", b"one\n");
234
    repo.commit("one", &[]).unwrap();
235
    repo.checkout(&[h1], false, "checkout").unwrap();
236
    write(root, "new.txt", b"two\n");
237
    repo.commit("two", &[]).unwrap();
238
    let r = repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main").unwrap();
239
    assert!(r.conflicted);
240
    assert!(root.join("new.txt.oxy-conflict-1").exists() && root.join("new.txt.oxy-conflict-2").exists());
241
    assert!(!root.join("new.txt").exists());
242
    // Candidate numbering follows change-hash order, so pick by content:
243
    // keep the "two" candidate under the real name and drop the other.
244
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" { (1, 2) } else { (2, 1) };
245
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
246
    fs::rename(root.join(format!("new.txt.oxy-conflict-{keep}")), root.join("new.txt")).unwrap();
247
    let h = repo.commit("pick two", &[]).unwrap();
248
    assert_eq!(repo.store().get_change(&h).unwrap().kind, ChangeKind::Resolution);
249
    // The resolution does not touch keep.txt, so it does not depend on h1;
250
    // the bookmark keeps both as heads and their union is the state.
251
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
252
    assert_eq!(heads, [h1, h].into_iter().collect());
253
    let snap = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap().materialize();
254
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
255
    assert_eq!(snap.files.keys().cloned().collect::<Vec<_>>(), ["keep.txt", "new.txt"]);
256
    assert!(matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n"));
257
}
258
259
#[test]
260
fn identities_and_signed_commits() {
261
    hermetic();
262
    let dir = tempfile::tempdir().unwrap();
263
    let root = dir.path();
264
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
265
    write(root, "a.txt", b"a\n");
266
    let h0 = repo.commit("unsigned", &[]).unwrap();
267
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
268
    assert_eq!(repo.store().get_change(&h0).unwrap().author, ObjectRef::ZERO);
269
270
    let (key, id) = repo.create_identity("Ada", "[email protected]", IdentityScope::Repo).unwrap();
271
    assert_eq!(id.hash(), key);
272
    assert_eq!(repo.config.author_key, Some(key));
273
    // Config survives reopen; the secret key is found again.
274
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
275
    assert_eq!(reopened.config.author_key, Some(key));
276
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
277
278
    // Default core.sign = seal: commits carry the author but no signature.
279
    write(root, "a.txt", b"a\nb\n");
280
    let h1 = repo.commit("authored", &[]).unwrap();
281
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
282
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
283
    // Signing later works too.
284
    repo.sign_change(&h1).unwrap();
285
    assert!(matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key));
286
287
    repo.config.set("core.sign", "change").unwrap();
288
    repo.save_config().unwrap();
289
    write(root, "a.txt", b"a\nb\nc\n");
290
    let h2 = repo.commit("signed", &[]).unwrap();
291
    assert_eq!(repo.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, name: "Ada".into(), email: "[email protected]".into(), sealed: false });
292
293
    // A signature by a key that is not the author or a delegate is rejected.
294
    let other = SecretKey::generate();
295
    let other_id = other.identity("Mallory", "[email protected]", 0);
296
    let other_key = repo.store().put_identity(&other_id).unwrap();
297
    let forged = other.sign(Domain::Change, &other_key, &h0);
298
    repo.store().put_signature(&h0, &forged).unwrap();
299
    assert!(matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author")));
300
301
    // Tampering with the stored signature invalidates it.
302
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
303
    sig.ed[0] ^= 1;
304
    repo.store().put_signature(&h2, &sig).unwrap();
305
    assert!(matches!(repo.verify_change(&h2).unwrap(), SignatureStatus::Invalid(_)));
306
307
    // Without the secret key, signing at commit fails cleanly.
308
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
309
    write(root, "a.txt", b"z\n");
310
    assert!(no_keys.commit("cannot sign", &[]).is_err());
311
}
312
313
#[test]
314
fn checkout_moves_the_working_copy() {
315
    hermetic();
316
    let dir = tempfile::tempdir().unwrap();
317
    let root = dir.path();
318
    let repo = Repo::init(root).unwrap();
319
    write(root, "a.txt", b"one\n");
320
    write(root, "sub/deep/b.txt", b"b\n");
321
    let h1 = repo.commit("first", &[]).unwrap();
322
    write(root, "a.txt", b"two\n");
323
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
324
    write(root, "bin.dat", &[0, 1, 2, 3]);
325
    let h2 = repo.commit("second", &[]).unwrap();
326
327
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
328
    assert_eq!(r, CheckoutReport { written: 2, removed: 1, conflicted: false });
329
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
330
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
331
    assert!(!root.join("bin.dat").exists());
332
    let (_, wc) = repo.working_copy().unwrap();
333
    assert_eq!(wc.deps, vec![h1]);
334
    assert!(!repo.snapshot("status").unwrap().changed, "checkout leaves a clean working copy");
335
    // The bookmark still points at h2.
336
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
337
338
    // Dirty working copy refuses without --discard.
339
    write(root, "a.txt", b"dirty\n");
340
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
341
    let r = repo.checkout(&[h2], true, "oxy checkout --discard").unwrap();
342
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
343
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
344
    assert!(!root.join("sub").exists(), "empty directories are pruned");
345
    assert_eq!(r.removed, 1);
346
    assert!(!repo.snapshot("status").unwrap().changed);
347
348
    // Refuses to write through a symlinked directory.
349
    #[cfg(unix)]
350
    {
351
        fs::remove_dir_all(root.join("sub")).ok();
352
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
353
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
354
    }
355
}
356
357
#[test]
358
fn large_files_are_chunked_and_read_back() {
359
    hermetic();
360
    let dir = tempfile::tempdir().unwrap();
361
    let repo = Repo::init(dir.path()).unwrap();
362
    let mut big = vec![0u8; 700 * 1024];
363
    for (i, b) in big.iter_mut().enumerate() {
364
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
365
    }
366
    let r = repo.store_blob(&big).unwrap();
367
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
368
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
369
    assert_eq!(repo.read_blob(&r).unwrap(), big);
370
    assert_eq!(Repo::blob_ref(&big), r);
371
}
372
373
#[test]
374
fn clone_push_pull_with_seals_and_attestations() {
375
    hermetic();
376
    let dir = tempfile::tempdir().unwrap();
377
    let root = dir.path();
378
    let origin_path = root.join("origin");
379
    let origin = Repo::init(&origin_path).unwrap();
380
    let origin_url = origin_path.to_string_lossy().to_string();
381
382
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
383
    let mut a = Repo::clone(&origin_url, &root.join("a")).unwrap().with_home(root.join("home-a"));
384
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
385
    let (key_a, _) = a.create_identity("Ada", "[email protected]", IdentityScope::Repo).unwrap();
386
    write(&root.join("a"), "f.txt", b"a\n");
387
    let h1 = a.commit("first", &[]).unwrap();
388
    let results = a.push("origin", false).unwrap();
389
    assert!(results[0].ok, "{}", results[0].reason);
390
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
391
    // The change was sealed at push and the reference attested.
392
    assert!(matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a));
393
    assert_eq!(origin.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
394
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
395
    assert!(matches!(att.attest.body, AttestBody::Ref { serial: 1, .. }));
396
    let again = a.push("origin", false).unwrap();
397
    assert!(again[0].ok && again[0].reason.contains("up to date"));
398
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
399
    assert!(matches!(att.attest.body, AttestBody::Ref { serial: 1, .. }), "a no-op push does not attest again");
400
401
    // B clones and sees the file and the seal.
402
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
403
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
404
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
405
    assert!(matches!(b.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { sealed: true, .. }));
406
407
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
408
    write(&root.join("b"), "f.txt", b"a\nb\n");
409
    let h2 = b.commit("second", &[]).unwrap();
410
    assert!(b.push("origin", false).unwrap()[0].ok);
411
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
412
413
    // A commits an independent change; push is refused until A pulls.
414
    write(&root.join("a"), "g.txt", b"g\n");
415
    let h3 = a.commit("third", &[]).unwrap();
416
    assert!(a.push("origin", false).is_err());
417
    let pr = a.pull("origin").unwrap();
418
    assert!(pr.changed && pr.checked_out);
419
    let mut want = vec![h2, h3];
420
    want.sort();
421
    assert_eq!(pr.heads, want);
422
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
423
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
424
    let results = a.push("origin", false).unwrap();
425
    assert!(results[0].ok, "{}", results[0].reason);
426
    let mut origin_heads = origin.bookmark_heads().unwrap();
427
    origin_heads.sort();
428
    assert_eq!(origin_heads, want);
429
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
430
    assert!(matches!(att.attest.body, AttestBody::Ref { serial: 2, .. }));
431
432
    // B pulls and ends up identical.
433
    let pr = b.pull("origin").unwrap();
434
    assert_eq!(pr.heads, want);
435
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
436
    assert!(!b.snapshot("status").unwrap().changed);
437
438
    // Concurrent edits of the same line: the union is a reified conflict.
439
    write(&root.join("a"), "f.txt", b"a\nA\n");
440
    a.commit("a-edit", &[]).unwrap();
441
    a.push("origin", false).unwrap();
442
    write(&root.join("b"), "f.txt", b"a\nB\n");
443
    b.commit("b-edit", &[]).unwrap();
444
    let pr = b.pull("origin").unwrap();
445
    assert!(pr.changed && pr.checked_out);
446
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
447
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
448
    write(&root.join("b"), "f.txt", b"a\nAB\n");
449
    let hr = b.commit("resolve", &[]).unwrap();
450
    assert_eq!(b.store().get_change(&hr).unwrap().kind, ChangeKind::Resolution);
451
    assert!(b.push("origin", false).unwrap()[0].ok);
452
    a.pull("origin").unwrap();
453
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
454
    // The resolution depends on the conflicting edits, but nothing depends
455
    // on "third" (it only added g.txt), so it stays a head beside it.
456
    let mut want = vec![hr, h3];
457
    want.sort();
458
    assert_eq!(a.bookmark_heads().unwrap(), want);
459
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
460
}
461
462
#[test]
463
fn receive_push_rejects_bad_updates() {
464
    hermetic();
465
    let dir = tempfile::tempdir().unwrap();
466
    let root = dir.path();
467
    let origin = Repo::init(&root.join("origin")).unwrap();
468
    let url = root.join("origin").to_string_lossy().to_string();
469
    let mut a = Repo::clone(&url, &root.join("a")).unwrap().with_home(root.join("home"));
470
    let (key, _) = a.create_identity("Ada", "a@b", IdentityScope::Repo).unwrap();
471
    write(&root.join("a"), "f.txt", b"x\n");
472
    let h1 = a.commit("one", &[]).unwrap();
473
    assert!(a.push("origin", false).unwrap()[0].ok);
474
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
475
    let s1 = origin.store().put_state(&StateObject::new(vec![h1])).unwrap();
476
477
    // Missing head.
478
    let ghost = origin.store().put_state(&StateObject::new(vec![ObjectRef([9; 32])])).unwrap();
479
    let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: s1, new_state: ghost, force: false, attestation: None }]).unwrap();
480
    assert!(!r[0].ok && r[0].reason.contains("missing"), "{}", r[0].reason);
481
482
    // Stale old_state.
483
    let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: empty, new_state: s1, force: false, attestation: None }]).unwrap();
484
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
485
486
    // Non-fast-forward without force is refused; with force it passes.
487
    let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: s1, new_state: empty, force: false, attestation: None }]).unwrap();
488
    assert!(!r[0].ok && r[0].reason.contains("fast-forward"), "{}", r[0].reason);
489
    let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: s1, new_state: empty, force: true, attestation: None }]).unwrap();
490
    assert!(r[0].ok);
491
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
492
493
    // Attestation with a stale serial is a rollback and is refused.
494
    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();
495
    let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: empty, new_state: s1, force: false, attestation: Some(sa.clone()) }]).unwrap();
496
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{}", r[0].reason);
497
    // An attestation for a different update is refused too.
498
    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();
499
    let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: empty, new_state: s1, force: false, attestation: Some(sa2) }]).unwrap();
500
    assert!(!r[0].ok && r[0].reason.contains("describe"), "{}", r[0].reason);
501
    let _ = key;
502
}
503
504
#[test]
505
fn user_config_supplies_defaults_and_clones_sign() {
506
    hermetic();
507
    let dir = tempfile::tempdir().unwrap();
508
    let root = dir.path();
509
    let home = root.join("home");
510
    let origin = Repo::init(&root.join("origin")).unwrap();
511
    let url = root.join("origin").to_string_lossy().to_string();
512
513
    // Identity at user scope: the repository file stays free of author keys.
514
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
515
    let (key, _) = a.create_identity("Ada", "[email protected]", IdentityScope::User).unwrap();
516
    assert!(!a.config.repo_layer().contains_key("author.key"));
517
    assert_eq!(a.config.author_key, Some(key));
518
    assert!(home.join("config.toml").exists());
519
    a.set_user_config("core.sign", "change").unwrap();
520
    assert!(a.config.sign_changes);
521
522
    // Repository settings override user settings and are the only ones saved.
523
    a.config.set("core.sign", "seal").unwrap();
524
    a.save_config().unwrap();
525
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
526
    assert!(!again.config.sign_changes);
527
    assert_eq!(again.config.author_key, Some(key));
528
    assert_eq!(read_config_file(&root.join("a/.oxy/config")).unwrap().get("core.sign").map(String::as_str), Some("seal"));
529
530
    // A fresh clone made by this user signs with the user-level identity,
531
    // even though the clone's store has never seen the identity object.
532
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
533
    assert!(b.config.sign_changes);
534
    write(&root.join("b"), "f.txt", b"f\n");
535
    let h = b.commit("signed from a clone", &[]).unwrap();
536
    assert!(matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key));
537
    assert!(b.push("origin", false).unwrap()[0].ok);
538
    assert!(matches!(origin.verify_change(&h).unwrap(), SignatureStatus::Valid { .. }));
539
}
540
541
#[test]
542
fn format1_repositories_are_migrated_on_open() {
543
    hermetic();
544
    use crate::oplog::{Format1Op, Format1View};
545
    let dir = tempfile::tempdir().unwrap();
546
    let root = dir.path();
547
    let repo = Repo::init(root).unwrap();
548
    write(root, "a.txt", b"a\n");
549
    let h1 = repo.commit("one", &[]).unwrap();
550
    let (wc_hash, _) = repo.working_copy().unwrap();
551
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
552
    let mut v1 = Format1View::default();
553
    v1.bookmarks.insert("main".into(), vec![]);
554
    v1.workspaces.insert(repo.workspace(), wc_hash);
555
    let init = Format1Op { parents: vec![], hlc: Hlc::default(), command: "oxy init".into(), view: v1.clone() };
556
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
557
    v1.bookmarks.insert("main".into(), vec![h1]);
558
    let commit = Format1Op { parents: vec![init_ref], hlc: Hlc::default(), command: "oxy commit".into(), view: v1 };
559
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
560
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
561
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
562
    drop(repo);
563
564
    let repo = Repo::open(root).unwrap();
565
    assert_eq!(fs::read_to_string(root.join(".oxy/format")).unwrap(), FORMAT_LINE);
566
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
567
    let ops = repo.op_log().unwrap();
568
    assert_eq!(ops.iter().map(|(_, o)| o.command.as_str()).collect::<Vec<_>>(), ["oxy commit", "oxy init"]);
569
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
570
    assert!(!repo.snapshot("status").unwrap().changed);
571
    // Reopening again is a no-op.
572
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
573
}
574
575
#[test]
576
fn undo_skips_snapshot_operations() {
577
    hermetic();
578
    let dir = tempfile::tempdir().unwrap();
579
    let root = dir.path();
580
    let repo = Repo::init(root).unwrap();
581
    write(root, "a.txt", b"a\n");
582
    let h1 = repo.commit("a", &[]).unwrap();
583
    // A later command snapshots new edits on top of the commit.
584
    write(root, "b.txt", b"b\n");
585
    let s = repo.snapshot("oxy status").unwrap();
586
    assert!(s.changed);
587
    assert!(repo.head_op().unwrap().1.is_snapshot());
588
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
589
    // Undo must undo the commit, not the snapshot.
590
    repo.undo().unwrap();
591
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
592
    let s = repo.snapshot("oxy status").unwrap();
593
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
594
    assert_eq!(paths, ["a.txt", "b.txt"], "both files are back in the working copy");
595
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
596
    // Only snapshots remain above `init`, so there is nothing left to undo.
597
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
598
    assert!(repo.undo().is_err());
599
}
600
601
#[test]
602
fn independent_changes_commute_and_make_multiple_heads() {
603
    hermetic();
604
    let dir = tempfile::tempdir().unwrap();
605
    let root = dir.path();
606
    let repo = Repo::init(root).unwrap();
607
    write(root, "a.txt", b"a\n");
608
    let h1 = repo.commit("a", &[]).unwrap();
609
    write(root, "b.txt", b"b\n");
610
    let h2 = repo.commit("b", &[]).unwrap();
611
    let c2 = repo.store().get_change(&h2).unwrap();
612
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
613
    let mut heads = repo.bookmark_heads().unwrap();
614
    heads.sort();
615
    let mut want = vec![h1, h2];
616
    want.sort();
617
    assert_eq!(heads, want);
618
    // Editing a.txt depends on h1 only.
619
    write(root, "a.txt", b"a\na2\n");
620
    let h3 = repo.commit("a2", &[]).unwrap();
621
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
622
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
623
    assert_eq!(heads, [h2, h3].into_iter().collect());
624
    // Explicit dependency.
625
    write(root, "c.txt", b"c\n");
626
    let h4 = repo.commit("c", &[h2]).unwrap();
627
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
628
}
629
630
#[test]
631
fn mode_change_and_text_binary_switch() {
632
    hermetic();
633
    let dir = tempfile::tempdir().unwrap();
634
    let root = dir.path();
635
    let repo = Repo::init(root).unwrap();
636
    write(root, "run.sh", b"#!/bin/sh\n");
637
    repo.commit("add script", &[]).unwrap();
638
    #[cfg(unix)]
639
    {
640
        use std::os::unix::fs::PermissionsExt;
641
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
642
        let s = repo.snapshot("status").unwrap();
643
        assert_eq!(statuses(&s), vec![("run.sh".into(), ChangeStatus::ModeChanged)]);
644
        let h = repo.commit("exec", &[]).unwrap();
645
        let snap = repo.load_state(&[h]).unwrap().materialize();
646
        assert!(snap.files["run.sh"].mode.exec);
647
    }
648
    // Text → binary → text.
649
    write(root, "run.sh", b"\0binary");
650
    let h = repo.commit("binary", &[]).unwrap();
651
    let snap = repo.load_state(&[h]).unwrap().materialize();
652
    assert!(snap.files["run.sh"].mode.opaque);
653
    write(root, "run.sh", b"text again\n");
654
    let h = repo.commit("text", &[]).unwrap();
655
    let snap = repo.load_state(&[h]).unwrap().materialize();
656
    assert!(!snap.files["run.sh"].mode.opaque);
657
    assert!(matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n"));
658
    assert!(!snap.is_conflicted());
659
}