OXYGENHUB
# 6706bdcfb63e oxygen / crates / oxy-core / src / repo / tests.rs
78.2 KiB · Rust · last changed Lazy blobs: clone --max-blob / filter.max-blob, absent-blob registry fetched on first read, objects endpoint (spec 0.6e) 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, 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
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1033
1034
    let dest = root.join("oxy");
1035
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1036
    let rep = repo.import_git(&g, "main").unwrap();
1037
    assert_eq!(rep.commits, expected_count);
1038
    assert_eq!(rep.merges, 2);
1039
    // The working copy equals the Git tree at main.
1040
    assert_eq!(fs::read(dest.join("src/lib.rs")).unwrap(), b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n");
1041
    assert_eq!(fs::read(dest.join("README.md")).unwrap(), b"# Hi\n\nMore.\n");
1042
    assert!(!dest.join("logo.png").exists());
1043
    #[cfg(unix)]
1044
    {
1045
        use std::os::unix::fs::PermissionsExt;
1046
        assert!(fs::metadata(dest.join("run.sh")).unwrap().permissions().mode() & 0o111 != 0);
1047
    }
1048
    assert!(!repo.snapshot("status").unwrap().changed, "clean after import");
1049
    let heads = repo.bookmark_heads().unwrap();
1050
    let st = repo.load_state(&heads).unwrap();
1051
    assert!(!st.materialize().is_conflicted());
1052
    assert_eq!(st.len(), expected_count);
1053
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1054
    let log = repo.log().unwrap();
1055
    let second = log.iter().find(|e| e.change.message.starts_with("second")).unwrap();
1056
    assert_eq!(second.change.change_id, ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap());
1057
    assert!(second.change.message.contains("Git-Author: Grace <[email protected]>"));
1058
    let resolve = log.iter().find(|e| e.change.message.starts_with("resolve clash")).unwrap();
1059
    assert_eq!(resolve.change.kind, ChangeKind::Resolution, "a conflicting Git merge becomes a resolution");
1060
    // Re-importing into another fresh repository gives the same ChangeIds.
1061
    let repo2 = Repo::init(&root.join("oxy2")).unwrap().with_home(root.join("home"));
1062
    repo2.import_git(&g, "main").unwrap();
1063
    let ids: BTreeSet<ChangeId> = repo.log().unwrap().iter().filter(|e| !e.is_working_copy).map(|e| e.change.change_id).collect();
1064
    let ids2: BTreeSet<ChangeId> = repo2.log().unwrap().iter().filter(|e| !e.is_working_copy).map(|e| e.change.change_id).collect();
1065
    assert_eq!(ids, ids2);
1066
    // Round trip back out to Git reproduces the tip tree.
1067
    let mirror = root.join("mirror.git");
1068
    repo.git_export(&mirror).unwrap();
1069
    let out = std::process::Command::new("git").arg("-C").arg(&mirror).args(["show", "main:src/lib.rs"]).output().unwrap();
1070
    assert_eq!(String::from_utf8_lossy(&out.stdout), "pub fn a() {}\npub fn b() {}\npub fn c() {}\n");
1071
}
1072
1073
#[test]
1074
fn checkpoints_accelerate_loading_and_stay_correct() {
1075
    hermetic();
1076
    let dir = tempfile::tempdir().unwrap();
1077
    let root = dir.path();
1078
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1079
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1080
    repo.save_config().unwrap();
1081
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1082
    let mut hashes = Vec::new();
1083
    for i in 0..12 {
1084
        write(root, "a.txt", format!("{}\n", (0..=i).map(|k| k.to_string()).collect::<Vec<_>>().join("\n")).as_bytes());
1085
        write(root, &format!("f{i}.txt"), b"x\n");
1086
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1087
    }
1088
    let (_, cp) = repo.latest_checkpoint("main").unwrap().expect("automatic checkpoint");
1089
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1090
    // Loading through the checkpoint equals loading everything.
1091
    let heads = repo.bookmark_heads().unwrap();
1092
    let fast = repo.load_state(&heads).unwrap();
1093
    let full = repo.load_state_full(&heads).unwrap();
1094
    assert_eq!(fast.len(), full.len());
1095
    assert_eq!(fast.heads(), full.heads());
1096
    let (a, b) = (fast.materialize(), full.materialize());
1097
    assert_eq!(a.files.keys().collect::<Vec<_>>(), b.files.keys().collect::<Vec<_>>());
1098
    for (p, f) in &a.files {
1099
        assert_eq!(f.content, b.files[p].content, "{p}");
1100
    }
1101
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1102
    // A head set that does not contain the checkpoint's heads falls back.
1103
    assert!(repo.load_state_checkpointed(&[hashes[0]]).unwrap().is_none());
1104
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1105
    // Everything else keeps working on top of the checkpoint.
1106
    assert!(!repo.snapshot("status").unwrap().changed);
1107
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1108
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1109
    let (r, n, bytes) = repo.checkpoint().unwrap();
1110
    assert!(n >= 12 && bytes > 0);
1111
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1112
    write(root, "a.txt", b"after\n");
1113
    let h_after = repo.commit("after", &[]).unwrap();
1114
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1115
    assert!(st.contains(&h_after));
1116
    assert!(matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n"));
1117
    assert_eq!(repo.log().unwrap().len(), 14);
1118
    // Checkpoints survive gc.
1119
    repo.gc(true).unwrap();
1120
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1121
    assert!(repo.load_state_checkpointed(&repo.bookmark_heads().unwrap()).unwrap().is_some());
1122
}
1123
1124
#[test]
1125
fn quick_status_for_prompts() {
1126
    hermetic();
1127
    let dir = tempfile::tempdir().unwrap();
1128
    let root = dir.path();
1129
    let origin = Repo::init(&root.join("origin")).unwrap();
1130
    let url = root.join("origin").to_string_lossy().to_string();
1131
    let a = Repo::clone(&url, &root.join("a")).unwrap().with_home(root.join("home"));
1132
    let ops_before = a.op_log().unwrap().len();
1133
    let info = a.quick_status().unwrap();
1134
    assert_eq!((info.bookmark.as_str(), info.heads, info.dirty, info.conflicted, info.ahead, info.behind), ("main", 0, false, false, Some(0), Some(0)));
1135
    write(&root.join("a"), "f.txt", b"f\n");
1136
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1137
    assert_eq!(a.op_log().unwrap().len(), ops_before, "quick_status records nothing");
1138
    // A snapshotted but uncommitted change is still dirty.
1139
    a.snapshot("status").unwrap();
1140
    assert!(a.quick_status().unwrap().dirty);
1141
    a.commit("f", &[]).unwrap();
1142
    let info = a.quick_status().unwrap();
1143
    assert!(!info.dirty, "clean right after a commit");
1144
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
1145
    assert_eq!(info.format("%b %c%d%x%A%D"), format!("main {}+1", info.change_id));
1146
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1147
    // Touching a file without changing it is not dirty; changing content of
1148
    // the same size is.
1149
    let p = root.join("a/f.txt");
1150
    let content = fs::read(&p).unwrap();
1151
    fs::write(&p, &content).unwrap();
1152
    assert!(!a.quick_status().unwrap().dirty);
1153
    fs::write(&p, b"g\n").unwrap();
1154
    assert!(a.quick_status().unwrap().dirty);
1155
    fs::write(&p, b"f\n").unwrap();
1156
    // Push, then a second clone commits and pushes: we are behind.
1157
    assert!(a.push("origin", false).unwrap()[0].ok);
1158
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
1159
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(root.join("home-b"));
1160
    write(&root.join("b"), "g.txt", b"g\n");
1161
    b.commit("g", &[]).unwrap();
1162
    b.push("origin", false).unwrap();
1163
    a.fetch("origin").unwrap();
1164
    let info = a.quick_status().unwrap();
1165
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1166
    assert_eq!(info.format("%A%D"), "-1");
1167
    let _ = origin;
1168
}
1169
1170
#[test]
1171
fn lazy_blobs_are_fetched_on_first_read() {
1172
    hermetic();
1173
    let dir = tempfile::tempdir().unwrap();
1174
    let root = dir.path();
1175
    let origin_dir = root.join("origin");
1176
    let origin = Repo::init(&origin_dir).unwrap().with_home(root.join("home"));
1177
    let url = origin_dir.to_string_lossy().to_string();
1178
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1179
    write(&origin_dir, "big.bin", &big);
1180
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1181
    write(&origin_dir, "t.txt", b"t\n");
1182
    let h = origin.commit("blobs", &[]).unwrap();
1183
    let big_ref = Repo::blob_ref(&big);
1184
1185
    // Fetch only (no checkout) with a filter: the big blob stays absent.
1186
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap()).unwrap().with_home(root.join("home"));
1187
    let a = {
1188
        let mut a = a;
1189
        a.config.set("remote.origin.url", &url).unwrap();
1190
        a.config.set("filter.max-blob", "100K").unwrap();
1191
        a.save_config().unwrap();
1192
        a
1193
    };
1194
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1195
    a.fetch("origin").unwrap();
1196
    assert!(a.store().has(&h));
1197
    assert!(!a.store().has(&big_ref), "withheld");
1198
    assert!(a.store().has(&Repo::blob_ref(&[0u8, 1, 2])), "small blob came along");
1199
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1200
1201
    // status and commit do not need it: adopt the state, edit a text file, commit.
1202
    let (op_ref, op) = a.head_op().unwrap();
1203
    let mut view = op.view.clone();
1204
    view.bookmarks.insert("main".into(), a.store().put_state(&StateObject::new(vec![h])).unwrap());
1205
    a.record_op(&[op_ref], "adopt", view).unwrap();
1206
    // Checkout reads the blob lazily, which fetches it.
1207
    a.checkout(&[h], true, "checkout").unwrap();
1208
    assert!(a.store().has(&big_ref), "fetched on first read");
1209
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1210
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1211
    write(&root.join("a"), "t.txt", b"t2\n");
1212
    a.commit("text edit", &[]).unwrap();
1213
1214
    // clone --max-blob records the filter; the checkout fetches lazily.
1215
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
1216
    assert_eq!(b.config.max_blob, Some(1024));
1217
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1218
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1219
    assert!(parse_size("lots").is_err());
1220
}
1221
1222
#[test]
1223
fn sparse_checkout_materializes_only_chosen_paths() {
1224
    hermetic();
1225
    let dir = tempfile::tempdir().unwrap();
1226
    let root = dir.path();
1227
    let origin_dir = root.join("origin");
1228
    let origin = Repo::init(&origin_dir).unwrap().with_home(root.join("home"));
1229
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1230
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1231
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1232
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1233
    write(&origin_dir, "docs/logo.png", &logo);
1234
    write(&origin_dir, "README.md", b"# top\n");
1235
    let h1 = origin.commit("tree", &[]).unwrap();
1236
    let url = origin_dir.to_string_lossy().to_string();
1237
1238
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()]).unwrap().with_home(root.join("home"));
1239
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1240
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1241
    assert!(root.join("a/src/main.rs").exists());
