OXYGENHUB
# 33be24095b4b oxygen / crates / oxy-core / src / repo / tests.rs
275.9 KiB · Rust · last changed Git import: a large merge's already-built file no longer renders empty 1 month ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
use crate::protocol::SignedPolicy;
5
use crate::repo::{BisectStep, Selection};
6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
137
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
138
    assert!(d.contains("-fn main() {}"), "{d}");
139
140
    // Resolution by prefix.
141
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
142
    assert_eq!(
143
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
144
        h1
145
    );
146
    assert!(repo.resolve_change("zzzz").is_err());
147
148
    // Undo the commit: bookmark and working copy go back.
149
    repo.undo().unwrap();
150
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
151
    let s = repo.snapshot("oxy status").unwrap();
152
    assert!(
153
        !s.changed,
154
        "files on disk still match the pre-commit working copy"
155
    );
156
    assert_eq!(s.statuses.len(), 3);
157
}
158
159
/// Make `main` conflicted: two commits on the same base that edit the same line.
160
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
161
    let dir = tempfile::tempdir().unwrap();
162
    let root = dir.path();
163
    let repo = Repo::init(root).unwrap();
164
    write(root, "f.txt", b"a\nb\nc\n");
165
    let h1 = repo.commit("base", &[]).unwrap();
166
    write(root, "f.txt", b"a\nB\nc\n");
167
    let h2 = repo.commit("upper", &[]).unwrap();
168
    repo.checkout(&[h1], false, "checkout").unwrap();
169
    write(root, "f.txt", b"a\nX\nc\n");
170
    let h3 = repo.commit("ex", &[]).unwrap();
171
    (dir, repo, h1, h2, h3)
172
}
173
174
#[test]
175
fn concurrent_edits_conflict_and_can_be_resolved() {
176
    hermetic();
177
    let (dir, repo, h1, h2, h3) = conflicted_repo();
178
    let root = dir.path();
179
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
180
    assert_eq!(heads, [h2, h3].into_iter().collect());
181
    let st = repo.load_state(&[h2, h3]).unwrap();
182
    assert!(st.materialize().is_conflicted());
183
184
    // Checking out main writes markers.
185
    let r = repo
186
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
187
        .unwrap();
188
    assert!(r.conflicted);
189
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
190
    assert!(
191
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
192
        "{marked}"
193
    );
194
    assert!(
195
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
196
        "{marked}"
197
    );
198
    assert!(has_conflict_markers(marked.as_bytes()));
199
    // Untouched markers: clean working copy; commit has nothing to do.
200
    let s = repo.snapshot("status").unwrap();
201
    assert!(s.statuses.is_empty());
202
    assert!(!s.resolves);
203
204
    // Partially edited file that still has markers cannot be committed.
205
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
206
    let s = repo.snapshot("status").unwrap();
207
    assert_eq!(
208
        statuses(&s),
209
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
210
    );
211
    assert!(repo.commit("no", &[]).is_err());
212
213
    // Resolve by keeping one side and adding a line elsewhere.
214
    write(root, "f.txt", b"a\nX\nc\nd\n");
215
    let s = repo.snapshot("status").unwrap();
216
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
217
    assert!(s.resolves);
218
    let h4 = repo.commit("resolve", &[]).unwrap();
219
    let c4 = repo.store().get_change(&h4).unwrap();
220
    assert_eq!(c4.kind, ChangeKind::Resolution);
221
    let mut want = vec![h1, h2, h3];
222
    want.sort();
223
    assert_eq!(
224
        c4.deps, want,
225
        "a resolution depends on exactly the contributors and what it references"
226
    );
227
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
228
    let snap = repo.load_state(&[h4]).unwrap().materialize();
229
    assert!(!snap.is_conflicted());
230
    assert!(
231
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
232
    );
233
    assert!(!repo.snapshot("status").unwrap().changed);
234
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
235
    // whatever order the changes arrive in.
236
    let mut st = State::new();
237
    for h in [h4, h3, h1, h2] {
238
        st.add_unchecked(repo.store().get_change(&h).unwrap());
239
    }
240
    st.validate().unwrap();
241
    assert!(
242
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
243
    );
244
}
245
246
#[test]
247
fn resolution_may_keep_both_sides_or_neither() {
248
    hermetic();
249
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
250
    let root = dir.path();
251
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
252
        .unwrap();
253
    // Keep both sides in a chosen order.
254
    write(root, "f.txt", b"a\nX\nB\nc\n");
255
    let h = repo.commit("both", &[]).unwrap();
256
    let snap = repo.load_state(&[h]).unwrap().materialize();
257
    assert!(!snap.is_conflicted());
258
    assert!(
259
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
260
    );
261
    // Undo and instead drop the whole region.
262
    repo.undo().unwrap();
263
    write(root, "f.txt", b"a\nc\n");
264
    let h = repo.commit("neither", &[]).unwrap();
265
    let snap = repo.load_state(&[h]).unwrap().materialize();
266
    assert!(!snap.is_conflicted());
267
    assert!(
268
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
269
    );
270
}
271
272
#[test]
273
fn name_conflict_resolved_by_removing_a_candidate() {
274
    hermetic();
275
    let dir = tempfile::tempdir().unwrap();
276
    let root = dir.path();
277
    let repo = Repo::init(root).unwrap();
278
    write(root, "keep.txt", b"k\n");
279
    let h1 = repo.commit("base", &[]).unwrap();
280
    write(root, "new.txt", b"one\n");
281
    repo.commit("one", &[]).unwrap();
282
    repo.checkout(&[h1], false, "checkout").unwrap();
283
    write(root, "new.txt", b"two\n");
284
    repo.commit("two", &[]).unwrap();
285
    let r = repo
286
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
287
        .unwrap();
288
    assert!(r.conflicted);
289
    assert!(
290
        root.join("new.txt.oxy-conflict-1").exists()
291
            && root.join("new.txt.oxy-conflict-2").exists()
292
    );
293
    assert!(!root.join("new.txt").exists());
294
    // Candidate numbering follows change-hash order, so pick by content:
295
    // keep the "two" candidate under the real name and drop the other.
296
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
297
        (1, 2)
298
    } else {
299
        (2, 1)
300
    };
301
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
302
    fs::rename(
303
        root.join(format!("new.txt.oxy-conflict-{keep}")),
304
        root.join("new.txt"),
305
    )
306
    .unwrap();
307
    let h = repo.commit("pick two", &[]).unwrap();
308
    assert_eq!(
309
        repo.store().get_change(&h).unwrap().kind,
310
        ChangeKind::Resolution
311
    );
312
    // The resolution does not touch keep.txt, so it does not depend on h1;
313
    // the bookmark keeps both as heads and their union is the state.
314
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
315
    assert_eq!(heads, [h1, h].into_iter().collect());
316
    let snap = repo
317
        .load_state(&repo.bookmark_heads().unwrap())
318
        .unwrap()
319
        .materialize();
320
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
321
    assert_eq!(
322
        snap.files.keys().cloned().collect::<Vec<_>>(),
323
        ["keep.txt", "new.txt"]
324
    );
325
    assert!(
326
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
327
    );
328
}
329
330
#[test]
331
fn identities_and_signed_commits() {
332
    hermetic();
333
    let dir = tempfile::tempdir().unwrap();
334
    let root = dir.path();
335
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
336
    write(root, "a.txt", b"a\n");
337
    let h0 = repo.commit("unsigned", &[]).unwrap();
338
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
339
    assert_eq!(
340
        repo.store().get_change(&h0).unwrap().author,
341
        ObjectRef::ZERO
342
    );
343
344
    let (key, id) = repo
345
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
346
        .unwrap();
347
    assert_eq!(id.hash(), key);
348
    assert_eq!(repo.config.author_key, Some(key));
349
    // Config survives reopen; the secret key is found again.
350
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
351
    assert_eq!(reopened.config.author_key, Some(key));
352
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
353
354
    // Default core.sign = seal: commits carry the author but no signature.
355
    write(root, "a.txt", b"a\nb\n");
356
    let h1 = repo.commit("authored", &[]).unwrap();
357
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
358
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
359
    // Signing later works too.
360
    repo.sign_change(&h1).unwrap();
361
    assert!(
362
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
363
    );
364
365
    repo.config.set("core.sign", "change").unwrap();
366
    repo.save_config().unwrap();
367
    write(root, "a.txt", b"a\nb\nc\n");
368
    let h2 = repo.commit("signed", &[]).unwrap();
369
    assert_eq!(
370
        repo.verify_change(&h2).unwrap(),
371
        SignatureStatus::Valid {
372
            key,
373
            name: "Ada".into(),
374
            email: "[email protected]".into(),
375
            sealed: false,
376
            revoked: false
377
        }
378
    );
379
380
    // A signature by a key that is not the author or a delegate is rejected
381
    // when the change names an author; an anonymous change (made before any
382
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
383
    let other = SecretKey::generate();
384
    let other_id = other.identity("Mallory", "[email protected]", 0);
385
    let other_key = repo.store().put_identity(&other_id).unwrap();
386
    write(root, "a.txt", b"a\nb\nc\nd\n");
387
    repo.config.set("core.sign", "seal").unwrap();
388
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
389
    let forged = other.sign(Domain::Change, &other_key, &h3);
390
    repo.store().put_signature(&h3, &forged).unwrap();
391
    assert!(
392
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
393
    );
394
    let adopted = other.sign(Domain::Change, &other_key, &h0);
395
    repo.store().put_signature(&h0, &adopted).unwrap();
396
    assert!(
397
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
398
    );
399
400
    // Tampering with the stored signature invalidates it.
401
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
402
    sig.ed[0] ^= 1;
403
    repo.store().put_signature(&h2, &sig).unwrap();
404
    assert!(matches!(
405
        repo.verify_change(&h2).unwrap(),
406
        SignatureStatus::Invalid(_)
407
    ));
408
409
    // Without the secret key, signing at commit fails cleanly.
410
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
411
    write(root, "a.txt", b"z\n");
412
    assert!(no_keys.commit("cannot sign", &[]).is_err());
413
}
414
415
#[test]
416
fn checkout_moves_the_working_copy() {
417
    hermetic();
418
    let dir = tempfile::tempdir().unwrap();
419
    let root = dir.path();
420
    let repo = Repo::init(root).unwrap();
421
    write(root, "a.txt", b"one\n");
422
    write(root, "sub/deep/b.txt", b"b\n");
423
    let h1 = repo.commit("first", &[]).unwrap();
424
    write(root, "a.txt", b"two\n");
425
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
426
    write(root, "bin.dat", &[0, 1, 2, 3]);
427
    let h2 = repo.commit("second", &[]).unwrap();
428
429
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
430
    assert_eq!(
431
        r,
432
        CheckoutReport {
433
            written: 2,
434
            removed: 1,
435
            conflicted: false,
436
            notes: vec![],
437
            lacks: 1,
438
        }
439
    );
440
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
441
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
442
    assert!(!root.join("bin.dat").exists());
443
    let (_, wc) = repo.working_copy().unwrap();
444
    assert_eq!(wc.deps, vec![h1]);
445
    assert!(
446
        !repo.snapshot("status").unwrap().changed,
447
        "checkout leaves a clean working copy"
448
    );
449
    // The bookmark still points at h2.
450
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
451
452
    // Dirty working copy refuses without --discard.
453
    write(root, "a.txt", b"dirty\n");
454
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
455
    let r = repo
456
        .checkout(&[h2], true, "oxy checkout --discard")
457
        .unwrap();
458
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
459
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
460
    assert!(!root.join("sub").exists(), "empty directories are pruned");
461
    assert_eq!(r.removed, 1);
462
    assert!(!repo.snapshot("status").unwrap().changed);
463
464
    // Refuses to write through a symlinked directory.
465
    #[cfg(unix)]
466
    {
467
        fs::remove_dir_all(root.join("sub")).ok();
468
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
469
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
470
    }
471
}
472
473
#[test]
474
fn large_files_are_chunked_and_read_back() {
475
    hermetic();
476
    let dir = tempfile::tempdir().unwrap();
477
    let repo = Repo::init(dir.path()).unwrap();
478
    let mut big = vec![0u8; 700 * 1024];
479
    for (i, b) in big.iter_mut().enumerate() {
480
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
481
    }
482
    let r = repo.store_blob(&big).unwrap();
483
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
484
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
485
    assert_eq!(repo.read_blob(&r).unwrap(), big);
486
    assert_eq!(Repo::blob_ref(&big), r);
487
}
488
489
#[test]
490
fn clone_push_pull_with_seals_and_attestations() {
491
    hermetic();
492
    let dir = tempfile::tempdir().unwrap();
493
    let root = dir.path();
494
    let origin_path = root.join("origin");
495
    let origin = Repo::init(&origin_path).unwrap();
496
    let origin_url = origin_path.to_string_lossy().to_string();
497
498
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
499
    let mut a = Repo::clone(&origin_url, &root.join("a"))
500
        .unwrap()
501
        .with_home(root.join("home-a"));
502
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
503
    let (key_a, _) = a
504
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
505
        .unwrap();
506
    write(&root.join("a"), "f.txt", b"a\n");
507
    let h1 = a.commit("first", &[]).unwrap();
508
    let results = a.push("origin", false).unwrap();
509
    assert!(results[0].ok, "{}", results[0].reason);
510
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
511
    // The change was sealed at push and the reference attested.
512
    assert!(
513
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
514
    );
515
    assert_eq!(
516
        origin.verify_change(&h1).unwrap(),
517
        SignatureStatus::Unsigned
518
    );
519
    let serial_of = |att: &SignedAttest| match att.attest.body {
520
        AttestBody::Ref { serial, .. } => serial,
521
        _ => unreachable!(),
522
    };
523
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
524
    // A bookmark new to the remote starts at the clock (past any deleted
525
    // namesake's serial); later updates count up from there.
526
    let first = serial_of(&att);
527
    assert!(first > 1_000_000_000_000, "{first}");
528
    let again = a.push("origin", false).unwrap();
529
    assert!(again[0].ok && again[0].reason.contains("up to date"));
530
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
531
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
532
533
    // B clones and sees the file and the seal.
534
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
535
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
536
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
537
    assert!(matches!(
538
        b.authenticate_change(&h1).unwrap(),
539
        SignatureStatus::Valid { sealed: true, .. }
540
    ));
541
542
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
543
    write(&root.join("b"), "f.txt", b"a\nb\n");
544
    let h2 = b.commit("second", &[]).unwrap();
545
    assert!(b.push("origin", false).unwrap()[0].ok);
546
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
547
548
    // A commits an independent change; push is refused until A pulls.
549
    write(&root.join("a"), "g.txt", b"g\n");
550
    let h3 = a.commit("third", &[]).unwrap();
551
    assert!(a.push("origin", false).is_err());
552
    let pr = a.pull("origin").unwrap();
553
    assert!(pr.changed && pr.checked_out);
554
    let mut want = vec![h2, h3];
555
    want.sort();
556
    assert_eq!(pr.heads, want);
557
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
558
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
559
    let results = a.push("origin", false).unwrap();
560
    assert!(results[0].ok, "{}", results[0].reason);
561
    let mut origin_heads = origin.bookmark_heads().unwrap();
562
    origin_heads.sort();
563
    assert_eq!(origin_heads, want);
564
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
565
    assert_eq!(serial_of(&att), first + 1);
566
567
    // B pulls and ends up identical.
568
    let pr = b.pull("origin").unwrap();
569
    assert_eq!(pr.heads, want);
570
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
571
    assert!(!b.snapshot("status").unwrap().changed);
572
573
    // Concurrent edits of the same line: the union is a reified conflict.
574
    write(&root.join("a"), "f.txt", b"a\nA\n");
575
    a.commit("a-edit", &[]).unwrap();
576
    a.push("origin", false).unwrap();
577
    write(&root.join("b"), "f.txt", b"a\nB\n");
578
    b.commit("b-edit", &[]).unwrap();
579
    let pr = b.pull("origin").unwrap();
580
    assert!(pr.changed && pr.checked_out);
581
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
582
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
583
    write(&root.join("b"), "f.txt", b"a\nAB\n");
584
    let hr = b.commit("resolve", &[]).unwrap();
585
    assert_eq!(
586
        b.store().get_change(&hr).unwrap().kind,
587
        ChangeKind::Resolution
588
    );
589
    assert!(b.push("origin", false).unwrap()[0].ok);
590
    a.pull("origin").unwrap();
591
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
592
    // The resolution depends on the conflicting edits, but nothing depends
593
    // on "third" (it only added g.txt), so it stays a head beside it.
594
    let mut want = vec![hr, h3];
595
    want.sort();
596
    assert_eq!(a.bookmark_heads().unwrap(), want);
597
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
598
}
599
600
#[test]
601
fn receive_push_rejects_bad_updates() {
602
    hermetic();
603
    let dir = tempfile::tempdir().unwrap();
604
    let root = dir.path();
605
    let origin = Repo::init(&root.join("origin")).unwrap();
606
    let url = root.join("origin").to_string_lossy().to_string();
607
    let mut a = Repo::clone(&url, &root.join("a"))
608
        .unwrap()
609
        .with_home(root.join("home"));
610
    let (key, _) = a
611
        .create_identity("Ada", "a@b", IdentityScope::Repo)
612
        .unwrap();
613
    write(&root.join("a"), "f.txt", b"x\n");
614
    let h1 = a.commit("one", &[]).unwrap();
615
    assert!(a.push("origin", false).unwrap()[0].ok);
616
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
617
    let s1 = origin
618
        .store()
619
        .put_state(&StateObject::new(vec![h1]))
620
        .unwrap();
621
622
    // Missing head.
623
    let ghost = origin
624
        .store()
625
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
626
        .unwrap();
627
    let r = origin
628
        .receive_push(
629
            Bundle::default(),
630
            vec![RefUpdate {
631
                name: "main".into(),
632
                old_state: s1,
633
                new_state: ghost,
634
                force: false,
635
                attestation: None,
636
            }],
637
            None,
638
            vec![],
639
        )
640
        .unwrap();
641
    assert!(
642
        !r[0].ok && r[0].reason.contains("missing"),
643
        "{}",
644
        r[0].reason
645
    );
646
647
    // Stale old_state.
648
    let r = origin
649
        .receive_push(
650
            Bundle::default(),
651
            vec![RefUpdate {
652
                name: "main".into(),
653
                old_state: empty,
654
                new_state: s1,
655
                force: false,
656
                attestation: None,
657
            }],
658
            None,
659
            vec![],
660
        )
661
        .unwrap();
662
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
663
664
    // Non-fast-forward without force is refused; with force it passes.
665
    let r = origin
666
        .receive_push(
667
            Bundle::default(),
668
            vec![RefUpdate {
669
                name: "main".into(),
670
                old_state: s1,
671
                new_state: empty,
672
                force: false,
673
                attestation: None,
674
            }],
675
            None,
676
            vec![],
677
        )
678
        .unwrap();
679
    assert!(
680
        !r[0].ok && r[0].reason.contains("fast-forward"),
681
        "{}",
682
        r[0].reason
683
    );
684
    let r = origin
685
        .receive_push(
686
            Bundle::default(),
687
            vec![RefUpdate {
688
                name: "main".into(),
689
                old_state: s1,
690
                new_state: empty,
691
                force: true,
692
                attestation: None,
693
            }],
694
            None,
695
            vec![],
696
        )
697
        .unwrap();
698
    assert!(r[0].ok);
699
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
700
701
    // Attestation with a stale serial is a rollback and is refused.
702
    let sa = a
703
        .sign_attest(&Attest {
704
            repo: a.id().unwrap(),
705
            hlc: Hlc::now(),
706
            body: AttestBody::Ref {
707
                name: "main".into(),
708
                old_state: empty,
709
                new_state: s1,
710
                serial: 1,
711
            },
712
        })
713
        .unwrap();
714
    let r = origin
715
        .receive_push(
716
            Bundle::default(),
717
            vec![RefUpdate {
718
                name: "main".into(),
719
                old_state: empty,
720
                new_state: s1,
721
                force: false,
722
                attestation: Some(sa.clone()),
723
            }],
724
            None,
725
            vec![],
726
        )
727
        .unwrap();
728
    assert!(
729
        !r[0].ok && r[0].reason.contains("serial"),
730
        "{}",
731
        r[0].reason
732
    );
733
    // An attestation for a different update is refused too.
734
    let sa2 = a
735
        .sign_attest(&Attest {
736
            repo: a.id().unwrap(),
737
            hlc: Hlc::now(),
738
            body: AttestBody::Ref {
739
                name: "main".into(),
740
                old_state: s1,
741
                new_state: empty,
742
                serial: 5,
743
            },
744
        })
745
        .unwrap();
746
    let r = origin
747
        .receive_push(
748
            Bundle::default(),
749
            vec![RefUpdate {
750
                name: "main".into(),
751
                old_state: empty,
752
                new_state: s1,
753
                force: false,
754
                attestation: Some(sa2),
755
            }],
756
            None,
757
            vec![],
758
        )
759
        .unwrap();
760
    assert!(
761
        !r[0].ok && r[0].reason.contains("describe"),
762
        "{}",
763
        r[0].reason
764
    );
765
    let _ = key;
766
}
767
768
#[test]
769
fn user_config_supplies_defaults_and_clones_sign() {
770
    hermetic();
771
    let dir = tempfile::tempdir().unwrap();
772
    let root = dir.path();
773
    let home = root.join("home");
774
    let origin = Repo::init(&root.join("origin")).unwrap();
775
    let url = root.join("origin").to_string_lossy().to_string();
776
777
    // Identity at user scope: the repository file stays free of author keys.
778
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
779
    let (key, _) = a
780
        .create_identity("Ada", "[email protected]", IdentityScope::User)
781
        .unwrap();
782
    assert!(!a.config.repo_layer().contains_key("author.key"));
783
    assert_eq!(a.config.author_key, Some(key));
784
    assert!(home.join("config.toml").exists());
785
    a.set_user_config("core.sign", "change").unwrap();
786
    assert!(a.config.sign_changes);
787
788
    // Repository settings override user settings and are the only ones saved.
789
    a.config.set("core.sign", "seal").unwrap();
790
    a.save_config().unwrap();
791
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
792
    assert!(!again.config.sign_changes);
793
    assert_eq!(again.config.author_key, Some(key));
794
    assert_eq!(
795
        read_config_file(&root.join("a/.oxy/config"))
796
            .unwrap()
797
            .get("core.sign")
798
            .map(String::as_str),
799
        Some("seal")
800
    );
801
802
    // A fresh clone made by this user signs with the user-level identity,
803
    // even though the clone's store has never seen the identity object.
804
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
805
    assert!(b.config.sign_changes);
806
    write(&root.join("b"), "f.txt", b"f\n");
807
    let h = b.commit("signed from a clone", &[]).unwrap();
808
    assert!(
809
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
810
    );
811
    assert!(b.push("origin", false).unwrap()[0].ok);
812
    assert!(matches!(
813
        origin.verify_change(&h).unwrap(),
814
        SignatureStatus::Valid { .. }
815
    ));
816
}
817
818
#[test]
819
fn format1_repositories_are_migrated_on_open() {
820
    hermetic();
821
    use crate::oplog::{Format1Op, Format1View};
822
    let dir = tempfile::tempdir().unwrap();
823
    let root = dir.path();
824
    let repo = Repo::init(root).unwrap();
825
    write(root, "a.txt", b"a\n");
826
    let h1 = repo.commit("one", &[]).unwrap();
827
    let (wc_hash, _) = repo.working_copy().unwrap();
828
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
829
    let mut v1 = Format1View::default();
830
    v1.bookmarks.insert("main".into(), vec![]);
831
    v1.workspaces.insert(repo.workspace(), wc_hash);
832
    let init = Format1Op {
833
        parents: vec![],
834
        hlc: Hlc::default(),
835
        command: "oxy init".into(),
836
        view: v1.clone(),
837
    };
838
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
839
    v1.bookmarks.insert("main".into(), vec![h1]);
840
    let commit = Format1Op {
841
        parents: vec![init_ref],
842
        hlc: Hlc::default(),
843
        command: "oxy commit".into(),
844
        view: v1,
845
    };
846
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
847
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
848
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
849
    drop(repo);
850
851
    let repo = Repo::open(root).unwrap();
852
    assert_eq!(
853
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
854
        FORMAT_LINE
855
    );
856
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
857
    let ops = repo.op_log().unwrap();
858
    assert_eq!(
859
        ops.iter()
860
            .map(|(_, o)| o.command.as_str())
861
            .collect::<Vec<_>>(),
862
        ["oxy commit", "oxy init"]
863
    );
864
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
865
    assert!(!repo.snapshot("status").unwrap().changed);
866
    // Reopening again is a no-op.
867
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
868
}
869
870
#[test]
871
fn undo_skips_snapshot_operations() {
872
    hermetic();
873
    let dir = tempfile::tempdir().unwrap();
874
    let root = dir.path();
875
    let repo = Repo::init(root).unwrap();
876
    write(root, "a.txt", b"a\n");
877
    let h1 = repo.commit("a", &[]).unwrap();
878
    // A later command snapshots new edits on top of the commit.
879
    write(root, "b.txt", b"b\n");
880
    let s = repo.snapshot("oxy status").unwrap();
881
    assert!(s.changed);
882
    assert!(repo.head_op().unwrap().1.is_snapshot());
883
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
884
    // Undo must undo the commit, not the snapshot.
885
    repo.undo().unwrap();
886
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
887
    let s = repo.snapshot("oxy status").unwrap();
888
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
889
    assert_eq!(
890
        paths,
891
        ["a.txt", "b.txt"],
892
        "both files are back in the working copy"
893
    );
894
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
895
    // Only snapshots remain above `init`, so there is nothing left to undo.
896
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
897
    assert!(repo.undo().is_err());
898
}
899
900
#[test]
901
fn independent_changes_commute_and_make_multiple_heads() {
902
    hermetic();
903
    let dir = tempfile::tempdir().unwrap();
904
    let root = dir.path();
905
    let repo = Repo::init(root).unwrap();
906
    write(root, "a.txt", b"a\n");
907
    let h1 = repo.commit("a", &[]).unwrap();
908
    write(root, "b.txt", b"b\n");
909
    let h2 = repo.commit("b", &[]).unwrap();
910
    let c2 = repo.store().get_change(&h2).unwrap();
911
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
912
    let mut heads = repo.bookmark_heads().unwrap();
913
    heads.sort();
914
    let mut want = vec![h1, h2];
915
    want.sort();
916
    assert_eq!(heads, want);
917
    // Editing a.txt depends on h1 only.
918
    write(root, "a.txt", b"a\na2\n");
919
    let h3 = repo.commit("a2", &[]).unwrap();
920
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
921
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
922
    assert_eq!(heads, [h2, h3].into_iter().collect());
923
    // Explicit dependency.
924
    write(root, "c.txt", b"c\n");
925
    let h4 = repo.commit("c", &[h2]).unwrap();
926
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
927
}
928
929
#[test]
930
fn mode_change_and_text_binary_switch() {
931
    hermetic();
932
    let dir = tempfile::tempdir().unwrap();
933
    let root = dir.path();
934
    let repo = Repo::init(root).unwrap();
935
    write(root, "run.sh", b"#!/bin/sh\n");
936
    repo.commit("add script", &[]).unwrap();
937
    #[cfg(unix)]
938
    {
939
        use std::os::unix::fs::PermissionsExt;
940
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
941
        let s = repo.snapshot("status").unwrap();
942
        assert_eq!(
943
            statuses(&s),
944
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
945
        );
946
        let h = repo.commit("exec", &[]).unwrap();
947
        let snap = repo.load_state(&[h]).unwrap().materialize();
948
        assert!(snap.files["run.sh"].mode.exec);
949
    }
950
    // Text → binary → text.
951
    write(root, "run.sh", b"\0binary");
952
    let h = repo.commit("binary", &[]).unwrap();
953
    let snap = repo.load_state(&[h]).unwrap().materialize();
954
    assert!(snap.files["run.sh"].mode.opaque);
955
    write(root, "run.sh", b"text again\n");
956
    let h = repo.commit("text", &[]).unwrap();
957
    let snap = repo.load_state(&[h]).unwrap().materialize();
958
    assert!(!snap.files["run.sh"].mode.opaque);
959
    assert!(
960
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
961
    );
962
    assert!(!snap.is_conflicted());
963
}
964
965
#[test]
966
fn trust_policy_governs_pushes_and_fetches() {
967
    hermetic();
968
    let dir = tempfile::tempdir().unwrap();
969
    let root = dir.path();
970
    let origin = Repo::init(&root.join("origin")).unwrap();
971
    let url = root.join("origin").to_string_lossy().to_string();
972
973
    // A is the root. Before the policy, an unsigned push from B is fine.
974
    let mut a = Repo::clone(&url, &root.join("a"))
975
        .unwrap()
976
        .with_home(root.join("home-a"));
977
    let (key_a, _) = a
978
        .create_identity("Ada", "[email protected]", IdentityScope::User)
979
        .unwrap();
980
    let mut b = Repo::clone(&url, &root.join("b"))
981
        .unwrap()
982
        .with_home(root.join("home-b"));
983
    write(&root.join("b"), "b.txt", b"b\n");
984
    b.commit("unsigned before policy", &[]).unwrap();
985
    assert!(b.push("origin", false).unwrap()[0].ok);
986
987
    // A creates the policy and pushes it; origin now enforces it.
988
    write(&root.join("a"), "a.txt", b"a\n");
989
    a.commit("a", &[]).unwrap();
990
    let sp = a.policy_init().unwrap();
991
    assert_eq!(sp.policy.serial, 1);
992
    a.pull("origin").unwrap();
993
    let results = a.push("origin", false).unwrap();
994
    assert!(results.iter().all(|r| r.ok), "{results:?}");
995
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
996
997
    // B pulls the policy. Without an identity B cannot push at all.
998
    b.pull("origin").unwrap();
999
    assert!(
1000
        b.current_policy().unwrap().is_some(),
1001
        "the policy arrived with the fetch"
1002
    );
1003
    assert!(b.push("origin", false).is_err());
1004
    // With an identity the policy does not list, the push is rejected by origin.
1005
    let (key_b, id_b) = b
1006
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1007
        .unwrap();
1008
    write(&root.join("b"), "b.txt", b"b2\n");
1009
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1010
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1011
    let r = b.push("origin", false).unwrap();
1012
    assert!(
1013
        !r[0].ok && r[0].reason.contains("may not update"),
1014
        "{:?}",
1015
        r
1016
    );
1017
1018
    // A grants B (identity handed over as a file) and publishes the policy.
1019
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1020
    assert_eq!(sp.policy.serial, 2);
1021
    let r = a.push("origin", false).unwrap();
1022
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1023
    // B must fetch the new policy before pushing.
1024
    assert!(b
1025
        .push("origin", false)
1026
        .unwrap_or_else(|e| vec![RefResult {
1027
            name: "main".into(),
1028
            ok: false,
1029
            reason: e.to_string()
1030
        }])
1031
        .iter()
1032
        .all(|x| !x.ok));
1033
    b.pull("origin").unwrap();
1034
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1035
    let r = b.push("origin", false).unwrap();
1036
    assert!(r[0].ok, "{:?}", r);
1037
    // Origin verified B's change under the policy.
1038
    let heads = origin.bookmark_heads().unwrap();
1039
    for h in &heads {
1040
        let c = origin.store().get_change(h).unwrap();
1041
        if c.author == key_b {
1042
            origin
1043
                .change_allowed(
1044
                    h,
1045
                    &origin.current_policy().unwrap().unwrap().1.policy,
1046
                    "main",
1047
                )
1048
                .unwrap();
1049
        }
1050
    }
1051
1052
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1053
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1054
    forged.serial = 3;
1055
    forged.roots = vec![key_b];
1056
    let fh = forged.hash();
1057
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1058
    let forged = SignedPolicy {
1059
        policy: forged,
1060
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1061
    };
1062
    let r = origin
1063
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1064
        .unwrap();
1065
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1066
    let stale = a.current_policy().unwrap().unwrap().1;
1067
    let mut old = stale.clone();
1068
    old.policy.serial = 1;
1069
    let r = origin
1070
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1071
        .unwrap();
1072
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1073
1074
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1075
    a.pull("origin").unwrap();
1076
    a.policy_revoke(&key_b).unwrap();
1077
    let r = a.push("origin", false).unwrap();
1078
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1079
    b.pull("origin").unwrap();
1080
    write(&root.join("b"), "b.txt", b"b3\n");
1081
    b.commit("b3", &[]).unwrap();
1082
    let r = b.push("origin", false).unwrap();
1083
    assert!(!r[0].ok, "{:?}", r);
1084
1085
    // A clone by a third party receives and verifies everything.
1086
    let c = Repo::clone(&url, &root.join("c"))
1087
        .unwrap()
1088
        .with_home(root.join("home-c"));
1089
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1090
    assert!(c
1091
        .current_policy()
1092
        .unwrap()
1093
        .unwrap()
1094
        .1
1095
        .policy
1096
        .roots
1097
        .contains(&key_a));
1098
    assert!(!c.snapshot("status").unwrap().changed);
1099
}
1100
1101
#[test]
1102
fn gc_packs_objects_and_history_still_works() {
1103
    hermetic();
1104
    let dir = tempfile::tempdir().unwrap();
1105
    let root = dir.path();
1106
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1107
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1108
        .unwrap();
1109
    repo.set_user_config("core.sign", "change").unwrap();
1110
    write(root, "a.txt", b"one\n");
1111
    let h1 = repo.commit("one", &[]).unwrap();
1112
    write(root, "a.txt", b"two\n");
1113
    write(root, "big.bin", &vec![0u8; 100_000]);
1114
    let h2 = repo.commit("two", &[]).unwrap();
1115
    // Several snapshots leave superseded working-copy versions behind.
1116
    for i in 0..5 {
1117
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1118
        repo.snapshot("status").unwrap();
1119
    }
1120
    write(root, "a.txt", b"two\n");
1121
    repo.snapshot("status").unwrap();
1122
    let before = repo.store().list().unwrap();
1123
    assert!(repo.store().loose_count().unwrap() > 0);
1124
1125
    // With the default retention every operation's view is a root: nothing prunes.
1126
    let r = repo.gc(true).unwrap();
1127
    assert_eq!(r.packed.objects, before.len());
1128
    assert_eq!(r.pruned.objects, 0);
1129
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1130
    assert_eq!(repo.store().list().unwrap(), before);
1131
1132
    // With zero retention only the current view is a root: superseded
1133
    // working copies go, everything reachable stays.
1134
    repo.config.set("core.op-retention", "0").unwrap();
1135
    repo.save_config().unwrap();
1136
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1137
    let r = repo.gc(true).unwrap();
1138
    assert!(r.pruned.objects >= 5, "{r:?}");
1139
    let after = repo.store().list().unwrap();
1140
    assert!(after.len() < before.len());
1141
    assert!(after.contains(&h1) && after.contains(&h2));
1142
    for (_, op) in repo.op_log().unwrap() {
1143
        assert!(!op.command.is_empty(), "operation objects are all kept");
1144
    }
1145
    // Everything still works from the pruned, packed store.
1146
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1147
    assert!(matches!(
1148
        repo.verify_change(&h2).unwrap(),
1149
        SignatureStatus::Valid { .. }
1150
    ));
1151
    assert_eq!(repo.log().unwrap().len(), 3);
1152
    repo.checkout(&[h1], false, "checkout").unwrap();
1153
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1154
    repo.checkout(&[h2], false, "checkout").unwrap();
1155
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1156
    assert!(!repo.snapshot("status").unwrap().changed);
1157
    // Grace period defers pruning of young garbage.
1158
    write(root, "a.txt", b"three\n");
1159
    repo.commit("three", &[]).unwrap();
1160
    let r = repo.gc(false).unwrap();
1161
    assert_eq!(r.pruned.objects, 0);
1162
    assert!(r.pruned.deferred > 0);
1163
    let r = repo.gc(true).unwrap();
1164
    assert!(r.pruned.objects > 0);
1165
    assert_eq!(repo.log().unwrap().len(), 4);
1166
    // Restoring the default retention makes the old views roots again; the
1167
    // working copies they name were pruned, which gc tolerates.
1168
    repo.config.set("core.op-retention", "90").unwrap();
1169
    repo.save_config().unwrap();
1170
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1171
    let r = repo.gc(false).unwrap();
1172
    assert_eq!(r.pruned.objects, 0);
1173
    assert_eq!(repo.log().unwrap().len(), 4);
1174
}
1175
1176
#[test]
1177
fn describe_amend_abandon_heads() {
1178
    hermetic();
1179
    let dir = tempfile::tempdir().unwrap();
1180
    let root = dir.path();
1181
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1182
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1183
        .unwrap();
1184
    repo.set_user_config("core.sign", "change").unwrap();
1185
    write(root, "a.txt", b"one\n");
1186
    let h1 = repo.commit("first", &[]).unwrap();
1187
    write(root, "a.txt", b"one\ntwo\n");
1188
    let h2 = repo.commit("secnod", &[]).unwrap();
1189
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1190
1191
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1192
    let h2b = repo.describe(&h2, "second").unwrap();
1193
    assert_ne!(h2b, h2);
1194
    let c = repo.store().get_change(&h2b).unwrap();
1195
    assert_eq!(
1196
        (c.change_id, c.message.as_str(), c.deps.clone()),
1197
        (id2, "second", vec![h1])
1198
    );
1199
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1200
    assert!(matches!(
1201
        repo.verify_change(&h2b).unwrap(),
1202
        SignatureStatus::Valid { .. }
1203
    ));
1204
    let s = repo.snapshot("status").unwrap();
1205
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1206
    assert_eq!(
1207
        repo.resolve_change(&id2.short(8)).unwrap(),
1208
        h2b,
1209
        "the old object is no longer reachable from the log"
1210
    );
1211
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1212
    let h1b = repo.describe(&h1, "first, described").unwrap();
1213
    assert_ne!(h1b, h1);
1214
    let heads = repo.bookmark_heads().unwrap();
1215
    assert_eq!(heads.len(), 1);
1216
    let top = repo.store().get_change(&heads[0]).unwrap();
1217
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1218
    assert!(
1219
        matches!(
1220
            repo.verify_change(&heads[0]).unwrap(),
1221
            SignatureStatus::Valid { .. }
1222
        ),
1223
        "rewritten own change is re-signed"
1224
    );
1225
    let (_, wc) = repo.working_copy().unwrap();
1226
    assert_eq!(
1227
        wc.deps,
1228
        vec![heads[0]],
1229
        "the working copy follows the rewrite"
1230
    );
1231
    assert!(!repo.snapshot("status").unwrap().changed);
1232
    let snap = repo.load_state(&heads).unwrap().materialize();
1233
    assert!(
1234
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1235
    );
1236
1237
    // amend: fold an edit into the head; the result is one change from h1.
1238
    write(root, "a.txt", b"one\ntwo\nthree\n");
1239
    write(root, "b.txt", b"b\n");
1240
    let h2c = repo.amend(None).unwrap();
1241
    let c = repo.store().get_change(&h2c).unwrap();
1242
    assert_eq!(c.change_id, id2);
1243
    assert_eq!(c.message, "second");
1244
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1245
    assert_eq!(
1246
        repo.log().unwrap().len(),
1247
        3,
1248
        "working copy, amended head, first"
1249
    );
1250
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1251
    assert!(
1252
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1253
    );
1254
    assert!(snap.files.contains_key("b.txt"));
1255
    assert!(!repo.snapshot("status").unwrap().changed);
1256
    assert!(
1257
        repo.amend(None).is_err(),
1258
        "clean working copy and no message"
1259
    );
1260
    let h2d = repo.amend(Some("second, amended")).unwrap();
1261
    assert_eq!(
1262
        repo.store().get_change(&h2d).unwrap().message,
1263
        "second, amended"
1264
    );
1265
1266
    // abandon: the head goes, its content stays as uncommitted work.
1267
    repo.abandon(&h2d).unwrap();
1268
    assert_eq!(
1269
        repo.bookmark_heads().unwrap(),
1270
        vec![h1b],
1271
        "the described first change is the head again"
1272
    );
1273
    let s = repo.snapshot("status").unwrap();
1274
    let paths: Vec<_> = s
1275
        .statuses
1276
        .iter()
1277
        .map(|p| (p.path.as_str(), p.status))
1278
        .collect();
1279
    assert_eq!(
1280
        paths,
1281
        vec![
1282
            ("a.txt", ChangeStatus::Modified),
1283
            ("b.txt", ChangeStatus::Added)
1284
        ]
1285
    );
1286
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1287
    let h3 = repo.commit("recommitted", &[]).unwrap();
1288
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1289
    // undo brings the abandoned head back.
1290
    repo.undo().unwrap();
1291
    repo.undo().unwrap();
1292
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1293
1294
    // Abandoning a non-head whose dependent references its atoms reifies
1295
    // the references (here: a.txt vanishes with it, so the dependent's edit
1296
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1297
    let base = repo.bookmark_heads().unwrap()[0];
1298
    let base_change = repo.store().get_change(&base).unwrap();
1299
    let h1_now = base_change.deps[0];
1300
    let notes = repo.abandon(&h1_now).unwrap();
1301
    assert!(
1302
        !notes.is_empty(),
1303
        "the dependent's edit of a.txt was reified"
1304
    );
1305
    let heads = repo.bookmark_heads().unwrap();
1306
    let after = repo.load_state(&heads).unwrap().materialize();
1307
    assert!(
1308
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1309
        "{:?}",
1310
        after.files.keys()
1311
    );
1312
    repo.undo().unwrap();
1313
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1314
    write(root, "c.txt", b"c\n");
1315
    let hc = repo.commit("c", &[]).unwrap();
1316
    write(root, "d.txt", b"d\n");
1317
    let hd = repo.commit("d", &[hc]).unwrap();
1318
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1319
    repo.abandon(&hc).unwrap();
1320
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1321
    assert!(!heads.contains(&hc));
1322
    let d_now = heads
1323
        .iter()
1324
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1325
        .copied()
1326
        .unwrap();
1327
    assert!(
1328
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1329
        "d inherited c's (empty) dependencies"
1330
    );
1331
    let s = repo.snapshot("status").unwrap();
1332
    assert_eq!(
1333
        s.statuses
1334
            .iter()
1335
            .map(|p| p.path.as_str())
1336
            .collect::<Vec<_>>(),
1337
        vec!["c.txt"],
1338
        "c's content is now uncommitted work"
1339
    );
1340
}
1341
1342
#[test]
1343
fn git_export_mirrors_history() {
1344
    hermetic();
1345
    if std::process::Command::new("git")
1346
        .arg("--version")
1347
        .output()
1348
        .is_err()
1349
    {
1350
        eprintln!("git not installed; skipping");
1351
        return;
1352
    }
1353
    let dir = tempfile::tempdir().unwrap();
1354
    let root = dir.path();
1355
    let mut repo = Repo::init(&root.join("r"))
1356
        .unwrap()
1357
        .with_home(root.join("home"));
1358
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1359
        .unwrap();
1360
    let r = root.join("r");
1361
    write(&r, "README.md", b"hello\n");
1362
    write(&r, "src/main.rs", b"fn main() {}\n");
1363
    let h1 = repo.commit("first", &[]).unwrap();
1364
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1365
    write(&r, "logo.png", b"\x89PNG\0\0");
1366
    let h2 = repo.commit("second", &[]).unwrap();
1367
1368
    let git_dir = root.join("mirror.git");
1369
    let rep = repo.git_export(&git_dir).unwrap();
1370
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1371
    let git = |args: &[&str]| -> String {
1372
        let out = std::process::Command::new("git")
1373
            .arg("-C")
1374
            .arg(&git_dir)
1375
            .args(args)
1376
            .output()
1377
            .unwrap();
1378
        assert!(
1379
            out.status.success(),
1380
            "{}",
1381
            String::from_utf8_lossy(&out.stderr)
1382
        );
1383
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1384
    };
1385
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1386
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1387
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1388
    let body = git(&["log", "-1", "--format=%B", "main"]);
1389
    assert!(
1390
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1391
        "{body}"
1392
    );
1393
    assert!(body.contains("Change-Id: "), "{body}");
1394
    assert_eq!(
1395
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1396
        "Ada Lovelace <[email protected]>"
1397
    );
1398
    assert_eq!(
1399
        git(&["ls-tree", "--name-only", "main"]),
1400
        "README.md\nlogo.png\nsrc"
1401
    );
1402
1403
    // Re-export is incremental.
1404
    let rep = repo.git_export(&git_dir).unwrap();
1405
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1406
1407
    // An independent change makes two heads; the next state is one more
1408
    // commit on the linear branch whose tree is the union.
1409
    repo.checkout(&[h1], false, "checkout").unwrap();
1410
    write(&r, "other.txt", b"o\n");
1411
    let h3 = repo.commit("third", &[]).unwrap();
1412
    let rep = repo.git_export(&git_dir).unwrap();
1413
    assert_eq!((rep.exported, rep.heads), (1, 2));
1414
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1415
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1416
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1417
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1418
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1419
    assert_eq!(
1420
        git(&["ls-tree", "--name-only", "main"]),
1421
        "README.md\nlogo.png\nother.txt\nsrc"
1422
    );
1423
    let body = git(&["log", "-1", "--format=%B", "main"]);
1424
    assert!(
1425
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1426
        "{body}"
1427
    );
1428
    // A rewrite is a new state whose one new change is the rewritten one.
1429
    repo.describe(&h3, "third, described").unwrap();
1430
    let rep = repo.git_export(&git_dir).unwrap();
1431
    assert_eq!(rep.exported, 1);
1432
    assert_eq!(
1433
        git(&["log", "-1", "--format=%s", "main"]),
1434
        "third, described"
1435
    );
1436
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1437
    let _ = h2;
1438
}
1439
1440
#[test]
1441
fn git_import_reproduces_trees() {
1442
    git_import_reproduces_trees_with(None);
1443
}
1444
1445
/// The same import with every merge rendered in batches of one file
1446
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1447
#[test]
1448
fn git_import_reproduces_trees_in_batches() {
1449
    git_import_reproduces_trees_with(Some(1));
1450
}
1451
1452
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1453
    crate::repo::git::set_merge_batch_for_tests(batch);
