OXYGENHUB
# b2ef93bb2366 oxygen / crates / oxy-core / src / repo / tests.rs
66.7 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
98286406 Andy McCall ↶ 1
//! Tests for the repository layer.
2
3
use super::*;
83e0677b Andy McCall ↶ 4
use crate::protocol::SignedPolicy;
98286406 Andy McCall ↶ 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();
132b884b Andy McCall ↶ 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();
98286406 Andy McCall ↶ 481
    assert!(!r[0].ok && r[0].reason.contains("missing"), "{}", r[0].reason);
482
483
    // Stale old_state.
132b884b Andy McCall ↶ 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();
98286406 Andy McCall ↶ 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.
132b884b Andy McCall ↶ 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();
98286406 Andy McCall ↶ 489
    assert!(!r[0].ok && r[0].reason.contains("fast-forward"), "{}", r[0].reason);
132b884b Andy McCall ↶ 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();
98286406 Andy McCall ↶ 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();
132b884b Andy McCall ↶ 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();
98286406 Andy McCall ↶ 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();
132b884b Andy McCall ↶ 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();
98286406 Andy McCall ↶ 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
}
83e0677b Andy McCall ↶ 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)] };
132b884b Andy McCall ↶ 727
    let r = origin.receive_push(Bundle::default(), vec![], Some(forged), vec![]).unwrap();
83e0677b Andy McCall ↶ 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;
132b884b Andy McCall ↶ 732
    let r = origin.receive_push(Bundle::default(), vec![], Some(old), vec![]).unwrap();
83e0677b Andy McCall ↶ 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
}
d02e545d Andy McCall ↶ 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();
ba160f60 Andy McCall ↶ 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();
d02e545d Andy McCall ↶ 773
    let before = repo.store().list().unwrap();
774
    assert!(repo.store().loose_count().unwrap() > 0);
ba160f60 Andy McCall ↶ 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);
d02e545d Andy McCall ↶ 780
    assert_eq!(repo.store().loose_count().unwrap(), 0);
781
    assert_eq!(repo.store().list().unwrap(), before);
ba160f60 Andy McCall ↶ 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();
d02e545d Andy McCall ↶ 787
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
ba160f60 Andy McCall ↶ 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.
d02e545d Andy McCall ↶ 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);
ba160f60 Andy McCall ↶ 805
    // Grace period defers pruning of young garbage.
d02e545d Andy McCall ↶ 806
    write(root, "a.txt", b"three\n");
807
    repo.commit("three", &[]).unwrap();
ba160f60 Andy McCall ↶ 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);
d02e545d Andy McCall ↶ 814
}
614541c3 Andy McCall ↶ 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");
c07e0e7d Andy McCall ↶ 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"));
614541c3 Andy McCall ↶ 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();
c07e0e7d Andy McCall ↶ 873
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1b], "the described first change is the head again");
614541c3 Andy McCall ↶ 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]);
c07e0e7d Andy McCall ↶ 884
885
    // Abandoning a non-head whose dependent references its atoms is refused;
886
    // one that is only an explicit dependency can go.
887
    let base = repo.bookmark_heads().unwrap()[0];
888
    let base_change = repo.store().get_change(&base).unwrap();
889
    let h1_now = base_change.deps[0];
890
    assert!(repo.abandon(&h1_now).unwrap_err().to_string().contains("not implemented"));
891
    write(root, "c.txt", b"c\n");
892
    let hc = repo.commit("c", &[]).unwrap();
893
    write(root, "d.txt", b"d\n");
894
    let hd = repo.commit("d", &[hc]).unwrap();
895
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
896
    repo.abandon(&hc).unwrap();
897
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
898
    assert!(!heads.contains(&hc));
899
    let d_now = heads.iter().find(|h| repo.store().get_change(h).unwrap().message == "d").copied().unwrap();
900
    assert!(repo.store().get_change(&d_now).unwrap().deps.is_empty(), "d inherited c's (empty) dependencies");
901
    let s = repo.snapshot("status").unwrap();
902
    assert_eq!(s.statuses.iter().map(|p| p.path.as_str()).collect::<Vec<_>>(), vec!["c.txt"], "c's content is now uncommitted work");