1242
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
1243
    assert!(!a.store().has(&Repo::blob_ref(&logo)), "out-of-scope blob never fetched");
1244
    assert!(!a.snapshot("status").unwrap().changed, "out-of-scope files are not removals");
1245
    assert_eq!(a.quick_status().unwrap().dirty, false);
1246
1247
    // Edits in scope commit normally and keep the rest of the tree intact.
1248
    write(&root.join("a"), "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1249
    let h2 = a.commit("edit lib", &[]).unwrap();
1250
    let st = a.load_state(&[h2]).unwrap().materialize();
1251
    assert!(st.files.contains_key("docs/guide.md"), "the state still has everything");
1252
    assert!(a.push("origin", false).unwrap()[0].ok);
1253
    // Files created outside the scope are ignored by status.
1254
    write(&root.join("a"), "docs/new.md", b"ignored\n");
1255
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
1256
1257
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
1258
    let mut a = a;
1259
    a.config.set("filter.paths", "src,docs").unwrap();
1260
    a.save_config().unwrap();
1261
    let r = a.checkout(&a.bookmark_heads().unwrap(), true, "widen").unwrap();
1262
    assert!(r.written >= 2);
1263
    assert_eq!(fs::read(root.join("a/docs/logo.png")).unwrap(), logo, "now fetched lazily");
1264
    assert!(!root.join("a/README.md").exists());
1265
    // Origin sees the change made under a sparse checkout with the full tree intact.
1266
    origin.pull("origin").err();
1267
    let full = origin.load_state(&origin.bookmark_heads().unwrap()).unwrap().materialize();
1268
    assert!(matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n"));
1269
    assert!(full.files.contains_key("README.md"));
1270
    let _ = h1;
1271
}
1272
1273
#[test]
1274
fn shallow_clone_and_deepen() {
1275
    hermetic();
1276
    let dir = tempfile::tempdir().unwrap();
1277
    let root = dir.path();
1278
    let origin_dir = root.join("origin");
1279
    let origin = Repo::init(&origin_dir).unwrap().with_home(root.join("home"));
1280
    let mut hashes = Vec::new();
1281
    for i in 0..8 {
1282
        write(&origin_dir, "a.txt", format!("{}\n", (0..=i).map(|k| k.to_string()).collect::<Vec<_>>().join("\n")).as_bytes());
1283
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
1284
    }
1285
    let url = origin_dir.to_string_lossy().to_string();
1286
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[]).unwrap().with_home(root.join("home"));
1287
    assert!(a.is_shallow());
1288
    assert_eq!(fs::read_to_string(root.join("a/a.txt")).unwrap(), "0\n1\n2\n3\n4\n5\n6\n7\n");
1289
    assert!(a.store().has(&hashes[7]) && a.store().has(&hashes[5]), "three levels present");
1290
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
1291
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
1292
    assert_eq!(a.log().unwrap().len(), 9, "the log shows every change from the checkpoint's metadata");
1293
    assert!(!a.snapshot("status").unwrap().changed);
1294
    assert_eq!(a.quick_status().unwrap().heads, 1);
1295
1296
    // Work continues on top of the shallow history and pushes back.
1297
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
1298
    let h_new = a.commit("c8", &[]).unwrap();
1299
    assert!(a.push("origin", false).unwrap()[0].ok);
1300
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
1301
    // Fetching new work from origin into the shallow clone works too.
1302
    write(&origin_dir, "b.txt", b"b\n");
1303
    origin.pull("origin").err();
1304
    let (_, wc) = origin.working_copy().unwrap();
1305
    let _ = wc;
1306
    origin.checkout(&origin.bookmark_heads().unwrap(), true, "co").unwrap();
1307
    write(&origin_dir, "b.txt", b"b\n");
1308
    let h_b = origin.commit("b", &[]).unwrap();
1309
    let pr = a.pull("origin").unwrap();
1310
    assert!(pr.changed);
1311
    assert!(a.store().has(&h_b));
1312
    assert!(root.join("a/b.txt").exists());
1313
1314
    // Deepening fetches older history until the boundary is gone.
1315
    // Every commit also depends on the change that created the file, so two
1316
    // levels below the boundary hold h4, h3, and the root.
1317
    assert!(a.deepen("origin", 2).unwrap() >= 2);
1318
    assert!(a.store().has(&hashes[3]));
1319
    assert!(a.is_shallow());
1320
    a.deepen("origin", 100).unwrap();
1321
    assert!(!a.is_shallow(), "boundary reached the root");
1322
    assert!(a.store().has(&hashes[0]));
1323
    assert_eq!(a.load_state_full(&a.bookmark_heads().unwrap()).unwrap().len(), 10);
1324
}
1325
1326
#[test]
1327
fn tags_are_immutable_named_states_and_travel() {
1328
    hermetic();
1329
    let dir = tempfile::tempdir().unwrap();
1330
    let root = dir.path();
1331
    let origin = Repo::init(&root.join("origin")).unwrap();
1332
    let url = root.join("origin").to_string_lossy().to_string();
1333
    let mut a = Repo::clone(&url, &root.join("a")).unwrap().with_home(root.join("home-a"));
1334
    let (key_a, _) = a.create_identity("Ada", "[email protected]", IdentityScope::User).unwrap();
1335
    write(&root.join("a"), "f.txt", b"1\n");
1336
    let h1 = a.commit("one", &[]).unwrap();
1337
    write(&root.join("a"), "f.txt", b"1\n2\n");
1338
    let h2 = a.commit("two", &[]).unwrap();
1339
1340
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
1341
    assert_eq!((t.heads.clone(), t.signer.as_deref()), (vec![h1], Some("Ada")));
1342
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
1343
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
1344
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
1345
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
1346
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
1347
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
1348
    assert_eq!(sa.sigs[0].key, key_a);
1349
    // Checkout by tag.
1350
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co").unwrap();
1351
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
1352
    a.checkout(&a.bookmark_heads().unwrap(), false, "co").unwrap();
1353
1354
    // Push carries the tag; a second attestation for the name is refused.
1355
    let r = a.push("origin", false).unwrap();
1356
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
1357
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
1358
    let mut forged = a.tag_refs().unwrap().into_iter().find(|t| t.name == "v1").unwrap();
1359
    forged.state = origin.store().put_state(&StateObject::new(vec![h2])).unwrap();
1360
    forged.heads = vec![h2];
1361
    forged.attestation = None;
1362
    let r = origin.receive_push(Bundle::default(), vec![], None, vec![forged]).unwrap();
1363
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
1364
1365
    // A clone gets the tag; a later tag arrives on fetch.
1366
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(root.join("home-b"));
1367
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
1368
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
1369
    a.tag_create("v2", &[h2], "second").unwrap();
1370
    a.push("origin", false).unwrap();
1371
    let rep = b.fetch("origin").unwrap();
1372
    assert_eq!(rep.new_tags, 1);
1373
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
1374
1375
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
1376
    a.policy_init().unwrap();
1377
    a.push("origin", false).unwrap();
1378
    let unattested = crate::protocol::TagRef { name: "v3".into(), state: origin.store().put_state(&StateObject::new(vec![h2])).unwrap(), heads: vec![h2], attestation: None };
1379
    let r = origin.receive_push(Bundle::default(), vec![], None, vec![unattested]).unwrap();
1380
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
1381
    a.tag_create("v3", &[h2], "").unwrap();
1382
    let r = a.push("origin", false).unwrap();
1383
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
1384
    assert!(a.gc(true).is_ok());
1385
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
1386
}
1387
1388
#[test]
1389
fn multiple_workspaces_share_a_repository() {
1390
    hermetic();
1391
    let dir = tempfile::tempdir().unwrap();
1392
    let root = dir.path();
1393
    let main_dir = root.join("main");
1394
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
1395
    write(&main_dir, "a.txt", b"a\n");
1396
    let h1 = repo.commit("a", &[]).unwrap();
1397
    assert_eq!(repo.workspaces().unwrap().len(), 1);
1398
1399
    // A second workspace elsewhere, checked out on the bookmark.
1400
    let ws_dir = root.join("ws2");
1401
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
1402
    assert!(ws_dir.join(".oxy").is_file());
1403
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
1404
    assert_ne!(ws.workspace(), repo.workspace());
1405
    let list = repo.workspaces().unwrap();
1406
    assert_eq!(list.len(), 2);
1407
    assert!(list.iter().any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
1408
    assert!(!ws.snapshot("status").unwrap().changed);
1409
1410
    // Work in the second workspace: its own working copy, shared bookmark.
1411
    write(&ws_dir, "b.txt", b"b\n");
1412
    let s = ws.snapshot("status").unwrap();
1413
    assert_eq!(s.statuses.len(), 1);
1414
    assert!(!repo.snapshot("status").unwrap().changed, "the first workspace is untouched");
1415
    let h2 = ws.commit("b from ws2", &[]).unwrap();
1416
    let mut heads = repo.bookmark_heads().unwrap();
1417
    heads.sort();
1418
    let mut want = vec![h1, h2];
1419
    want.sort();
1420
    assert_eq!(heads, want, "both workspaces see the bookmark move");
1421
    assert!(!main_dir.join("b.txt").exists());
1422
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co").unwrap();
1423
    assert!(main_dir.join("b.txt").exists());
1424
1425
    // Reopening from inside the second workspace finds the shared repository.
1426
    let reopened = Repo::open(&ws_dir).unwrap();
1427
    assert_eq!(reopened.workspace(), ws.workspace());
1428
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
1429
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
1430
1431
    // Workspaces cannot nest; forget drops one from the view but keeps files.
1432
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
1433
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
1434
    repo.workspace_forget(&ws.workspace()).unwrap();
1435
    assert_eq!(repo.workspaces().unwrap().len(), 1);
1436
    assert!(ws_dir.join("b.txt").exists());
1437
    assert!(ws.snapshot("status").is_err(), "a forgotten workspace is no longer in the view");
1438
1439
    // The snapshot lock: a fresh lock blocks a second, a stale one is taken over.
1440
    let lock = repo.lock_snapshot().unwrap();
1441
    drop(lock);
1442
    let lock_path = main_dir.join(".oxy/workspaces").join(repo.workspace().to_hex()).join("lock");
1443
    fs::write(&lock_path, "1").unwrap();
1444
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
1445
    fs::File::open(&lock_path).unwrap().set_modified(old).unwrap();
1446
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
1447
}
1448
1449
#[test]
1450
fn attributes_binary_eol_nocompress_lockable() {
1451
    hermetic();
1452
    let dir = tempfile::tempdir().unwrap();
1453
    let root = dir.path();
1454
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
1455
    write(root, ".oxyattributes", b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n");
1456
    write(root, "plain.dat", b"no nul bytes here\n");
1457
    write(root, "notes.txt", b"one\r\ntwo\r\n");
1458
    write(root, "assets/model.bin", b"\0model");
1459
    let h = repo.commit("attrs", &[]).unwrap();
1460
    let snap = repo.load_state(&[h]).unwrap().materialize();
1461
    assert!(snap.files["plain.dat"].mode.opaque, "binary attribute forces opaque without NUL bytes");
1462
    assert!(matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"), "stored with LF");
1463
    assert!(!repo.snapshot("status").unwrap().changed, "CRLF on disk equals LF in the state");
1464
    // nocompress chunks pack raw.
1465
    let r = repo.gc(true).unwrap();
1466
    assert!(r.packed.objects > 0);
1467
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
1468
    fs::remove_file(root.join("notes.txt")).unwrap();
1469
    repo.checkout(&[h], true, "co").unwrap();
1470
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
1471
    assert!(fs::metadata(root.join("assets/model.bin")).unwrap().permissions().readonly());
1472
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
1473
    repo.lock_path("assets/model.bin").unwrap();
1474
    assert!(!fs::metadata(root.join("assets/model.bin")).unwrap().permissions().readonly());
1475
    assert!(repo.is_locked("assets/model.bin"));
1476
    write(root, "assets/model.bin", b"\0model2");
1477
    repo.commit("edit model", &[]).unwrap();
1478
    repo.unlock_path("assets/model.bin").unwrap();
1479
    assert!(fs::metadata(root.join("assets/model.bin")).unwrap().permissions().readonly());
1480
    // A later checkout can still overwrite a read-only lockable file.
1481
    repo.checkout(&[h], true, "co").unwrap();
1482
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
1483
}
1484
1485
#[cfg(unix)]
1486
#[test]
1487
fn hooks_can_veto_observe_and_add_dependencies() {
1488
    use std::os::unix::fs::PermissionsExt;
1489
    hermetic();
1490
    let dir = tempfile::tempdir().unwrap();
1491
    let root = dir.path();
1492
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1493
    let hooks = root.join(".oxy/hooks");
1494
    fs::create_dir_all(&hooks).unwrap();
1495
    let hook = |name: &str, body: &str| {
1496
        let p = hooks.join(name);
1497
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
1498
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
1499
    };
1500
    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");
1501
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
1502
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
1503
    hook("pre-push", "echo pushing blocked >&2; exit 3");
1504
    write(root, ".oxyignore", b".last-*\n");
1505
    write(root, "a.txt", b"a\n");
1506
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
1507
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
1508
    let h1 = repo.commit("first", &[]).unwrap();
1509
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
1510
    assert!(pre.contains("\"event\":\"pre-commit\"") && pre.contains("\"path\":\"a.txt\"") && pre.contains("\"message\":\"first\""), "{pre}");
1511
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
1512
    assert!(post.contains(&h1.to_hex()), "{post}");
1513
    repo.checkout(&[h1], false, "co").unwrap();
1514
    assert!(fs::read_to_string(root.join(".last-post-checkout")).unwrap().contains("post-checkout"));
1515
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
1516
    repo.save_config().unwrap();
1517
    let err = repo.push("origin", false).unwrap_err().to_string();
1518
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
1519
1520
    // semantic-deps: only when enabled; adds an explicit dependency.
1521
    write(root, "b.txt", b"b\n");
1522
    hook("semantic-deps", &format!("cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'", h1.to_hex()));
1523
    let h2 = repo.commit("b without hook", &[]).unwrap();
1524
    assert!(repo.store().get_change(&h2).unwrap().deps.is_empty(), "hook disabled by default");
1525
    repo.config.set("hooks.semantic-deps", "true").unwrap();
1526
    repo.save_config().unwrap();
1527
    write(root, "c.txt", b"c\n");
1528
    let h3 = repo.commit("c with hook", &[]).unwrap();
1529
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
1530
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
1531
    assert!(sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"), "{sem}");
1532
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
1533
}
1534
1535
#[test]
1536
fn amend_into_older_change_and_split() {
1537
    hermetic();
1538
    let dir = tempfile::tempdir().unwrap();
1539
    let root = dir.path();
1540
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1541
    repo.create_identity("Ada", "a@b", IdentityScope::User).unwrap();
1542
    repo.set_user_config("core.sign", "change").unwrap();
1543
    write(root, "a.txt", b"one\ntwo\n");
1544
    let h0 = repo.commit("base", &[]).unwrap();
1545
    write(root, "a.txt", b"one\nTWO\n");
1546
    let h1 = repo.commit("edit two", &[]).unwrap();
1547
    write(root, "a.txt", b"one\nTWO\nthree\n");
1548
    let h2 = repo.commit("add three", &[]).unwrap();
1549
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
1550
1551
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
1552
    write(root, "a.txt", b"one\nTWO!\nthree\n");
1553
    let h1b = repo.amend_into(&h1, None).unwrap();
1554
    assert_ne!(h1b, h1);
1555
    let c1b = repo.store().get_change(&h1b).unwrap();
1556
    assert_eq!(c1b.change_id, id1);
1557
    assert_eq!(c1b.deps, vec![h0]);
1558
    assert!(matches!(repo.verify_change(&h1b).unwrap(), SignatureStatus::Valid { .. }));
1559
    let heads = repo.bookmark_heads().unwrap();
1560
    assert_eq!(heads.len(), 1);
1561
    let top = repo.store().get_change(&heads[0]).unwrap();
1562
    assert_eq!(top.message, "add three");
1563
    assert_eq!(top.deps.iter().copied().collect::<BTreeSet<_>>(), [h0, h1b].into_iter().collect(), "depends on the file's creator and the rewritten line");
1564
    let snap = repo.load_state(&heads).unwrap().materialize();
1565
    assert!(matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n"));
1566
    assert!(!repo.snapshot("status").unwrap().changed, "the working copy is clean after folding");
1567
    // Only h1b's own state shows the fix without "three".
1568
    let only = repo.load_state(&[h1b]).unwrap().materialize();
1569
    assert!(matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n"));
1570
    assert_eq!(repo.log().unwrap().len(), 4);
1571
1572
    // An edit to a line introduced by h2 cannot fold into h1.
1573
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
1574
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
1575
    assert!(err.contains("introduced after"), "{err}");
1576
    assert!(repo.snapshot("status").unwrap().statuses.len() == 1, "nothing was changed by the refusal");
1577
    write(root, "a.txt", b"one\nTWO!\nthree\n");
1578
1579
    // Split the head that touches two files.
1580
    write(root, "b.txt", b"b\n");
1581
    write(root, "c.txt", b"c\n");
1582
    let h3 = repo.commit("b and c", &[]).unwrap();
1583
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
1584
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
1585
    let c_1 = repo.store().get_change(&p1).unwrap();
1586
    let c_2 = repo.store().get_change(&p2).unwrap();
1587
    assert!(c_1.message.contains("part 1: b.txt"));
1588
    assert_eq!(c_2.change_id, id3);
1589
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1590
    assert!(heads.contains(&p1) && heads.contains(&p2), "independent parts are both heads");
1591
    let snap = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap().materialize();
1592
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
1593
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
1594
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
1595
    assert!(!repo.snapshot("status").unwrap().changed);
1596
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
1597
    let _ = h2;
1598
}