1454
    hermetic();
1455
    if std::process::Command::new("git")
1456
        .arg("--version")
1457
        .output()
1458
        .is_err()
1459
    {
1460
        eprintln!("git not installed; skipping");
1461
        return;
1462
    }
1463
    let dir = tempfile::tempdir().unwrap();
1464
    let root = dir.path();
1465
    let g = root.join("src.git");
1466
    fs::create_dir_all(&g).unwrap();
1467
    let git = |args: &[&str]| -> String {
1468
        let out = std::process::Command::new("git")
1469
            .arg("-C")
1470
            .arg(&g)
1471
            .args([
1472
                "-c",
1473
                "user.name=Grace",
1474
                "-c",
1475
                "[email protected]",
1476
                "-c",
1477
                "commit.gpgsign=false",
1478
            ])
1479
            .args(args)
1480
            .output()
1481
            .unwrap();
1482
        assert!(
1483
            out.status.success(),
1484
            "git {args:?}: {}",
1485
            String::from_utf8_lossy(&out.stderr)
1486
        );
1487
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1488
    };
1489
    git(&["init", "-q", "-b", "main"]);
1490
    write(&g, "README.md", b"# Hi\n");
1491
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1492
    git(&["add", "."]);
1493
    git(&["commit", "-q", "-m", "initial"]);
1494
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1495
    write(&g, "run.sh", b"#!/bin/sh\n");
1496
    #[cfg(unix)]
1497
    {
1498
        use std::os::unix::fs::PermissionsExt;
1499
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1500
    }
1501
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1502
    git(&["add", "."]);
1503
    git(&[
1504
        "commit",
1505
        "-q",
1506
        "-m",
1507
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1508
    ]);
1509
    // A branch that edits README, merged back with a conflict-free merge.
1510
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1511
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1512
    git(&["commit", "-q", "-am", "readme"]);
1513
    git(&["checkout", "-q", "main"]);
1514
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1515
    // A branch from the initial commit inserting at the same place as
1516
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1517
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1518
    git(&["checkout", "-q", "-b", "clash", &initial]);
1519
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1520
    git(&["commit", "-q", "-am", "clash"]);
1521
    git(&["checkout", "-q", "main"]);
1522
    let _ = std::process::Command::new("git")
1523
        .arg("-C")
1524
        .arg(&g)
1525
        .args(["merge", "-q", "clash"])
1526
        .output();
1527
    write(
1528
        &g,
1529
        "src/lib.rs",
1530
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1531
    );
1532
    git(&["add", "."]);
1533
    git(&["commit", "-q", "-m", "resolve clash"]);
1534
    git(&["rm", "-q", "logo.png"]);
1535
    git(&["commit", "-q", "-m", "drop logo"]);
1536
    // A rename with a small edit is imported as a move of the same node.
1537
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1538
    write(
1539
        &g,
1540
        "src/lib2.rs",
1541
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1542
    );
1543
    git(&["add", "."]);
1544
    git(&["commit", "-q", "-m", "rename lib"]);
1545
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1546
    // run.sh is the same as in the first parent's tree, but the merged
1547
    // change touched it, so the importer must compare it, not skip it.
1548
    git(&["checkout", "-q", "-b", "discarded"]);
1549
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1550
    git(&["commit", "-q", "-am", "discarded edit"]);
1551
    git(&["checkout", "-q", "main"]);
1552
    git(&[
1553
        "merge",
1554
        "-q",
1555
        "-s",
1556
        "ours",
1557
        "-m",
1558
        "merge discarded, keeping ours",
1559
        "discarded",
1560
    ]);
1561
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1562
1563
    let dest = root.join("oxy");
1564
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1565
    let rep = repo.import_git(&g, "main").unwrap();
1566
    assert_eq!(rep.commits, expected_count);
1567
    assert_eq!(rep.merges, 3);
1568
    assert_eq!(
1569
        fs::read(dest.join("run.sh")).unwrap(),
1570
        b"#!/bin/sh\n",
1571
        "the ours merge kept main's run.sh"
1572
    );
1573
    let v = repo.verify_git_import(&g, "main").unwrap();
1574
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1575
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1576
    // The working copy equals the Git tree at main.
1577
    assert_eq!(
1578
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1579
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1580
    );
1581
    assert!(!dest.join("src/lib.rs").exists());
1582
    assert_eq!(
1583
        fs::read(dest.join("README.md")).unwrap(),
1584
        b"# Hi\n\nMore.\n"
1585
    );
1586
    assert!(!dest.join("logo.png").exists());
1587
    #[cfg(unix)]
1588
    {
1589
        use std::os::unix::fs::PermissionsExt;
1590
        assert!(
1591
            fs::metadata(dest.join("run.sh"))
1592
                .unwrap()
1593
                .permissions()
1594
                .mode()
1595
                & 0o111
1596
                != 0
1597
        );
1598
    }
1599
    assert!(
1600
        !repo.snapshot("status").unwrap().changed,
1601
        "clean after import"
1602
    );
1603
    let heads = repo.bookmark_heads().unwrap();
1604
    let st = repo.load_state(&heads).unwrap();
1605
    assert!(!st.materialize().is_conflicted());
1606
    assert_eq!(st.len(), expected_count);
1607
    let tip = repo
1608
        .log()
1609
        .unwrap()
1610
        .into_iter()
1611
        .find(|e| e.change.message.starts_with("rename lib"))
1612
        .unwrap();
1613
    let c = repo.store().get_change(&tip.hash).unwrap();
1614
    assert!(
1615
        c.tree_ops
1616
            .iter()
1617
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1618
        "{:?}",
1619
        c.tree_ops
1620
    );