614541c3 Andy McCall ↶ 903
}
79ab8528 Andy McCall ↶ 904
905
#[test]
906
fn git_export_mirrors_history() {
907
    hermetic();
908
    if std::process::Command::new("git").arg("--version").output().is_err() {
909
        eprintln!("git not installed; skipping");
910
        return;
911
    }
912
    let dir = tempfile::tempdir().unwrap();
913
    let root = dir.path();
914
    let mut repo = Repo::init(&root.join("r")).unwrap().with_home(root.join("home"));
915
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User).unwrap();
916
    let r = root.join("r");
917
    write(&r, "README.md", b"hello\n");
918
    write(&r, "src/main.rs", b"fn main() {}\n");
919
    let h1 = repo.commit("first", &[]).unwrap();
920
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
921
    write(&r, "logo.png", b"\x89PNG\0\0");
922
    let h2 = repo.commit("second", &[]).unwrap();
923
924
    let git_dir = root.join("mirror.git");
925
    let rep = repo.git_export(&git_dir).unwrap();
926
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
927
    let git = |args: &[&str]| -> String {
928
        let out = std::process::Command::new("git").arg("-C").arg(&git_dir).args(args).output().unwrap();
929
        assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
930
        String::from_utf8_lossy(&out.stdout).trim().to_string()
931
    };
932
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
933
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
934
    assert_eq!(git(&["show", "main:README.md"]), "hello");
935
    let body = git(&["log", "-1", "--format=%B", "main"]);
936
    assert!(body.contains(&format!("Oxy-Hash: {}", h2.to_hex())), "{body}");
937
    assert!(body.contains("Change-Id: "), "{body}");
938
    assert_eq!(git(&["log", "-1", "--format=%an <%ae>", "main"]), "Ada Lovelace <[email protected]>");
939
    assert_eq!(git(&["ls-tree", "--name-only", "main"]), "README.md\nlogo.png\nsrc");
940
941
    // Re-export is incremental.
942
    let rep = repo.git_export(&git_dir).unwrap();
943
    assert_eq!((rep.exported, rep.skipped), (0, 2));
944
945
    // An independent change makes two heads; the next state is one more
946
    // commit on the linear branch whose tree is the union.
947
    repo.checkout(&[h1], false, "checkout").unwrap();
948
    write(&r, "other.txt", b"o\n");
949
    let h3 = repo.commit("third", &[]).unwrap();
950
    let rep = repo.git_export(&git_dir).unwrap();
951
    assert_eq!((rep.exported, rep.heads), (1, 2));
952
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
953
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
954
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
955
    assert_eq!(git(&["show", "main:other.txt"]), "o");
956
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
957
    assert_eq!(git(&["ls-tree", "--name-only", "main"]), "README.md\nlogo.png\nother.txt\nsrc");
958
    let body = git(&["log", "-1", "--format=%B", "main"]);
