OXYGENHUB
# e8b4e156f2fa oxygen / crates / oxy-core / src / repo / tests.rs
44.1 KiB · Rust · last changed Git bridge, export side: one commit per bookmark state via git fast-import, Change-Id/Oxy-Hash/Oxy-State trailers, incremental marks 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 });
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 });
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).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).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).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).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).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).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)).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)).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
    // Non-heads cannot be rewritten yet.
841
    assert!(repo.describe(&h1, "x").is_err());
842
843
    // amend: fold an edit into the head; the result is one change from h1.
844
    write(root, "a.txt", b"one\ntwo\nthree\n");
845
    write(root, "b.txt", b"b\n");
846
    let h2c = repo.amend(None).unwrap();
847
    let c = repo.store().get_change(&h2c).unwrap();
848
    assert_eq!(c.change_id, id2);
849
    assert_eq!(c.message, "second");
850
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
851
    assert_eq!(repo.log().unwrap().len(), 3, "working copy, amended head, first");
852
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
853
    assert!(matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n"));
854
    assert!(snap.files.contains_key("b.txt"));
855
    assert!(!repo.snapshot("status").unwrap().changed);
856
    assert!(repo.amend(None).is_err(), "clean working copy and no message");
857
    let h2d = repo.amend(Some("second, amended")).unwrap();
858
    assert_eq!(repo.store().get_change(&h2d).unwrap().message, "second, amended");
859
860
    // abandon: the head goes, its content stays as uncommitted work.
861
    repo.abandon(&h2d).unwrap();
862
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
863
    let s = repo.snapshot("status").unwrap();
864
    let paths: Vec<_> = s.statuses.iter().map(|p| (p.path.as_str(), p.status)).collect();
865
    assert_eq!(paths, vec![("a.txt", ChangeStatus::Modified), ("b.txt", ChangeStatus::Added)]);
866
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
867
    let h3 = repo.commit("recommitted", &[]).unwrap();
868
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
869
    // undo brings the abandoned head back.
870
    repo.undo().unwrap();
871
    repo.undo().unwrap();
872
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
873
}
874
875
#[test]
876
fn git_export_mirrors_history() {
877
    hermetic();
878
    if std::process::Command::new("git").arg("--version").output().is_err() {
879
        eprintln!("git not installed; skipping");
880
        return;
881
    }
882
    let dir = tempfile::tempdir().unwrap();
883
    let root = dir.path();
884
    let mut repo = Repo::init(&root.join("r")).unwrap().with_home(root.join("home"));
885
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User).unwrap();
886
    let r = root.join("r");
887
    write(&r, "README.md", b"hello\n");
888
    write(&r, "src/main.rs", b"fn main() {}\n");
889
    let h1 = repo.commit("first", &[]).unwrap();
890
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
891
    write(&r, "logo.png", b"\x89PNG\0\0");
892
    let h2 = repo.commit("second", &[]).unwrap();
893
894
    let git_dir = root.join("mirror.git");
895
    let rep = repo.git_export(&git_dir).unwrap();
896
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
897
    let git = |args: &[&str]| -> String {
898
        let out = std::process::Command::new("git").arg("-C").arg(&git_dir).args(args).output().unwrap();
899
        assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
900
        String::from_utf8_lossy(&out.stdout).trim().to_string()
901
    };
902
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
903
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
904
    assert_eq!(git(&["show", "main:README.md"]), "hello");
905
    let body = git(&["log", "-1", "--format=%B", "main"]);
906
    assert!(body.contains(&format!("Oxy-Hash: {}", h2.to_hex())), "{body}");
907
    assert!(body.contains("Change-Id: "), "{body}");
908
    assert_eq!(git(&["log", "-1", "--format=%an <%ae>", "main"]), "Ada Lovelace <[email protected]>");
909
    assert_eq!(git(&["ls-tree", "--name-only", "main"]), "README.md\nlogo.png\nsrc");
910
911
    // Re-export is incremental.
912
    let rep = repo.git_export(&git_dir).unwrap();
913
    assert_eq!((rep.exported, rep.skipped), (0, 2));
914
915
    // An independent change makes two heads; the next state is one more
916
    // commit on the linear branch whose tree is the union.
917
    repo.checkout(&[h1], false, "checkout").unwrap();
918
    write(&r, "other.txt", b"o\n");
919
    let h3 = repo.commit("third", &[]).unwrap();
920
    let rep = repo.git_export(&git_dir).unwrap();
921
    assert_eq!((rep.exported, rep.heads), (1, 2));
922
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
923
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
924
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
925
    assert_eq!(git(&["show", "main:other.txt"]), "o");
926
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
927
    assert_eq!(git(&["ls-tree", "--name-only", "main"]), "README.md\nlogo.png\nother.txt\nsrc");
928
    let body = git(&["log", "-1", "--format=%B", "main"]);
929
    assert!(body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "), "{body}");
930
    // A rewrite is a new state whose one new change is the rewritten one.
931
    repo.describe(&h3, "third, described").unwrap();
932
    let rep = repo.git_export(&git_dir).unwrap();
933
    assert_eq!(rep.exported, 1);
934
    assert_eq!(git(&["log", "-1", "--format=%s", "main"]), "third, described");
935
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
936
    let _ = h2;
937
}