1621
    assert!(!c
1622
        .tree_ops
1623
        .iter()
1624
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1625
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1626
    let log = repo.log().unwrap();
1627
    let second = log
1628
        .iter()
1629
        .find(|e| e.change.message.starts_with("second"))
1630
        .unwrap();
1631
    assert_eq!(
1632
        second.change.change_id,
1633
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1634
    );
1635
    assert!(second
1636
        .change
1637
        .message
1638
        .contains("Git-Author: Grace <[email protected]>"));
1639
    let resolve = log
1640
        .iter()
1641
        .find(|e| e.change.message.starts_with("resolve clash"))
1642
        .unwrap();
1643
    assert_eq!(
1644
        resolve.change.kind,
1645
        ChangeKind::Resolution,
1646
        "a conflicting Git merge becomes a resolution"
1647
    );
1648
    // Re-importing into another fresh repository gives the same ChangeIds.
1649
    let repo2 = Repo::init(&root.join("oxy2"))
1650
        .unwrap()
1651
        .with_home(root.join("home"));
1652
    repo2.import_git(&g, "main").unwrap();
1653
    // New nodes' identifiers derive from the commit (spec §23), so the
1654
    // re-import is not just the same ChangeIds but the same changes.
1655
    assert_eq!(
1656
        repo2.bookmark_heads().unwrap(),
1657
        repo.bookmark_heads().unwrap()
1658
    );
1659
    let ids: BTreeSet<ChangeId> = repo
1660
        .log()
1661
        .unwrap()
1662
        .iter()
1663
        .filter(|e| !e.is_working_copy)
1664
        .map(|e| e.change.change_id)
1665
        .collect();
1666
    let ids2: BTreeSet<ChangeId> = repo2
1667
        .log()
1668
        .unwrap()
1669
        .iter()
1670
        .filter(|e| !e.is_working_copy)
1671
        .map(|e| e.change.change_id)
1672
        .collect();
1673
    assert_eq!(ids, ids2);
1674
    // Round trip back out to Git reproduces the tip tree.
1675
    let mirror = root.join("mirror.git");
1676
    repo.git_export(&mirror).unwrap();
1677
    let out = std::process::Command::new("git")
1678
        .arg("-C")
1679
        .arg(&mirror)
1680
        .args(["show", "main:src/lib2.rs"])
1681
        .output()
1682
        .unwrap();
1683
    assert_eq!(
1684
        String::from_utf8_lossy(&out.stdout),
1685
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1686
    );
1687
    let out = std::process::Command::new("git")
1688
        .arg("-C")
1689
        .arg(&mirror)
1690
        .args(["show", "main:src/lib.rs"])
1691
        .output()
1692
        .unwrap();
1693
    assert!(
1694
        !out.status.success(),
1695
        "the old path is gone from the export"
1696
    );
1697
}
1698
1699
#[test]
1700
fn checkpoints_accelerate_loading_and_stay_correct() {
1701
    hermetic();
1702
    let dir = tempfile::tempdir().unwrap();
1703
    let root = dir.path();
1704
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1705
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1706
    repo.save_config().unwrap();
1707
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1708
    let mut hashes = Vec::new();
1709
    for i in 0..12 {
1710
        write(
1711
            root,
1712
            "a.txt",
1713
            format!(
1714
                "{}\n",
1715
                (0..=i)
1716
                    .map(|k| k.to_string())
1717
                    .collect::<Vec<_>>()
1718
                    .join("\n")
1719
            )
1720
            .as_bytes(),
1721
        );
1722
        write(root, &format!("f{i}.txt"), b"x\n");
1723
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1724
    }
1725
    let (_, cp) = repo
1726
        .latest_checkpoint("main")
1727
        .unwrap()
1728
        .expect("automatic checkpoint");
1729
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1730
    // Loading through the checkpoint equals loading everything.
1731
    let heads = repo.bookmark_heads().unwrap();
1732
    let fast = repo.load_state(&heads).unwrap();
1733
    let full = repo.load_state_full(&heads).unwrap();
1734
    assert_eq!(fast.len(), full.len());
1735
    assert_eq!(fast.heads(), full.heads());
1736
    let (a, b) = (fast.materialize(), full.materialize());
1737
    assert_eq!(
1738
        a.files.keys().collect::<Vec<_>>(),
1739
        b.files.keys().collect::<Vec<_>>()
1740
    );
1741
    for (p, f) in &a.files {
1742
        assert_eq!(f.content, b.files[p].content, "{p}");
1743
    }
1744
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1745
    // A head set that does not contain the checkpoint's heads falls back.
1746
    assert!(repo
1747
        .load_state_checkpointed(&[hashes[0]])
1748
        .unwrap()
1749
        .is_none());
1750
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1751
    // Everything else keeps working on top of the checkpoint.
1752
    assert!(!repo.snapshot("status").unwrap().changed);
1753
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1754
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1755
    let (r, n, bytes) = repo.checkpoint().unwrap();
1756
    assert!(n >= 12 && bytes > 0);
1757
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1758
    write(root, "a.txt", b"after\n");
1759
    let h_after = repo.commit("after", &[]).unwrap();
1760
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1761
    assert!(st.contains(&h_after));
1762
    assert!(
1763
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1764
    );
1765
    assert_eq!(repo.log().unwrap().len(), 14);
1766
    // Checkpoints survive gc.
1767
    repo.gc(true).unwrap();
1768
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1769
    assert!(repo
1770
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1771
        .unwrap()
1772
        .is_some());
1773
}
1774
1775
#[test]
1776
fn quick_status_for_prompts() {
1777
    hermetic();
1778
    let dir = tempfile::tempdir().unwrap();
1779
    let root = dir.path();
1780
    let origin = Repo::init(&root.join("origin")).unwrap();
1781
    let url = root.join("origin").to_string_lossy().to_string();
1782
    let a = Repo::clone(&url, &root.join("a"))
1783
        .unwrap()
1784
        .with_home(root.join("home"));
1785
    let ops_before = a.op_log().unwrap().len();
1786
    let info = a.quick_status().unwrap();
1787
    assert_eq!(
1788
        (
1789
            info.bookmark.as_str(),
1790
            info.heads,
1791
            info.dirty,
1792
            info.conflicted,
1793
            info.ahead,
1794
            info.behind
1795
        ),
1796
        ("main", 0, false, false, Some(0), Some(0))
1797
    );
1798
    write(&root.join("a"), "f.txt", b"f\n");
1799
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1800
    assert_eq!(
1801
        a.op_log().unwrap().len(),
1802
        ops_before,
1803
        "quick_status records nothing"
1804
    );
1805
    // A snapshotted but uncommitted change is still dirty.
1806
    a.snapshot("status").unwrap();
1807
    assert!(a.quick_status().unwrap().dirty);
1808
    a.commit("f", &[]).unwrap();
1809
    let info = a.quick_status().unwrap();
1810
    assert!(!info.dirty, "clean right after a commit");
1811
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
1812
    assert_eq!(
1813
        info.format("%b %c%d%x%A%D"),
1814
        format!("main {}+1", info.change_id)
1815
    );
1816
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1817
    // Touching a file without changing it is not dirty; changing content of
1818
    // the same size is.
1819
    let p = root.join("a/f.txt");
1820
    let content = fs::read(&p).unwrap();
1821
    fs::write(&p, &content).unwrap();
1822
    assert!(!a.quick_status().unwrap().dirty);
1823
    fs::write(&p, b"g\n").unwrap();
1824
    assert!(a.quick_status().unwrap().dirty);
1825
    fs::write(&p, b"f\n").unwrap();
1826
    // Push, then a second clone commits and pushes: we are behind.
1827
    assert!(a.push("origin", false).unwrap()[0].ok);
1828
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
1829
    let b = Repo::clone(&url, &root.join("b"))
1830
        .unwrap()
1831
        .with_home(root.join("home-b"));
1832
    write(&root.join("b"), "g.txt", b"g\n");
1833
    b.commit("g", &[]).unwrap();
1834
    b.push("origin", false).unwrap();
1835
    a.fetch("origin").unwrap();
1836
    let info = a.quick_status().unwrap();
1837
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1838
    assert_eq!(info.format("%A%D"), "-1");
1839
    let _ = origin;
1840
}
1841
1842
#[test]
1843
fn lazy_blobs_are_fetched_on_first_read() {
1844
    hermetic();
1845
    let dir = tempfile::tempdir().unwrap();
1846
    let root = dir.path();
1847
    let origin_dir = root.join("origin");
1848
    let origin = Repo::init(&origin_dir)
1849
        .unwrap()
1850
        .with_home(root.join("home"));
1851
    let url = origin_dir.to_string_lossy().to_string();
1852
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1853
    write(&origin_dir, "big.bin", &big);
1854
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1855
    write(&origin_dir, "t.txt", b"t\n");
1856
    let h = origin.commit("blobs", &[]).unwrap();
1857
    let big_ref = Repo::blob_ref(&big);
1858
1859
    // Fetch only (no checkout) with a filter: the big blob stays absent.
1860
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1861
        .unwrap()
1862
        .with_home(root.join("home"));
1863
    let a = {
1864
        let mut a = a;
1865
        a.config.set("remote.origin.url", &url).unwrap();
1866
        a.config.set("filter.max-blob", "100K").unwrap();
1867
        a.save_config().unwrap();
1868
        a
1869
    };
1870
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1871
    a.fetch("origin").unwrap();
1872
    assert!(a.store().has(&h));
1873
    assert!(!a.store().has(&big_ref), "withheld");
1874
    assert!(
1875
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1876
        "small blob came along"
1877
    );
1878
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1879
1880
    // status and commit do not need it: adopt the state, edit a text file, commit.
1881
    let (op_ref, op) = a.head_op().unwrap();
1882
    let mut view = op.view.clone();
1883
    view.bookmarks.insert(
1884
        "main".into(),
1885
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1886
    );
1887
    a.record_op(&[op_ref], "adopt", view).unwrap();
1888
    // Checkout reads the blob lazily, which fetches it.
1889
    a.checkout(&[h], true, "checkout").unwrap();
1890
    assert!(a.store().has(&big_ref), "fetched on first read");
1891
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1892
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1893
    write(&root.join("a"), "t.txt", b"t2\n");
1894
    a.commit("text edit", &[]).unwrap();
1895
1896
    // clone --max-blob records the filter; the checkout fetches lazily.
1897
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
1898
    assert_eq!(b.config.max_blob, Some(1024));
1899
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1900
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1901
    assert!(parse_size("lots").is_err());
1902
}
1903
1904
#[test]
1905
fn sparse_checkout_materializes_only_chosen_paths() {
1906
    hermetic();
1907
    let dir = tempfile::tempdir().unwrap();
1908
    let root = dir.path();
1909
    let origin_dir = root.join("origin");
1910
    let origin = Repo::init(&origin_dir)
1911
        .unwrap()
1912
        .with_home(root.join("home"));
1913
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1914
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1915
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1916
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1917
    write(&origin_dir, "docs/logo.png", &logo);
1918
    write(&origin_dir, "README.md", b"# top\n");
1919
    let h1 = origin.commit("tree", &[]).unwrap();
1920
    let url = origin_dir.to_string_lossy().to_string();
1921
1922
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
1923
        .unwrap()
1924
        .with_home(root.join("home"));
1925
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1926
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1927
    assert!(root.join("a/src/main.rs").exists());
1928
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
1929
    assert!(
1930
        !a.store().has(&Repo::blob_ref(&logo)),
1931
        "out-of-scope blob never fetched"
1932
    );
1933
    assert!(
1934
        !a.snapshot("status").unwrap().changed,
1935
        "out-of-scope files are not removals"
1936
    );
1937
    assert!(!a.quick_status().unwrap().dirty);
1938
1939
    // Edits in scope commit normally and keep the rest of the tree intact.
1940
    write(
1941
        &root.join("a"),
1942
        "src/lib.rs",
1943
        b"pub fn a() {}\npub fn b() {}\n",
1944
    );
1945
    let h2 = a.commit("edit lib", &[]).unwrap();
1946
    let st = a.load_state(&[h2]).unwrap().materialize();
1947
    assert!(
1948
        st.files.contains_key("docs/guide.md"),
1949
        "the state still has everything"
1950
    );
1951
    assert!(a.push("origin", false).unwrap()[0].ok);
1952
    // Files created outside the scope are ignored by status.
1953
    write(&root.join("a"), "docs/new.md", b"ignored\n");
1954
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
1955
1956
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
1957
    let mut a = a;
1958
    a.config.set("filter.paths", "src,docs").unwrap();
1959
    a.save_config().unwrap();
1960
    let r = a
1961
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
1962
        .unwrap();
1963
    assert!(r.written >= 2);
1964
    assert_eq!(
1965
        fs::read(root.join("a/docs/logo.png")).unwrap(),
1966
        logo,
1967
        "now fetched lazily"
1968
    );
1969
    assert!(!root.join("a/README.md").exists());
1970
    // Origin sees the change made under a sparse checkout with the full tree intact.
1971
    origin.pull("origin").err();
1972
    let full = origin
1973
        .load_state(&origin.bookmark_heads().unwrap())
1974
        .unwrap()
1975
        .materialize();
1976
    assert!(
1977
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
1978
    );
1979
    assert!(full.files.contains_key("README.md"));
1980
    let _ = h1;
1981
}
1982
1983
#[test]
1984
fn shallow_clone_and_deepen() {
1985
    hermetic();
1986
    let dir = tempfile::tempdir().unwrap();
1987
    let root = dir.path();
1988
    let origin_dir = root.join("origin");
1989
    let origin = Repo::init(&origin_dir)
1990
        .unwrap()
1991
        .with_home(root.join("home"));
1992
    let mut hashes = Vec::new();
1993
    for i in 0..8 {
1994
        write(
1995
            &origin_dir,
1996
            "a.txt",
1997
            format!(
1998
                "{}\n",
1999
                (0..=i)
2000
                    .map(|k| k.to_string())
2001
                    .collect::<Vec<_>>()
2002
                    .join("\n")
2003
            )
2004
            .as_bytes(),
2005
        );
2006
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2007
    }
2008
    let url = origin_dir.to_string_lossy().to_string();
2009
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2010
        .unwrap()
2011
        .with_home(root.join("home"));
2012
    assert!(a.is_shallow());
2013
    assert_eq!(
2014
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2015
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2016
    );
2017
    assert!(
2018
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2019
        "three levels present"
2020
    );
2021
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2022
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2023
    assert_eq!(
2024
        a.log().unwrap().len(),
2025
        9,
2026
        "the log shows every change from the checkpoint's metadata"
2027
    );
2028
    assert!(!a.snapshot("status").unwrap().changed);
2029
    assert_eq!(a.quick_status().unwrap().heads, 1);
2030
2031
    // Work continues on top of the shallow history and pushes back.
2032
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2033
    let h_new = a.commit("c8", &[]).unwrap();
2034
    assert!(a.push("origin", false).unwrap()[0].ok);
2035
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2036
    // Fetching new work from origin into the shallow clone works too.
2037
    write(&origin_dir, "b.txt", b"b\n");
2038
    origin.pull("origin").err();
2039
    let (_, wc) = origin.working_copy().unwrap();
2040
    let _ = wc;
2041
    origin
2042
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2043
        .unwrap();
2044
    write(&origin_dir, "b.txt", b"b\n");
2045
    let h_b = origin.commit("b", &[]).unwrap();
2046
    let pr = a.pull("origin").unwrap();
2047
    assert!(pr.changed);
2048
    assert!(a.store().has(&h_b));
2049
    assert!(root.join("a/b.txt").exists());
2050
2051
    // Deepening fetches older history until the boundary is gone.
2052
    // Every commit also depends on the change that created the file, so two
2053
    // levels below the boundary hold h4, h3, and the root.
2054
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2055
    assert!(a.store().has(&hashes[3]));
2056
    assert!(a.is_shallow());
2057
    a.deepen("origin", 100).unwrap();
2058
    assert!(!a.is_shallow(), "boundary reached the root");
2059
    assert!(a.store().has(&hashes[0]));
2060
    assert_eq!(
2061
        a.load_state_full(&a.bookmark_heads().unwrap())
2062
            .unwrap()
2063
            .len(),
2064
        10
2065
    );
2066
}
2067
2068
#[test]
2069
fn tags_are_immutable_named_states_and_travel() {
2070
    hermetic();
2071
    let dir = tempfile::tempdir().unwrap();
2072
    let root = dir.path();
2073
    let origin = Repo::init(&root.join("origin")).unwrap();
2074
    let url = root.join("origin").to_string_lossy().to_string();
2075
    let mut a = Repo::clone(&url, &root.join("a"))
2076
        .unwrap()
2077
        .with_home(root.join("home-a"));
2078
    let (key_a, _) = a
2079
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2080
        .unwrap();
2081
    write(&root.join("a"), "f.txt", b"1\n");
2082
    let h1 = a.commit("one", &[]).unwrap();
2083
    write(&root.join("a"), "f.txt", b"1\n2\n");
2084
    let h2 = a.commit("two", &[]).unwrap();
2085
2086
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2087
    assert_eq!(
2088
        (t.heads.clone(), t.signer.as_deref()),
2089
        (vec![h1], Some("Ada"))
2090
    );
2091
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2092
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2093
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2094
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2095
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2096
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2097
    assert_eq!(sa.sigs[0].key, key_a);
2098
    // Checkout by tag.
2099
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2100
        .unwrap();
2101
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2102
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2103
        .unwrap();
2104
2105
    // Push carries the tag; a second attestation for the name is refused.
2106
    let r = a.push("origin", false).unwrap();
2107
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2108
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2109
    let mut forged = a
2110
        .tag_refs()
2111
        .unwrap()
2112
        .into_iter()
2113
        .find(|t| t.name == "v1")
2114
        .unwrap();
2115
    forged.state = origin
2116
        .store()
2117
        .put_state(&StateObject::new(vec![h2]))
2118
        .unwrap();
2119
    forged.heads = vec![h2];
2120
    forged.attestation = None;
2121
    let r = origin
2122
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2123
        .unwrap();
2124
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2125
2126
    // A clone gets the tag; a later tag arrives on fetch.
2127
    let b = Repo::clone(&url, &root.join("b"))
2128
        .unwrap()
2129
        .with_home(root.join("home-b"));
2130
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2131
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2132
    a.tag_create("v2", &[h2], "second").unwrap();
2133
    a.push("origin", false).unwrap();
2134
    let rep = b.fetch("origin").unwrap();
2135
    assert_eq!(rep.new_tags, 1);
2136
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2137
2138
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2139
    a.policy_init().unwrap();
2140
    a.push("origin", false).unwrap();
2141
    let unattested = crate::protocol::TagRef {
2142
        name: "v3".into(),
2143
        state: origin
2144
            .store()
2145
            .put_state(&StateObject::new(vec![h2]))
2146
            .unwrap(),
2147
        heads: vec![h2],
2148
        attestation: None,
2149
    };
2150
    let r = origin
2151
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2152
        .unwrap();
2153
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2154
    a.tag_create("v3", &[h2], "").unwrap();
2155
    let r = a.push("origin", false).unwrap();
2156
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2157
    assert!(a.gc(true).is_ok());
2158
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2159
}
2160
2161
#[test]
2162
fn multiple_workspaces_share_a_repository() {
2163
    hermetic();
2164
    let dir = tempfile::tempdir().unwrap();
2165
    let root = dir.path();
2166
    let main_dir = root.join("main");
2167
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2168
    write(&main_dir, "a.txt", b"a\n");
2169
    let h1 = repo.commit("a", &[]).unwrap();
2170
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2171
2172
    // A second workspace elsewhere, checked out on the bookmark.
2173
    let ws_dir = root.join("ws2");
2174
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2175
    assert!(ws_dir.join(".oxy").is_file());
2176
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2177
    assert_ne!(ws.workspace(), repo.workspace());
2178
    let list = repo.workspaces().unwrap();
2179
    assert_eq!(list.len(), 2);
2180
    assert!(list
2181
        .iter()
2182
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2183
    assert!(!ws.snapshot("status").unwrap().changed);
2184
2185
    // Work in the second workspace: its own working copy, shared bookmark.
2186
    write(&ws_dir, "b.txt", b"b\n");
2187
    let s = ws.snapshot("status").unwrap();
2188
    assert_eq!(s.statuses.len(), 1);
2189
    assert!(
2190
        !repo.snapshot("status").unwrap().changed,
2191
        "the first workspace is untouched"
2192
    );
2193
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2194
    let mut heads = repo.bookmark_heads().unwrap();
2195
    heads.sort();
2196
    let mut want = vec![h1, h2];
2197
    want.sort();
2198
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2199
    assert!(!main_dir.join("b.txt").exists());
2200
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2201
        .unwrap();
2202
    assert!(main_dir.join("b.txt").exists());
2203
2204
    // Reopening from inside the second workspace finds the shared repository.
2205
    let reopened = Repo::open(&ws_dir).unwrap();
2206
    assert_eq!(reopened.workspace(), ws.workspace());
2207
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2208
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2209
2210
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2211
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2212
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2213
    repo.workspace_forget(&ws.workspace()).unwrap();
2214
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2215
    assert!(ws_dir.join("b.txt").exists());
2216
    assert!(
2217
        ws.snapshot("status").is_err(),
2218
        "a forgotten workspace is no longer in the view"
2219
    );
2220
2221
    // The working-copy lock: re-entrant in a thread; a lock whose process
2222
    // is gone is taken over, and a live process's is not, however old.
2223
    let lock = repo.lock_snapshot().unwrap();
2224
    let again = repo.lock_working_copy().unwrap();
2225
    drop(again);
2226
    drop(lock);
2227
    let lock_path = main_dir
2228
        .join(".oxy/workspaces")
2229
        .join(repo.workspace().to_hex())
2230
        .join("lock");
2231
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2232
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2233
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2234
    age(&lock_path);
2235
    assert!(
2236
        !super::workspace::lock_is_stale(&lock_path),
2237
        "a live process keeps its lock"
2238
    );
2239
    fs::write(&lock_path, "4294967295").unwrap();
2240
    age(&lock_path);
2241
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2242
}
2243
2244
#[test]
2245
fn attributes_binary_eol_nocompress_lockable() {
2246
    hermetic();
2247
    let dir = tempfile::tempdir().unwrap();
2248
    let root = dir.path();
2249
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2250
    write(
2251
        root,
2252
        ".oxyattributes",
2253
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2254
    );
2255
    write(root, "plain.dat", b"no nul bytes here\n");
2256
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2257
    write(root, "assets/model.bin", b"\0model");
2258
    let h = repo.commit("attrs", &[]).unwrap();
2259
    let snap = repo.load_state(&[h]).unwrap().materialize();
2260
    assert!(
2261
        snap.files["plain.dat"].mode.opaque,
2262
        "binary attribute forces opaque without NUL bytes"
2263
    );
2264
    assert!(
2265
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2266
        "stored with LF"
2267
    );
2268
    assert!(
2269
        !repo.snapshot("status").unwrap().changed,
2270
        "CRLF on disk equals LF in the state"
2271
    );
2272
    // nocompress chunks pack raw.
2273
    let r = repo.gc(true).unwrap();
2274
    assert!(r.packed.objects > 0);
2275
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2276
    fs::remove_file(root.join("notes.txt")).unwrap();
2277
    repo.checkout(&[h], true, "co").unwrap();
2278
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2279
    assert!(fs::metadata(root.join("assets/model.bin"))
2280
        .unwrap()
2281
        .permissions()
2282
        .readonly());
2283
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2284
    repo.lock_path("assets/model.bin").unwrap();
2285
    assert!(!fs::metadata(root.join("assets/model.bin"))
2286
        .unwrap()
2287
        .permissions()
2288
        .readonly());
2289
    assert!(repo.is_locked("assets/model.bin"));
2290
    write(root, "assets/model.bin", b"\0model2");
2291
    repo.commit("edit model", &[]).unwrap();
2292
    repo.unlock_path("assets/model.bin").unwrap();
2293
    assert!(fs::metadata(root.join("assets/model.bin"))
2294
        .unwrap()
2295
        .permissions()
2296
        .readonly());
2297
    // A later checkout can still overwrite a read-only lockable file.
2298
    repo.checkout(&[h], true, "co").unwrap();
2299
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2300
}
2301
2302
#[cfg(unix)]
2303
#[test]
2304
fn hooks_can_veto_observe_and_add_dependencies() {
2305
    use std::os::unix::fs::PermissionsExt;
2306
    hermetic();
2307
    let dir = tempfile::tempdir().unwrap();
2308
    let root = dir.path();
2309
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2310
    let hooks = root.join(".oxy/hooks");
2311
    fs::create_dir_all(&hooks).unwrap();
2312
    let hook = |name: &str, body: &str| {
2313
        let p = hooks.join(name);
2314
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2315
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2316
    };
2317
    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");
2318
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2319
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2320
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2321
    write(root, ".oxyignore", b".last-*\n");
2322
    write(root, "a.txt", b"a\n");
2323
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2324
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2325
    let h1 = repo.commit("first", &[]).unwrap();
2326
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2327
    assert!(
2328
        pre.contains("\"event\":\"pre-commit\"")
2329
            && pre.contains("\"path\":\"a.txt\"")
2330
            && pre.contains("\"message\":\"first\""),
2331
        "{pre}"
2332
    );
2333
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2334
    assert!(post.contains(&h1.to_hex()), "{post}");
2335
    repo.checkout(&[h1], false, "co").unwrap();
2336
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2337
        .unwrap()
2338
        .contains("post-checkout"));
2339
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2340
    repo.save_config().unwrap();
2341
    let err = repo.push("origin", false).unwrap_err().to_string();
2342
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2343
2344
    // semantic-deps: only when enabled; adds an explicit dependency.
2345
    write(root, "b.txt", b"b\n");
2346
    hook(
2347
        "semantic-deps",
2348
        &format!(
2349
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2350
            h1.to_hex()
2351
        ),
2352
    );
2353
    let h2 = repo.commit("b without hook", &[]).unwrap();
2354
    assert!(
2355
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2356
        "hook disabled by default"
2357
    );
2358
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2359
    repo.save_config().unwrap();
2360
    write(root, "c.txt", b"c\n");
2361
    let h3 = repo.commit("c with hook", &[]).unwrap();
2362
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2363
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2364
    assert!(
2365
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2366
        "{sem}"
2367
    );
2368
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2369
}
2370
2371
#[test]
2372
fn amend_into_older_change_and_split() {
2373
    hermetic();
2374
    let dir = tempfile::tempdir().unwrap();
2375
    let root = dir.path();
2376
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2377
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2378
        .unwrap();
2379
    repo.set_user_config("core.sign", "change").unwrap();
2380
    write(root, "a.txt", b"one\ntwo\n");
2381
    let h0 = repo.commit("base", &[]).unwrap();
2382
    write(root, "a.txt", b"one\nTWO\n");
2383
    let h1 = repo.commit("edit two", &[]).unwrap();
2384
    write(root, "a.txt", b"one\nTWO\nthree\n");
2385
    let h2 = repo.commit("add three", &[]).unwrap();
2386
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2387
2388
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2389
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2390
    let h1b = repo.amend_into(&h1, None).unwrap();
2391
    assert_ne!(h1b, h1);
2392
    let c1b = repo.store().get_change(&h1b).unwrap();
2393
    assert_eq!(c1b.change_id, id1);
2394
    assert_eq!(c1b.deps, vec![h0]);
2395
    assert!(matches!(
2396
        repo.verify_change(&h1b).unwrap(),
2397
        SignatureStatus::Valid { .. }
2398
    ));
2399
    let heads = repo.bookmark_heads().unwrap();
2400
    assert_eq!(heads.len(), 1);
2401
    let top = repo.store().get_change(&heads[0]).unwrap();
2402
    assert_eq!(top.message, "add three");
2403
    assert_eq!(
2404
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2405
        [h0, h1b].into_iter().collect(),
2406
        "depends on the file's creator and the rewritten line"
2407
    );
2408
    let snap = repo.load_state(&heads).unwrap().materialize();
2409
    assert!(
2410
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2411
    );
2412
    assert!(
2413
        !repo.snapshot("status").unwrap().changed,
2414
        "the working copy is clean after folding"
2415
    );
2416
    // Only h1b's own state shows the fix without "three".
2417
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2418
    assert!(
2419
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2420
    );
2421
    assert_eq!(repo.log().unwrap().len(), 4);
2422
2423
    // An edit to a line introduced by h2 cannot fold into h1.
2424
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2425
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2426
    assert!(err.contains("introduced after"), "{err}");
2427
    assert!(
2428
        repo.snapshot("status").unwrap().statuses.len() == 1,
2429
        "nothing was changed by the refusal"
2430
    );
2431
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2432
2433
    // Split the head that touches two files.
2434
    write(root, "b.txt", b"b\n");
2435
    write(root, "c.txt", b"c\n");
2436
    let h3 = repo.commit("b and c", &[]).unwrap();
2437
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2438
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2439
    let c_1 = repo.store().get_change(&p1).unwrap();
2440
    let c_2 = repo.store().get_change(&p2).unwrap();
2441
    assert!(c_1.message.contains("part 1: b.txt"));
2442
    assert_eq!(c_2.change_id, id3);
2443
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2444
    assert!(
2445
        heads.contains(&p1) && heads.contains(&p2),
2446
        "independent parts are both heads"
2447
    );
2448
    let snap = repo
2449
        .load_state(&repo.bookmark_heads().unwrap())
2450
        .unwrap()
2451
        .materialize();
2452
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2453
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2454
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2455
    assert!(!repo.snapshot("status").unwrap().changed);
2456
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2457
    let _ = h2;
2458
}
2459
2460
#[test]
2461
fn identity_lifecycle() {
2462
    hermetic();
2463
    let dir = tempfile::tempdir().unwrap();
2464
    let root = dir.path();
2465
    let origin = Repo::init(&root.join("origin")).unwrap();
2466
    let url = root.join("origin").to_string_lossy().to_string();
2467
    let mut a = Repo::clone(&url, &root.join("a"))
2468
        .unwrap()
2469
        .with_home(root.join("home-a"));
2470
    a.set_user_config("core.sign", "change").unwrap();
2471
    let (key_a, _) = a
2472
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2473
        .unwrap();
2474
    write(&root.join("a"), "a.txt", b"a\n");
2475
    let h1 = a.commit("one", &[]).unwrap();
2476
    assert!(a.policy_init().unwrap().applied);
2477
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2478
2479
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2480
    let mut e = Repo::init(&root.join("e"))
2481
        .unwrap()
2482
        .with_home(root.join("home-e"));
2483
    e.set_user_config("core.sign", "change").unwrap();
2484
    e.create_identity_with(
2485
        "Eve",
2486
        "[email protected]",
2487
        IdentityScope::User,
2488
        Some(Hlc::now().wall_ms - 1),
2489
    )
2490
    .unwrap();
2491
    write(&root.join("e"), "e.txt", b"e\n");
2492
    let he = e.commit("late", &[]).unwrap();
2493
    assert!(
2494
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2495
    );
2496
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2497
    let r = e
2498
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2499
        .unwrap();
2500
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2501
    write(&root.join("e"), "e.txt", b"e2\n");
2502
    let he2 = e.commit("in time", &[]).unwrap();
2503
    assert!(
2504
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2505
    );
2506
2507
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2508
    let r = a.rotate_identity().unwrap();
2509
    assert_eq!(r.old, key_a);
2510
    assert_eq!(a.config.author_key, Some(r.new));
2511
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2512
    assert!(r.policy.as_ref().unwrap().applied);
2513
    let (_, sp) = a.current_policy().unwrap().unwrap();
2514
    assert_eq!(
2515
        (sp.policy.serial, sp.policy.roots.clone()),
2516
        (2, vec![r.new])
2517
    );
2518
    assert!(
2519
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2520
        "superseded, not revoked"
2521
    );
2522
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2523
    assert!(
2524
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2525
    );
2526
    write(&root.join("a"), "a.txt", b"a2\n");
2527
    let h2 = a.commit("two", &[]).unwrap();
2528
    assert!(
2529
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2530
    );
2531
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2532
    let res = a.push("origin", false).unwrap();
2533
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2534
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2535
    let key_a = r.new;
2536
2537
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2538
    // identity object, so Ada's KeyId changes while her keys stay the same.
2539
    let mut b = Repo::clone(&url, &root.join("b"))
2540
        .unwrap()
2541
        .with_home(root.join("home-b"));
2542
    let (key_b, id_b) = b
2543
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2544
        .unwrap();
2545
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
2546
    assert_eq!(r.old, key_a);
2547
    let key_a2 = r.new;
2548
    assert_eq!(
2549
        a.identity(&key_a2).unwrap().delegates,
2550
        vec![Delegate::full(key_b)]
2551
    );
2552
    assert_eq!(
2553
        a.identity(&key_a2).unwrap().ed25519_pk,
2554
        a.identity(&key_a).unwrap().ed25519_pk
2555
    );
2556
    assert!(
2557
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2558
        "already a delegate"
2559
    );
2560
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2561
    write(&root.join("a"), "a.txt", b"a3\n");
2562
    let h3 = a.commit("three", &[]).unwrap();
2563
    assert!(
2564
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2565
        "the same secret signs under the new KeyId"
2566
    );
2567
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2568
    a.set_user_config("core.sign", "seal").unwrap();
2569
    write(&root.join("a"), "a.txt", b"a4\n");
2570
    let h4 = a.commit("four", &[]).unwrap();
2571
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2572
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2573
    a.store()
2574
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2575
        .unwrap();
2576
    assert!(
2577
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2578
    );
2579
    a.set_user_config("core.sign", "change").unwrap();
2580
    // Withdrawing the delegation re-issues the identity again.
2581
    let r = a.delegate_remove(&key_b).unwrap();
2582
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2583
    assert!(a.delegate_remove(&key_b).is_err());
2584
    let key_a3 = r.new;
2585
    let res = a.push("origin", false).unwrap();
2586
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2587
2588
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2589
    // both applied under the old threshold of 1. A grant then needs Bob too.
2590
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2591
    assert!(a.policy_root_add(id_b.clone()).is_err());
2592
    assert!(a.policy_set_threshold(3).is_err());
2593
    assert!(a.policy_set_threshold(2).unwrap().applied);
2594
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2595
    b.pull("origin").unwrap();
2596
    assert_eq!(
2597
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2598
        2
2599
    );
2600
    let mut c = Repo::init(&root.join("c"))
2601
        .unwrap()
2602
        .with_home(root.join("home-c"));
2603
    let (key_c, id_c) = c
2604
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2605
        .unwrap();
2606
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2607
    let proposal = a.policy_grant(id_c, None).unwrap();
2608
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2609
    assert_eq!(proposal.policy.serial, serial_before + 1);
2610
    assert_eq!(
2611
        a.current_policy().unwrap().unwrap().1.policy.serial,
2612
        serial_before,
2613
        "a proposal changes nothing yet"
2614
    );
2615
    // Bob signs the proposal, handed over as a file, and it applies for him.
2616
    let bytes = proposal.signed().encode();
2617
    let signed = b
2618
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2619
        .unwrap();
2620
    assert!(signed.applied && signed.sigs.len() == 2);
2621
    assert!(b
2622
        .current_policy()
2623
        .unwrap()
2624
        .unwrap()
2625
        .1
2626
        .policy
2627
        .authorizes(&key_c, "main"));
2628
    assert!(
2629
        b.policy_sign(signed.signed()).is_err(),
2630
        "a stale proposal is refused"
2631
    );
2632
    // Bob publishes it and Ada picks it up.
2633
    assert!(b
2634
        .push("origin", false)
2635
        .unwrap()
2636
        .iter()
2637
        .any(|x| x.name == "policy" && x.ok));
2638
    a.pull("origin").unwrap();
2639
    assert_eq!(
2640
        a.current_policy().unwrap().unwrap().1.policy.serial,
2641
        serial_before + 1
2642
    );
2643
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2644
    assert!(a.policy_revoke(&key_a3).is_err());
2645
    let u = a
2646
        .revoke_identity(&key_c, "left the project")
2647
        .unwrap()
2648
        .unwrap();
2649
    assert!(!u.applied);
2650
    assert!(a.is_revoked(&key_c).unwrap());
2651
    assert!(!b.is_revoked(&key_c).unwrap());
2652
    let u = b.policy_sign(u.signed()).unwrap();
2653
    assert!(u.applied && u.policy.is_revoked(&key_c));
2654
    assert!(b.is_revoked(&key_c).unwrap());
2655
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2656
    assert!(
2657
        b.policy_revoke(&key_a3).is_err(),
2658
        "would leave one root for a threshold of 2"
2659
    );
2660
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2661
    let key_c_own = c.config.author_key.unwrap();
2662
    assert!(c
2663
        .revoke_identity(&key_c_own, "lost laptop")
2664
        .unwrap()
2665
        .is_none());
2666
    assert!(c.is_revoked(&key_c_own).unwrap());
2667
    assert_eq!(key_c_own, key_c);
2668
}
2669
2670
#[test]
2671
fn renames_are_detected_and_tracked_as_moves() {
2672
    hermetic();
2673
    let dir = tempfile::tempdir().unwrap();
2674
    let root = dir.path();
2675
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2676
    write(
2677
        root,
2678
        "src/old.rs",
2679
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2680
    );
2681
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2682
    write(root, "tiny.txt", b"x\n");
2683
    let h1 = repo.commit("base", &[]).unwrap();
2684
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2685
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2686
2687
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2688
    // that shares nothing with the removed file.
2689
    fs::remove_file(root.join("src/old.rs")).unwrap();
2690
    write(
2691
        root,
2692
        "lib/new.rs",
2693
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2694
    );
2695
    fs::remove_file(root.join("img.bin")).unwrap();
2696
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2697
    fs::remove_file(root.join("tiny.txt")).unwrap();
2698
    write(root, "other.txt", b"completely different\n");
2699
    let snap = repo.snapshot("status").unwrap();
2700
    let statuses: Vec<(&str, ChangeStatus)> = snap
2701
        .statuses
2702
        .iter()
2703
        .map(|s| (s.path.as_str(), s.status))
2704
        .collect();
2705
    assert_eq!(
2706
        statuses,
2707
        vec![
2708
            ("assets/img.bin", ChangeStatus::Renamed),
2709
            ("lib/new.rs", ChangeStatus::Renamed),
2710
            ("other.txt", ChangeStatus::Added),
2711
            ("src", ChangeStatus::Removed),
2712
            ("tiny.txt", ChangeStatus::Removed)
2713
        ]
2714
    );
2715
    let h2 = repo.commit("move things", &[]).unwrap();
2716
    let c = repo.store().get_change(&h2).unwrap();
2717
    let moves: Vec<_> = c
2718
        .tree_ops
2719
        .iter()
2720
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2721
        .collect();
2722
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
2723
    assert!(c.tree_ops.iter().any(
2724
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2725
    ));
2726
    assert!(c.tree_ops.iter().any(
2727
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2728
    ));
2729
    let snap = repo.load_state(&[h2]).unwrap().materialize();
2730
    assert_eq!(
2731
        snap.files["lib/new.rs"].node, node_old,
2732
        "the node survives the rename"
2733
    );
2734
    assert!(
2735
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2736
    );
2737
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
2738
    assert!(render_change(
2739
        &c,
2740
        &repo.load_state(&[h1]).unwrap(),
2741
        &repo.load_state(&[h1]).unwrap().materialize()
2742
    )
2743
    .contains("R "));
2744
    // A fresh checkout reproduces the tree.
2745
    let other = tempfile::tempdir().unwrap();
2746
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
2747
    assert_eq!(
2748
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2749
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2750
    );
2751
    assert!(!other.path().join("src").exists());
2752
    assert!(!clone.snapshot("status").unwrap().changed);
2753
    // Similarity is line based, byte weighted.
2754
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2755
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2756
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2757
    assert_eq!(similarity(b"", b"x\n"), 0);
2758
}
2759
2760
#[test]
2761
fn git_fetch_and_push_round_trip() {
2762
    hermetic();
2763
    if std::process::Command::new("git")
2764
        .arg("--version")
2765
        .output()
2766
        .is_err()
2767
    {
2768
        eprintln!("git not installed; skipping");
2769
        return;
2770
    }
2771
    let dir = tempfile::tempdir().unwrap();
2772
    let root = dir.path();
2773
    let git_in = |d: &Path, args: &[&str]| -> String {
2774
        let out = std::process::Command::new("git")
2775
            .arg("-C")
2776
            .arg(d)
2777
            .args([
2778
                "-c",
2779
                "user.name=Grace",
2780
                "-c",
2781
                "[email protected]",
2782
                "-c",
2783
                "commit.gpgsign=false",
2784
            ])
2785
            .args(args)
2786
            .output()
2787
            .unwrap();
2788
        assert!(
2789
            out.status.success(),
2790
            "git {args:?}: {}",
2791
            String::from_utf8_lossy(&out.stderr)
2792
        );
2793
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2794
    };
2795
    // A bare "remote" and a work tree that pushes to it.
2796
    let remote = root.join("remote.git");
2797
    fs::create_dir_all(&remote).unwrap();
2798
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2799
    let work = root.join("work");
2800
    git_in(
2801
        root,
2802
        &[
2803
            "clone",
2804
            "-q",
2805
            remote.to_str().unwrap(),
2806
            work.to_str().unwrap(),
2807
        ],
2808
    );
2809
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2810
    write(&work, "README.md", b"# Project\n");
2811
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2812
    git_in(&work, &["add", "."]);
2813
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2814
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2815
    git_in(&work, &["commit", "-q", "-am", "second"]);
2816
    git_in(&work, &["push", "-q", "origin", "main"]);
2817
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2818
2819
    // Fetch into a fresh oxy repository.
2820
    let o = root.join("oxy");
2821
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
2822
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2823
        .unwrap();
2824
    let url = remote.to_string_lossy().to_string();
2825
    let r = repo.git_fetch(&url, "main").unwrap();
2826
    assert_eq!((r.commits, r.heads), (2, 1));
2827
    assert_eq!(
2828
        fs::read(o.join("src/lib.rs")).unwrap(),
2829
        b"pub fn a() {}\npub fn b() {}\n"
2830
    );
2831
    assert!(!repo.snapshot("status").unwrap().changed);
2832
    assert_eq!(
2833
        repo.git_fetch(&url, "main").unwrap().commits,
2834
        0,
2835
        "nothing new"
2836
    );
2837
2838
    // An oxy change, pushed back: one commit on top of the Git tip.
2839
    write(
2840
        &o,
2841
        "src/lib.rs",
2842
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2843
    );
2844
    write(&o, "NOTES.md", b"from oxy\n");
2845
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2846
    let r = repo.git_push(&url, "main").unwrap();
2847
    assert_eq!(r.exported, 1, "{r:?}");
2848
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2849
    assert_eq!(
2850
        git_in(&work, &["log", "--format=%s", "main"]),
2851
        "add c and notes\nsecond\ninitial"
2852
    );
2853
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2854
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2855
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
2856
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2857
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2858
    assert_eq!(
2859
        repo.git_push(&url, "main").unwrap().exported,
2860
        0,
2861
        "already pushed"
2862
    );
2863
2864
    // Git moves on; pushing without fetching is refused, fetching brings
2865
    // the commit in and the working copy follows.
2866
    write(&work, "README.md", b"# Project\n\nMore.\n");
2867
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2868
    git_in(&work, &["push", "-q", "origin", "main"]);
2869
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
2870
    assert!(repo
2871
        .git_push(&url, "main")
2872
        .unwrap_err()
2873
        .to_string()
2874
        .contains("fetch"));
2875
    let r = repo.git_fetch(&url, "main").unwrap();
2876
    assert_eq!(
2877
        (r.commits, r.heads),
2878
        (1, 2),
2879
        "the Git change and the oxy change commute"
2880
    );
2881
    assert_eq!(
2882
        fs::read(o.join("README.md")).unwrap(),
2883
        b"# Project\n\nMore.\n"
2884
    );
2885
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2886
    assert!(!repo.snapshot("status").unwrap().changed);
2887
    // Another oxy change pushes on top of Git's newest commit.
2888
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2889
    repo.commit("notes again", &[]).unwrap();
2890
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2891
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2892
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
2893
    assert_eq!(
2894
        fs::read(work.join("NOTES.md")).unwrap(),
2895
        b"from oxy\nagain\n"
2896
    );
2897
    assert_eq!(
2898
        git_in(&work, &["log", "--format=%s", "main"])
2899
            .lines()
2900
            .count(),
2901
        5
2902
    );
2903
}
2904
2905
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2906
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2907
#[test]
2908
#[ignore]
2909
fn bench_one_gibibyte_file() {
2910
    hermetic();
2911
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2912
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2913
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2914
        None => tempfile::tempdir().unwrap(),
2915
    };
2916
    let root = dir.path();
2917
    let repo = Repo::init(&root.join("r"))
2918
        .unwrap()
2919
        .with_home(root.join("home"));
2920
    let size = 1usize << 30;
2921
    let mut data = vec![0u8; size];
2922
    let mut x = 0x9e3779b97f4a7c15u64;
2923
    for chunk in data.chunks_mut(8) {
2924
        x ^= x << 13;
2925
        x ^= x >> 7;
2926
        x ^= x << 17;
2927
        let b = x.to_le_bytes();
2928
        chunk.copy_from_slice(&b[..chunk.len()]);
2929
    }
2930
    let t = std::time::Instant::now();
2931
    write(&root.join("r"), "big.bin", &data);
2932
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
2933
    let t = std::time::Instant::now();
2934
    let h = repo.commit("big", &[]).unwrap();
2935
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
2936
    let t = std::time::Instant::now();
2937
    assert!(!repo.snapshot("status").unwrap().changed);