959
    assert!(body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "), "{body}");
960
    // A rewrite is a new state whose one new change is the rewritten one.
961
    repo.describe(&h3, "third, described").unwrap();
962
    let rep = repo.git_export(&git_dir).unwrap();
963
    assert_eq!(rep.exported, 1);
964
    assert_eq!(git(&["log", "-1", "--format=%s", "main"]), "third, described");
965
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
966
    let _ = h2;
967
}
c3069537 Andy McCall ↶ 968
969
#[test]
970
fn git_import_reproduces_trees() {
971
    hermetic();
972
    if std::process::Command::new("git").arg("--version").output().is_err() {
973
        eprintln!("git not installed; skipping");
974
        return;
975
    }
976
    let dir = tempfile::tempdir().unwrap();
977
    let root = dir.path();
978
    let g = root.join("src.git");
979
    fs::create_dir_all(&g).unwrap();
980
    let git = |args: &[&str]| -> String {
981
        let out = std::process::Command::new("git")
982
            .arg("-C")
983
            .arg(&g)
984
            .args(["-c", "user.name=Grace", "-c", "[email protected]", "-c", "commit.gpgsign=false"])
985
            .args(args)
986
            .output()
987
            .unwrap();
988
        assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
989
        String::from_utf8_lossy(&out.stdout).trim().to_string()
990
    };
991
    git(&["init", "-q", "-b", "main"]);
992
    write(&g, "README.md", b"# Hi\n");
993
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
994
    git(&["add", "."]);
995
    git(&["commit", "-q", "-m", "initial"]);
996
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
997
    write(&g, "run.sh", b"#!/bin/sh\n");
998
    #[cfg(unix)]
999
    {
1000
        use std::os::unix::fs::PermissionsExt;
1001
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1002
    }
1003
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1004
    git(&["add", "."]);
1005
    git(&["commit", "-q", "-m", "second\n\nChange-Id: 0123456789abcdef0123456789abcdef"]);
1006
    // A branch that edits README, merged back with a conflict-free merge.
1007
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1008
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1009
    git(&["commit", "-q", "-am", "readme"]);
1010
    git(&["checkout", "-q", "main"]);
1011
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1012
    // A branch from the initial commit inserting at the same place as
1013
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1014
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1015
    git(&["checkout", "-q", "-b", "clash", &initial]);
1016
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1017
    git(&["commit", "-q", "-am", "clash"]);
1018
    git(&["checkout", "-q", "main"]);
1019
    let _ = std::process::Command::new("git").arg("-C").arg(&g).args(["merge", "-q", "clash"]).output();
1020
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n");
1021
    git(&["add", "."]);
1022
    git(&["commit", "-q", "-m", "resolve clash"]);
1023
    git(&["rm", "-q", "logo.png"]);
1024
    git(&["commit", "-q", "-m", "drop logo"]);
1025
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1026
1027
    let dest = root.join("oxy");
1028
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1029
    let rep = repo.import_git(&g, "main").unwrap();
1030
    assert_eq!(rep.commits, expected_count);
1031
    assert_eq!(rep.merges, 2);
1032
    // The working copy equals the Git tree at main.
1033
    assert_eq!(fs::read(dest.join("src/lib.rs")).unwrap(), b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n");
1034
    assert_eq!(fs::read(dest.join("README.md")).unwrap(), b"# Hi\n\nMore.\n");
1035
    assert!(!dest.join("logo.png").exists());
1036
    #[cfg(unix)]
1037
    {
1038
        use std::os::unix::fs::PermissionsExt;
1039
        assert!(fs::metadata(dest.join("run.sh")).unwrap().permissions().mode() & 0o111 != 0);
1040
    }
1041
    assert!(!repo.snapshot("status").unwrap().changed, "clean after import");
1042
    let heads = repo.bookmark_heads().unwrap();
1043
    let st = repo.load_state(&heads).unwrap();
1044
    assert!(!st.materialize().is_conflicted());
1045
    assert_eq!(st.len(), expected_count);
1046
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1047
    let log = repo.log().unwrap();
1048
    let second = log.iter().find(|e| e.change.message.starts_with("second")).unwrap();
1049
    assert_eq!(second.change.change_id, ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap());
1050
    assert!(second.change.message.contains("Git-Author: Grace <[email protected]>"));
1051
    let resolve = log.iter().find(|e| e.change.message.starts_with("resolve clash")).unwrap();
1052
    assert_eq!(resolve.change.kind, ChangeKind::Resolution, "a conflicting Git merge becomes a resolution");
1053
    // Re-importing into another fresh repository gives the same ChangeIds.
1054
    let repo2 = Repo::init(&root.join("oxy2")).unwrap().with_home(root.join("home"));
1055
    repo2.import_git(&g, "main").unwrap();
1056
    let ids: BTreeSet<ChangeId> = repo.log().unwrap().iter().filter(|e| !e.is_working_copy).map(|e| e.change.change_id).collect();
1057
    let ids2: BTreeSet<ChangeId> = repo2.log().unwrap().iter().filter(|e| !e.is_working_copy).map(|e| e.change.change_id).collect();
1058
    assert_eq!(ids, ids2);
1059
    // Round trip back out to Git reproduces the tip tree.
1060
    let mirror = root.join("mirror.git");
1061
    repo.git_export(&mirror).unwrap();
1062
    let out = std::process::Command::new("git").arg("-C").arg(&mirror).args(["show", "main:src/lib.rs"]).output().unwrap();
1063
    assert_eq!(String::from_utf8_lossy(&out.stdout), "pub fn a() {}\npub fn b() {}\npub fn c() {}\n");
1064
}
252e8cb2 Andy McCall ↶ 1065
1066
#[test]
1067
fn checkpoints_accelerate_loading_and_stay_correct() {
1068
    hermetic();
1069
    let dir = tempfile::tempdir().unwrap();
1070
    let root = dir.path();
1071
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1072
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1073
    repo.save_config().unwrap();
1074
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1075
    let mut hashes = Vec::new();
1076
    for i in 0..12 {
1077
        write(root, "a.txt", format!("{}\n", (0..=i).map(|k| k.to_string()).collect::<Vec<_>>().join("\n")).as_bytes());
1078
        write(root, &format!("f{i}.txt"), b"x\n");
1079
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1080
    }
1081
    let (_, cp) = repo.latest_checkpoint("main").unwrap().expect("automatic checkpoint");
1082
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1083
    // Loading through the checkpoint equals loading everything.
1084
    let heads = repo.bookmark_heads().unwrap();
1085
    let fast = repo.load_state(&heads).unwrap();
1086
    let full = repo.load_state_full(&heads).unwrap();
1087
    assert_eq!(fast.len(), full.len());
1088
    assert_eq!(fast.heads(), full.heads());
1089
    let (a, b) = (fast.materialize(), full.materialize());
1090
    assert_eq!(a.files.keys().collect::<Vec<_>>(), b.files.keys().collect::<Vec<_>>());
1091
    for (p, f) in &a.files {
1092
        assert_eq!(f.content, b.files[p].content, "{p}");
1093
    }
1094
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1095
    // A head set that does not contain the checkpoint's heads falls back.
1096
    assert!(repo.load_state_checkpointed(&[hashes[0]]).unwrap().is_none());
1097
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1098
    // Everything else keeps working on top of the checkpoint.
1099
    assert!(!repo.snapshot("status").unwrap().changed);
1100
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1101
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1102
    let (r, n, bytes) = repo.checkpoint().unwrap();
1103
    assert!(n >= 12 && bytes > 0);
1104
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1105
    write(root, "a.txt", b"after\n");
1106
    let h_after = repo.commit("after", &[]).unwrap();
1107
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1108
    assert!(st.contains(&h_after));
1109
    assert!(matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n"));
1110
    assert_eq!(repo.log().unwrap().len(), 14);
1111
    // Checkpoints survive gc.
1112
    repo.gc(true).unwrap();
1113
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1114
    assert!(repo.load_state_checkpointed(&repo.bookmark_heads().unwrap()).unwrap().is_some());
1115
}
135212de Andy McCall ↶ 1116
1117
#[test]
1118
fn quick_status_for_prompts() {
1119
    hermetic();
1120
    let dir = tempfile::tempdir().unwrap();
1121
    let root = dir.path();
1122
    let origin = Repo::init(&root.join("origin")).unwrap();
1123
    let url = root.join("origin").to_string_lossy().to_string();
1124
    let a = Repo::clone(&url, &root.join("a")).unwrap().with_home(root.join("home"));
1125
    let ops_before = a.op_log().unwrap().len();
1126
    let info = a.quick_status().unwrap();
1127
    assert_eq!((info.bookmark.as_str(), info.heads, info.dirty, info.conflicted, info.ahead, info.behind), ("main", 0, false, false, Some(0), Some(0)));
1128
    write(&root.join("a"), "f.txt", b"f\n");
1129
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1130
    assert_eq!(a.op_log().unwrap().len(), ops_before, "quick_status records nothing");
1131
    // A snapshotted but uncommitted change is still dirty.
1132
    a.snapshot("status").unwrap();
1133
    assert!(a.quick_status().unwrap().dirty);
1134
    a.commit("f", &[]).unwrap();
1135
    let info = a.quick_status().unwrap();
1136
    assert!(!info.dirty, "clean right after a commit");
1137
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
1138
    assert_eq!(info.format("%b %c%d%x%A%D"), format!("main {}+1", info.change_id));
1139
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1140
    // Touching a file without changing it is not dirty; changing content of
1141
    // the same size is.
1142
    let p = root.join("a/f.txt");
1143
    let content = fs::read(&p).unwrap();
1144
    fs::write(&p, &content).unwrap();
1145
    assert!(!a.quick_status().unwrap().dirty);
1146
    fs::write(&p, b"g\n").unwrap();
1147
    assert!(a.quick_status().unwrap().dirty);
1148
    fs::write(&p, b"f\n").unwrap();
1149
    // Push, then a second clone commits and pushes: we are behind.
1150
    assert!(a.push("origin", false).unwrap()[0].ok);
1151
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
1152
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(root.join("home-b"));
1153
    write(&root.join("b"), "g.txt", b"g\n");
1154
    b.commit("g", &[]).unwrap();
1155
    b.push("origin", false).unwrap();
1156
    a.fetch("origin").unwrap();
1157
    let info = a.quick_status().unwrap();
1158
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1159
    assert_eq!(info.format("%A%D"), "-1");
1160
    let _ = origin;
1161
}
b3c5a59a Andy McCall ↶ 1162
1163
#[test]
1164
fn lazy_blobs_are_fetched_on_first_read() {
1165
    hermetic();
1166
    let dir = tempfile::tempdir().unwrap();
1167
    let root = dir.path();
1168
    let origin_dir = root.join("origin");
1169
    let origin = Repo::init(&origin_dir).unwrap().with_home(root.join("home"));
1170
    let url = origin_dir.to_string_lossy().to_string();
1171
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1172
    write(&origin_dir, "big.bin", &big);
1173
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1174
    write(&origin_dir, "t.txt", b"t\n");
1175
    let h = origin.commit("blobs", &[]).unwrap();
1176
    let big_ref = Repo::blob_ref(&big);
1177
1178
    // Fetch only (no checkout) with a filter: the big blob stays absent.
1179
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap()).unwrap().with_home(root.join("home"));
1180
    let a = {
1181
        let mut a = a;
1182
        a.config.set("remote.origin.url", &url).unwrap();
1183
        a.config.set("filter.max-blob", "100K").unwrap();
1184
        a.save_config().unwrap();
1185
        a
1186
    };
1187
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1188
    a.fetch("origin").unwrap();
1189
    assert!(a.store().has(&h));
1190
    assert!(!a.store().has(&big_ref), "withheld");
1191
    assert!(a.store().has(&Repo::blob_ref(&[0u8, 1, 2])), "small blob came along");
1192
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1193
1194
    // status and commit do not need it: adopt the state, edit a text file, commit.
1195
    let (op_ref, op) = a.head_op().unwrap();
1196
    let mut view = op.view.clone();
1197
    view.bookmarks.insert("main".into(), a.store().put_state(&StateObject::new(vec![h])).unwrap());
1198
    a.record_op(&[op_ref], "adopt", view).unwrap();
1199
    // Checkout reads the blob lazily, which fetches it.
1200
    a.checkout(&[h], true, "checkout").unwrap();
1201
    assert!(a.store().has(&big_ref), "fetched on first read");
1202
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1203
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1204
    write(&root.join("a"), "t.txt", b"t2\n");
1205
    a.commit("text edit", &[]).unwrap();
1206
1207
    // clone --max-blob records the filter; the checkout fetches lazily.
7421309f Andy McCall ↶ 1208
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
b3c5a59a Andy McCall ↶ 1209
    assert_eq!(b.config.max_blob, Some(1024));
1210
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1211
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1212
    assert!(parse_size("lots").is_err());
1213
}
7421309f Andy McCall ↶ 1214
1215
#[test]
1216
fn sparse_checkout_materializes_only_chosen_paths() {
1217
    hermetic();
1218
    let dir = tempfile::tempdir().unwrap();
1219
    let root = dir.path();
1220
    let origin_dir = root.join("origin");
1221
    let origin = Repo::init(&origin_dir).unwrap().with_home(root.join("home"));
1222
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1223
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1224
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1225
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1226
    write(&origin_dir, "docs/logo.png", &logo);
1227
    write(&origin_dir, "README.md", b"# top\n");
1228
    let h1 = origin.commit("tree", &[]).unwrap();
1229
    let url = origin_dir.to_string_lossy().to_string();
1230
1231
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()]).unwrap().with_home(root.join("home"));
1232
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1233
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1234
    assert!(root.join("a/src/main.rs").exists());