2938
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
2939
    let t = std::time::Instant::now();
2940
    let objects = repo.store().list().unwrap().len();
2941
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
2942
    let t = std::time::Instant::now();
2943
    let g = repo.gc(true).unwrap();
2944
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
2945
    let t = std::time::Instant::now();
2946
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
2947
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
2948
    let t = std::time::Instant::now();
2949
    let back = fs::read(root.join("c/big.bin")).unwrap();
2950
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
2951
    eprintln!("read back and verify: {:.2?}", t.elapsed());
2952
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
2953
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
2954
    eprintln!(
2955
        "store size: {:.1} MiB for 1 GiB of data",
2956
        store_bytes as f64 / (1024.0 * 1024.0)
2957
    );
2958
}
2959
2960
fn walkdir_size(p: &Path) -> u64 {
2961
    let mut total = 0;
2962
    if let Ok(rd) = fs::read_dir(p) {
2963
        for e in rd.flatten() {
2964
            let path = e.path();
2965
            if path.is_dir() {
2966
                total += walkdir_size(&path);
2967
            } else if let Ok(m) = fs::metadata(&path) {
2968
                total += m.len();
2969
            }
2970
        }
2971
    }
2972
    total
2973
}
2974
2975
/// An opaque file whose size and mtime match the manifest is not read on
2976
/// the next snapshot: its blob comes from the manifest's stat cache.
2977
#[cfg(unix)]
2978
#[test]
2979
fn stat_cache_skips_reading_unchanged_opaque_files() {
2980
    use std::os::unix::fs::PermissionsExt;
2981
    hermetic();
2982
    let dir = tempfile::tempdir().unwrap();
2983
    let root = dir.path();
2984
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2985
    let mut big = vec![0u8; 300 * 1024];
2986
    for (i, b) in big.iter_mut().enumerate() {
2987
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
2988
    }
2989
    big[0] = 0;
2990
    write(root, "big.bin", &big);
2991
    write(root, "a.txt", b"text\n");
2992
    let h1 = repo.commit("base", &[]).unwrap();
2993
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
2994
    assert!(
2995
        m.entries["big.bin"].blob.is_some(),
2996
        "opaque files record their blob"
2997
    );
2998
    assert!(m.entries["a.txt"].blob.is_none());
2999
    let blob = m.entries["big.bin"].blob.unwrap();
3000
    assert!(repo.store().has(&blob));
3001
3002
    // Files modified within two seconds of the manifest are racy and still
3003
    // read; age the file so the cache applies, then snapshot to record it.
3004
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3005
    fs::File::options()
3006
        .write(true)
3007
        .open(root.join("big.bin"))
3008
        .unwrap()
3009
        .set_modified(old)
3010
        .unwrap();
3011
    assert!(!repo.snapshot("status").unwrap().changed);
3012
    // Now the file cannot be read at all; the snapshot succeeds without it.
3013
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3014
    let snap = repo.snapshot("status").unwrap();
3015
    assert!(
3016
        !snap.changed && snap.statuses.is_empty(),
3017
        "{:?}",
3018
        snap.statuses
3019
    );
3020
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3021
    // A real change (new mtime, new content) is seen and committed correctly.
3022
    let mut big2 = big.clone();
3023
    big2[10] ^= 0xff;
3024
    write(root, "big.bin", &big2);
3025
    let snap = repo.snapshot("status").unwrap();
3026
    assert_eq!(
3027
        snap.statuses
3028
            .iter()
3029
            .map(|s| (s.path.as_str(), s.status))
3030
            .collect::<Vec<_>>(),
3031
        vec![("big.bin", ChangeStatus::Modified)]
3032
    );
3033
    let h2 = repo.commit("edit", &[]).unwrap();
3034
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3035
    assert_eq!(
3036
        files["big.bin"].content,
3037
        FileContent::Opaque {
3038
            blobs: vec![Repo::blob_ref(&big2)]
3039
        }
3040
    );
3041
    // Checkout writes a manifest with blobs too, so the next status is cached.
3042
    repo.checkout(&[h1], false, "checkout").unwrap();
3043
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3044
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3045
    assert!(!repo.snapshot("status").unwrap().changed);
3046
}
3047
3048
#[test]
3049
fn status_json_lists_conflicts_with_contributors() {
3050
    hermetic();
3051
    let dir = tempfile::tempdir().unwrap();
3052
    let root = dir.path();
3053
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3054
    write(root, "a.txt", b"one\n");
3055
    let h1 = repo.commit("base", &[]).unwrap();
3056
    write(root, "a.txt", b"one\nleft\n");
3057
    let ha = repo.commit("left", &[]).unwrap();
3058
    repo.checkout(&[h1], true, "checkout").unwrap();
3059
    write(root, "a.txt", b"one\nright\n");
3060
    let hb = repo.commit("right", &[]).unwrap();
3061
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3062
    let snap = repo.snapshot("status").unwrap();
3063
    assert!(snap.base_snapshot.is_conflicted());
3064
    let json = repo.status_json(&snap).unwrap();
3065
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3066
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3067
    assert!(json.contains("\"conflicted\":true"), "{json}");
3068
    assert!(
3069
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3070
        "{json}"
3071
    );
3072
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3073
    assert!(json.contains("\"resolved\":false"), "{json}");
3074
    assert!(json.starts_with('{') && json.ends_with('}'));
3075
    // Resolve and the report says so; a clean copy has no conflicts.
3076
    write(root, "a.txt", b"one\nleft\nright\n");
3077
    let snap = repo.snapshot("status").unwrap();
3078
    let json = repo.status_json(&snap).unwrap();
3079
    assert!(json.contains("\"resolved\":true"), "{json}");
3080
    repo.commit("resolve", &[]).unwrap();
3081
    let snap = repo.snapshot("status").unwrap();
3082
    let json = repo.status_json(&snap).unwrap();
3083
    assert!(
3084
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3085
        "{json}"
3086
    );
3087
}
3088
3089
#[test]
3090
fn ignore_rules_do_not_untrack_files() {
3091
    hermetic();
3092
    let dir = tempfile::tempdir().unwrap();
3093
    let root = dir.path();
3094
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3095
    write(root, "src.c", b"int x;\n");
3096
    write(root, "build/out.o", b"\0obj");
3097
    write(root, "sub/keep.log", b"keep\n");
3098
    write(root, "sub/junk.log", b"junk\n");
3099
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3100
    let snap = repo.snapshot("status").unwrap();
3101
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3102
    assert_eq!(
3103
        added,
3104
        vec![".oxyignore", "src.c", "sub/keep.log"],
3105
        "anchored, glob, and negated rules"
3106
    );
3107
    let h1 = repo.commit("base", &[]).unwrap();
3108
    // Ignoring a tracked file changes nothing about it.
3109
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3110
    let snap = repo.snapshot("status").unwrap();
3111
    assert_eq!(
3112
        snap.statuses
3113
            .iter()
3114
            .map(|s| s.path.as_str())
3115
            .collect::<Vec<_>>(),
3116
        vec![".oxyignore"]
3117
    );
3118
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3119
    assert!(repo
3120
        .load_state(&[h2])
3121
        .unwrap()
3122
        .materialize()
3123
        .files
3124
        .contains_key("src.c"));
3125
    // Its edits are still seen, by status and by the prompt.
3126
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3127
    write(root, "src.c", b"int x, y;\n");
3128
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3129
    let snap = repo.snapshot("status").unwrap();
3130
    assert_eq!(
3131
        snap.statuses
3132
            .iter()
3133
            .map(|s| (s.path.as_str(), s.status))
3134
            .collect::<Vec<_>>(),
3135
        vec![("src.c", ChangeStatus::Modified)]
3136
    );
3137
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3138
    assert!(
3139
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3140
    );
3141
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3142
    fs::remove_file(root.join("src.c")).unwrap();
3143
    let snap = repo.snapshot("status").unwrap();
3144
    assert_eq!(
3145
        snap.statuses
3146
            .iter()
3147
            .map(|s| (s.path.as_str(), s.status))
3148
            .collect::<Vec<_>>(),
3149
        vec![("src.c", ChangeStatus::Removed)]
3150
    );
3151
    repo.checkout(&[h3], true, "checkout").unwrap();
3152
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3153
    assert!(!repo.snapshot("status").unwrap().changed);
3154
    let _ = h1;
3155
}
3156
3157
#[test]
3158
fn split_works_on_non_heads_by_node() {
3159
    hermetic();
3160
    let dir = tempfile::tempdir().unwrap();
3161
    let root = dir.path();
3162
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3163
    write(root, "a.txt", b"one\n");
3164
    write(root, "junk/x.lock", b"lock\n");
3165
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3166
    write(root, "a.txt", b"one\ntwo\n");
3167
    let h2 = repo.commit("more work", &[]).unwrap();
3168
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3169
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3170
    // h1 is not a head: split it by node.
3171
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3172
    assert_ne!(h1b, h1);
3173
    assert_eq!(
3174
        repo.store().get_change(&h1b).unwrap().change_id,
3175
        id1,
3176
        "the rest keeps the ChangeId"
3177
    );
3178
    let junk = repo.store().get_change(&hj).unwrap();
3179
    assert!(junk.tree_ops.iter().all(
3180
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3181
    ));
3182
    let heads = repo.bookmark_heads().unwrap();
3183
    assert!(
3184
        heads.contains(&hj),
3185
        "the split-off part is a head of its own"
3186
    );
3187
    let snap = repo.load_state(&heads).unwrap().materialize();
3188
    assert!(
3189
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3190
        "the dependent was rewritten onto the new hash"
3191
    );
3192
    assert!(snap.files.contains_key("junk/x.lock"));
3193
    let h2b = heads
3194
        .iter()
3195
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3196
        .copied()
3197
        .unwrap();
3198
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3199
    assert!(!repo.snapshot("status").unwrap().changed);
3200
    // Abandoning the split-off head removes the junk from history.
3201
    repo.abandon(&hj).unwrap();
3202
    let heads = repo.bookmark_heads().unwrap();
3203
    let snap = repo.load_state(&heads).unwrap().materialize();
3204
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3205
    assert!(snap.files.contains_key("a.txt"));
3206
    // A dependent that touches the split-off paths blocks the split.
3207
    write(root, "junk/y.lock", b"y\n");
3208
    let hb = repo.commit("junk base", &[]).unwrap();
3209
    write(root, "junk/y.lock", b"yy\n");
3210
    write(root, "b.txt", b"b\n");
3211
    repo.commit("touches junk", &[]).unwrap();
3212
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3213
    assert!(err.contains("depends on the split-off paths"), "{err}");
3214
}
3215
3216
#[test]
3217
fn bookmarks_switch_merge_and_push() {
3218
    hermetic();
3219
    let dir = tempfile::tempdir().unwrap();
3220
    let root = dir.path();
3221
    let origin = Repo::init(&root.join("origin")).unwrap();
3222
    let url = root.join("origin").to_string_lossy().to_string();
3223
    let mut repo = Repo::clone(&url, &root.join("r"))
3224
        .unwrap()
3225
        .with_home(root.join("home"));
3226
    let r = root.join("r");
3227
    write(&r, "a.txt", b"a\n");
3228
    let h_a = repo.commit("a", &[]).unwrap();
3229
    assert!(repo.push("origin", false).unwrap()[0].ok);
3230
3231
    // A bookmark at the working copy's base, then work on it.
3232
    assert!(repo.bookmark_create("bad name..", None).is_err());
3233
    assert!(repo.bookmark_create("-x", None).is_err());
3234
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3235
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3236
    repo.bookmark_switch("feature", false).unwrap();
3237
    assert_eq!(repo.config.bookmark, "feature");
3238
    write(&r, "a.txt", b"a\nb\n");
3239
    write(&r, "b.txt", b"b\n");
3240
    let h_b = repo.commit("b on feature", &[]).unwrap();
3241
    assert_eq!(
3242
        repo.bookmark_heads().unwrap(),
3243
        vec![h_b],
3244
        "b edits a.txt, so it depends on a"
3245
    );
3246
    assert_eq!(
3247
        repo.resolve_heads("main").unwrap(),
3248
        vec![h_a],
3249
        "main is untouched"
3250
    );
3251
    assert_eq!(
3252
        repo.resolve_change("feature").unwrap(),
3253
        h_b,
3254
        "a one-head bookmark names its change"
3255
    );
3256
    // Reopening keeps the workspace's bookmark.
3257
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3258
    assert_eq!(reopened.config.bookmark, "feature");
3259
    // Back to main: b.txt goes away; work there.
3260
    repo.bookmark_switch("main", false).unwrap();
3261
    assert!(!r.join("b.txt").exists());
3262
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3263
    write(&r, "c.txt", b"c\n");
3264
    let h_c = repo.commit("c on main", &[]).unwrap();
3265
    let list = repo.bookmarks().unwrap();
3266
    assert_eq!(
3267
        list.iter()
3268
            .map(|b| (b.name.as_str(), b.current))
3269
            .collect::<Vec<_>>(),
3270
        vec![("feature", false), ("main", true)]
3271
    );
3272
    assert_eq!(
3273
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3274
        Some(1),
3275
        "c is not on origin yet"
3276
    );
3277
    // Merge feature into main: the union, both heads, no merge change.
3278
    let m = repo.merge("feature").unwrap();
3279
    assert!(m.changed && m.checked_out);
3280
    let mut want = vec![h_b, h_c];
3281
    want.sort();
3282
    assert_eq!(m.heads, want);
3283
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3284
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3285
    assert!(repo.merge("main").is_err());
3286
    // The other bookmark can be pushed by name and appears at origin.
3287
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3288
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3289
    assert!(repo.push("origin", false).unwrap()[0].ok);
3290
    assert_eq!(
3291
        repo.bookmarks()
3292
            .unwrap()
3293
            .iter()
3294
            .find(|b| b.name == "main")
3295
            .unwrap()
3296
            .ahead,
3297
        Some(0)
3298
    );
3299
    // A second workspace inherits the current bookmark and can switch independently.
3300
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3301
    assert_eq!(ws.config.bookmark, "main");
3302
    let mut ws = ws;
3303
    ws.bookmark_switch("feature", false).unwrap();
3304
    assert_eq!(
3305
        Repo::open(&r).unwrap().config.bookmark,
3306
        "main",
3307
        "the first workspace is unaffected"
3308
    );
3309
    assert!(
3310
        repo.bookmark_delete("feature").is_err(),
3311
        "current bookmark of another workspace"
3312
    );
3313
    ws.bookmark_switch("main", false).unwrap();
3314
    // Set and delete.
3315
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3316
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3317
    repo.bookmark_delete("feature").unwrap();
3318
    assert!(repo.resolve_heads("feature").is_err());
3319
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3320
    assert!(
3321
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3322
        "changes of a deleted bookmark remain"
3323
    );
3324
}
3325
3326
#[test]
3327
fn oxygen_subrepos_pin_follow_and_update() {
3328
    hermetic();
3329
    let dir = tempfile::tempdir().unwrap();
3330
    let root = dir.path();
3331
    // A library repository with two commits, and a bare-ish origin for it.
3332
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3333
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3334
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3335
        .unwrap()
3336
        .with_home(root.join("home"));
3337
    write(&root.join("lib"), "lib.txt", b"v1\n");
3338
    let l1 = lib.commit("lib v1", &[]).unwrap();
3339
    assert!(lib.push("origin", false).unwrap()[0].ok);
3340
    let _ = lib_origin;
3341
3342
    // The application (a clone of its own origin) adds it as a subrepo.
3343
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3344
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3345
    let _ = app_origin;
3346
    let app_dir = root.join("app");
3347
    let app = Repo::clone(&app_url, &app_dir)
3348
        .unwrap()
3349
        .with_home(root.join("home"));
3350
    write(&app_dir, "main.txt", b"app\n");
3351
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3352
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3353
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3354
    let snap = app.snapshot("status").unwrap();
3355
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3356
    assert_eq!(
3357
        paths,
3358
        vec![".oxymodules", "libs/lib", "main.txt"],
3359
        "the nested files are not walked"
3360
    );
3361
    let a1 = app.commit("app with lib", &[]).unwrap();
3362
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3363
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3364
    assert!(!files.contains_key("libs/lib/lib.txt"));
3365
    assert!(!app.snapshot("status").unwrap().changed);
3366
    let subs = app.subrepos().unwrap();
3367
    assert_eq!(subs.len(), 1);
3368
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3369
3370
    // Advance the nested repository: the parent sees a modified pin.
3371
    let nested = Repo::open(&app_dir.join("libs/lib"))
3372
        .unwrap()
3373
        .with_home(root.join("home"));
3374
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3375
    let l2 = nested.commit("lib v2", &[]).unwrap();
3376
    assert!(nested.push("origin", false).unwrap()[0].ok);
3377
    let snap = app.snapshot("status").unwrap();
3378
    assert_eq!(
3379
        snap.statuses
3380
            .iter()
3381
            .map(|s| (s.path.as_str(), s.status))
3382
            .collect::<Vec<_>>(),
3383
        vec![("libs/lib", ChangeStatus::Modified)]
3384
    );
3385
    let a2 = app.commit("bump lib", &[]).unwrap();
3386
    // Checking out the older app state brings the nested working copy back
3387
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3388
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3389
    assert!(
3390
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3391
        "{:?}",
3392
        r.notes
3393
    );
3394
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3395
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3396
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3397
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3398
    assert!(!app.snapshot("status").unwrap().changed);
3399
    // A dirty nested repository is left alone and reported.
3400
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3401
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3402
    assert!(
3403
        r.notes.iter().any(|n| n.contains("uncommitted")),
3404
        "{:?}",
3405
        r.notes
3406
    );
3407
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3408
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3409
    let r = app.submodule_update(false, &[]).unwrap();
3410
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3411
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3412
    let _ = l2;
3413
3414
    // A fresh clone of the app has the pin but no nested repository until update --init.
3415
    assert!(app.push("origin", false).unwrap()[0].ok);
3416
    let clone_dir = root.join("app-clone");
3417
    let clone = Repo::clone(&app_url, &clone_dir)
3418
        .unwrap()
3419
        .with_home(root.join("home"));
3420
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3421
    assert_eq!(
3422
        clone.submodule_update(false, &[]).unwrap(),
3423
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3424
    );
3425
    assert_eq!(
3426
        clone.submodule_update(true, &[]).unwrap(),
3427
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3428
    );
3429
    assert_eq!(
3430
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3431
        b"v2\n"
3432
    );
3433
    assert!(!clone.snapshot("status").unwrap().changed);
3434
    // Removing the subrepo leaves the directory and drops the node.
3435
    clone.submodule_remove("libs/lib").unwrap();
3436
    let snap = clone.snapshot("status").unwrap();
3437
    assert!(
3438
        snap.statuses
3439
            .iter()
3440
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3441
        "{:?}",
3442
        snap.statuses
3443
    );
3444
    let c = clone.commit("drop lib", &[]).unwrap();
3445
    assert!(!clone
3446
        .load_state(&[c])
3447
        .unwrap()
3448
        .materialize()
3449
        .files
3450
        .contains_key("libs/lib"));
3451
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3452
    assert!(
3453
        !clone.snapshot("status").unwrap().changed,
3454
        "an unregistered nested repository is ignored"
3455
    );
3456
}
3457
3458
#[test]
3459
fn git_submodules_import_and_export_as_gitlinks() {
3460
    hermetic();
3461
    if std::process::Command::new("git")
3462
        .arg("--version")
3463
        .output()
3464
        .is_err()
3465
    {
3466
        eprintln!("git not installed; skipping");
3467
        return;
3468
    }
3469
    let dir = tempfile::tempdir().unwrap();
3470
    let root = dir.path();
3471
    let git_in = |d: &Path, args: &[&str]| -> String {
3472
        let out = std::process::Command::new("git")
3473
            .arg("-C")
3474
            .arg(d)
3475
            .args([
3476
                "-c",
3477
                "user.name=Grace",
3478
                "-c",
3479
                "[email protected]",
3480
                "-c",
3481
                "commit.gpgsign=false",
3482
                "-c",
3483
                "protocol.file.allow=always",
3484
            ])
3485
            .args(args)
3486
            .output()
3487
            .unwrap();
3488
        assert!(
3489
            out.status.success(),
3490
            "git {args:?}: {}",
3491
            String::from_utf8_lossy(&out.stderr)
3492
        );
3493
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3494
    };
3495
    let sub = root.join("sub");
3496
    fs::create_dir_all(&sub).unwrap();
3497
    git_in(&sub, &["init", "-q", "-b", "main"]);
3498
    write(&sub, "s.txt", b"sub\n");
3499
    git_in(&sub, &["add", "."]);
3500
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3501
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3502
    let g = root.join("main.git");
3503
    fs::create_dir_all(&g).unwrap();
3504
    git_in(&g, &["init", "-q", "-b", "main"]);
3505
    write(&g, "README.md", b"# app\n");
3506
    git_in(&g, &["add", "."]);
3507
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3508
    git_in(
3509
        &g,
3510
        &[
3511
            "submodule",
3512
            "add",
3513
            "-q",
3514
            sub.to_str().unwrap(),
3515
            "vendor/sub",
3516
        ],
3517
    );
3518
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3519
3520
    let dest = root.join("oxy");
3521
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3522
    let rep = repo.import_git(&g, "main").unwrap();
3523
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3524
    let files = repo
3525
        .load_state(&repo.bookmark_heads().unwrap())
3526
        .unwrap()
3527
        .materialize()
3528
        .files;
3529
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3530
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3531
        panic!()
3532
    };
3533
    assert_eq!(
3534
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3535
        crate::subrepo::Pin::Git {
3536
            sha: sub_sha.clone(),
3537
            branch: "HEAD".into()
3538
        }
3539
    );
3540
    let modules =
3541
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3542
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3543
    assert!(modules.entries["vendor/sub"].git);
3544
    assert!(
3545
        files.contains_key(".gitmodules"),
3546
        "the Git file is kept for round trips"
3547
    );
3548
    assert!(
3549
        !dest.join("vendor/sub/.git").exists(),
3550
        "not cloned until update --init"
3551
    );
3552
    assert!(!repo.snapshot("status").unwrap().changed);
3553
    // update --init clones it at the pinned commit; status is unchanged.
3554
    assert_eq!(
3555
        repo.submodule_update(true, &[]).unwrap(),
3556
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3557
    );
3558
    assert_eq!(
3559
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3560
        sub_sha
3561
    );
3562
    assert!(!repo.snapshot("status").unwrap().changed);
3563
    // Export writes the gitlink and .gitmodules back.
3564
    let mirror = root.join("mirror.git");
3565
    let rep = repo.git_export(&mirror).unwrap();
3566
    assert_eq!(rep.skipped_subrepos, 0);
3567
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3568
    assert!(
3569
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3570
        "{ls}"
3571
    );
3572
    assert_eq!(
3573
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3574
        ".gitmodules\nREADME.md\nvendor"
3575
    );
3576
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3577
    assert_eq!(
3578
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3579
        orig_tree,
3580
        "tree round trip"
3581
    );
3582
}
3583
3584
#[test]
3585
fn partial_commits_by_path_and_by_hunk() {
3586
    hermetic();
3587
    let dir = tempfile::tempdir().unwrap();
3588
    let root = dir.path();
3589
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3590
    write(root, "a.txt", b"1\n2\n3\n");
3591
    write(root, "b.txt", b"b\n");
3592
    let h0 = repo.commit("base", &[]).unwrap();
3593
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3594
    write(root, "b.txt", b"b\nbb\n");
3595
    write(root, "c.txt", b"c\n");
3596
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3597
    let h1 = repo
3598
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3599
        .unwrap();
3600
    let c1 = repo.store().get_change(&h1).unwrap();
3601
    assert!(
3602
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3603
        "{:?}",
3604
        c1.tree_ops
3605
    );
3606
    assert_eq!(c1.deps, vec![h0]);
3607
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3608
    assert!(
3609
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3610
    );
3611
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3612
    assert!(!files.contains_key("c.txt"));
3613
    let snap = repo.snapshot("status").unwrap();
3614
    assert_eq!(
3615
        snap.statuses
3616
            .iter()
3617
            .map(|s| (s.path.as_str(), s.status))
3618
            .collect::<Vec<_>>(),
3619
        vec![
3620
            ("b.txt", ChangeStatus::Modified),
3621
            ("c.txt", ChangeStatus::Added)
3622
        ]
3623
    );
3624
    assert_eq!(
3625
        fs::read(root.join("b.txt")).unwrap(),
3626
        b"b\nbb\n",
3627
        "disk untouched"
3628
    );
3629
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3630
    let (_, hunks) = repo.hunks().unwrap();
3631
    let b_hunk = hunks
3632
        .iter()
3633
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3634
        .unwrap()
3635
        .index;
3636
    let h2 = repo
3637
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3638
        .unwrap();
3639
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3640
    assert!(
3641
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3642
    );
3643
    assert!(!files.contains_key("c.txt"));
3644
    let snap = repo.snapshot("status").unwrap();
3645
    assert_eq!(
3646
        snap.statuses
3647
            .iter()
3648
            .map(|s| s.path.as_str())
3649
            .collect::<Vec<_>>(),
3650
        vec!["c.txt"]
3651
    );
3652
    // Choosing only the content hunk of a file in a new directory pulls in
3653
    // the directory and file additions it needs.
3654
    write(root, "d/e.txt", b"e\n");
3655
    let (_, hunks) = repo.hunks().unwrap();
3656
    let e_insert = hunks
3657
        .iter()
3658
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3659
        .unwrap()
3660
        .index;
3661
    let h3 = repo
3662
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3663
        .unwrap();
3664
    let c3 = repo.store().get_change(&h3).unwrap();
3665
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3666
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3667
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3668
    // Choosing a new file's addition hunk brings its content along.
3669
    write(root, "f/g.txt", b"g\n");
3670
    let (_, hunks) = repo.hunks().unwrap();
3671
    let g_add = hunks
3672
        .iter()
3673
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3674
        .unwrap()
3675
        .index;
3676
    let h4 = repo
3677
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3678
        .unwrap();
3679
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
3680
    assert!(
3681
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3682
    );
3683
    assert!(!repo
3684
        .snapshot("status")
3685
        .unwrap()
3686
        .statuses
3687
        .iter()
3688
        .any(|s| s.path == "f/g.txt"));
3689
    // Everything left commits normally; the working copy is then clean.
3690
    repo.commit("the rest", &[]).unwrap();
3691
    assert!(!repo.snapshot("status").unwrap().changed);
3692
    let files = repo
3693
        .load_state(&repo.bookmark_heads().unwrap())
3694
        .unwrap()
3695
        .materialize()
3696
        .files;
3697
    assert!(files.contains_key("c.txt"));
3698
}
3699
3700
#[test]
3701
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3702
    hermetic();
3703
    let dir = tempfile::tempdir().unwrap();
3704
    let root = dir.path();
3705
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3706
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3707
        .unwrap();
3708
    write(root, "a.txt", b"one\n");
3709
    let h1 = repo.commit("first", &[]).unwrap();
3710
    write(root, "a.txt", b"one\ntwo\n");
3711
    let h2 = repo.commit("second", &[]).unwrap();
3712
    let b = repo.blame("a.txt").unwrap();
3713
    assert_eq!(
3714
        b.iter()
3715
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3716
            .collect::<Vec<_>>(),
3717
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3718
    );
3719
    assert!(b.iter().all(|l| l.author == "Ada"));
3720
    assert_eq!(
3721
        b[0].change_id,
3722
        repo.store().get_change(&h1).unwrap().change_id
3723
    );
3724
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3725
    repo.commit("rename", &[]).unwrap();
3726
    let b = repo.blame("b.txt").unwrap();
3727
    assert_eq!(
3728
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3729
        vec![h1, h2],
3730
        "the node survives the rename"
3731
    );
3732
    assert!(repo.blame("a.txt").is_err());