1235
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
1236
    assert!(!a.store().has(&Repo::blob_ref(&logo)), "out-of-scope blob never fetched");
1237
    assert!(!a.snapshot("status").unwrap().changed, "out-of-scope files are not removals");
1238
    assert_eq!(a.quick_status().unwrap().dirty, false);
1239
1240
    // Edits in scope commit normally and keep the rest of the tree intact.
1241
    write(&root.join("a"), "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1242
    let h2 = a.commit("edit lib", &[]).unwrap();
1243
    let st = a.load_state(&[h2]).unwrap().materialize();
1244
    assert!(st.files.contains_key("docs/guide.md"), "the state still has everything");
1245
    assert!(a.push("origin", false).unwrap()[0].ok);
1246
    // Files created outside the scope are ignored by status.
1247
    write(&root.join("a"), "docs/new.md", b"ignored\n");
1248
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
1249
1250
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
1251
    let mut a = a;
1252
    a.config.set("filter.paths", "src,docs").unwrap();
1253
    a.save_config().unwrap();
1254
    let r = a.checkout(&a.bookmark_heads().unwrap(), true, "widen").unwrap();
1255
    assert!(r.written >= 2);
1256
    assert_eq!(fs::read(root.join("a/docs/logo.png")).unwrap(), logo, "now fetched lazily");
1257
    assert!(!root.join("a/README.md").exists());
1258
    // Origin sees the change made under a sparse checkout with the full tree intact.
1259
    origin.pull("origin").err();
1260
    let full = origin.load_state(&origin.bookmark_heads().unwrap()).unwrap().materialize();
1261
    assert!(matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n"));
1262
    assert!(full.files.contains_key("README.md"));
1263
    let _ = h1;
1264
}
2863456a Andy McCall ↶ 1265
1266
#[test]
1267
fn shallow_clone_and_deepen() {
1268
    hermetic();
1269
    let dir = tempfile::tempdir().unwrap();
1270
    let root = dir.path();
1271
    let origin_dir = root.join("origin");
1272
    let origin = Repo::init(&origin_dir).unwrap().with_home(root.join("home"));
1273
    let mut hashes = Vec::new();
1274
    for i in 0..8 {
1275
        write(&origin_dir, "a.txt", format!("{}\n", (0..=i).map(|k| k.to_string()).collect::<Vec<_>>().join("\n")).as_bytes());
1276
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
1277
    }
1278
    let url = origin_dir.to_string_lossy().to_string();
1279
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[]).unwrap().with_home(root.join("home"));
1280
    assert!(a.is_shallow());
1281
    assert_eq!(fs::read_to_string(root.join("a/a.txt")).unwrap(), "0\n1\n2\n3\n4\n5\n6\n7\n");
1282
    assert!(a.store().has(&hashes[7]) && a.store().has(&hashes[5]), "three levels present");
1283
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
1284
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
1285
    assert_eq!(a.log().unwrap().len(), 9, "the log shows every change from the checkpoint's metadata");
1286
    assert!(!a.snapshot("status").unwrap().changed);
1287
    assert_eq!(a.quick_status().unwrap().heads, 1);
1288
1289
    // Work continues on top of the shallow history and pushes back.
1290
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
1291
    let h_new = a.commit("c8", &[]).unwrap();
1292
    assert!(a.push("origin", false).unwrap()[0].ok);
1293
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
1294
    // Fetching new work from origin into the shallow clone works too.
1295
    write(&origin_dir, "b.txt", b"b\n");
1296
    origin.pull("origin").err();
1297
    let (_, wc) = origin.working_copy().unwrap();
1298
    let _ = wc;
1299
    origin.checkout(&origin.bookmark_heads().unwrap(), true, "co").unwrap();
1300
    write(&origin_dir, "b.txt", b"b\n");
1301
    let h_b = origin.commit("b", &[]).unwrap();
1302
    let pr = a.pull("origin").unwrap();
1303
    assert!(pr.changed);
1304
    assert!(a.store().has(&h_b));
1305
    assert!(root.join("a/b.txt").exists());
1306
1307
    // Deepening fetches older history until the boundary is gone.
1308
    // Every commit also depends on the change that created the file, so two
1309
    // levels below the boundary hold h4, h3, and the root.
1310
    assert!(a.deepen("origin", 2).unwrap() >= 2);
1311
    assert!(a.store().has(&hashes[3]));
1312
    assert!(a.is_shallow());
1313
    a.deepen("origin", 100).unwrap();
1314
    assert!(!a.is_shallow(), "boundary reached the root");
1315
    assert!(a.store().has(&hashes[0]));
1316
    assert_eq!(a.load_state_full(&a.bookmark_heads().unwrap()).unwrap().len(), 10);
1317
}
132b884b Andy McCall ↶ 1318
1319
#[test]
1320
fn tags_are_immutable_named_states_and_travel() {
1321
    hermetic();
1322
    let dir = tempfile::tempdir().unwrap();
1323
    let root = dir.path();
1324
    let origin = Repo::init(&root.join("origin")).unwrap();
1325
    let url = root.join("origin").to_string_lossy().to_string();
1326
    let mut a = Repo::clone(&url, &root.join("a")).unwrap().with_home(root.join("home-a"));
1327
    let (key_a, _) = a.create_identity("Ada", "[email protected]", IdentityScope::User).unwrap();
1328
    write(&root.join("a"), "f.txt", b"1\n");
1329
    let h1 = a.commit("one", &[]).unwrap();
1330
    write(&root.join("a"), "f.txt", b"1\n2\n");
1331
    let h2 = a.commit("two", &[]).unwrap();
1332
1333
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
1334
    assert_eq!((t.heads.clone(), t.signer.as_deref()), (vec![h1], Some("Ada")));
1335
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
1336
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
1337
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
1338
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
1339
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
1340
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
1341
    assert_eq!(sa.sigs[0].key, key_a);
1342
    // Checkout by tag.
1343
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co").unwrap();
1344
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
1345
    a.checkout(&a.bookmark_heads().unwrap(), false, "co").unwrap();
1346
1347
    // Push carries the tag; a second attestation for the name is refused.
1348
    let r = a.push("origin", false).unwrap();
1349
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
1350
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
1351
    let mut forged = a.tag_refs().unwrap().into_iter().find(|t| t.name == "v1").unwrap();
1352
    forged.state = origin.store().put_state(&StateObject::new(vec![h2])).unwrap();
1353
    forged.heads = vec![h2];
1354
    forged.attestation = None;
1355
    let r = origin.receive_push(Bundle::default(), vec![], None, vec![forged]).unwrap();
1356
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
1357
1358
    // A clone gets the tag; a later tag arrives on fetch.
1359
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(root.join("home-b"));
1360
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
1361
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
1362
    a.tag_create("v2", &[h2], "second").unwrap();
1363
    a.push("origin", false).unwrap();
1364
    let rep = b.fetch("origin").unwrap();
1365
    assert_eq!(rep.new_tags, 1);
1366
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
1367
1368
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
1369
    a.policy_init().unwrap();
1370
    a.push("origin", false).unwrap();
1371
    let unattested = crate::protocol::TagRef { name: "v3".into(), state: origin.store().put_state(&StateObject::new(vec![h2])).unwrap(), heads: vec![h2], attestation: None };
1372
    let r = origin.receive_push(Bundle::default(), vec![], None, vec![unattested]).unwrap();
1373
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
1374
    a.tag_create("v3", &[h2], "").unwrap();
1375
    let r = a.push("origin", false).unwrap();
1376
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
1377
    assert!(a.gc(true).is_ok());
1378
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
1379
}