3733
}
3734
3735
#[test]
3736
fn bisect_finds_the_first_bad_change() {
3737
    hermetic();
3738
    let dir = tempfile::tempdir().unwrap();
3739
    let root = dir.path();
3740
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3741
    let mut content = String::new();
3742
    let mut hashes = Vec::new();
3743
    for i in 1..=8 {
3744
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3745
        write(root, "f.txt", content.as_bytes());
3746
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3747
    }
3748
    // Each step appends after the previous line, so the chain is linear.
3749
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3750
    repo.bisect_start().unwrap();
3751
    assert!(matches!(
3752
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3753
        BisectStep::NeedMarks { good: 1, bad: 0 }
3754
    ));
3755
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3756
    assert!(
3757
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3758
        "{step:?}"
3759
    );
3760
    // Automated: bad when the bug line is present.
3761
    let step = repo
3762
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3763
        .unwrap();
3764
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3765
    assert_eq!(
3766
        repo.bisect_status().unwrap(),
3767
        Some(BisectStep::Found { culprit: hashes[4] })
3768
    );
3769
    repo.bisect_reset().unwrap();
3770
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3771
    assert!(repo.bisect_status().unwrap().is_none());
3772
    assert!(!repo.snapshot("status").unwrap().changed);
3773
    // Manual marks and a skip.
3774
    repo.bisect_start().unwrap();
3775
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3776
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3777
    let mut skipped_once = false;
3778
    let mut guard = 0;
3779
    while let BisectStep::Testing { .. } = step {
3780
        guard += 1;
3781
        assert!(guard < 20);
3782
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3783
        if !skipped_once && text.contains("line 6") {
3784
            // An untestable state away from the boundary: the search routes around it.
3785
            skipped_once = true;
3786
            step = repo.bisect_mark(None, &[]).unwrap();
3787
            continue;
3788
        }
3789
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3790
    }
3791
    assert!(skipped_once);
3792
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3793
    repo.bisect_reset().unwrap();
3794
    // Skipping the culprit itself leaves it among the candidates reported.
3795
    repo.bisect_start().unwrap();
3796
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3797
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3798
    let mut guard = 0;
3799
    while let BisectStep::Testing { heads, .. } = &step {
3800
        guard += 1;
3801
        assert!(guard < 20);
3802
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3803
        let is_culprit_state =
3804
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3805
        step = if is_culprit_state {
3806
            repo.bisect_mark(None, &[]).unwrap()
3807
        } else {
3808
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3809
        };
3810
    }
3811
    match step {
3812
        BisectStep::Inconclusive { candidates } => assert!(
3813
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3814
            "{candidates:?}"
3815
        ),
3816
        other => panic!("{other:?}"),
3817
    }
3818
    repo.bisect_reset().unwrap();
3819
}
3820
3821
#[test]
3822
fn squash_folds_a_change_into_its_dependency() {
3823
    hermetic();
3824
    let dir = tempfile::tempdir().unwrap();
3825
    let root = dir.path();
3826
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3827
    write(root, "a.txt", b"1\n");
3828
    let a = repo.commit("A", &[]).unwrap();
3829
    write(root, "a.txt", b"1\n2\n");
3830
    let c = repo.commit("C", &[]).unwrap();
3831
    write(root, "a.txt", b"1\n2\n3\n");
3832
    let e = repo.commit("E", &[]).unwrap();
3833
    write(root, "b.txt", b"b\n");
3834
    let b = repo.commit("B", &[]).unwrap();
3835
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3836
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3837
    // E depends on C which A lacks: refused, naming it.
3838
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3839
    assert!(err.contains(&c.short(12)), "{err}");
3840
    // C into A: A' has both, C is gone, E follows and still reads the same.
3841
    let a2 = repo.squash(&c, &a).unwrap();
3842
    let a2c = repo.store().get_change(&a2).unwrap();
3843
    assert_eq!(a2c.change_id, id_a);
3844
    assert!(a2c.deps.is_empty());
3845
    let heads = repo.bookmark_heads().unwrap();
3846
    let st = repo.load_state(&heads).unwrap();
3847
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
3848
    let e2 = st
3849
        .changes()
3850
        .find(|(_, m)| m.change_id == id_e)
3851
        .map(|(h, _)| *h)
3852
        .unwrap();
3853
    assert_eq!(
3854
        repo.store().get_change(&e2).unwrap().deps,
3855
        vec![a2],
3856
        "E now depends on A' alone"
3857
    );
3858
    let files = st.materialize().files;
3859
    assert!(
3860
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3861
    );
3862
    assert!(files.contains_key("b.txt"));
3863
    assert!(st.contains(&b));
3864
    assert!(!repo.snapshot("status").unwrap().changed);
3865
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3866
    // Undo restores the three original changes.
3867
    repo.undo().unwrap();
3868
    repo.undo().unwrap();
3869
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3870
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3871
}
3872
3873
#[test]
3874
fn rebase_re_expresses_a_change_against_another_base() {
3875
    hermetic();
3876
    let dir = tempfile::tempdir().unwrap();
3877
    let root = dir.path();
3878
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3879
    write(root, "a.txt", b"1\n2\n");
3880
    let a = repo.commit("A", &[]).unwrap();
3881
    write(root, "a.txt", b"1\n2\n3\n");
3882
    let c = repo.commit("C: append 3", &[]).unwrap();
3883
    write(root, "a.txt", b"1\n2\n3\n4\n");
3884
    let e = repo.commit("E: append 4", &[]).unwrap();
3885
    // A different base: A plus a change that prepends a line.
3886
    repo.checkout(&[a], true, "checkout").unwrap();
3887
    write(root, "a.txt", b"0\n1\n2\n");
3888
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3889
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3890
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3891
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3892
    let c2 = repo.rebase(&c, &[d]).unwrap();
3893
    let c2c = repo.store().get_change(&c2).unwrap();
3894
    assert_eq!(c2c.change_id, id_c);
3895
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3896
    let heads = repo.bookmark_heads().unwrap();
3897
    let st = repo.load_state(&heads).unwrap();
3898
    assert!(!st.contains(&c) && st.contains(&d));
3899
    let e2 = st
3900
        .changes()
3901
        .find(|(_, m)| m.change_id == id_e)
3902
        .map(|(h, _)| *h)
3903
        .unwrap();
3904
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
3905
    assert!(
3906
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3907
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3908
    );
3909
    let files = st.materialize().files;
3910
    assert!(
3911
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3912
        "{:?}",
3913
        files["a.txt"].content
3914
    );
3915
    assert!(!files["a.txt"].is_conflicted());
3916
    // Rebasing onto a state that already contains the change is refused.
3917
    assert!(repo.rebase(&c2, &[c2]).is_err());
3918
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
3919
    assert!(
3920
        err.contains("lacks dependencies"),
3921
        "E needs C, which D's state does not have: {err}"
3922
    );
3923
}
3924
3925
#[test]
3926
fn unsigned_tags_keep_their_message() {
3927
    hermetic();
3928
    let dir = tempfile::tempdir().unwrap();
3929
    let root = dir.path();
3930
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3931
    write(root, "a.txt", b"a\n");
3932
    repo.commit("a", &[]).unwrap();
3933
    assert!(repo.secret_key().unwrap().is_none());
3934
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
3935
        .unwrap();
3936
    let tags = repo.tags().unwrap();
3937
    assert_eq!(
3938
        (
3939
            tags[0].name.as_str(),
3940
            tags[0].message.as_str(),
3941
            tags[0].signer.as_deref()
3942
        ),
3943
        ("v1", "first release", None)
3944
    );
3945
    assert!(
3946
        repo.tag_refs().unwrap()[0].attestation.is_none(),
3947
        "an unsigned attestation is not advertised"
3948
    );
3949
}
3950
3951
#[test]
3952
fn fsck_passes_a_sound_repository_and_names_each_fault() {
3953
    hermetic();
3954
    let dir = tempfile::tempdir().unwrap();
3955
    let root = dir.path();
3956
    let origin_path = root.join("origin");
3957
    let origin = Repo::init(&origin_path).unwrap();
3958
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
3959
        .unwrap()
3960
        .with_home(root.join("home-a"));
3961
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
3962
        .unwrap();
3963
    write(&root.join("a"), "f.txt", b"one\n");
3964
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
3965
    let h1 = a.commit("first", &[]).unwrap();
3966
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
3967
    let h2 = a.commit("second", &[]).unwrap();
3968
    a.tag_create("v1", &[h2], "first release").unwrap();
3969
    a.checkpoint().unwrap();
3970
    assert!(a.push("origin", false).unwrap()[0].ok);
3971
3972
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
3973
    for repo in [&a, &origin] {
3974
        let rep = repo.fsck().unwrap();
3975
        assert_eq!(rep.problems, vec![], "{rep:?}");
3976
        // The two commits, plus the working copy's change in `a`.
3977
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
3978
        assert!(rep.ops > 1 && rep.objects > 5);
3979
    }
3980
    assert!(origin.fsck().unwrap().attestations >= 1);
3981
3982
    // A flipped byte in a stored object is corruption, named by hash.
3983
    let c1 = a.store().path_for(&h1);
3984
    let pristine = fs::read(&c1).unwrap();
3985
    let mut bytes = pristine.clone();
3986
    *bytes.last_mut().unwrap() ^= 1;
3987
    fs::write(&c1, &bytes).unwrap();
3988
    let rep = a.fsck().unwrap();
3989
    assert!(rep.errors() >= 1);
3990
    assert!(
3991
        rep.problems
3992
            .iter()
3993
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
3994
        "{rep:?}"
3995
    );
3996
    fs::write(&c1, &pristine).unwrap();
3997
    assert_eq!(a.fsck().unwrap().errors(), 0);
3998
3999
    // A missing change is named with what needed it.
4000
    fs::remove_file(&c1).unwrap();
4001
    let rep = a.fsck().unwrap();
4002
    assert!(
4003
        rep.problems.iter().any(|p| p.severity == Severity::Error
4004
            && p.object == Some(h1)
4005
            && p.what.contains("change missing, needed by change")),
4006
        "{rep:?}"
4007
    );
4008
    fs::write(&c1, &pristine).unwrap();
4009
4010
    // A missing blob is an error in a full clone.
4011
    let c2 = a.store().get_change(&h1).unwrap();
4012
    let blob = c2
4013
        .edits
4014
        .iter()
4015
        .find_map(|e| match e {
4016
            Edit::Replace { new: Some(b), .. } => Some(*b),
4017
            _ => None,
4018
        })
4019
        .expect("the binary file is a blob");
4020
    let bp = a.store().path_for(&blob);
4021
    let blob_bytes = fs::read(&bp).unwrap();
4022
    fs::remove_file(&bp).unwrap();
4023
    let rep = a.fsck().unwrap();
4024
    assert!(
4025
        rep.problems
4026
            .iter()
4027
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4028
        "{rep:?}"
4029
    );
4030
    fs::write(&bp, &blob_bytes).unwrap();
4031
4032
    // A broken op log head is reported, not a crash.
4033
    let head = root.join("a/.oxy/ops/head");
4034
    let saved = fs::read(&head).unwrap();
4035
    fs::write(&head, b"not a hash").unwrap();
4036
    let rep = a.fsck().unwrap();
4037
    assert!(
4038
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4039
        "{rep:?}"
4040
    );
4041
    fs::write(&head, saved).unwrap();
4042
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4043
}
4044
4045
/// Copy a directory tree (for restoring a pristine repository).
4046
fn copy_tree(from: &Path, to: &Path) {
4047
    fs::create_dir_all(to).unwrap();
4048
    for e in fs::read_dir(from).unwrap() {
4049
        let e = e.unwrap();
4050
        let target = to.join(e.file_name());
4051
        if e.file_type().unwrap().is_dir() {
4052
            copy_tree(&e.path(), &target);
4053
        } else {
4054
            fs::copy(e.path(), &target).unwrap();
4055
        }
4056
    }
4057
}
4058
4059
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4060
/// would, and check that both repositories still open, pass `fsck`, and
4061
/// accept the same operation again.
4062
#[test]
4063
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4064
    use crate::durable::failpoint;
4065
    hermetic();
4066
    let dir = tempfile::tempdir().unwrap();
4067
    let pristine = dir.path().join("pristine");
4068
    let origin_path = pristine.join("origin");
4069
    Repo::init(&origin_path).unwrap();
4070
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4071
        .unwrap()
4072
        .with_home(dir.path().join("home"));
4073
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4074
        .unwrap();
4075
    write(&pristine.join("a"), "f.txt", b"one\n");
4076
    a.commit("first", &[]).unwrap();
4077
    assert!(a.push("origin", false).unwrap()[0].ok);
4078
    drop(a);
4079
4080
    type Op = fn(&Repo) -> Result<()>;
4081
    let edit_and_commit: Op = |r| {
4082
        write(r.root(), "f.txt", b"one\ntwo\n");
4083
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4084
        r.commit("second", &[]).map(|_| ())
4085
    };
4086
    let push: Op = |r| {
4087
        let res = r.push("origin", false)?;
4088
        if res.iter().all(|x| x.ok) {
4089
            Ok(())
4090
        } else {
4091
            Err(RepoError::Msg(format!("{res:?}")))
4092
        }
4093
    };
4094
4095
    for (name, prepare, op) in [
4096
        ("commit", None, edit_and_commit),
4097
        ("push", Some(edit_and_commit), push),
4098
    ] {
4099
        let mut steps = 0;
4100
        for n in 1.. {
4101
            let run = dir.path().join(format!("{name}-{n}"));
4102
            copy_tree(&pristine, &run);
4103
            // Clones record their remote by path; point it at this copy.
4104
            let open = |p: &Path| {
4105
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4106
                r.config
4107
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4108
                    .unwrap();
4109
                r.save_config().unwrap();
4110
                r
4111
            };
4112
            let a = open(&run.join("a"));
4113
            if let Some(prep) = prepare {
4114
                prep(&a).unwrap();
4115
            }
4116
            failpoint::crash_after(n);
4117
            let outcome = op(&a);
4118
            let crashed = failpoint::disarm();
4119
            drop(a);
4120
            if !crashed {
4121
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4122
                steps = n - 1;
4123
                break;
4124
            }
4125
            assert!(
4126
                outcome.is_err(),
4127
                "{name}: a crash at step {n} was swallowed"
4128
            );
4129
            for repo in ["a", "origin"] {
4130
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4131
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4132
                });
4133
                let rep = r.fsck().unwrap();
4134
                assert_eq!(
4135
                    rep.errors(),
4136
                    0,
4137
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4138
                    rep.problems
4139
                );
4140
            }
4141
            // The interrupted operation can simply be run again.
4142
            let a = open(&run.join("a"));
4143
            // A crash after the commit point leaves the commit done.
4144
            let landed = a
4145
                .bookmark_heads()
4146
                .unwrap()
4147
                .iter()
4148
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4149
            let again = match (name, landed) {
4150
                ("commit", true) => Ok(()),
4151
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4152
                _ => op(&a),
4153
            };
4154
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4155
            assert_eq!(a.fsck().unwrap().errors(), 0);
4156
            fs::remove_dir_all(&run).unwrap();
4157
        }
4158
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4159
    }
4160
}
4161
4162
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4163
/// running at the same time lose nothing: every commit ends up on the
4164
/// bookmark, locally and on the remote, and the repository passes fsck.
4165
#[test]
4166
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4167
    hermetic();
4168
    let dir = tempfile::tempdir().unwrap();
4169
    let root = dir.path();
4170
    let origin = root.join("origin");
4171
    Repo::init_bare_unbound(&origin).unwrap();
4172
    let main = root.join("main");
4173
    let mut repo = Repo::init(&main).unwrap();
4174
    repo.config
4175
        .set("remote.origin.url", &origin.to_string_lossy())
4176
        .unwrap();
4177
    repo.save_config().unwrap();
4178
    write(&main, "seed.txt", b"seed\n");
4179
    repo.commit("seed", &[]).unwrap();
4180
    let second = root.join("second");
4181
    repo.workspace_add(&second, None).unwrap();
4182
    drop(repo);
4183
4184
    const EACH: usize = 15;
4185
    std::thread::scope(|s| {
4186
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4187
            s.spawn(move || {
4188
                let r = Repo::open(&dir).unwrap();
4189
                for i in 0..EACH {
4190
                    write(
4191
                        &dir,
4192
                        &format!("{tag}-{i}.txt"),
4193
                        format!("{tag} {i}\n").as_bytes(),
4194
                    );
4195
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4196
                    if push && i % 5 == 4 {
4197
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4198
                        let _ = r.push("origin", false);
4199
                    }
4200
                }
4201
            });
4202
        }
4203
    });
4204
4205
    let repo = Repo::open(&main).unwrap();
4206
    let heads = repo.bookmark_heads().unwrap();
4207
    let state = repo.load_state(&heads).unwrap();
4208
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4209
    for tag in ["a", "b"] {
4210
        for i in 0..EACH {
4211
            assert!(
4212
                messages.contains(&format!("{tag} {i}")),
4213
                "lost commit {tag} {i}; have {messages:?}"
4214
            );
4215
        }
4216
    }
4217
    let rep = repo.fsck().unwrap();
4218
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4219
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4220
    let hosted = Repo::open(&origin).unwrap();
4221
    let hosted_heads = hosted.bookmark_heads().unwrap();
4222
    assert_eq!(
4223
        hosted.load_state(&hosted_heads).unwrap().len(),
4224
        state.len(),
4225
        "the remote has every commit"
4226
    );
4227
}
4228
4229
/// Two operations recorded from the same parent (what two processes do
4230
/// when they race) are merged: both bookmarks' heads survive, and a
4231
/// change made on one side only is kept.
4232
#[test]
4233
fn operations_from_the_same_parent_are_merged() {
4234
    hermetic();
4235
    let dir = tempfile::tempdir().unwrap();
4236
    let root = dir.path();
4237
    let repo = Repo::init(root).unwrap();
4238
    write(root, "a.txt", b"a\n");
4239
    let a = repo.commit("a", &[]).unwrap();
4240
    write(root, "b.txt", b"b\n");
4241
    let b = repo.commit("b", &[]).unwrap();
4242
    let (x, op) = repo.head_op().unwrap();
4243
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4244
4245
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4246
    let mut one = op.view.clone();
4247
    one.bookmarks.insert("main".into(), state(vec![a]));
4248
    one.bookmarks.insert("topic".into(), state(vec![a]));
4249
    let mut two = op.view.clone();
4250
    two.bookmarks.insert("main".into(), state(vec![b]));
4251
    repo.record_op(&[x], "one", one).unwrap();
4252
    let merged = repo.record_op(&[x], "two", two).unwrap();
4253
4254
    let (head, op) = repo.head_op().unwrap();
4255
    assert_eq!(head, merged);
4256
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4257
    assert!(op.command.contains("merged with a concurrent operation"));
4258
    let mut main = repo
4259
        .store()
4260
        .get_state(&op.view.bookmarks["main"])
4261
        .unwrap()
4262
        .heads;
4263
    main.sort();
4264
    let mut want = vec![a, b];
4265
    want.sort();
4266
    assert_eq!(main, want, "both sides' heads are kept");
4267
    assert!(
4268
        op.view.bookmarks.contains_key("topic"),
4269
        "a one-sided change survives"
4270
    );
4271
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4272
}
4273
4274
#[test]
4275
fn failed_requests_come_with_a_next_step() {
4276
    use crate::protocol::hint_for;
4277
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4278
        .unwrap()
4279
        .contains("token"));
4280
    assert!(hint_for("…: HTTP 403: forbidden")
4281
        .unwrap()
4282
        .contains("repo:write"));
4283
    assert!(hint_for("…: HTTP 404: no such repository")
4284
        .unwrap()
4285
        .contains("owner and repository name"));
4286
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4287
        .unwrap()
4288
        .contains("oxyhub-ca.pem"));
4289
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4290
        .unwrap()
4291
        .contains("running"));
4292
    assert!(hint_for("Dns Failed: failed to lookup address information")
4293
        .unwrap()
4294
        .contains("resolve"));
4295
    assert_eq!(hint_for("something else entirely"), None);
4296
}
4297
4298
#[test]
4299
fn doctor_names_problems_and_what_to_do() {
4300
    hermetic();
4301
    let dir = tempfile::tempdir().unwrap();
4302
    let root = dir.path();
4303
    let origin = root.join("origin");
4304
    Repo::init_bare_unbound(&origin).unwrap();
4305
    let mut repo = Repo::init(&root.join("r"))
4306
        .unwrap()
4307
        .with_home(root.join("home"));
4308
    let find = |r: &DoctorReport, area: &str, h: Health| {
4309
        r.checks
4310
            .iter()
4311
            .find(|c| c.area == area && c.health == h)
4312
            .cloned()
4313
    };
4314
4315
    let r = repo.doctor(true);
4316
    assert!(find(&r, "identity", Health::Warn)
4317
        .unwrap()
4318
        .hint
4319
        .unwrap()
4320
        .contains("oxy identity create"));
4321
    assert!(find(&r, "repository", Health::Ok).is_some());
4322
4323
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4324
        .unwrap();
4325
    repo.config.set("author.name", "Ada").unwrap();
4326
    repo.config.set("author.email", "[email protected]").unwrap();
4327
    repo.config
4328
        .set("remote.origin.url", &origin.to_string_lossy())
4329
        .unwrap();
4330
    repo.config
4331
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4332
        .unwrap();
4333
    repo.config.set("remote.down.token", "t").unwrap();
4334
    repo.config
4335
        .set("remote.badca.url", "https://example.invalid/a/b")
4336
        .unwrap();
4337
    repo.config
4338
        .set(
4339
            "remote.badca.ca",
4340
            &root.join("missing.pem").to_string_lossy(),
4341
        )
4342
        .unwrap();
4343
    repo.save_config().unwrap();
4344
4345
    let r = repo.doctor(true);
4346
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4347
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4348
    assert!(find(&r, "remote origin", Health::Ok)
4349
        .unwrap()
4350
        .message
4351
        .contains("first push binds it"));
4352
    let down = find(&r, "remote down", Health::Fail).unwrap();
4353
    assert!(
4354
        down.hint.as_deref().unwrap_or("").contains("running"),
4355
        "{down:?}"
4356
    );
4357
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4358
    assert!(
4359
        badca.hint.unwrap().contains("remote.badca.ca"),
4360
        "the remote's own name is in the hint"
4361
    );
4362
    assert_eq!(r.worst(), Health::Fail);
4363
4364
    // Offline, nothing is contacted.
4365
    let r = repo.doctor(false);
4366
    assert!(find(&r, "remote down", Health::Fail).is_none());
4367
    assert!(find(&r, "remote down", Health::Ok)
4368
        .unwrap()
4369
        .message
4370
        .contains("not contacted"));
4371
}
4372
4373
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4374
/// after it. Inserting after `b` and then deleting `b`, one commit after
4375
/// the other, must not leave a delete/insert conflict.
4376
#[test]
4377
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4378
    hermetic();
4379
    let dir = tempfile::tempdir().unwrap();
4380
    let root = dir.path();
4381
    let repo = Repo::init(root).unwrap();
4382
    write(root, "f", b"a\nb\nc\n");
4383
    repo.commit("base", &[]).unwrap();
4384
    write(root, "f", b"a\nb\nx\nc\n");
4385
    let insert = repo.commit("insert x after b", &[]).unwrap();
4386
    write(root, "f", b"a\nx\nc\n");
4387
    let delete = repo.commit("delete b", &[]).unwrap();
4388
    assert!(
4389
        repo.store()
4390
            .get_change(&delete)
4391
            .unwrap()
4392
            .deps
4393
            .contains(&insert),
4394
        "the deletion depends on the insertion below the deleted line"
4395
    );
4396
    let heads = repo.bookmark_heads().unwrap();
4397
    assert_eq!(heads, vec![delete]);
4398
    let snap = repo.load_state(&heads).unwrap().materialize();
4399
    assert!(!snap.is_conflicted());
4400
    assert!(
4401
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4402
    );
4403
}
4404
4405
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4406
/// replacement depends on the change that set the blob it replaces.
4407
#[test]
4408
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4409
    hermetic();
4410
    let dir = tempfile::tempdir().unwrap();
4411
    let root = dir.path();
4412
    let repo = Repo::init(root).unwrap();
4413
    write(root, "bin", b"\0A");
4414
    let v1 = repo.commit("v1", &[]).unwrap();
4415
    write(root, "bin", b"\0B");
4416
    let v2 = repo.commit("v2", &[]).unwrap();
4417
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4418
    write(root, "bin", b"\0A");
4419
    let v3 = repo.commit("back to A", &[]).unwrap();
4420
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4421
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4422
    let state = repo.load_state(&[v3]).unwrap();
4423
    let snap = state.materialize();
4424
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4425
        panic!("opaque")
4426
    };
4427
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4428
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4429
}
4430
4431
/// Spec §23: a binary file changed on two branches and merged in Git to
4432
/// one side's version comes back as that version at the merge, and the
4433
/// import verifies commit by commit.
4434
#[test]
4435
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4436
    hermetic();
4437
    if std::process::Command::new("git")
4438
        .arg("--version")
4439
        .output()
4440
        .is_err()
4441
    {
4442
        eprintln!("git not installed; skipping");
4443
        return;
4444
    }
4445
    let dir = tempfile::tempdir().unwrap();
4446
    let root = dir.path();
4447
    let g = root.join("src.git");
4448
    fs::create_dir_all(&g).unwrap();
4449
    let git = |args: &[&str]| -> String {
4450
        let out = std::process::Command::new("git")
4451
            .arg("-C")
4452
            .arg(&g)
4453
            .args([
4454
                "-c",
4455
                "user.name=Grace",
4456
                "-c",
4457
                "[email protected]",
4458
                "-c",
4459
                "commit.gpgsign=false",
4460
            ])
4461
            .args(args)
4462
            .output()
4463
            .unwrap();
4464
        assert!(
4465
            out.status.success(),
4466
            "git {args:?}: {}",
4467
            String::from_utf8_lossy(&out.stderr)
4468
        );
4469
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4470
    };
4471
    git(&["init", "-q", "-b", "main"]);
4472
    write(&g, "logo.bin", b"\0base");
4473
    write(&g, "notes.txt", b"a\nb\nc\n");
4474
    git(&["add", "."]);
4475
    git(&["commit", "-qm", "base"]);
4476
    git(&["checkout", "-qb", "side"]);
4477
    write(&g, "logo.bin", b"\0side");
4478
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4479
    git(&["commit", "-qam", "side"]);
4480
    git(&["checkout", "-q", "main"]);
4481
    write(&g, "logo.bin", b"\0main");
4482
    git(&["commit", "-qam", "main"]);
4483
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4484
    let _ = std::process::Command::new("git")
4485
        .arg("-C")
4486
        .arg(&g)
4487
        .args([
4488
            "-c",
4489
            "user.name=G",
4490
            "-c",
4491
            "user.email=g@e",
4492
            "merge",
4493
            "-q",
4494
            "side",
4495
        ])
4496
        .output();
4497
    write(&g, "logo.bin", b"\0main");
4498
    git(&["add", "."]);
4499
    git(&["commit", "-qm", "merge side"]);
4500
    // Then a revert of the binary to its first version.
4501
    write(&g, "logo.bin", b"\0base");
4502
    git(&["commit", "-qam", "back to base"]);
4503
4504
    let repo = Repo::init(&root.join("o")).unwrap();
4505
    let rep = repo.import_git(&g, "main").unwrap();
4506
    assert_eq!(rep.merges, 1);
4507
    let v = repo.verify_git_import(&g, "main").unwrap();
4508
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4509
    assert_eq!(v.commits, 5);
4510
    let snap = repo
4511
        .load_state(&repo.bookmark_heads().unwrap())
4512
        .unwrap()
4513
        .materialize();
4514
    assert!(!snap.is_conflicted());
4515
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4516
        panic!("opaque")
4517
    };
4518
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4519
}
4520
4521
/// Spec §7.7 on a file system without executable bits or symlinks: the
4522
/// recorded bit is kept, and a symlink checked out as a plain file holding
4523
/// its target is still that symlink.
4524
#[cfg(unix)]
4525
#[test]
4526
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4527
    use crate::portable::Platform;
4528
    use std::os::unix::fs::PermissionsExt;
4529
    hermetic();
4530
    let dir = tempfile::tempdir().unwrap();
4531
    let root = dir.path();
4532
    let repo = Repo::init(root).unwrap();
4533
    write(root, "run.sh", b"#!/bin/sh\n");
4534
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4535
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4536
    repo.commit("script and link", &[]).unwrap();
4537
    drop(repo);
4538
4539
    // What checking out on Windows leaves: no exec bit, the link as a file.
4540
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4541
    fs::remove_file(root.join("link")).unwrap();
4542
    write(root, "link", b"run.sh");
4543
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4544
    let s = win.snapshot("oxy status").unwrap();
4545
    assert!(
4546
        s.statuses.is_empty(),
4547
        "nothing changed on Windows: {:?}",
4548
        statuses(&s)
4549
    );
4550
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4551
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4552
    write(root, "link", b"other");
4553
    let h = win.commit("edit on Windows", &[]).unwrap();
4554
    let snap = win.load_state(&[h]).unwrap().materialize();
4555
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4556
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4557
    // The same working copy read as Linux sees the lost bit and the plain file.
4558
    let linux = Repo::open(root).unwrap();
4559
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4560
}
4561
4562
/// Paths that collide on case-insensitive or Windows file systems are
4563
/// named at checkout there, and by doctor everywhere.
4564
#[test]
4565
fn paths_other_platforms_cannot_hold_are_reported() {
4566
    use crate::portable::Platform;
4567
    hermetic();
4568
    let dir = tempfile::tempdir().unwrap();
4569
    let root = dir.path();
4570
    let repo = Repo::init(root).unwrap();
4571
    write(root, "README.md", b"a\n");
4572
    write(root, "readme.md", b"b\n");
4573
    write(root, "src/aux.c", b"int x;\n");
4574
    let h = repo.commit("unportable", &[]).unwrap();
4575
    let r = repo.doctor(false);
4576
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4577
    assert_eq!(port.health, Health::Warn);
4578
    assert!(
4579
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4580
        "{}",
4581
        port.message
4582
    );
4583
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4584
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4585
    assert!(
4586
        rep.notes
4587
            .iter()
4588
            .any(|n| n.contains("README.md and readme.md")),
4589
        "{:?}",
4590
        rep.notes
4591
    );
4592
    assert!(
4593
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4594
        "macOS allows aux.c"
4595
    );
4596
}
4597
4598
#[test]
4599
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4600
    hermetic();
4601
    let dir = tempfile::tempdir().unwrap();
4602
    let repo = Repo::init(dir.path()).unwrap();
4603
    write(dir.path(), "a.txt", b"one\n");
4604
    write(dir.path(), "other.txt", b"x\n");
4605
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4606
    repo.snapshot("t").unwrap();
4607
    let c1 = repo.commit("first", &[]).unwrap();
4608
    write(dir.path(), "other.txt", b"y\n");
4609
    repo.snapshot("t").unwrap();
4610
    repo.commit("other only", &[]).unwrap();
4611
    write(dir.path(), "a.txt", b"one\ntwo\n");
4612
    repo.snapshot("t").unwrap();
4613
    let c3 = repo.commit("second line", &[]).unwrap();
4614
    write(dir.path(), "other.txt", b"z\n");
4615
    repo.snapshot("t").unwrap();
4616
    repo.commit("other again", &[]).unwrap();
4617
4618
    let heads = repo.bookmark_heads().unwrap();
4619
    let state = repo.load_state(&heads).unwrap();
4620
    let full: Vec<ChangeHash> = repo
4621
        .log_for_path_in("a.txt", &heads)
4622
        .unwrap()
4623
        .iter()
4624
        .map(|e| e.hash)
4625
        .collect();
4626
    assert_eq!(
4627
        full,
4628
        vec![c3, c1],
4629
        "newest first, only changes touching the path"
4630
    );
4631
    let newest: Vec<ChangeHash> = repo
4632
        .log_for_path_of(&state, "a.txt", Some(1))
4633
        .unwrap()
4634
        .iter()
4635
        .map(|e| e.hash)
4636
        .collect();
4637
    assert_eq!(newest, vec![c3], "stops at the first");
4638
    assert_eq!(
4639
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4640
        2
4641
    );
4642
    assert!(repo
4643
        .log_for_path_of(&state, "missing.txt", Some(1))
4644
        .is_err());
4645
    assert_eq!(
4646
        repo.log_state(&heads).unwrap().len(),
4647
        repo.log_of(&state).len()
4648
    );
4649
4650
    let tree = state.tree().view();
4651
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4652
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4653
    assert_eq!(
4654
        via_state
4655
            .iter()
4656
            .map(|l| (l.hash, l.text.clone()))
4657
            .collect::<Vec<_>>(),
4658
        via_heads
4659
            .iter()
4660
            .map(|l| (l.hash, l.text.clone()))
4661
            .collect::<Vec<_>>()
4662
    );
4663
    assert_eq!(
4664
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4665
        vec![c1, c3]
4666
    );
4667
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4668
}
4669
4670
/// A text file whose stat matches the manifest and whose recorded hash is
4671
/// the base's content is taken from the base without reading it; anything
4672
/// else is read, so no edit is missed (spec §12.3).
4673
#[cfg(unix)]
4674
#[test]
4675
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4676
    use std::os::unix::fs::PermissionsExt;
4677
    hermetic();
4678
    let dir = tempfile::tempdir().unwrap();
4679
    let root = dir.path();
4680
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4681
    write(root, "a.txt", b"one\ntwo\n");
4682
    write(root, "b.txt", b"bee\n");
4683
    repo.commit("base", &[]).unwrap();
4684
    let age = |p: &str| {
4685
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4686
        fs::File::options()
4687
            .write(true)
4688
            .open(root.join(p))
4689
            .unwrap()
4690
            .set_modified(old)
4691
            .unwrap();
4692
    };
4693
    age("a.txt");
4694
    age("b.txt");
4695
    assert!(
4696
        !repo.snapshot("status").unwrap().changed,
4697
        "records the aged stat"
4698
    );
4699
4700
    // Clean and equal to the base: not read at all.
4701
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4702
    let snap = repo.snapshot("status").unwrap();
4703
    assert!(
4704
        !snap.changed && snap.statuses.is_empty(),
4705
        "{:?}",
4706
        snap.statuses
4707
    );
4708
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4709
4710
    // An uncommitted edit that is older than the manifest: stat-clean, but
4711
    // its hash is not the base's, so it is read and stays visible.
4712
    write(root, "b.txt", b"bee edited\n");
4713
    age("b.txt");
4714
    let first = repo.snapshot("status").unwrap();
4715
    assert_eq!(
4716
        statuses(&first),
4717
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4718
    );
4719
    let again = repo.snapshot("status").unwrap();
4720
    assert_eq!(
4721
        statuses(&again),
4722
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4723
        "still seen once stat-clean"
4724
    );
4725
    assert!(!again.changed, "and the working copy hashes the same");
4726
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4727
    assert!(
4728
        repo.snapshot("status").is_err(),
4729
        "an edited file must be read, never taken from the base"
4730
    );
4731
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4732
4733
    // A same-size edit made just now is racy and read.
4734
    write(root, "a.txt", b"one\nTWO\n");
4735
    assert_eq!(
4736
        statuses(&repo.snapshot("status").unwrap()),
4737
        vec![
4738
            ("a.txt".to_string(), ChangeStatus::Modified),
4739
            ("b.txt".to_string(), ChangeStatus::Modified)
4740
        ]
4741
    );
4742
    // Committing makes the edits the base: both are clean and served from it again.
4743
    repo.commit("edits", &[]).unwrap();
4744
    age("a.txt");
4745
    age("b.txt");
4746
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4747
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4748
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4749
    let snap = repo.snapshot("status").unwrap();
4750
    assert!(!snap.changed && snap.statuses.is_empty());
4751
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4752
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4753
}
4754
4755
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4756
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4757
/// file is unchanged, and loading through the checkpoint equals a full load.
4758
#[test]
4759
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4760
    hermetic();
4761
    let dir = tempfile::tempdir().unwrap();
4762
    let root = dir.path();
4763
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4764
    let long: String = (0..300)
4765
        .map(|i| format!("line {i} of a long file\n"))
4766
        .collect();
4767
    write(root, "long.txt", long.as_bytes());
4768
    write(root, "short.txt", b"short\n");
4769
    repo.commit("base", &[]).unwrap();
4770
    let (r1, _, _) = repo.checkpoint().unwrap();
4771
    let cp1 = crate::objects::Checkpoint::decode(
4772
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4773
    )
4774
    .unwrap();
4775
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4776
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4777
4778
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4779
    repo.gc(true).unwrap();
4780
    assert!(repo.store().has(&graphs1[0]));
4781
    let report = repo.fsck().unwrap();
4782
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4783
4784
    // Loading through the checkpoint equals a full load.
4785
    write(root, "short.txt", b"short, edited\n");
4786
    repo.commit("edit the short file", &[]).unwrap();
4787
    let heads = repo.bookmark_heads().unwrap();
4788
    let fast = repo.load_state(&heads).unwrap();
4789
    let full = repo.load_state_full(&heads).unwrap();
4790
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4791
4792
    // The next checkpoint shares the unchanged long file's graph.
4793
    let (r2, _, _) = repo.checkpoint().unwrap();
4794
    let cp2 = crate::objects::Checkpoint::decode(
4795
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
4796
    )
4797
    .unwrap();
4798
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
4799
4800
    // A shallow clone's bundle carries the graph blob with the checkpoint.
4801
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
4802
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
4803
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
4804
4805
    // A version 1 checkpoint written by an older oxy still loads.
4806
    let state = repo.load_state_full(&heads).unwrap();
4807
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
4808
    let cp_old = crate::objects::Checkpoint {
4809
        heads: cp2.heads.clone(),
4810
        count: cp2.count,
4811
        payload: old,
4812
    };
4813
    let r_old = repo
4814
        .store()
4815
        .put(ObjectType::Checkpoint, &cp_old.encode())
4816
        .unwrap();
4817
    repo.install_checkpoint("main", &r_old).unwrap();
4818
    assert_eq!(
4819
        repo.load_state(&heads).unwrap().checkpoint_payload(),
4820
        full.checkpoint_payload()
4821
    );
4822
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4823
4824
    // A lost graph blob fails the load loudly rather than dropping the
4825
    // file, and fsck reports it (a fresh repository, objects still loose).
4826
    let dir2 = tempfile::tempdir().unwrap();
4827
    let root2 = dir2.path();
4828
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
4829
    write(root2, "long.txt", long.as_bytes());
4830
    repo2.commit("base", &[]).unwrap();
4831
    let (r, _, _) = repo2.checkpoint().unwrap();
4832
    let cp = crate::objects::Checkpoint::decode(
4833
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
4834
    )
4835
    .unwrap();
4836
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
4837
    fs::remove_file(repo2.store().path_for(&graph)).unwrap();
4838
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
4839
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
4840
}
4841
4842
/// A new repository has not stored the user's identity yet (that happens
4843
/// at the first signed change); looking it up falls back to the key
4844
/// directory, and a file there that does not hash to the key is refused.
4845
#[test]
4846
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
4847
    hermetic();
4848
    let dir = tempfile::tempdir().unwrap();
4849
    let home = dir.path().join("home");
4850
    let mut first = Repo::init(&dir.path().join("a"))
4851
        .unwrap()
4852
        .with_home(home.clone());
4853
    let (key, _) = first
4854
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4855
        .unwrap();
4856
    let fresh = Repo::init(&dir.path().join("b"))
4857
        .unwrap()
4858
        .with_home(home.clone());
4859
    assert!(!fresh.store().has(&key), "nothing stored yet");
4860
    let id = fresh.identity(&key).unwrap();
4861
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
4862
    // A key file that is not this identity is an error, not a wrong answer.
4863
    let keys = fresh.keys_dir.clone();
4864
    let (other, _) = first
4865
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4866
        .unwrap();
4867
    fs::copy(
4868
        keys.join(format!("{}.identity", other.to_hex())),
4869
        keys.join(format!("{}.identity", key.to_hex())),
4870
    )
4871
    .unwrap();
4872
    assert!(fresh
4873
        .identity(&key)
4874
        .unwrap_err()
4875
        .to_string()
4876
        .contains("does not hold identity"));
4877
}
4878
4879
/// Status snapshots (spec §12.3): a text file whose stat matches the
4880
/// manifest, and whose base graph key is the one the manifest recorded it
4881
/// equal to, is neither read nor rendered; any edit, and any change to the
4882
/// file's graph in the base, brings it back.
4883
#[cfg(unix)]
4884
#[test]
4885
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
4886
    use std::os::unix::fs::PermissionsExt;
4887
    hermetic();
4888
    let dir = tempfile::tempdir().unwrap();
4889
    let root = dir.path();
4890
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4891
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
4892
        write(root, p, c.as_bytes());
4893
    }
4894
    repo.commit("base", &[]).unwrap();
4895
    let age = |p: &str| {
4896
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4897
        fs::File::options()
4898
            .write(true)
4899
            .open(root.join(p))
4900
            .unwrap()
4901
            .set_modified(old)
4902
            .unwrap();
4903
    };
4904
    let lock = |p: &str, mode: u32| {
4905
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
4906
    };
4907
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4908
        age(p);
4909
    }
4910
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4911
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4912
    assert!(
4913
        m.entries.values().all(|e| e.graph.is_some()),
4914
        "keys recorded"
4915
    );
4916
4917
    // Unreadable files prove they are not read; the status snapshot does
4918
    // not render them either, and its base lacks their graphs.
4919
    lock("a.txt", 0o000);
4920
    lock("b.txt", 0o000);
4921
    let snap = repo.snapshot_status("status").unwrap();
4922
    assert!(!snap.changed && snap.statuses.is_empty());
4923
    assert_eq!(
4924
        snap.base_snapshot
4925
            .unrendered
4926
            .iter()
4927
            .cloned()
4928
            .collect::<Vec<_>>(),
4929
        vec!["a.txt", "b.txt", "d/c.txt"]
4930
    );
4931
    assert!(!snap.base.is_full());
4932
    assert!(!snap.base_snapshot.is_conflicted());
4933
    // A full snapshot does not read them either, but renders everything.
4934
    let full = repo.snapshot("status").unwrap();
4935
    assert!(full.statuses.is_empty() && full.base.is_full());
4936
    assert!(full.base_snapshot.unrendered.is_empty());
4937
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
4938
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
4939
4940
    // An edit is seen; the file is rendered, the others still are not.
4941
    write(root, "d/c.txt", b"sea edited\n");
4942
    let snap = repo.snapshot_status("status").unwrap();
4943
    assert_eq!(
4944
        statuses(&snap),
4945
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
4946
    );
4947
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
4948
    // So is a mode change of an unread file.
4949
    lock("b.txt", 0o100);
4950
    assert_eq!(
4951
        statuses(&repo.snapshot_status("status").unwrap()),
4952
        vec![
4953
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
4954
            ("d/c.txt".to_string(), ChangeStatus::Modified)
4955
        ]
4956
    );
4957
    lock("b.txt", 0o000);
4958
4959
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
4960
    // stays unread, c.txt is read once and then skipped too.
4961
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
4962
        .unwrap();
4963
    age("d/c.txt");
4964
    let snap = repo.snapshot_status("status").unwrap();
4965
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
4966
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
4967
    lock("d/c.txt", 0o000);
4968
    let snap = repo.snapshot_status("status").unwrap();
4969
    assert!(snap.statuses.is_empty());
4970
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
4971
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4972
        lock(p, 0o644);
4973
    }
4974
}
4975
4976
/// Attributes decide how a file compares with the base, so a changed
4977
/// `.oxyattributes` makes every text file be compared again.
4978
#[cfg(unix)]
4979
#[test]
4980
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
4981
    hermetic();
4982
    let dir = tempfile::tempdir().unwrap();
4983
    let root = dir.path();
4984
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4985
    write(root, "a.txt", b"crlf\r\n");
4986
    repo.commit("base", &[]).unwrap();
4987
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4988
    fs::File::options()
4989
        .write(true)
4990
        .open(root.join("a.txt"))
4991
        .unwrap()
4992
        .set_modified(old)
4993
        .unwrap();
4994
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
4995
    assert!(repo
4996
        .snapshot_status("status")
4997
        .unwrap()
4998
        .base_snapshot
4999
        .unrendered
5000
        .contains("a.txt"));
5001
    // With eol=lf, a.txt as stored no longer equals the base.
5002
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5003
    let snap = repo.snapshot_status("status").unwrap();
5004
    assert_eq!(
5005
        statuses(&snap),
5006
        vec![
5007
            (".oxyattributes".to_string(), ChangeStatus::Added),
5008
            ("a.txt".to_string(), ChangeStatus::Modified)
5009
        ]
5010
    );
5011
}
5012
5013
/// Bookmarks with `/` in their names: pushing records their
5014
/// attestations, and checkpoints are kept for them, beside `feature`
5015
/// itself.
5016
#[test]
5017
fn bookmarks_with_slashes_push_and_checkpoint() {
5018
    hermetic();
5019
    let dir = tempfile::tempdir().unwrap();
5020
    let root = dir.path();
5021
    let origin = Repo::init(&root.join("origin")).unwrap();
5022
    let url = root.join("origin").to_string_lossy().to_string();
5023
    let mut repo = Repo::clone(&url, &root.join("r"))
5024
        .unwrap()
5025
        .with_home(root.join("home"));
5026
    // With an identity, pushes carry reference attestations: the case
5027
    // that failed, since the attestation is a file named after the bookmark.
5028
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5029
        .unwrap();
5030
    let r = root.join("r");
5031
    write(&r, "a.txt", b"a\n");
5032
    let h_a = repo.commit("a", &[]).unwrap();
5033
    assert!(repo.push("origin", false).unwrap()[0].ok);
5034
    repo.bookmark_create("feature", None).unwrap();
5035
    repo.bookmark_create("feature/x", None).unwrap();
5036
    repo.bookmark_switch("feature/x", false).unwrap();
5037
    write(&r, "b.txt", b"b\n");
5038
    let h_b = repo.commit("b", &[]).unwrap();
5039
    for name in ["feature", "feature/x"] {
5040
        let res = repo.push_bookmark("origin", name, false).unwrap();
5041
        assert!(res[0].ok, "{name}: {res:?}");
5042
    }
5043
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5044
    assert_eq!(
5045
        origin.resolve_heads("feature/x").unwrap(),
5046
        repo.resolve_heads("feature/x").unwrap()
5047
    );
5048
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5049
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5050
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5051
5052
    // A checkpoint of feature/x is found again when loading its state.
5053
    let (cp, _, _) = repo.checkpoint().unwrap();
5054
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5055
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5056
    let heads = repo.resolve_heads("feature/x").unwrap();
5057
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5058
}
5059
5060
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5061
/// never the remote's own bookmark, and a bookmark created again later is
5062
/// accepted although the deletion's attestation stays the latest.
5063
#[test]
5064
fn bookmarks_are_deleted_on_a_remote() {
5065
    hermetic();
5066
    let dir = tempfile::tempdir().unwrap();
5067
    let root = dir.path();
5068
    let origin = Repo::init(&root.join("origin")).unwrap();
5069
    let url = root.join("origin").to_string_lossy().to_string();
5070
    let mut repo = Repo::clone(&url, &root.join("r"))
5071
        .unwrap()
5072
        .with_home(root.join("home"));
5073
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5074
        .unwrap();
5075
    let r = root.join("r");
5076
    write(&r, "a.txt", b"a\n");
5077
    repo.commit("a", &[]).unwrap();
5078
    assert!(repo.push("origin", false).unwrap()[0].ok);
5079
    repo.bookmark_create("feature/x", None).unwrap();
5080
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5081
    assert!(origin.resolve_heads("feature/x").is_ok());
5082
5083
    let res = repo.push_delete("origin", "feature/x").unwrap();
5084
    assert!(res[0].ok, "{res:?}");
5085
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5086
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5087
    assert!(
5088
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5089
        "the deletion is attested"
5090
    );
5091
    assert!(
5092
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5093
        "the local bookmark stays"
5094
    );
5095
    assert!(!repo
5096
        .view()
5097
        .unwrap()
5098
        .remotes
5099
        .get("origin")
5100
        .is_some_and(|m| m.contains_key("feature/x")));
5101
5102
    // Pushing it again creates it again, past the deletion's serial.
5103
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5104
    assert!(res[0].ok, "{res:?}");
5105
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5106
5107
    // Nothing to delete, and never the remote's own bookmark.
5108
    assert!(repo.push_delete("origin", "nope").is_err());
5109
    let res = repo.push_delete("origin", "main").unwrap();
5110
    assert!(
5111
        !res[0].ok && res[0].reason.contains("default bookmark"),
5112
        "{res:?}"
5113
    );
5114
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5115
}
5116
5117
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5118
/// when the target has the same versions of the files it touches, and is
5119
/// refused, untouched, when it has others.
5120
#[test]
5121
fn switching_bookmarks_carries_uncommitted_work() {
5122
    hermetic();
5123
    let dir = tempfile::tempdir().unwrap();
5124
    let root = dir.path();
5125
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5126
    write(root, "a.txt", b"a\n");
5127
    write(root, "b.txt", b"b\n");
5128
    write(root, "gone.txt", b"gone\n");
5129
    repo.commit("base", &[]).unwrap();
5130
    repo.bookmark_create("feature", None).unwrap();
5131
    // Started on main, belongs on feature: edit, add, remove.
5132
    write(root, "a.txt", b"a\nmore\n");
5133
    write(root, "new.txt", b"new\n");
5134
    fs::remove_file(root.join("gone.txt")).unwrap();
5135
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5136
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5137
    assert_eq!(repo.config.bookmark, "feature");
5138
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5139
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5140
    assert!(!root.join("gone.txt").exists());
5141
    let snap = repo.snapshot("status").unwrap();
5142
    assert_eq!(
5143
        statuses(&snap),
5144
        vec![
5145
            ("a.txt".to_string(), ChangeStatus::Modified),
5146
            ("gone.txt".to_string(), ChangeStatus::Removed),
5147
            ("new.txt".to_string(), ChangeStatus::Added)
5148
        ]
5149
    );
5150
    repo.commit("the work", &[]).unwrap();
5151
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5152
5153
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5154
    repo.bookmark_switch("main", false).unwrap();
5155
    write(root, "b.txt", b"b on main\n");
5156
    repo.commit("b on main", &[]).unwrap();
5157
    repo.bookmark_switch("feature", false).unwrap();
5158
    write(root, "b.txt", b"b edited\n");
5159
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5160
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5161
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5162
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5163
}
5164
5165
/// Merging and checking out (feedback 3): a working copy without changes
5166
/// follows a merge whichever state it sat on; a refused checkout names
5167
/// what is in the way; `checkout --carry` takes the work along.
5168
#[test]
5169
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5170
    hermetic();
5171
    let dir = tempfile::tempdir().unwrap();
5172
    let root = dir.path();
5173
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5174
    write(root, "a.txt", b"a\n");
5175
    let h1 = repo.commit("a", &[]).unwrap();
5176
    write(root, "b.txt", b"b\n");
5177
    repo.commit("b", &[]).unwrap();
5178
    repo.bookmark_create("feature", None).unwrap();
5179
    repo.bookmark_switch("feature", false).unwrap();
5180
    write(root, "c.txt", b"c\n");
5181
    repo.commit("c on feature", &[]).unwrap();
5182
    repo.bookmark_switch("main", false).unwrap();
5183
    // The working copy sits on an older state than main's heads.
5184
    repo.checkout(&[h1], false, "checkout").unwrap();
5185
    assert!(!root.join("b.txt").exists());
5186
    let m = repo.merge("feature").unwrap();
5187
    assert!(m.checked_out, "a clean working copy follows the merge");
5188
    for f in ["a.txt", "b.txt", "c.txt"] {
5189
        assert!(root.join(f).exists(), "{f}");
5190
    }
5191
5192
    // A refusal says which paths are in the way and what to do.
5193
    fs::remove_file(root.join("b.txt")).unwrap();
5194
    write(root, "a.txt", b"a edited\n");
5195
    let err = repo
5196
        .checkout(&[h1], false, "checkout")
5197
        .unwrap_err()
5198
        .to_string();
5199
    assert!(
5200
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5201
        "{err}"
5202
    );
5203
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5204
    // is carried as absent (h1 has none either, so that is refused).
5205
    let err = repo
5206
        .checkout_carry(&[h1], "the first change", "checkout")
5207
        .unwrap_err()
5208
        .to_string();
5209
    assert!(
5210
        err.contains("b.txt") && err.contains("the first change"),
5211
        "{err}"
5212
    );
5213
    write(root, "b.txt", b"b\n");
5214
    let (_, carried) = repo
5215
        .checkout_carry(&[h1], "the first change", "checkout")
5216
        .unwrap();
5217
    assert_eq!(carried, vec!["a.txt"]);
5218
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5219
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5220
}
5221
5222
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5223
/// user identity not stored in a new repository yet is fine while its
5224
/// secret key is there; an added subrepo is listed as not committed yet.
5225
#[test]
5226
fn a_new_repository_is_healthy_before_its_first_commit() {
5227
    hermetic();
5228
    let dir = tempfile::tempdir().unwrap();
5229
    let root = dir.path();
5230
    let home = root.join("home");
5231
    let mut first = Repo::init(&root.join("first"))
5232
        .unwrap()
5233
        .with_home(home.clone());
5234
    let (key, _) = first
5235
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5236
        .unwrap();
5237
    let repo = Repo::init(&root.join("second"))
5238
        .unwrap()
5239
        .with_home(home.clone());
5240
    // Only the secret key: no identity object anywhere this repository sees.
5241
    let keys = repo.keys_dir.clone();
5242
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5243
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5244
    let r = repo.doctor(true);
5245
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5246
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5247
    assert!(id.message.contains("first signed change"), "{}", id.message);
5248
5249
    // A subrepo added and not committed yet is listed, pinned where it is.
5250
    let lib = root.join("lib");
5251
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5252
    write(&lib, "x.txt", b"x\n");
5253
    l.commit("x", &[]).unwrap();
5254
    let second = root.join("second");
5255
    write(&second, "a.txt", b"a\n");
5256
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5257
        .unwrap();
5258
    let subs = repo.subrepos().unwrap();
5259
    assert_eq!(subs.len(), 1);
5260
    assert_eq!(
5261
        (subs[0].path.as_str(), subs[0].committed),
5262
        ("deps/lib", false)
5263
    );
5264
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5265
    repo.commit("add lib", &[]).unwrap();
5266
    let subs = repo.subrepos().unwrap();
5267
    assert!(subs[0].committed, "committed now");
5268
}
5269
5270
/// Commit, diff, hunks and discard use the partial snapshot: a file
5271
/// unchanged since the manifest is neither read nor rendered, and showing
5272
/// a change renders only what it edits, the same as from a full base.
5273
#[cfg(unix)]
5274
#[test]
5275
fn commits_and_diffs_leave_unchanged_files_alone() {
5276
    use std::os::unix::fs::PermissionsExt;
5277
    hermetic();
5278
    let dir = tempfile::tempdir().unwrap();
5279
    let root = dir.path();
5280
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5281
    write(root, "big.txt", b"lots\nof\nlines\n");
5282
    write(root, "a.txt", b"one\ntwo\n");
5283
    repo.commit("base", &[]).unwrap();
5284
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5285
    for f in ["big.txt", "a.txt"] {
5286
        fs::File::options()
5287
            .write(true)
5288
            .open(root.join(f))
5289
            .unwrap()
5290
            .set_modified(old)
5291
            .unwrap();
5292
    }
5293
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5294
    // big.txt cannot be read at all from here on.
5295
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5296
5297
    write(root, "a.txt", b"one\nTWO\nthree\n");
5298
    let diff = repo.diff_files(None).unwrap();
5299
    assert_eq!(
5300
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5301
        ["a.txt"]
5302
    );
5303
    let (_, hunks) = repo.hunks().unwrap();
5304
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5305
    let h = repo.commit("edit a", &[]).unwrap();
5306
5307
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5308
    let c = repo.store().get_change(&h).unwrap();
5309
    let full = repo.load_state(&c.deps).unwrap();
5310
    let want = render_change(&c, &full, &full.materialize());
5311
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5312
    let (base, snap) = repo.change_base(&c).unwrap();
5313
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5314
5315
    // Discarding works the same way.
5316
    write(root, "a.txt", b"scratch\n");
5317
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5318
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5319
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5320
}
5321
5322
/// A replace conflict (spec §9.3) is settled by a change that writes one
5323
/// candidate, or new bytes, at the path when the caller names it; a plain
5324
/// snapshot of a checkout never settles it on its own.
5325
#[test]
5326
fn replace_conflicts_are_settled_when_asked() {
5327
    hermetic();
5328
    let dir = tempfile::tempdir().unwrap();
5329
    let root = dir.path();
5330
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5331
    let blob = |n: u8| {
5332
        let mut v = vec![0u8; 64];
5333
        v[1] = n;
5334
        v
5335
    };
5336
    write(root, "img.bin", &blob(1));
5337
    repo.commit("add img", &[]).unwrap();
5338
    repo.bookmark_create("other", None).unwrap();
5339
    write(root, "img.bin", &blob(2));
5340
    repo.commit("img two", &[]).unwrap();
5341
    repo.bookmark_switch("other", false).unwrap();
5342
    write(root, "img.bin", &blob(3));
5343
    repo.commit("img three", &[]).unwrap();
5344
    repo.bookmark_switch("main", false).unwrap();
5345
    repo.merge("other").unwrap();
5346
    let heads = repo.bookmark_heads().unwrap();
5347
    let merged = repo.load_state(&heads).unwrap().materialize();
5348
    assert!(
5349
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5350
        "a replace conflict"
5351
    );
5352
    // A snapshot of the checkout records nothing.
5353
    assert!(repo
5354
        .snapshot("status")
5355
        .unwrap()
5356
        .statuses
5357
        .iter()
5358
        .all(|s| s.path != "img.bin"));
5359
5360
    // Keeping candidate 3 settles it.
5361
    let author = repo.author();
5362
    let edits = [FileEdit {
5363
        path: "img.bin".into(),
5364
        content: Some(blob(3)),
5365
    }];
5366
    let c = repo
5367
        .build_change(&heads, &edits, "keep three", author)
5368
        .unwrap();
5369
    assert_eq!(c.kind, ChangeKind::Resolution);
5370
    let mut st = repo.load_state(&heads).unwrap();
5371
    for d in &c.deps {
5372
        assert!(st.contains(d));
5373
    }
5374
    assert!(
5375
        heads.iter().all(|h| c.deps.contains(h)),
5376
        "depends on both contributors"
5377
    );
5378
    st.add(c).unwrap();
5379
    let after = st.materialize();
5380
    assert!(!after.is_conflicted());
5381
    assert_eq!(
5382
        after.files["img.bin"].content,
5383
        FileContent::Opaque {
5384
            blobs: vec![Repo::blob_ref(&blob(3))]
5385
        }
5386
    );
5387
5388
    // New bytes settle it too.
5389
    let edits = [FileEdit {
5390
        path: "img.bin".into(),
5391
        content: Some(blob(9)),
5392
    }];
5393
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5394
    let mut st = repo.load_state(&heads).unwrap();
5395
    st.add(c).unwrap();
5396
    assert_eq!(
5397
        st.materialize().files["img.bin"].content,
5398
        FileContent::Opaque {
5399
            blobs: vec![Repo::blob_ref(&blob(9))]
5400
        }
5401
    );
5402
}
5403
5404
/// The history of a range of lines (spec §27): the changes that wrote
5405
/// or deleted its atoms, or deleted atoms from between them; edits outside
5406
/// the range and changes the range's lines survived are not in it.
5407
#[test]
5408
fn line_ranges_have_exact_histories() {
5409
    hermetic();
5410
    let dir = tempfile::tempdir().unwrap();
5411
    let root = dir.path();
5412
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5413
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5414
    let base = repo.commit("add f", &[]).unwrap();
5415
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5416
    let outside = repo.commit("change the import", &[]).unwrap();
5417
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5418
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5419
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5420
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5421
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5422
    let after = repo.commit("add b after a", &[]).unwrap();
5423
    let heads = repo.bookmark_heads().unwrap();
5424
5425
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5426
    let hist: Vec<ChangeHash> = repo
5427
        .line_history(&heads, "f.rs", 2, 4)
5428
        .unwrap()
5429
        .iter()
5430
        .map(|e| e.hash)
5431
        .collect();
5432
    for (h, what) in [
5433
        (base, "wrote it"),
5434
        (inside, "edited a line"),
5435
        (deleted, "deleted a line from inside"),
5436
    ] {
5437
        assert!(hist.contains(&h), "{what}");
5438
    }
5439
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5440
        assert!(!hist.contains(&h), "{what}");
5441
    }
5442
    assert_eq!(hist[0], deleted, "newest first");
5443
    // One line: only what touched it.
5444
    let one: Vec<ChangeHash> = repo
5445
        .line_history(&heads, "f.rs", 1, 1)
5446
        .unwrap()
5447
        .iter()
5448
        .map(|e| e.hash)
5449
        .collect();
5450
    assert!(one.contains(&outside) && !one.contains(&inside));
5451
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5452
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5453
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5454
}
5455
5456
#[test]
5457
fn receipts_are_kept_with_their_state_and_verified() {
5458
    use crate::receipt::{Receipt, SignedReceipt};
5459
    hermetic();
5460
    let dir = tempfile::tempdir().unwrap();
5461
    let root = dir.path();
5462
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5463
    write(root, "a.txt", b"1\n");
5464
    repo.commit("A", &[]).unwrap();
5465
    let heads = repo.bookmark_heads().unwrap();
5466
    let state = repo
5467
        .store()
5468
        .put_state(&StateObject::new(heads.clone()))
5469
        .unwrap();
5470
    let out = repo.store_blob(b"built\n").unwrap();
5471
    let receipt = Receipt {
5472
        job_name: "build".into(),
5473
        pipeline_hash: ObjectRef([1; 32]),
5474
        scope_tree_hash: ObjectRef([2; 32]),
5475
        inputs: vec![],
5476
        environment: ObjectRef([3; 32]),
5477
        outputs: vec![out],
5478
        exit_code: 0,
5479
        duration_ms: 42,
5480
    };
5481
    let sk = SecretKey::generate();
5482
    let runner = sk.identity("earth-1", "runner@earth", 1);
5483
    let sr = SignedReceipt::sign(
5484
        receipt.clone(),
5485
        repo.id().unwrap(),
5486
        state,
5487
        "demo#1",
5488
        &runner,
5489
        &sk,
5490
    );
5491
5492
    let r = repo.add_receipt(&sr).unwrap();
5493
    let found = repo.receipts(&heads).unwrap();
5494
    assert_eq!(found.len(), 1);
5495
    assert_eq!(found[0].attest, r);
5496
    assert_eq!(found[0].signed, sr);
5497
    assert!(found[0].problem.is_none() && !found[0].revoked);
5498
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5499
5500
    // Another repository's receipt, or a forged one, is refused.
5501
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5502
    assert!(repo
5503
        .add_receipt(&elsewhere)
5504
        .unwrap_err()
5505
        .to_string()
5506
        .contains("another repository"));
5507
    let mut forged = sr.clone();
5508
    forged.receipt.exit_code = 1;
5509
    assert!(repo
5510
        .add_receipt(&forged)
5511
        .unwrap_err()
5512
        .to_string()
5513
        .contains("does not verify"));
5514
5515
    // gc keeps the receipt, its runner and its output while the state lives.
5516
    repo.gc(true).unwrap();
5517
    assert_eq!(repo.receipts(&heads).unwrap().len(), 1);
5518
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5519
    assert!(repo.fsck().unwrap().problems.is_empty());
5520
}
5521
5522
#[test]
5523
fn status_leaves_an_unchanged_manifest_alone() {
5524
    hermetic();
5525
    let dir = tempfile::tempdir().unwrap();
5526
    let root = dir.path();
5527
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5528
    write(root, "a.txt", b"1\n");
5529
    write(root, "b.txt", b"2\n");
5530
    repo.commit("A", &[]).unwrap();
5531
    // Files last touched well outside the racy window.
5532
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5533
    for f in ["a.txt", "b.txt"] {
5534
        fs::File::options()
5535
            .write(true)
5536
            .open(root.join(f))
5537
            .unwrap()
5538
            .set_modified(old)
5539
            .unwrap();
5540
    }
5541
    repo.snapshot_status("status").unwrap();
5542
    let path = repo.manifest_path();
5543
    let first = fs::read(&path).unwrap();
5544
    repo.snapshot_status("status").unwrap();
5545
    assert_eq!(
5546
        fs::read(&path).unwrap(),
5547
        first,
5548
        "an unchanged tree does not rewrite the manifest"
5549
    );
5550
    // A change rewrites it.
5551
    write(root, "a.txt", b"1\n2\n");
5552
    repo.snapshot_status("status").unwrap();
5553
    assert_ne!(fs::read(&path).unwrap(), first);
5554
}
5555
5556
#[test]
5557
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5558
    hermetic();
5559
    let dir = tempfile::tempdir().unwrap();
5560
    let root = dir.path();
5561
    let origin_path = root.join("origin");
5562
    Repo::init(&origin_path).unwrap();
5563
    let origin_url = origin_path.to_string_lossy().to_string();
5564
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5565
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5566
    write(&root.join("a"), "big.txt", big.as_bytes());
5567
    write(&root.join("a"), "small.txt", b"small\n");
5568
    let h1 = a.commit("large", &[]).unwrap();
5569
    let (_, body) = a.store().get(&h1).unwrap();
5570
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5571
    assert!(a.push("origin", false).unwrap()[0].ok);
5572
5573
    // A clone reads the text from the blobs that came with the change.
5574
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5575
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5576
    // An edit in the middle of the stored insert is an ordinary change.
5577
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5578
    write(&root.join("b"), "big.txt", edited.as_bytes());
5579
    let h2 = b.commit("edit", &[]).unwrap();
5580
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5581
    assert!(b.push("origin", false).unwrap()[0].ok);
5582
    assert!(a.pull("origin").unwrap().checked_out);
5583
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5584
    assert_eq!(
5585
        a.fsck().unwrap().errors(),
5586
        0,
5587
        "{:?}",
5588
        a.fsck().unwrap().problems
5589
    );
5590
5591
    // With zero retention gc keeps the text blobs of every kept change.
5592
    let mut a = Repo::open(&root.join("a")).unwrap();
5593
    a.config.set("core.op-retention", "0").unwrap();
5594
    a.save_config().unwrap();
5595
    let a = Repo::open(&root.join("a")).unwrap();
5596
    a.gc(true).unwrap();
5597
    let a = Repo::open(&root.join("a")).unwrap();
5598
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5599
    assert_eq!(
5600
        a.fsck().unwrap().errors(),
5601
        0,
5602
        "{:?}",
5603
        a.fsck().unwrap().problems
5604
    );
5605
    // And a clone of the packed repository reads them from its packs.
5606
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5607
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5608
    drop(c);
5609
}
5610
5611
#[test]
5612
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5613
    hermetic();
5614
    let dir = tempfile::tempdir().unwrap();
5615
    let root = dir.path();
5616
    let repo = Repo::init(root).unwrap();
5617
    write(root, "a.txt", b"a\n");
5618
    let a = repo.commit("a", &[]).unwrap();
5619
    write(root, "b.txt", b"b\n");
5620
    repo.commit("b", &[]).unwrap();
5621
    let (x, op) = repo.head_op().unwrap();
5622
    let ws = *op.view.workspaces.keys().next().unwrap();
5623
    let mut one = op.view.clone();
5624
    one.workspaces.insert(ws, a);
5625
    let mut two = op.view.clone();
5626
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5627
    let first = repo.record_op(&[x], "one", one).unwrap();
5628
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5629
    assert!(
5630
        e.to_string()
5631
            .contains("changed this working copy at the same time"),
5632
        "{e}"
5633
    );
5634
    assert_eq!(
5635
        repo.head_op().unwrap().0,
5636
        first,
5637
        "the second is not recorded"
5638
    );
5639
}
5640
5641
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5642
/// rewrote the working copy recorded the half-written files as edits, and
5643
/// its view replaced the switch's.
5644
#[test]
5645
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5646
    hermetic();
5647
    let dir = tempfile::tempdir().unwrap();
5648
    let root = dir.path().to_path_buf();
5649
    let mut repo = Repo::init(&root).unwrap();
5650
    write(&root, "keep.txt", b"keep\n");
5651
    repo.commit("base", &[]).unwrap();
5652
    repo.bookmark_create("small", None).unwrap();
5653
    for i in 0..300 {
5654
        write(
5655
            &root,
5656
            &format!("many/f{i}.txt"),
5657
            format!("file {i}\n").as_bytes(),
5658
        );
5659
    }
5660
    repo.commit("many", &[]).unwrap();
5661
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5662
    let watcher = {
5663
        let (root, stop) = (root.clone(), stop.clone());
5664
        std::thread::spawn(move || {
5665
            let r = Repo::open(&root).unwrap();
5666
            let mut ran = 0;
5667
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
5668
                if r.snapshot_status("oxy status").is_ok() {
5669
                    ran += 1;
5670
                }
5671
            }
5672
            ran
5673
        })
5674
    };
5675
    for i in 0..20 {
5676
        let to = if i % 2 == 0 { "small" } else { "main" };
5677
        repo.bookmark_switch(to, false).unwrap();
5678
    }
5679
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
5680
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
5681
    // Back on main, clean, with every file where main has it.
5682
    let repo = Repo::open(&root).unwrap();
5683
    let s = repo.snapshot_status("oxy status").unwrap();
5684
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
5685
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
5686
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
5687
    assert!(root.join("many/f299.txt").exists());
5688
}
5689
5690
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
5691
/// put a subrepo that was ahead of its pin back at the pin and moved the
5692
/// subrepo's own bookmark backwards.
5693
#[test]
5694
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
5695
    hermetic();
5696
    let dir = tempfile::tempdir().unwrap();
5697
    let root = dir.path();
5698
    Repo::init(&root.join("lib-origin")).unwrap();
5699
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5700
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
5701
    write(&root.join("lib"), "lib.txt", b"v1\n");
5702
    lib.commit("lib v1", &[]).unwrap();
5703
    assert!(lib.push("origin", false).unwrap()[0].ok);
5704
5705
    let app_dir = root.join("app");
5706
    let mut app = Repo::init(&app_dir).unwrap();
5707
    write(&app_dir, "main.txt", b"app\n");
5708
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5709
    app.commit("app with lib", &[]).unwrap();
5710
    app.bookmark_create("feature", None).unwrap();
5711
5712
    // New work in the subrepo, not yet pinned by the parent.
5713
    let nested_dir = app_dir.join("libs/lib");
5714
    let nested = Repo::open(&nested_dir).unwrap();
5715
    write(&nested_dir, "new.txt", b"new\n");
5716
    let l2 = nested.commit("lib: new file", &[]).unwrap();
5717
    drop(nested);
5718
5719
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
5720
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
5721
    let nested = Repo::open(&nested_dir).unwrap();
5722
    assert!(
5723
        nested.bookmark_heads().unwrap().contains(&l2),
5724
        "its bookmark kept its work"
5725
    );
5726
    assert!(nested_dir.join("new.txt").exists(), "and its files");
5727
    let s = app.snapshot("status").unwrap();
5728
    assert_eq!(
5729
        statuses(&s),
5730
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
5731
    );
5732
}
5733
5734
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
5735
/// moving `main` to a change this clone had pushed on another bookmark,
5736
/// the first `pull` said "Already up to date" while `main` was behind.
5737
#[test]
5738
fn pull_takes_a_remote_move_to_changes_already_here() {
5739
    hermetic();
5740
    let dir = tempfile::tempdir().unwrap();
5741
    let root = dir.path();
5742
    let origin_path = root.join("origin");
5743
    let origin = Repo::init(&origin_path).unwrap();
5744
    let url = origin_path.to_string_lossy().to_string();
5745
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
5746
    write(&root.join("b"), "base.txt", b"base\n");
5747
    b.commit("base", &[]).unwrap();
5748
    assert!(b.push("origin", false).unwrap()[0].ok);
5749
5750
    // A feature bookmark with one change, pushed.
5751
    b.bookmark_create("feat", None).unwrap();
5752
    b.bookmark_switch("feat", false).unwrap();
5753
    write(&root.join("b"), "x.txt", b"x\n");
5754
    let x = b.commit("x", &[]).unwrap();
5755
    assert!(b.push("origin", false).unwrap()[0].ok);
5756
    b.bookmark_switch("main", false).unwrap();
5757
5758
    // The remote lands it: its main moves to the feature's state.
5759
    let feat = origin
5760
        .store()
5761
        .get_state(&origin.view().unwrap().bookmarks["feat"])
5762
        .unwrap()
5763
        .heads;
5764
    origin.bookmark_set("main", &feat).unwrap();
5765
5766
    let r = b.pull("origin").unwrap();
5767
    assert!(r.changed, "{r:?}");
5768
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
5769
    let main = b
5770
        .bookmarks()
5771
        .unwrap()
5772
        .into_iter()
5773
        .find(|m| m.name == "main")
5774
        .unwrap();
5775
    assert_eq!(main.behind, Some(0), "{main:?}");
5776
}
5777
5778
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
5779
/// to one only the remote has makes a local bookmark from it; a pull moves
5780
/// every local bookmark the remote has too; a clone checks out the remote's
5781
/// default bookmark.
5782
#[test]
5783
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
5784
    hermetic();
5785
    let dir = tempfile::tempdir().unwrap();
5786
    let root = dir.path();
5787
    let origin_path = root.join("origin");
5788
    let mut origin = Repo::init(&origin_path).unwrap();
5789
    let url = origin_path.to_string_lossy().to_string();
5790
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
5791
    write(&root.join("a"), "base.txt", b"base\n");
5792
    a.commit("base", &[]).unwrap();
5793
    assert!(a.push("origin", false).unwrap()[0].ok);
5794
    a.bookmark_create("develop", None).unwrap();
5795
    a.bookmark_switch("develop", false).unwrap();
5796
    write(&root.join("a"), "base.txt", b"base\nd1\n");
5797
    let d1 = a.commit("d1", &[]).unwrap();
5798
    assert!(a.push("origin", false).unwrap()[0].ok);
5799
5800
    // A clone has main only; origin/develop is a name all the same.
5801
    let c_root = root.join("c");
5802
    let mut c = Repo::clone(&url, &c_root).unwrap();
5803
    assert_eq!(c.config.bookmark, "main");
5804
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
5805
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
5806
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
5807
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
5808
5809
    // Switching makes the local bookmark from origin's.
5810
    c.bookmark_switch("develop", false).unwrap();
5811
    assert_eq!(c.config.bookmark, "develop");
5812
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
5813
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
5814
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
5815
    assert!(c.bookmark_switch("nowhere", false).is_err());
5816
5817
    // Both bookmarks move on the remote; one pull takes both.
5818
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
5819
    let d2 = a.commit("d2", &[]).unwrap();
5820
    assert!(a.push("origin", false).unwrap()[0].ok);
5821
    a.bookmark_switch("main", false).unwrap();
5822
    write(&root.join("a"), "m.txt", b"m\n");
5823
    let m = a.commit("m", &[]).unwrap();
5824
    assert!(a.push("origin", false).unwrap()[0].ok);
5825
    let r = c.pull("origin").unwrap();
5826
    assert!(r.changed && r.checked_out, "{r:?}");
5827
    assert_eq!(r.heads, vec![d2]);
5828
    assert_eq!(r.others, vec!["main".to_string()]);
5829
    assert!(c.resolve_heads("main").unwrap().contains(&m));
5830
    assert_eq!(
5831
        fs::read(c_root.join("base.txt")).unwrap(),
5832
        b"base\nd1\nd2\n"
5833
    );
5834
    let again = c.pull("origin").unwrap();
5835
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
5836
5837
    // A clone checks out the remote's default bookmark.
5838
    origin.config.set("workspace.bookmark", "develop").unwrap();
5839
    origin.save_config().unwrap();
5840
    let e = Repo::clone(&url, &root.join("e")).unwrap();
5841
    assert_eq!(e.config.bookmark, "develop");
5842
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
5843
    let reopened = Repo::open(&root.join("e")).unwrap();
5844
    assert_eq!(reopened.config.bookmark, "develop");
5845
    // REMOTE/NAME names the remote's bookmark to switch to.
5846
    let mut e = reopened;
5847
    e.bookmark_switch("origin/main", false).unwrap();
5848
    assert_eq!(e.config.bookmark, "main");
5849
    assert!(e.bookmark_heads().unwrap().contains(&m));
5850
}
5851
5852
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
5853
/// op restore goes back to an operation, files included, and undo takes
5854
/// the restore back whole; op revert undoes one operation alone; each
5855
/// operation's changes are described from the views.
5856
#[test]
5857
fn operations_can_be_read_restored_and_reverted() {
5858
    hermetic();
5859
    let dir = tempfile::tempdir().unwrap();
5860
    let root = dir.path();
5861
    let repo = Repo::init(root).unwrap();
5862
    write(root, "a.txt", b"a\n");
5863
    let first = repo.commit("first", &[]).unwrap();
5864
    write(root, "a.txt", b"a\nb\n");
5865
    let second = repo.commit("second", &[]).unwrap();
5866
    let at_second = repo.head_op().unwrap().0.to_hex();
5867
    repo.bookmark_create("keep", None).unwrap();
5868
    let created = repo.head_op().unwrap().0.to_hex();
5869
    write(root, "n.txt", b"n\n");
5870
    let third = repo.commit("third", &[]).unwrap();
5871
5872
    // What each operation changed.
5873
    let ops = repo.op_log().unwrap();
5874
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
5875
    assert!(
5876
        changes
5877
            .iter()
5878
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
5879
        "{changes:?}"
5880
    );
5881
    assert!(changes
5882
        .iter()
5883
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
5884
5885
    // Reading at an earlier operation.
5886
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
5887
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
5888
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
5889
    write(root, "z.txt", b"z\n");
5890
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
5891
    fs::remove_file(root.join("z.txt")).unwrap();
5892
    assert!(repo.resolve_op("zz").is_err());
5893
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
5894
5895
    // Restore goes back, files and all; undo takes it back whole.
5896
    repo.op_restore(&at_second, false).unwrap();
5897
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
5898
    assert!(!root.join("n.txt").exists());
5899
    repo.undo().unwrap();
5900
    let mut heads = repo.bookmark_heads().unwrap();
5901
    heads.sort();
5902
    let mut want = vec![second, third];
5903
    want.sort();
5904
    assert_eq!(heads, want);
5905
    assert!(
5906
        root.join("n.txt").exists(),
5907
        "the files came back with the undo"
5908
    );
5909
5910
    // Revert the bookmark's creation alone: the commit after it stays.
5911
    let r = repo.op_revert(&created).unwrap();
5912
    assert_eq!(r.reverted, vec!["keep".to_string()]);
5913
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
5914
    assert!(repo
5915
        .load_state(&repo.bookmark_heads().unwrap())
5916
        .unwrap()
5917
        .contains(&third));
5918
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
5919
    let _ = first;
5920
}
5921
5922
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
5923
/// from the status cache while every file is as the snapshot left it, and
5924
/// from a snapshot again as soon as one is not.
5925
#[test]
5926
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
5927
    hermetic();
5928
    let dir = tempfile::tempdir().unwrap();
5929
    let root = dir.path();
5930
    let repo = Repo::init(root).unwrap();
5931
    write(root, "a.txt", b"a\n");
5932
    write(root, "b.txt", b"b\n");
5933
    repo.commit("base", &[]).unwrap();
5934
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
5935
5936
    write(root, "a.txt", b"a\nmore\n");
5937
    assert_eq!(
5938
        repo.status_by_manifest().unwrap(),
5939
        None,
5940
        "no snapshot of the edit yet"
5941
    );
5942
    let snap = repo.snapshot_status("oxy status").unwrap();
5943
    assert_eq!(snap.statuses.len(), 1);
5944
    let cached = repo
5945
        .status_by_manifest()
5946
        .unwrap()
5947
        .expect("answered from the cache");
5948
    assert_eq!(cached.len(), 1);
5949
    assert_eq!(
5950
        (cached[0].path.as_str(), cached[0].status),
5951
        ("a.txt", ChangeStatus::Modified)
5952
    );
5953
5954
    // Any further change sends status back to a snapshot.
5955
    write(root, "a.txt", b"a\nmore\nand more\n");
5956
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
5957
    repo.snapshot_status("oxy status").unwrap();
5958
    assert!(repo.status_by_manifest().unwrap().is_some());
5959
    write(root, "new.txt", b"n\n");
5960
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
5961
    fs::remove_file(root.join("new.txt")).unwrap();
5962
    assert!(
5963
        repo.status_by_manifest().unwrap().is_some(),
5964
        "back as it was"
5965
    );
5966
    fs::remove_file(root.join("b.txt")).unwrap();
5967
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
5968
    write(root, "b.txt", b"b\n");
5969
5970
    // A commit leaves nothing uncommitted: clean again, no cache needed.
5971
    repo.snapshot_status("oxy status").unwrap();
5972
    repo.commit("more", &[]).unwrap();
5973
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
5974
}
5975
5976
/// oxygen#41: while the status cache holds, the working copy's diff is
5977
/// rendered from the stored working-copy change, and says exactly what a
5978
/// snapshot's diff says.
5979
#[test]
5980
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
5981
    hermetic();
5982
    let dir = tempfile::tempdir().unwrap();
5983
    let root = dir.path();
5984
    let repo = Repo::init(root).unwrap();
5985
    write(root, "a.txt", b"one\ntwo\nthree\n");
5986
    write(root, "gone.txt", b"bye\n");
5987
    repo.commit("base", &[]).unwrap();
5988
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
5989
    write(root, "new.txt", b"hello\n");
5990
    fs::remove_file(root.join("gone.txt")).unwrap();
5991
    let snap = repo.snapshot_status("oxy status").unwrap();
5992
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
5993
    assert!(
5994
        repo.status_by_manifest().unwrap().is_some(),
5995
        "the cache holds"
5996
    );
5997
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
5998
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
5999
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6000
}
6001
6002
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6003
/// while none has moved, the check stats the tracked files without listing
6004
/// the tree, and a file added or removed anywhere moves its directory's
6005
/// time, so the tree is listed again.
6006
#[test]
6007
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6008
    hermetic();
6009
    let dir = tempfile::tempdir().unwrap();
6010
    let root = dir.path();
6011
    let repo = Repo::init(root).unwrap();
6012
    write(root, "a.txt", b"a\n");
6013
    write(root, "sub/deep/b.txt", b"b\n");
6014
    repo.commit("base", &[]).unwrap();
6015
    // Out of the racy window: every file and directory a minute old.
6016
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6017
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6018
        fs::File::open(root.join(p))
6019
            .unwrap()
6020
            .set_modified(old)
6021
            .unwrap();
6022
    }
6023
    repo.snapshot_status("oxy status").unwrap();
6024
    repo.write_manifest(false, false).unwrap();
6025
    let m = repo.read_manifest().unwrap().unwrap().2;
6026
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6027
    assert_eq!(
6028
        repo.disk_differs_by_dirs(&m),
6029
        Some(false),
6030
        "no listing needed"
6031
    );
6032
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6033
6034
    // A same-size edit with a new time: found by its stat.
6035
    write(root, "sub/deep/b.txt", b"c\n");
6036
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6037
    write(root, "sub/deep/b.txt", b"b\n");
6038
    fs::File::open(root.join("sub/deep/b.txt"))
6039
        .unwrap()
6040
        .set_modified(old)
6041
        .unwrap();
6042
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6043
6044
    // A new file moves its directory's time: the tree must be listed.
6045
    write(root, "sub/deep/new.txt", b"n\n");
6046
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6047
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6048
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6049
    // A removed one too.
6050
    fs::remove_file(root.join("a.txt")).unwrap();
6051
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6052
}
6053
6054
/// oxygen#41: a commit right after a status takes the snapshot the status
6055
/// left (the status cache holds) rather than walking again, and commits
6056
/// exactly what a snapshot would have.
6057
#[test]
6058
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6059
    hermetic();
6060
    let dir = tempfile::tempdir().unwrap();
6061
    let root = dir.path();
6062
    let repo = Repo::init(root).unwrap();
6063
    write(root, "a.txt", b"a\nb\n");
6064
    write(root, ".oxyattributes", b"*.bin binary\n");
6065
    repo.commit("base", &[]).unwrap();
6066
    write(root, "a.txt", b"a\nB\n");
6067
    write(root, "new.txt", b"new\n");
6068
    let snap = repo.snapshot_status("oxy status").unwrap();
6069
    let cached = repo
6070
        .snapshot_from_cache()
6071
        .unwrap()
6072
        .expect("the cache holds");
6073
    assert_eq!(cached.wc_hash, snap.wc_hash);
6074
    assert_eq!(cached.statuses, snap.statuses);
6075
    assert!(
6076
        !cached.attributes.is_empty(),
6077
        "the .oxyattributes file was read"
6078
    );
6079
    let h = repo.commit("edit", &[]).unwrap();
6080
    let c = repo.store().get_change(&h).unwrap();
6081
    assert_eq!(
6082
        c.tree_ops.len() + c.edits.len(),
6083
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6084
    );
6085
    assert_eq!(
6086
        repo.status_by_manifest().unwrap(),
6087
        Some(vec![]),
6088
        "clean after the commit"
6089
    );
6090
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6091
}
6092
6093
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6094
/// stored insert's text blob only when it builds that file's graph, and
6095
/// builds the same graph a full load does.
6096
#[test]
6097
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6098
    hermetic();
6099
    let dir = tempfile::tempdir().unwrap();
6100
    let root = dir.path();
6101
    let repo = Repo::init(root).unwrap();
6102
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6103
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6104
    write(root, "big.txt", big.as_bytes());
6105
    write(root, "other.txt", other.as_bytes());
6106
    let h = repo.commit("two large files", &[]).unwrap();
6107
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6108
    let h2 = repo.commit("append", &[]).unwrap();
6109
6110
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6111
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6112
        FileContent::Text { bytes, .. } => bytes.clone(),
6113
        other => panic!("{other:?}"),
6114
    };
6115
    // Built on demand, every graph renders as the full load's.
6116
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6117
    let big_node = full.files["big.txt"].node;
6118
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6119
    repo.load_all_graphs(&mut hist).unwrap();
6120
    let rendered = hist.materialize();
6121
    for p in ["big.txt", "other.txt"] {
6122
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6123
    }
6124
6125
    // Without other.txt's text blob, history still loads and big.txt still
6126
    // builds: nothing read the other text.
6127
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6128
    assert_eq!(texts.len(), 2);
6129
    let content = |r: &ObjectRef| -> Vec<u8> {
6130
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6131
        blob.chunks
6132
            .iter()
6133
            .flat_map(|c| repo.store().get(c).unwrap().1)
6134
            .collect()
6135
    };
6136
    let other_text = texts
6137
        .iter()
6138
        .filter_map(|t| match t {
6139
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6140
            _ => None,
6141
        })
6142
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6143
        .unwrap();
6144
    fs::remove_file(repo.store().path_for(&other_text)).unwrap();
6145
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6146
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6147
    assert!(repo
6148
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6149
        .is_err());
6150
}
6151
6152
/// oxygen#35: the first status after a commit read and rendered every
6153
/// file (79 s and more than 14 GB on the Linux tree), because the
6154
/// manifest had no graph keys for files the commit added.
6155
#[test]
6156
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6157
    use std::os::unix::fs::PermissionsExt;
6158
    hermetic();
6159
    let dir = tempfile::tempdir().unwrap();
6160
    let root = dir.path();
6161
    let repo = Repo::init(root).unwrap();
6162
    let files = ["a.txt", "b.txt", "d/c.txt"];
6163
    for p in files {
6164
        write(root, p, format!("{p}\n").as_bytes());
6165
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6166
        fs::File::options()
6167
            .write(true)
6168
            .open(root.join(p))
6169
            .unwrap()
6170
            .set_modified(old)
6171
            .unwrap();
6172
    }
6173
    repo.commit("added", &[]).unwrap();
6174
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6175
    assert!(
6176
        m.entries.values().all(|e| e.graph.is_some()),
6177
        "keys recorded at commit"
6178
    );
6179
    // Unreadable files prove the next status reads none of them.
6180
    for p in files {
6181
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6182
    }
6183
    let snap = repo.snapshot_status("status").unwrap();
6184
    for p in files {
6185
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6186
    }
6187
    assert!(!snap.changed && snap.statuses.is_empty());
6188
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6189
}
6190
6191
/// oxygen#35: a checkout reads, renders and writes only the files whose
6192
/// graphs differ, and renders the rest a batch at a time.
6193
#[test]
6194
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6195
    use std::os::unix::fs::PermissionsExt;
6196
    hermetic();
6197
    let dir = tempfile::tempdir().unwrap();
6198
    let root = dir.path();
6199
    let origin = root.join("origin");
6200
    let mut repo = Repo::init(&origin).unwrap();
6201
    // More files than one batch holds.
6202
    let n = 2100;
6203
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6204
    for i in 0..n {
6205
        let p = format!("f/{i:04}.txt");
6206
        write(&origin, &p, format!("file {i}\n").as_bytes());
6207
        fs::File::options()
6208
            .write(true)
6209
            .open(origin.join(&p))
6210
            .unwrap()
6211
            .set_modified(old)
6212
            .unwrap();
6213
    }
6214
    repo.commit("many", &[]).unwrap();
6215
    repo.bookmark_create("feature", None).unwrap();
6216
    repo.bookmark_switch("feature", false).unwrap();
6217
    write(&origin, "f/0007.txt", b"changed\n");
6218
    repo.commit("one change", &[]).unwrap();
6219
6220
    // Switching back to main must not read the unchanged files.
6221
    for i in 0..n {
6222
        if i != 7 {
6223
            let p = origin.join(format!("f/{i:04}.txt"));
6224
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6225
        }
6226
    }
6227
    let r = repo.bookmark_switch("main", false).unwrap();
6228
    for i in 0..n {
6229
        let p = origin.join(format!("f/{i:04}.txt"));
6230
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6231
    }
6232
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6233
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6234
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6235
6236
    // A clone renders every file, across batches.
6237
    let c = root.join("clone");
6238
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6239
    for i in [0, 2047, 2048, n - 1] {
6240
        assert_eq!(
6241
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6242
            format!("file {i}\n").as_bytes()
6243
        );
6244
    }
6245
    let cloned = Repo::open(&c).unwrap();
6246
    assert!(cloned
6247
        .snapshot_status("status")
6248
        .unwrap()
6249
        .statuses
6250
        .is_empty());
6251
}
6252
6253
/// A file written just before the manifest (inside the racy window) is
6254
/// checked by its hash: trusted when equal, caught when edited in place
6255
/// with the same size and time.
6256
#[test]
6257
fn a_racy_manifest_entry_is_checked_by_hash() {
6258
    hermetic();
6259
    let dir = tempfile::tempdir().unwrap();
6260
    let root = dir.path();
6261
    let repo = Repo::init(root).unwrap();
6262
    write(root, "a.txt", b"one\n");
6263
    repo.commit("fresh", &[]).unwrap();
6264
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6265
    let t = fs::metadata(root.join("a.txt"))
6266
        .unwrap()
6267
        .modified()
6268
        .unwrap();
6269
    write(root, "a.txt", b"two\n");
6270
    fs::File::options()
6271
        .write(true)
6272
        .open(root.join("a.txt"))
6273
        .unwrap()
6274
        .set_modified(t)
6275
        .unwrap();
6276
    assert!(
6277
        !repo.clean_by_manifest().unwrap(),
6278
        "same size and time, other bytes"
6279
    );
6280
    assert_eq!(
6281
        statuses(&repo.snapshot_status("status").unwrap()),
6282
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6283
    );
6284
}
6285
6286
/// A fetch on one machine moves changes as stored, text blobs among the
6287
/// objects; a change whose text blob did not come is refused, not stored.
6288
#[test]
6289
fn a_raw_bundle_without_a_changes_text_is_refused() {
6290
    hermetic();
6291
    let dir = tempfile::tempdir().unwrap();
6292
    let root = dir.path();
6293
    let a = Repo::init(&root.join("a")).unwrap();
6294
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6295
    write(&root.join("a"), "big.txt", big.as_bytes());
6296
    let h = a.commit("big", &[]).unwrap();
6297
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6298
    assert_eq!(bundle.raw_changes.len(), 1);
6299
    assert!(bundle.changes.is_empty());
6300
    let b = Repo::init(&root.join("b")).unwrap();
6301
    let mut without = bundle.clone();
6302
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6303
    let e = b.import_bundle(&without, false).unwrap_err();
6304
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6305
    assert!(!b.store().has(&h));
6306
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6307
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6308
}
6309
6310
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6311
/// again was a second node for one Git path, so a file moved into it on
6312
/// another line, where the first node still stood, ended up in two places.
6313
/// An import now brings the directory back rather than make a new one.
6314
#[test]
6315
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6316
    hermetic();
6317
    if std::process::Command::new("git")
6318
        .arg("--version")
6319
        .output()
6320
        .is_err()
6321
    {
6322
        eprintln!("git not installed; skipping");
6323
        return;
6324
    }
6325
    let dir = tempfile::tempdir().unwrap();
6326
    let root = dir.path();
6327
    let g = root.join("src.git");
6328
    fs::create_dir_all(&g).unwrap();
6329
    let git = |args: &[&str]| -> String {
6330
        let out = std::process::Command::new("git")
6331
            .arg("-C")
6332
            .arg(&g)
6333
            .args([
6334
                "-c",
6335
                "user.name=Grace",
6336
                "-c",
6337
                "[email protected]",
6338
                "-c",
6339
                "commit.gpgsign=false",
6340
            ])
6341
            .args(args)
6342
            .output()
6343
            .unwrap();
6344
        assert!(
6345
            out.status.success(),
6346
            "git {args:?}: {}",
6347
            String::from_utf8_lossy(&out.stderr)
6348
        );
6349
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6350
    };
6351
    git(&["init", "-q", "-b", "main"]);
6352
    write(&g, "d/a.txt", b"a\n");
6353
    write(&g, "c/x.txt", b"x\n");
6354
    git(&["add", "."]);
6355
    git(&["commit", "-qm", "base"]);
6356
    // One line: move x into d while d still stands.
6357
    git(&["checkout", "-qb", "side"]);
6358
    git(&["mv", "c/x.txt", "d/x.txt"]);
6359
    git(&["commit", "-qm", "x into d"]);
6360
    // The other: d goes, comes back, and x moves into it too.
6361
    git(&["checkout", "-q", "main"]);
6362
    git(&["rm", "-q", "d/a.txt"]);
6363
    git(&["commit", "-qm", "d goes"]);
6364
    write(&g, "d/b.txt", b"b\n");
6365
    git(&["add", "."]);
6366
    git(&["commit", "-qm", "d comes back"]);
6367
    git(&["mv", "c/x.txt", "d/x.txt"]);
6368
    git(&["commit", "-qm", "x into d again"]);
6369
    git(&["merge", "-q", "--no-edit", "side"]);
6370
6371
    let repo = Repo::init(&root.join("o")).unwrap();
6372
    repo.import_git(&g, "main").unwrap();
6373
    let v = repo.verify_git_import(&g, "main").unwrap();
6374
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6375
    let st = repo
6376
        .load_state_history(&repo.bookmark_heads().unwrap())
6377
        .unwrap();
6378
    let view = st.tree().view();
6379
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6380
    // The directory is the one the first commit made.
6381
    // Commits made in one second tie on time: find the first by its message.
6382
    let first = repo
6383
        .log()
6384
        .unwrap()
6385
        .into_iter()
6386
        .find(|e| e.change.message.starts_with("base"))
6387
        .unwrap();
6388
    let base = repo
6389
        .load_state_history(&[first.hash])
6390
        .unwrap()
6391
        .tree()
6392
        .view();
6393
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6394
}
6395
6396
/// oxygen#30, the rest: a placement left under a directory another line
6397
/// removed is out of sight, so no diff reaches it; the merge that settles
6398
/// where the file is retires it.
6399
#[test]
6400
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6401
    hermetic();
6402
    if std::process::Command::new("git")
6403
        .arg("--version")
6404
        .output()
6405
        .is_err()
6406
    {
6407
        eprintln!("git not installed; skipping");
6408
        return;
6409
    }
6410
    let dir = tempfile::tempdir().unwrap();
6411
    let root = dir.path();
6412
    let g = root.join("src.git");
6413
    fs::create_dir_all(&g).unwrap();
6414
    let run = |args: &[&str]| {
6415
        std::process::Command::new("git")
6416
            .arg("-C")
6417
            .arg(&g)
6418
            .args([
6419
                "-c",
6420
                "user.name=Grace",
6421
                "-c",
6422
                "[email protected]",
6423
                "-c",
6424
                "commit.gpgsign=false",
6425
            ])
6426
            .args(args)
6427
            .output()
6428
            .unwrap()
6429
    };
6430
    let git = |args: &[&str]| {
6431
        let out = run(args);
6432
        assert!(
6433
            out.status.success(),
6434
            "git {args:?}: {}",
6435
            String::from_utf8_lossy(&out.stderr)
6436
        );
6437
    };
6438
    git(&["init", "-q", "-b", "main"]);
6439
    write(&g, "c/x.txt", b"x\n");
6440
    write(&g, "keep.txt", b"k\n");
6441
    git(&["add", "."]);
6442
    git(&["commit", "-qm", "base"]);
6443
    // One line renames the file within c; the other moves it out of c,
6444
    // which goes.
6445
    git(&["checkout", "-qb", "side"]);
6446
    git(&["mv", "c/x.txt", "c/y.txt"]);
6447
    git(&["commit", "-qm", "rename within c"]);
6448
    git(&["checkout", "-q", "main"]);
6449
    fs::create_dir_all(g.join("n")).unwrap();
6450
    git(&["mv", "c/x.txt", "n/x.txt"]);
6451
    git(&["commit", "-qm", "move out of c"]);
6452
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6453
    let _ = run(&["merge", "-q", "side"]);
6454
    let _ = run(&[
6455
        "rm",
6456
        "-q",
6457
        "--cached",
6458
        "--ignore-unmatch",
6459
        "c/y.txt",
6460
        "c/x.txt",
6461
    ]);
6462
    let _ = std::fs::remove_dir_all(g.join("c"));
6463
    write(&g, "n/x.txt", b"x\n");
6464
    git(&["add", "-A"]);
6465
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6466
6467
    let repo = Repo::init(&root.join("o")).unwrap();
6468
    repo.import_git(&g, "main").unwrap();
6469
    let v = repo.verify_git_import(&g, "main").unwrap();
6470
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6471
    let st = repo
6472
        .load_state_history(&repo.bookmark_heads().unwrap())
6473
        .unwrap();
6474
    let view = st.tree().view();
6475
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6476
    assert!(view.entries.contains_key("n/x.txt"));
6477
}
6478
6479
/// oxygen#30, orphans: a file added on one line into a directory the other
6480
/// line removed is placed where the tree cannot show it; Git's merge keeps
6481
/// the file, and the import's merge leaves exactly one of it.
6482
#[test]
6483
fn git_import_merge_leaves_no_orphan_behind() {
6484
    hermetic();
6485
    if std::process::Command::new("git")
6486
        .arg("--version")
6487
        .output()
6488
        .is_err()
6489
    {
6490
        eprintln!("git not installed; skipping");
6491
        return;
6492
    }
6493
    let dir = tempfile::tempdir().unwrap();
6494
    let root = dir.path();
6495
    let g = root.join("src.git");
6496
    fs::create_dir_all(&g).unwrap();
6497
    let git = |args: &[&str]| {
6498
        let out = std::process::Command::new("git")
6499
            .arg("-C")
6500
            .arg(&g)
6501
            .args([
6502
                "-c",
6503
                "user.name=Grace",
6504
                "-c",
6505
                "[email protected]",
6506
                "-c",
6507
                "commit.gpgsign=false",
6508
            ])
6509
            .args(args)
6510
            .output()
6511
            .unwrap();
6512
        assert!(
6513
            out.status.success(),
6514
            "git {args:?}: {}",
6515
            String::from_utf8_lossy(&out.stderr)
6516
        );
6517
    };
6518
    git(&["init", "-q", "-b", "main"]);
6519
    write(&g, "d/f.txt", b"f\n");
6520
    write(&g, "keep.txt", b"k\n");
6521
    git(&["add", "."]);
6522
    git(&["commit", "-qm", "base"]);
6523
    git(&["checkout", "-qb", "side"]);
6524
    write(&g, "d/new.txt", b"new\n");
6525
    git(&["add", "."]);
6526
    git(&["commit", "-qm", "add into d"]);
6527
    git(&["checkout", "-q", "main"]);
6528
    git(&["rm", "-q", "d/f.txt"]);
6529
    git(&["commit", "-qm", "d goes"]);
6530
    git(&["merge", "-q", "--no-edit", "side"]);
6531
6532
    let repo = Repo::init(&root.join("o")).unwrap();
6533
    repo.import_git(&g, "main").unwrap();
6534
    let v = repo.verify_git_import(&g, "main").unwrap();
6535
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6536
    let st = repo
6537
        .load_state_history(&repo.bookmark_heads().unwrap())
6538
        .unwrap();
6539
    let view = st.tree().view();
6540
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6541
    assert!(view.entries.contains_key("d/new.txt"));
6542
}
6543
6544
/// fsck checks a change's text as the blobs it is stored in, without
6545
/// decoding it: a missing text blob is an error named for the change.
6546
#[test]
6547
fn fsck_names_a_missing_text_blob() {
6548
    hermetic();
6549
    let dir = tempfile::tempdir().unwrap();
6550
    let root = dir.path();
6551
    let repo = Repo::init(root).unwrap();
6552
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6553
    write(root, "big.txt", big.as_bytes());
6554
    let h = repo.commit("big", &[]).unwrap();
6555
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6556
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6557
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6558
        panic!("a stored text")
6559
    };
6560
    fs::remove_file(repo.store().path_for(&b)).unwrap();
6561
    let rep = repo.fsck().unwrap();
6562
    assert!(rep.errors() > 0);
6563
    assert!(
6564
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6565
        "{:?}",
6566
        rep.problems
6567
    );
6568
}
6569
6570
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6571
/// reached with that remote's token and CA (a private subrepo then clones
6572
/// for anyone who can read the parent); another hub gets none of them.
6573
#[test]
6574
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6575
    hermetic();
6576
    let dir = tempfile::tempdir().unwrap();
6577
    let mut repo = Repo::init(dir.path()).unwrap();
6578
    repo.config
6579
        .set(
6580
            "remote.origin.url",
6581
            "https://Hub.example:7343/doomsdayone/metalgear",
6582
        )
6583
        .unwrap();
6584
    repo.config.set("remote.origin.token", "secret").unwrap();
6585
    repo.config
6586
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6587
        .unwrap();
6588
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6589
    assert_eq!(same.token.as_deref(), Some("secret"));
6590
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6591
    for other in [
6592
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6593
        "https://hub.example/doomsdayone/rstar-api",
6594
        "http://hub.example:7343/doomsdayone/rstar-api",
6595
    ] {
6596
        let o = repo.credentials_for(other);
6597
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6598
    }
6599
}
6600
6601
/// oxygen#47: a remote with no token of its own uses the user's credential
6602
/// store for its hub, and a nested checkout finds its parent's remote
6603
/// token there instead of keeping a copy.
6604
#[test]
6605
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
6606
    hermetic();
6607
    let home = tempfile::tempdir().unwrap();
6608
    let dir = tempfile::tempdir().unwrap();
6609
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
6610
    parent
6611
        .config
6612
        .set("remote.origin.url", "https://hub.example/o/parent")
6613
        .unwrap();
6614
    parent.save_config().unwrap();
6615
    assert_eq!(parent.remote_options("origin").token, None);
6616
    crate::credentials::Credentials::at(home.path())
6617
        .save("https://hub.example", "stored", Some("andy"), None)
6618
        .unwrap();
6619
    assert_eq!(
6620
        parent.remote_options("origin").token.as_deref(),
6621
        Some("stored")
6622
    );
6623
6624
    let empty_home = tempfile::tempdir().unwrap();
6625
    let nested = dir.path().join("deps").join("child");
6626
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
6627
    child
6628
        .config
6629
        .set("remote.origin.url", "https://hub.example/o/child")
6630
        .unwrap();
6631
    child.save_config().unwrap();
6632
    assert_eq!(child.remote_options("origin").token, None);
6633
    parent
6634
        .config
6635
        .set("remote.origin.token", "checkout")
6636
        .unwrap();
6637
    parent.save_config().unwrap();
6638
    assert_eq!(
6639
        child.remote_options("origin").token.as_deref(),
6640
        Some("checkout")
6641
    );
6642
    // Another hub's checkout token is not borrowed.
6643
    child
6644
        .config
6645
        .set("remote.origin.url", "https://other.example/o/child")
6646
        .unwrap();
6647
    assert_eq!(child.remote_options("origin").token, None);
6648
}
6649
6650
#[test]
6651
fn the_metadata_cache_survives_a_torn_tail() {
6652
    hermetic();
6653
    let dir = tempfile::tempdir().unwrap();
6654
    let root = dir.path();
6655
    let repo = Repo::init(root).unwrap();
6656
    write(root, "a.txt", b"1\n");
6657
    let h = repo.commit("first", &[]).unwrap();
6658
    let meta = repo.store().get_change_meta(&h).unwrap();
6659
    let cache = repo.store().dir().join("metas");
6660
    let len = fs::metadata(&cache).unwrap().len();
6661
    assert!(len > 0, "a change read is cached");
6662
    // A torn record at the end: the cache reads up to it and cuts it off.
6663
    fs::OpenOptions::new()
6664
        .append(true)
6665
        .open(&cache)
6666
        .unwrap()
6667
        .write_all(&[7; 20])
6668
        .unwrap();
6669
    let again = Repo::open(root).unwrap();
6670
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
6671
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
6672
}
6673
6674
#[test]
6675
fn a_manifest_that_does_not_check_reads_as_none() {
6676
    hermetic();
6677
    let dir = tempfile::tempdir().unwrap();
6678
    let root = dir.path();
6679
    let repo = Repo::init(root).unwrap();
6680
    write(root, "a.txt", b"1\n");
6681
    repo.commit("first", &[]).unwrap();
6682
    let path = repo.manifest_path();
6683
    let mut bytes = fs::read(&path).unwrap();
6684
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
6685
    let last = bytes.len() - 1;
6686
    bytes[last] ^= 1;
6687
    fs::write(&path, &bytes).unwrap();
6688
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
6689
    // The next status reads the files and writes it again.
6690
    let again = Repo::open(root).unwrap();
6691
    assert!(!again.snapshot("status").unwrap().changed);
6692
    assert!(again.read_manifest().unwrap().is_some());
6693
}
6694
6695
#[test]
6696
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
6697
    hermetic();
6698
    let dir = tempfile::tempdir().unwrap();
6699
    let root = dir.path();
6700
    let repo = Repo::init(root).unwrap();
6701
    write(root, "a.txt", b"1\n");
6702
    write(root, "b.txt", b"2\n");
6703
    // b.txt outside the racy window, so snapshots take it as unchanged.
6704
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6705
    fs::File::options()
6706
        .write(true)
6707
        .open(root.join("b.txt"))
6708
        .unwrap()
6709
        .set_modified(old)
6710
        .unwrap();
6711
    repo.commit("first", &[]).unwrap();
6712
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
6713
    repo.snapshot_status("status").unwrap();
6714
    write(root, "a.txt", b"1\n2\n");
6715
    repo.commit("second", &[]).unwrap();
6716
    assert!(
6717
        repo.clean_by_manifest().unwrap(),
6718
        "after a commit of one file"
6719
    );
6720
    // Edited, seen by a status, edited again, then committed: the status
6721
    // left the first edit's stat, which the commit must not keep.
6722
    write(root, "a.txt", b"1\n2\n3\n");
6723
    repo.snapshot_status("status").unwrap();
6724
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
6725
    repo.commit("third", &[]).unwrap();
6726
    assert!(
6727
        repo.clean_by_manifest().unwrap(),
6728
        "after an edit a status saw"
6729
    );
6730
}
6731
6732
#[test]
6733
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
6734
    hermetic();
6735
    let dir = tempfile::tempdir().unwrap();
6736
    let root = dir.path();
6737
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6738
    write(root, "a.txt", b"1\n2\n");
6739
    let a = repo.commit("A", &[]).unwrap();
6740
    repo.bookmark_create("develop", Some(&[a])).unwrap();
6741
    write(root, "a.txt", b"1\nX\n");
6742
    let c = repo.commit("C: 2 to X", &[]).unwrap();
6743
    repo.bookmark_switch("develop", false).unwrap();
6744
    write(root, "a.txt", b"1\nY\n");
6745
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
6746
    repo.bookmark_switch("main", false).unwrap();
6747
6748
    let err = repo.rebase(&c, &[d]).unwrap_err();
6749
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
6750
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
6751
    assert!(r.changed && r.checked_out);
6752
    let snap = repo.snapshot_status("status").unwrap();
6753
    assert!(
6754
        snap.base_snapshot.is_conflicted(),
6755
        "the conflict is in the working copy"
6756
    );
6757
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
6758
    assert!(text.contains('X') && text.contains('Y'), "{text}");
6759
6760
    write(root, "a.txt", b"1\nXY\n");
6761
    repo.commit("Resolve", &[]).unwrap();
6762
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
6763
    assert!(st.contains(&c) && st.contains(&d));
6764
    let files = st.materialize().files;
6765
    assert!(!files["a.txt"].is_conflicted());
6766
    assert!(
6767
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
6768
    );
6769
6770
    // A change the current bookmark does not hold is refused.
6771
    repo.bookmark_switch("develop", false).unwrap();
6772
    write(root, "b.txt", b"b\n");
6773
    let e = repo.commit("E", &[]).unwrap();
6774
    repo.bookmark_switch("main", false).unwrap();
6775
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
6776
    assert!(
6777
        err.to_string().contains("not on the current bookmark"),
6778
        "{err}"
6779
    );
6780
}
6781
6782
#[test]
6783
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
6784
    hermetic();
6785
    let dir = tempfile::tempdir().unwrap();
6786
    let root = dir.path();
6787
    let repo = Repo::init(root).unwrap();
6788
    write(root, "a.txt", b"a\n");
6789
    write(root, "kept.log", b"tracked\n");
6790
    repo.commit("first", &[]).unwrap();
6791
    write(root, "build.log", b"made\n");
6792
    let snap = repo.snapshot_status("status").unwrap();
6793
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
6794
    // A rule written afterwards leaves the added file out again, while the
6795
    // committed one stays tracked.
6796
    write(root, ".gitignore", b"*.log\n");
6797
    let snap = repo.snapshot_status("status").unwrap();
6798
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
6799
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
6800
    write(root, "kept.log", b"tracked, edited\n");
6801
    let snap = repo.snapshot_status("status").unwrap();
6802
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
6803
}
6804
6805
#[test]
6806
fn shed_graphs_come_back_the_same() {
6807
    hermetic();
6808
    let dir = tempfile::tempdir().unwrap();
6809
    let root = dir.path();
6810
    let repo = Repo::init(root).unwrap();
6811
    write(root, "a.txt", b"1\n2\n3\n");
6812
    write(root, "b.txt", b"x\n");
6813
    repo.commit("first", &[]).unwrap();
6814
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
6815
    repo.commit("second", &[]).unwrap();
6816
    let heads = repo.bookmark_heads().unwrap();
6817
    let mut st = repo.load_state_history(&heads).unwrap();
6818
    let view = st.tree().view();
6819
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
6820
        .iter()
6821
        .map(|p| view.entries[*p].node)
6822
        .collect();
6823
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6824
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6825
    assert_eq!(st.built_count(), 2);
6826
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
6827
    assert_eq!((shed, st.built_count()), (2, 0));
6828
    // A later change applies on top of the shed history.
6829
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
6830
    let h3 = repo.commit("third", &[]).unwrap();
6831
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
6832
    st.add_known(h3, skeleton, texts);
6833
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6834
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6835
    assert_eq!(after[1], before[1]);
6836
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
6837
}
6838
6839
#[test]
6840
fn many_edited_files_diff_in_parallel() {
6841
    // Enough edited files that the builder diffs them in parallel; the
6842
    // commit must hold exactly what is on disk, and a second snapshot
6843
    // must find nothing left to commit.
6844
    hermetic();
6845
    let dir = tempfile::tempdir().unwrap();
6846
    let root = dir.path();
6847
    let repo = Repo::init(root).unwrap();
6848
    let text = |i: usize, round: usize| {
6849
        let mut s = String::new();
6850
        for line in 0..50 {
6851
            if round > 0 && line % 7 == i % 7 {
6852
                s.push_str(&format!("edited {round} {i} {line}\n"));
6853
            } else {
6854
                s.push_str(&format!("file {i} line {line}\n"));
6855
            }
6856
        }
6857
        if round > 0 && i.is_multiple_of(3) {
6858
            s.push_str("appended\n");
6859
        }
6860
        s
6861
    };
6862
    for i in 0..40 {
6863
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
6864
    }
6865
    repo.commit("first", &[]).unwrap();
6866
    for i in 0..40 {
6867
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
6868
    }
6869
    let h = repo.commit("edit every file", &[]).unwrap();
6870
    let snap = repo.load_state(&[h]).unwrap().materialize();
6871
    for i in 0..40 {
6872
        let want = text(i, 1);
6873
        assert!(
6874
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
6875
            "d/f{i}.txt as committed"
6876
        );
6877
    }
6878
    assert!(
6879
        repo.commit("nothing", &[]).is_err(),
6880
        "nothing left to commit"
6881
    );
6882
}
6883
6884
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
6885
/// is known (fetch printed "up to date" while main was behind), a change
6886
/// only fetched resolves and says where it is, and a checkout whose only
6887
/// remote is not `origin` uses that one.
6888
#[test]
6889
fn a_fetched_change_shows_as_behind_and_resolves() {
6890
    hermetic();
6891
    let dir = tempfile::tempdir().unwrap();
6892
    let root = dir.path();
6893
    let origin = Repo::init(&root.join("origin")).unwrap();
6894
    drop(origin);
6895
    let url = root.join("origin").to_string_lossy().to_string();
6896
    let a = Repo::clone(&url, &root.join("a"))
6897
        .unwrap()
6898
        .with_home(root.join("home-a"));
6899
    write(&root.join("a"), "f.txt", b"one\n");
6900
    a.commit("one", &[]).unwrap();
6901
    a.push("origin", false).unwrap();
6902
    let b = Repo::clone(&url, &root.join("b"))
6903
        .unwrap()
6904
        .with_home(root.join("home-b"));
6905
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
6906
6907
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
6908
    let h2 = a.commit("two", &[]).unwrap();
6909
    a.push("origin", false).unwrap();
6910
    b.fetch("origin").unwrap();
6911
    // Fetched, not pulled: one behind, the change found and placed.
6912
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
6913
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
6914
    assert_eq!(
6915
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
6916
            .unwrap(),
6917
        h2
6918
    );
6919
    assert_eq!(
6920
        b.remote_only_location(&h2).unwrap().as_deref(),
6921
        Some("origin/main")
6922
    );
6923
    // Fetching again changes nothing: still behind, which is what the
6924
    // CLI now says rather than "up to date".
6925
    b.fetch("origin").unwrap();
6926
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
6927
    b.pull("origin").unwrap();
6928
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
6929
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
6930
6931
    // One remote, not called origin: it is the default.
6932
    let mut c = Repo::init(&root.join("c")).unwrap();
6933
    assert_eq!(c.default_remote(), "origin");
6934
    c.config.set("remote.earth.url", &url).unwrap();
6935
    assert_eq!(c.default_remote(), "earth");
6936
    c.config.set("remote.origin.url", &url).unwrap();
6937
    assert_eq!(c.default_remote(), "origin");
6938
}
6939
6940
/// oxygen#57: a clone from a relative local path records the remote as an
6941
/// absolute path, so fetch still finds it from inside the clone.
6942
#[test]
6943
fn a_clone_from_a_relative_path_records_it_absolute() {
6944
    hermetic();
6945
    let dir = tempfile::tempdir().unwrap();
6946
    let root = dir.path();
6947
    Repo::init(&root.join("origin")).unwrap();
6948
    let rel = crate::protocol::stored_url("relative/repo");
6949
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
6950
    assert_eq!(
6951
        crate::protocol::stored_url("https://hub.example/o/n"),
6952
        "https://hub.example/o/n"
6953
    );
6954
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
6955
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
6956
    // A bucket is kept as written: it is not a path.
6957
    assert_eq!(
6958
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
6959
        "s3://bucket/prefix?profile=p"
6960
    );
6961
    let url = root.join("origin").to_string_lossy().to_string();
6962
    let b = Repo::clone(&url, &root.join("b")).unwrap();
6963
    assert_eq!(b.config.remotes["origin"], url);
6964
    b.fetch("origin").unwrap();
6965
}
6966
6967
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
6968
/// and gets its subrepos at their pins from this workspace's copies, with
6969
/// their remotes pointing where the subrepos come from.
6970
#[test]
6971
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
6972
    hermetic();
6973
    let dir = tempfile::tempdir().unwrap();
6974
    let root = dir.path();
6975
    Repo::init(&root.join("lib-origin")).unwrap();
6976
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6977
    let lib = Repo::clone(&lib_url, &root.join("lib"))
6978
        .unwrap()
6979
        .with_home(root.join("home"));
6980
    write(&root.join("lib"), "lib.txt", b"v1\n");
6981
    let l1 = lib.commit("lib v1", &[]).unwrap();
6982
    assert!(lib.push("origin", false).unwrap()[0].ok);
6983
6984
    let app_dir = root.join("app");
6985
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
6986
    write(&app_dir, "main.txt", b"app\n");
6987
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6988
    app.commit("app with lib", &[]).unwrap();
6989
    // A second bookmark, and the main workspace on another.
6990
    app.bookmark_create("develop", None).unwrap();
6991
    app.bookmark_create("feature", None).unwrap();
6992
    let mut app = app;
6993
    app.bookmark_switch("feature", false).unwrap();
6994
    assert_eq!(app.config.bookmark, "feature");
6995
6996
    // The library's origin goes away: the subrepo must come from here.
6997
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
6998
    let heads = app.resolve_heads("develop").unwrap();
6999
    let ws = app
7000
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7001
        .unwrap();
7002
    assert_eq!(
7003
        ws.config.bookmark, "develop",
7004
        "the new workspace is on develop"
7005
    );
7006
    assert_eq!(
7007
        app.config.bookmark, "feature",
7008
        "and this one stays on its own"
7009
    );
7010
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7011
    assert_eq!(
7012
        sub.config.remotes["origin"], lib_url,
7013
        "its origin is the subrepo's URL"
7014
    );
7015
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7016
    assert_eq!(
7017
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7018
        b"v1\n"
7019
    );
7020
}
7021
7022
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7023
/// operators and the predicates, over a small graph with two heads and
7024
/// a rename.
7025
#[test]
7026
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7027
    hermetic();
7028
    let dir = tempfile::tempdir().unwrap();
7029
    let root = dir.path();
7030
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7031
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7032
        .unwrap();
7033
    write(root, "src/a.rs", b"one\n");
7034
    let a = repo.commit("first: add a", &[]).unwrap();
7035
    write(root, "src/a.rs", b"one\ntwo\n");
7036
    let b = repo.commit("second: grow a", &[]).unwrap();
7037
    // A second head, independent of b: a new file on top of a.
7038
    repo.checkout(&[a], false, "checkout a").unwrap();
7039
    write(root, "docs/notes.md", b"notes\n");
7040
    let c = repo.commit("third: notes", &[]).unwrap();
7041
    // Back to both heads, then rename a.rs: the node keeps its identity.
7042
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7043
        .unwrap();
7044
    fs::remove_file(root.join("src/a.rs")).unwrap();
7045
    write(root, "src/z.rs", b"one\ntwo\n");
7046
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7047
    let wc = repo.working_copy().unwrap().0;
7048
    // A saved revset is checked when set.
7049
    repo.set_user_config("revset.mine", "author(me) & ::main")
7050
        .unwrap();
7051
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7052
    let set = |src: &str| -> Vec<ChangeHash> {
7053
        let mut v = repo.revset(src).unwrap().hashes;
7054
        v.sort();
7055
        v
7056
    };
7057
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7058
        let mut v = hs.to_vec();
7059
        v.sort();
7060
        v
7061
    };
7062
7063
    // Changes commute: a new file depends on nothing and the rename on the
7064
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7065
    // copy on the three heads b, c, d.
7066
    let heads = sorted(&repo.bookmark_heads().unwrap());
7067
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7068
    assert!(heads.contains(&d) && heads.contains(&c));
7069
    // Symbols and closures.
7070
    assert_eq!(set("main"), heads);
7071
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7072
    assert_eq!(set("@"), vec![wc]);
7073
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7074
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7075
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7076
    assert_eq!(
7077
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7078
        sorted(&[a, b])
7079
    );
7080
    // Ranges: what main has beyond b, and `..` forms.
7081
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7082
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7083
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7084
    // Operators and precedence: ~ binds tighter than &, & than |.
7085
    assert_eq!(
7086
        set(&format!("::main ~ #{}", d.short(12))),
7087
        sorted(&[a, b, c])
7088
    );
7089
    assert_eq!(
7090
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7091
        sorted(&[b, c])
7092
    );
7093
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7094
    // Relations.
7095
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7096
    head_deps.sort();
7097
    head_deps.dedup();
7098
    assert_eq!(set("deps(main)"), head_deps);
7099
    let on_a: Vec<ChangeHash> = [b, c, d]
7100
        .into_iter()
7101
        .filter(|h| meta(h).deps.contains(&a))
7102
        .collect();
7103
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7104
    assert_eq!(set("heads(::main)"), heads);
7105
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7106
    assert_eq!(
7107
        set(&format!(
7108
            "heads(#{} | #{} | #{})",
7109
            a.short(12),
7110
            b.short(12),
7111
            c.short(12)
7112
        )),
7113
        sorted(&[b, c])
7114
    );
7115
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7116
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7117
    assert_eq!(set("none()"), vec![]);
7118
    // Predicates: author by name, email, key prefix and `me`.
7119
    let key = repo.config.author_key.unwrap();
7120
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7121
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7122
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7123
    assert_eq!(set("author(me) & ::main").len(), 4);
7124
    assert_eq!(set("author(nobody)"), vec![]);
7125
    assert_eq!(set("description(notes)"), vec![c]);
7126
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7127
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7128
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7129
    // touches follows the node through the rename, in the current state.
7130
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7131
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7132
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7133
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7134
    // Newest first in the result order.
7135
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7136
    // The saved revset, and errors that say what is wrong.
7137
    assert_eq!(set("mine()").len(), 4);
7138
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7139
    assert!(e.contains("unknown function nosuch()"), "{e}");
7140
    let e = repo.revset("main &").unwrap_err().to_string();
7141
    assert!(e.contains("at character"), "{e}");
7142
    let e = repo.revset("zzzz").unwrap_err().to_string();
7143
    assert!(e.contains("no change matches"), "{e}");
7144
    let e = repo
7145
        .revset_with_budget("::main", std::time::Duration::ZERO)
7146
        .unwrap_err()
7147
        .to_string();
7148
    assert!(e.contains("budget"), "{e}");
7149
    // The log entries carry the bookmark's heads and the working copy.
7150
    let entries = repo.log_revset("::@").unwrap();
7151
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7152
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7153
    // push); then a signed change, a tag, and a revocation.
7154
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7155
    assert_eq!(set("signed_by(me)"), vec![]);
7156
    repo.sign_change(&d).unwrap();
7157
    assert_eq!(set("signed_by(me)"), vec![d]);
7158
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7159
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7160
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7161
    assert_eq!(set("delegated()"), vec![]);
7162
    assert_eq!(set("revoked()"), vec![]);
7163
    assert_eq!(set("attested(tag)"), vec![]);
7164
    repo.tag_create("v1", &[b], "first").unwrap();
7165
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7166
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7167
    assert_eq!(set("attested(receipt)"), vec![]);
7168
    assert_eq!(set("built(test)"), vec![]);
7169
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7170
    assert!(e.contains("tag, receipt or ref"), "{e}");
7171
    repo.revoke_identity(&key, "test").unwrap();
7172
    assert_eq!(set("revoked()"), vec![d]);
7173
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7174
}
7175
7176
#[test]
7177
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7178
    let dir = tempfile::tempdir().unwrap();
7179
    let root = dir.path();
7180
    let home = root.join("home");
7181
    // Ada's identity lives in the user file; repository `a` pins the same
7182
    // key in its own file, repository `b` names none.
7183
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7184
    let (key, _) = a
7185
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7186
        .unwrap();
7187
    a.config.set("author.key", &key.to_hex()).unwrap();
7188
    a.save_config().unwrap();
7189
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7190
    let r = a
7191
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7192
        .unwrap();
7193
    assert_eq!(
7194
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7195
        r.new.to_hex(),
7196
        "the user file follows"
7197
    );
7198
    assert_eq!(
7199
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7200
        r.new.to_hex(),
7201
        "the pinning repository follows"
7202
    );
7203
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7204
    assert_eq!(
7205
        b.config.author_key,
7206
        Some(r.new),
7207
        "a checkout without a pin follows the user file"
7208
    );
7209
    // A repository-scoped identity leaves the user file alone.
7210
    let other_home = root.join("home2");
7211
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7212
    let (ck, _) = c
7213
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7214
        .unwrap();
7215
    assert!(!other_home.join("config.toml").exists());
7216
    let r2 = c.rotate_identity().unwrap();
7217
    assert_ne!(r2.new, ck);
7218
    assert_eq!(
7219
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7220
        r2.new.to_hex()
7221
    );
7222
    assert!(
7223
        !other_home.join("config.toml").exists(),
7224
        "a repository-scoped identity stays repository-scoped"
7225
    );
7226
    // Several delegates in one rotation; a repeat is refused.
7227
    let (d1, d2) = (
7228
        SecretKey::generate().identity("D1", "d1@x", 1),
7229
        SecretKey::generate().identity("D2", "d2@x", 1),
7230
    );
7231
    let r3 = c
7232
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7233
        .unwrap();
7234
    assert_eq!(r3.identity.delegates.len(), 2);
7235
    assert!(c
7236
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7237
        .is_err());
7238
}
7239
7240
/// Two unrelated histories that both add the same file, joined by two
7241
/// independent merges on two branches, then those branches merged: Git
7242
/// merges identical additions cleanly, and the import must too (#71,
7243
/// found in VS Code's history).
7244
#[test]
7245
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7246
    // Batches of one: every merge renders apart from the state, where a
7247
    // file whose graph the state had built came out empty (#71).
7248
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7249
    hermetic();
7250
    if std::process::Command::new("git")
7251
        .arg("--version")
7252
        .output()
7253
        .is_err()
7254
    {
7255
        eprintln!("git not installed; skipping");
7256
        return;
7257
    }
7258
    let dir = tempfile::tempdir().unwrap();
7259
    let root = dir.path();
7260
    let g = root.join("src.git");
7261
    fs::create_dir_all(&g).unwrap();
7262
    let git = |args: &[&str]| -> String {
7263
        let out = std::process::Command::new("git")
7264
            .arg("-C")
7265
            .arg(&g)
7266
            .args([
7267
                "-c",
7268
                "user.name=Grace",
7269
                "-c",
7270
                "[email protected]",
7271
                "-c",
7272
                "commit.gpgsign=false",
7273
            ])
7274
            .args(args)
7275
            .output()
7276
            .unwrap();
7277
        assert!(
7278
            out.status.success(),
7279
            "git {args:?}: {}",
7280
            String::from_utf8_lossy(&out.stderr)
7281
        );
7282
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7283
    };
7284
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7285
    // History A: main.
7286
    git(&["init", "-q", "-b", "main"]);
7287
    write(&g, "gulpfile.js", text);
7288
    write(&g, "a.txt", b"a\n");
7289
    git(&["add", "."]);
7290
    git(&["commit", "-q", "-m", "A root"]);
7291
    // History B: an unrelated root adding the same file, identical.
7292
    git(&["checkout", "-q", "--orphan", "fork"]);
7293
    git(&["rm", "-q", "-r", "--cached", "."]);
7294
    for f in ["gulpfile.js", "a.txt"] {
7295
        let _ = fs::remove_file(g.join(f));
7296
    }
7297
    write(&g, "gulpfile.js", text);
7298
    write(&g, "b.txt", b"b\n");
7299
    git(&["add", "."]);
7300
    git(&["commit", "-q", "-m", "B root"]);
7301
    // Two branches from main, each joining B on its own.
7302
    git(&["checkout", "-q", "-b", "one", "main"]);
7303
    git(&[
7304
        "merge",
7305
        "-q",
7306
        "--no-ff",
7307
        "--allow-unrelated-histories",
7308
        "-m",
7309
        "join on one",
7310
        "fork",
7311
    ]);
7312
    git(&["checkout", "-q", "-b", "two", "main"]);
7313
    write(&g, "a.txt", b"a\ntwo\n");
7314
    git(&["commit", "-q", "-am", "work on two"]);
7315
    git(&[
7316
        "merge",
7317
        "-q",
7318
        "--no-ff",
7319
        "--allow-unrelated-histories",
7320
        "-m",
7321
        "join on two",
7322
        "fork",
7323
    ]);
7324
    // Then the two joins meet, and the file is reformatted after.
7325
    git(&["checkout", "-q", "main"]);
7326
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7327
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7328
    write(
7329
        &g,
7330
        "gulpfile.js",
7331
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7332
    );
7333
    git(&["commit", "-q", "-am", "after"]);
7334
7335
    let dest = root.join("dest");
7336
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7337
    repo.import_git(&g, "main").unwrap();
7338
    let v = repo.verify_git_import(&g, "main").unwrap();
7339
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7340
    assert_eq!(
7341
        fs::read(dest.join("gulpfile.js")).unwrap(),
7342
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7343
    );
7344
}
7345
7346
/// As above, but the two joins keep different copies (each branch had a
7347
/// different version when it joined), and later work edits each copy:
7348
/// the shape of VS Code's c67ef57cda90 (#71).
7349
#[test]
7350
fn git_import_joins_where_each_join_kept_a_different_copy() {
7351
    // Batches of one: every merge renders apart from the state, where a
7352
    // file whose graph the state had built came out empty (#71).
7353
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7354
    hermetic();
7355
    if std::process::Command::new("git")
7356
        .arg("--version")
7357
        .output()
7358
        .is_err()
7359
    {
7360
        eprintln!("git not installed; skipping");
7361
        return;
7362
    }
7363
    let dir = tempfile::tempdir().unwrap();
7364
    let root = dir.path();
7365
    let g = root.join("src.git");
7366
    fs::create_dir_all(&g).unwrap();
7367
    let run = |args: &[&str]| {
7368
        std::process::Command::new("git")
7369
            .arg("-C")
7370
            .arg(&g)
7371
            .args([
7372
                "-c",
7373
                "user.name=Grace",
7374
                "-c",
7375
                "[email protected]",
7376
                "-c",
7377
                "commit.gpgsign=false",
7378
            ])
7379
            .args(args)
7380
            .output()
7381
            .unwrap()
7382
    };
7383
    let git = |args: &[&str]| -> String {
7384
        let out = run(args);
7385
        assert!(
7386
            out.status.success(),
7387
            "git {args:?}: {}",
7388
            String::from_utf8_lossy(&out.stderr)
7389
        );
7390
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7391
    };
7392
    git(&["init", "-q", "-b", "main"]);
7393
    write(
7394
        &g,
7395
        "gulpfile.js",
7396
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7397
    );
7398
    git(&["add", "."]);
7399
    git(&["commit", "-q", "-m", "A root"]);
7400
    write(
7401
        &g,
7402
        "gulpfile.js",
7403
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7404
    );
7405
    git(&["commit", "-q", "-am", "whitespace"]);
7406
    git(&["checkout", "-q", "--orphan", "fork"]);
7407
    git(&["rm", "-q", "-r", "--cached", "."]);
7408
    let _ = fs::remove_file(g.join("gulpfile.js"));
7409
    write(
7410
        &g,
7411
        "gulpfile.js",
7412
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7413
    );
7414
    git(&["add", "."]);
7415
    git(&["commit", "-q", "-m", "B root"]);
7416
    // Branch one joins B keeping main's copy; branch two keeps B's.
7417
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7418
        git(&["checkout", "-q", "-b", branch, "main"]);
7419
        let _ = run(&[
7420
            "merge",
7421
            "-q",
7422
            "--no-ff",
7423
            "--allow-unrelated-histories",
7424
            "-m",
7425
            "join",
7426
            "fork",
7427
        ]);
7428
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7429
        git(&["add", "gulpfile.js"]);
7430
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7431
    }
7432
    // Each branch then edits its copy.
7433
    git(&["checkout", "-q", "one"]);
7434
    write(
7435
        &g,
7436
        "gulpfile.js",
7437
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7438
    );
7439
    git(&["commit", "-q", "-am", "tslint on one"]);
7440
    git(&["checkout", "-q", "two"]);
7441
    write(
7442
        &g,
7443
        "gulpfile.js",
7444
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7445
    );
7446
    write(&g, "extra.txt", b"x\n");
7447
    write(&g, "more.txt", b"m\n");
7448
    git(&["add", "."]);
7449
    git(&["commit", "-q", "-am", "fmt on two"]);
7450
    // They meet: resolved by hand.
7451
    git(&["checkout", "-q", "one"]);
7452
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7453
    write(
7454
        &g,
7455
        "gulpfile.js",
7456
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7457
    );
7458
    git(&["add", "gulpfile.js"]);
7459
    git(&["commit", "-q", "-m", "merge two into one"]);
7460
7461
    let dest = root.join("dest");
7462
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7463
    repo.import_git(&g, "one").unwrap();
7464
    let v = repo.verify_git_import(&g, "one").unwrap();
7465
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7466
}