OXYGENHUB
# 69953b507188 oxygen / crates / oxy-core / src / repo / tests.rs
267.9 KiB · Rust · last changed Commit a resolution by paths, and amend only some paths 18 days 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
/// oxygen#118 (Metal Gear): a resolution commits by paths, leaving other
247
/// work uncommitted, so long as it takes every file it resolves; and
248
/// `amend PATHS` folds only those paths into the head.
249
#[test]
250
fn resolutions_and_amends_take_paths() {
251
    hermetic();
252
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
253
    let root = dir.path();
254
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
255
        .unwrap();
256
    // The conflict resolved, and other work beside it.
257
    write(root, "f.txt", b"a\nX\nc\n");
258
    write(root, "notes.txt", b"pending\n");
259
    let s = repo.snapshot("status").unwrap();
260
    assert!(s.resolves);
261
    let err = repo
262
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["notes.txt".into()]))
263
        .unwrap_err()
264
        .to_string();
265
    assert!(
266
        err.contains("takes every file it resolves") && err.contains("f.txt"),
267
        "{err}"
268
    );
269
    let (h4, partial) = repo
270
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["f.txt".into()]))
271
        .unwrap();
272
    assert!(partial);
273
    assert_eq!(
274
        repo.store().get_change(&h4).unwrap().kind,
275
        ChangeKind::Resolution
276
    );
277
    assert!(!repo
278
        .load_state(&[h4])
279
        .unwrap()
280
        .materialize()
281
        .is_conflicted());
282
    let s = repo.snapshot("status").unwrap();
283
    assert_eq!(
284
        statuses(&s),
285
        vec![("notes.txt".into(), ChangeStatus::Added)],
286
        "the other work waits"
287
    );
288
289
    // amend PATHS: only those paths join the head; it keeps its ChangeId.
290
    // On the resolution, so the bookmark has one head to amend.
291
    let h5 = repo.commit("notes", &[h4]).unwrap();
292
    let id5 = repo.store().get_change(&h5).unwrap().change_id;
293
    write(root, "notes.txt", b"pending\nmore\n");
294
    write(root, "other.txt", b"later\n");
295
    let h6 = repo
296
        .amend_paths(Some("notes, amended"), &["notes.txt".into()])
297
        .unwrap();
298
    let c6 = repo.store().get_change(&h6).unwrap();
299
    assert_eq!((c6.change_id, c6.message.as_str()), (id5, "notes, amended"));
300
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h6]);
301
    let snap6 = repo.load_state(&[h6]).unwrap().materialize();
302
    assert!(
303
        matches!(&snap6.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"pending\nmore\n")
304
    );
305
    assert!(
306
        !snap6.files.contains_key("other.txt"),
307
        "other.txt stays out"
308
    );
309
    let s = repo.snapshot("status").unwrap();
310
    assert_eq!(
311
        statuses(&s),
312
        vec![("other.txt".into(), ChangeStatus::Added)]
313
    );
314
}
315
316
#[test]
317
fn resolution_may_keep_both_sides_or_neither() {
318
    hermetic();
319
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
320
    let root = dir.path();
321
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
322
        .unwrap();
323
    // Keep both sides in a chosen order.
324
    write(root, "f.txt", b"a\nX\nB\nc\n");
325
    let h = repo.commit("both", &[]).unwrap();
326
    let snap = repo.load_state(&[h]).unwrap().materialize();
327
    assert!(!snap.is_conflicted());
328
    assert!(
329
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
330
    );
331
    // Undo and instead drop the whole region.
332
    repo.undo().unwrap();
333
    write(root, "f.txt", b"a\nc\n");
334
    let h = repo.commit("neither", &[]).unwrap();
335
    let snap = repo.load_state(&[h]).unwrap().materialize();
336
    assert!(!snap.is_conflicted());
337
    assert!(
338
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
339
    );
340
}
341
342
#[test]
343
fn name_conflict_resolved_by_removing_a_candidate() {
344
    hermetic();
345
    let dir = tempfile::tempdir().unwrap();
346
    let root = dir.path();
347
    let repo = Repo::init(root).unwrap();
348
    write(root, "keep.txt", b"k\n");
349
    let h1 = repo.commit("base", &[]).unwrap();
350
    write(root, "new.txt", b"one\n");
351
    repo.commit("one", &[]).unwrap();
352
    repo.checkout(&[h1], false, "checkout").unwrap();
353
    write(root, "new.txt", b"two\n");
354
    repo.commit("two", &[]).unwrap();
355
    let r = repo
356
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
357
        .unwrap();
358
    assert!(r.conflicted);
359
    assert!(
360
        root.join("new.txt.oxy-conflict-1").exists()
361
            && root.join("new.txt.oxy-conflict-2").exists()
362
    );
363
    assert!(!root.join("new.txt").exists());
364
    // Candidate numbering follows change-hash order, so pick by content:
365
    // keep the "two" candidate under the real name and drop the other.
366
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
367
        (1, 2)
368
    } else {
369
        (2, 1)
370
    };
371
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
372
    fs::rename(
373
        root.join(format!("new.txt.oxy-conflict-{keep}")),
374
        root.join("new.txt"),
375
    )
376
    .unwrap();
377
    let h = repo.commit("pick two", &[]).unwrap();
378
    assert_eq!(
379
        repo.store().get_change(&h).unwrap().kind,
380
        ChangeKind::Resolution
381
    );
382
    // The resolution does not touch keep.txt, so it does not depend on h1;
383
    // the bookmark keeps both as heads and their union is the state.
384
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
385
    assert_eq!(heads, [h1, h].into_iter().collect());
386
    let snap = repo
387
        .load_state(&repo.bookmark_heads().unwrap())
388
        .unwrap()
389
        .materialize();
390
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
391
    assert_eq!(
392
        snap.files.keys().cloned().collect::<Vec<_>>(),
393
        ["keep.txt", "new.txt"]
394
    );
395
    assert!(
396
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
397
    );
398
}
399
400
#[test]
401
fn identities_and_signed_commits() {
402
    hermetic();
403
    let dir = tempfile::tempdir().unwrap();
404
    let root = dir.path();
405
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
406
    write(root, "a.txt", b"a\n");
407
    let h0 = repo.commit("unsigned", &[]).unwrap();
408
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
409
    assert_eq!(
410
        repo.store().get_change(&h0).unwrap().author,
411
        ObjectRef::ZERO
412
    );
413
414
    let (key, id) = repo
415
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
416
        .unwrap();
417
    assert_eq!(id.hash(), key);
418
    assert_eq!(repo.config.author_key, Some(key));
419
    // Config survives reopen; the secret key is found again.
420
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
421
    assert_eq!(reopened.config.author_key, Some(key));
422
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
423
424
    // Default core.sign = seal: commits carry the author but no signature.
425
    write(root, "a.txt", b"a\nb\n");
426
    let h1 = repo.commit("authored", &[]).unwrap();
427
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
428
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
429
    // Signing later works too.
430
    repo.sign_change(&h1).unwrap();
431
    assert!(
432
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
433
    );
434
435
    repo.config.set("core.sign", "change").unwrap();
436
    repo.save_config().unwrap();
437
    write(root, "a.txt", b"a\nb\nc\n");
438
    let h2 = repo.commit("signed", &[]).unwrap();
439
    assert_eq!(
440
        repo.verify_change(&h2).unwrap(),
441
        SignatureStatus::Valid {
442
            key,
443
            name: "Ada".into(),
444
            email: "[email protected]".into(),
445
            sealed: false,
446
            revoked: false
447
        }
448
    );
449
450
    // A signature by a key that is not the author or a delegate is rejected
451
    // when the change names an author; an anonymous change (made before any
452
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
453
    let other = SecretKey::generate();
454
    let other_id = other.identity("Mallory", "[email protected]", 0);
455
    let other_key = repo.store().put_identity(&other_id).unwrap();
456
    write(root, "a.txt", b"a\nb\nc\nd\n");
457
    repo.config.set("core.sign", "seal").unwrap();
458
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
459
    let forged = other.sign(Domain::Change, &other_key, &h3);
460
    repo.store().put_signature(&h3, &forged).unwrap();
461
    assert!(
462
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
463
    );
464
    let adopted = other.sign(Domain::Change, &other_key, &h0);
465
    repo.store().put_signature(&h0, &adopted).unwrap();
466
    assert!(
467
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
468
    );
469
470
    // Tampering with the stored signature invalidates it.
471
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
472
    sig.ed[0] ^= 1;
473
    repo.store().put_signature(&h2, &sig).unwrap();
474
    assert!(matches!(
475
        repo.verify_change(&h2).unwrap(),
476
        SignatureStatus::Invalid(_)
477
    ));
478
479
    // Without the secret key, signing at commit fails cleanly.
480
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
481
    write(root, "a.txt", b"z\n");
482
    assert!(no_keys.commit("cannot sign", &[]).is_err());
483
}
484
485
#[test]
486
fn checkout_moves_the_working_copy() {
487
    hermetic();
488
    let dir = tempfile::tempdir().unwrap();
489
    let root = dir.path();
490
    let repo = Repo::init(root).unwrap();
491
    write(root, "a.txt", b"one\n");
492
    write(root, "sub/deep/b.txt", b"b\n");
493
    let h1 = repo.commit("first", &[]).unwrap();
494
    write(root, "a.txt", b"two\n");
495
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
496
    write(root, "bin.dat", &[0, 1, 2, 3]);
497
    let h2 = repo.commit("second", &[]).unwrap();
498
499
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
500
    assert_eq!(
501
        r,
502
        CheckoutReport {
503
            written: 2,
504
            removed: 1,
505
            conflicted: false,
506
            notes: vec![],
507
            lacks: 1,
508
        }
509
    );
510
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
511
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
512
    assert!(!root.join("bin.dat").exists());
513
    let (_, wc) = repo.working_copy().unwrap();
514
    assert_eq!(wc.deps, vec![h1]);
515
    assert!(
516
        !repo.snapshot("status").unwrap().changed,
517
        "checkout leaves a clean working copy"
518
    );
519
    // The bookmark still points at h2.
520
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
521
522
    // Dirty working copy refuses without --discard.
523
    write(root, "a.txt", b"dirty\n");
524
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
525
    let r = repo
526
        .checkout(&[h2], true, "oxy checkout --discard")
527
        .unwrap();
528
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
529
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
530
    assert!(!root.join("sub").exists(), "empty directories are pruned");
531
    assert_eq!(r.removed, 1);
532
    assert!(!repo.snapshot("status").unwrap().changed);
533
534
    // Refuses to write through a symlinked directory.
535
    #[cfg(unix)]
536
    {
537
        fs::remove_dir_all(root.join("sub")).ok();
538
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
539
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
540
    }
541
}
542
543
#[test]
544
fn large_files_are_chunked_and_read_back() {
545
    hermetic();
546
    let dir = tempfile::tempdir().unwrap();
547
    let repo = Repo::init(dir.path()).unwrap();
548
    let mut big = vec![0u8; 700 * 1024];
549
    for (i, b) in big.iter_mut().enumerate() {
550
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
551
    }
552
    let r = repo.store_blob(&big).unwrap();
553
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
554
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
555
    assert_eq!(repo.read_blob(&r).unwrap(), big);
556
    assert_eq!(Repo::blob_ref(&big), r);
557
}
558
559
#[test]
560
fn clone_push_pull_with_seals_and_attestations() {
561
    hermetic();
562
    let dir = tempfile::tempdir().unwrap();
563
    let root = dir.path();
564
    let origin_path = root.join("origin");
565
    let origin = Repo::init(&origin_path).unwrap();
566
    let origin_url = origin_path.to_string_lossy().to_string();
567
568
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
569
    let mut a = Repo::clone(&origin_url, &root.join("a"))
570
        .unwrap()
571
        .with_home(root.join("home-a"));
572
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
573
    let (key_a, _) = a
574
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
575
        .unwrap();
576
    write(&root.join("a"), "f.txt", b"a\n");
577
    let h1 = a.commit("first", &[]).unwrap();
578
    let results = a.push("origin", false).unwrap();
579
    assert!(results[0].ok, "{}", results[0].reason);
580
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
581
    // The change was sealed at push and the reference attested.
582
    assert!(
583
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
584
    );
585
    assert_eq!(
586
        origin.verify_change(&h1).unwrap(),
587
        SignatureStatus::Unsigned
588
    );
589
    let serial_of = |att: &SignedAttest| match att.attest.body {
590
        AttestBody::Ref { serial, .. } => serial,
591
        _ => unreachable!(),
592
    };
593
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
594
    // A bookmark new to the remote starts at the clock (past any deleted
595
    // namesake's serial); later updates count up from there.
596
    let first = serial_of(&att);
597
    assert!(first > 1_000_000_000_000, "{first}");
598
    let again = a.push("origin", false).unwrap();
599
    assert!(again[0].ok && again[0].reason.contains("up to date"));
600
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
601
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
602
603
    // B clones and sees the file and the seal.
604
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
605
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
606
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
607
    assert!(matches!(
608
        b.authenticate_change(&h1).unwrap(),
609
        SignatureStatus::Valid { sealed: true, .. }
610
    ));
611
612
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
613
    write(&root.join("b"), "f.txt", b"a\nb\n");
614
    let h2 = b.commit("second", &[]).unwrap();
615
    assert!(b.push("origin", false).unwrap()[0].ok);
616
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
617
618
    // A commits an independent change; push is refused until A pulls.
619
    write(&root.join("a"), "g.txt", b"g\n");
620
    let h3 = a.commit("third", &[]).unwrap();
621
    assert!(a.push("origin", false).is_err());
622
    let pr = a.pull("origin").unwrap();
623
    assert!(pr.changed && pr.checked_out);
624
    let mut want = vec![h2, h3];
625
    want.sort();
626
    assert_eq!(pr.heads, want);
627
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
628
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
629
    let results = a.push("origin", false).unwrap();
630
    assert!(results[0].ok, "{}", results[0].reason);
631
    let mut origin_heads = origin.bookmark_heads().unwrap();
632
    origin_heads.sort();
633
    assert_eq!(origin_heads, want);
634
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
635
    assert_eq!(serial_of(&att), first + 1);
636
637
    // B pulls and ends up identical.
638
    let pr = b.pull("origin").unwrap();
639
    assert_eq!(pr.heads, want);
640
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
641
    assert!(!b.snapshot("status").unwrap().changed);
642
643
    // Concurrent edits of the same line: the union is a reified conflict.
644
    write(&root.join("a"), "f.txt", b"a\nA\n");
645
    a.commit("a-edit", &[]).unwrap();
646
    a.push("origin", false).unwrap();
647
    write(&root.join("b"), "f.txt", b"a\nB\n");
648
    b.commit("b-edit", &[]).unwrap();
649
    let pr = b.pull("origin").unwrap();
650
    assert!(pr.changed && pr.checked_out);
651
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
652
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
653
    write(&root.join("b"), "f.txt", b"a\nAB\n");
654
    let hr = b.commit("resolve", &[]).unwrap();
655
    assert_eq!(
656
        b.store().get_change(&hr).unwrap().kind,
657
        ChangeKind::Resolution
658
    );
659
    assert!(b.push("origin", false).unwrap()[0].ok);
660
    a.pull("origin").unwrap();
661
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
662
    // The resolution depends on the conflicting edits, but nothing depends
663
    // on "third" (it only added g.txt), so it stays a head beside it.
664
    let mut want = vec![hr, h3];
665
    want.sort();
666
    assert_eq!(a.bookmark_heads().unwrap(), want);
667
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
668
}
669
670
#[test]
671
fn receive_push_rejects_bad_updates() {
672
    hermetic();
673
    let dir = tempfile::tempdir().unwrap();
674
    let root = dir.path();
675
    let origin = Repo::init(&root.join("origin")).unwrap();
676
    let url = root.join("origin").to_string_lossy().to_string();
677
    let mut a = Repo::clone(&url, &root.join("a"))
678
        .unwrap()
679
        .with_home(root.join("home"));
680
    let (key, _) = a
681
        .create_identity("Ada", "a@b", IdentityScope::Repo)
682
        .unwrap();
683
    write(&root.join("a"), "f.txt", b"x\n");
684
    let h1 = a.commit("one", &[]).unwrap();
685
    assert!(a.push("origin", false).unwrap()[0].ok);
686
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
687
    let s1 = origin
688
        .store()
689
        .put_state(&StateObject::new(vec![h1]))
690
        .unwrap();
691
692
    // Missing head.
693
    let ghost = origin
694
        .store()
695
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
696
        .unwrap();
697
    let r = origin
698
        .receive_push(
699
            Bundle::default(),
700
            vec![RefUpdate {
701
                name: "main".into(),
702
                old_state: s1,
703
                new_state: ghost,
704
                force: false,
705
                attestation: None,
706
            }],
707
            None,
708
            vec![],
709
        )
710
        .unwrap();
711
    assert!(
712
        !r[0].ok && r[0].reason.contains("missing"),
713
        "{}",
714
        r[0].reason
715
    );
716
717
    // Stale old_state.
718
    let r = origin
719
        .receive_push(
720
            Bundle::default(),
721
            vec![RefUpdate {
722
                name: "main".into(),
723
                old_state: empty,
724
                new_state: s1,
725
                force: false,
726
                attestation: None,
727
            }],
728
            None,
729
            vec![],
730
        )
731
        .unwrap();
732
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
733
734
    // Non-fast-forward without force is refused; with force it passes.
735
    let r = origin
736
        .receive_push(
737
            Bundle::default(),
738
            vec![RefUpdate {
739
                name: "main".into(),
740
                old_state: s1,
741
                new_state: empty,
742
                force: false,
743
                attestation: None,
744
            }],
745
            None,
746
            vec![],
747
        )
748
        .unwrap();
749
    assert!(
750
        !r[0].ok && r[0].reason.contains("fast-forward"),
751
        "{}",
752
        r[0].reason
753
    );
754
    let r = origin
755
        .receive_push(
756
            Bundle::default(),
757
            vec![RefUpdate {
758
                name: "main".into(),
759
                old_state: s1,
760
                new_state: empty,
761
                force: true,
762
                attestation: None,
763
            }],
764
            None,
765
            vec![],
766
        )
767
        .unwrap();
768
    assert!(r[0].ok);
769
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
770
771
    // Attestation with a stale serial is a rollback and is refused.
772
    let sa = a
773
        .sign_attest(&Attest {
774
            repo: a.id().unwrap(),
775
            hlc: Hlc::now(),
776
            body: AttestBody::Ref {
777
                name: "main".into(),
778
                old_state: empty,
779
                new_state: s1,
780
                serial: 1,
781
            },
782
        })
783
        .unwrap();
784
    let r = origin
785
        .receive_push(
786
            Bundle::default(),
787
            vec![RefUpdate {
788
                name: "main".into(),
789
                old_state: empty,
790
                new_state: s1,
791
                force: false,
792
                attestation: Some(sa.clone()),
793
            }],
794
            None,
795
            vec![],
796
        )
797
        .unwrap();
798
    assert!(
799
        !r[0].ok && r[0].reason.contains("serial"),
800
        "{}",
801
        r[0].reason
802
    );
803
    // An attestation for a different update is refused too.
804
    let sa2 = a
805
        .sign_attest(&Attest {
806
            repo: a.id().unwrap(),
807
            hlc: Hlc::now(),
808
            body: AttestBody::Ref {
809
                name: "main".into(),
810
                old_state: s1,
811
                new_state: empty,
812
                serial: 5,
813
            },
814
        })
815
        .unwrap();
816
    let r = origin
817
        .receive_push(
818
            Bundle::default(),
819
            vec![RefUpdate {
820
                name: "main".into(),
821
                old_state: empty,
822
                new_state: s1,
823
                force: false,
824
                attestation: Some(sa2),
825
            }],
826
            None,
827
            vec![],
828
        )
829
        .unwrap();
830
    assert!(
831
        !r[0].ok && r[0].reason.contains("describe"),
832
        "{}",
833
        r[0].reason
834
    );
835
    let _ = key;
836
}
837
838
#[test]
839
fn user_config_supplies_defaults_and_clones_sign() {
840
    hermetic();
841
    let dir = tempfile::tempdir().unwrap();
842
    let root = dir.path();
843
    let home = root.join("home");
844
    let origin = Repo::init(&root.join("origin")).unwrap();
845
    let url = root.join("origin").to_string_lossy().to_string();
846
847
    // Identity at user scope: the repository file stays free of author keys.
848
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
849
    let (key, _) = a
850
        .create_identity("Ada", "[email protected]", IdentityScope::User)
851
        .unwrap();
852
    assert!(!a.config.repo_layer().contains_key("author.key"));
853
    assert_eq!(a.config.author_key, Some(key));
854
    assert!(home.join("config.toml").exists());
855
    a.set_user_config("core.sign", "change").unwrap();
856
    assert!(a.config.sign_changes);
857
858
    // Repository settings override user settings and are the only ones saved.
859
    a.config.set("core.sign", "seal").unwrap();
860
    a.save_config().unwrap();
861
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
862
    assert!(!again.config.sign_changes);
863
    assert_eq!(again.config.author_key, Some(key));
864
    assert_eq!(
865
        read_config_file(&root.join("a/.oxy/config"))
866
            .unwrap()
867
            .get("core.sign")
868
            .map(String::as_str),
869
        Some("seal")
870
    );
871
872
    // A fresh clone made by this user signs with the user-level identity,
873
    // even though the clone's store has never seen the identity object.
874
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
875
    assert!(b.config.sign_changes);
876
    write(&root.join("b"), "f.txt", b"f\n");
877
    let h = b.commit("signed from a clone", &[]).unwrap();
878
    assert!(
879
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
880
    );
881
    assert!(b.push("origin", false).unwrap()[0].ok);
882
    assert!(matches!(
883
        origin.verify_change(&h).unwrap(),
884
        SignatureStatus::Valid { .. }
885
    ));
886
}
887
888
#[test]
889
fn format1_repositories_are_migrated_on_open() {
890
    hermetic();
891
    use crate::oplog::{Format1Op, Format1View};
892
    let dir = tempfile::tempdir().unwrap();
893
    let root = dir.path();
894
    let repo = Repo::init(root).unwrap();
895
    write(root, "a.txt", b"a\n");
896
    let h1 = repo.commit("one", &[]).unwrap();
897
    let (wc_hash, _) = repo.working_copy().unwrap();
898
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
899
    let mut v1 = Format1View::default();
900
    v1.bookmarks.insert("main".into(), vec![]);
901
    v1.workspaces.insert(repo.workspace(), wc_hash);
902
    let init = Format1Op {
903
        parents: vec![],
904
        hlc: Hlc::default(),
905
        command: "oxy init".into(),
906
        view: v1.clone(),
907
    };
908
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
909
    v1.bookmarks.insert("main".into(), vec![h1]);
910
    let commit = Format1Op {
911
        parents: vec![init_ref],
912
        hlc: Hlc::default(),
913
        command: "oxy commit".into(),
914
        view: v1,
915
    };
916
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
917
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
918
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
919
    drop(repo);
920
921
    let repo = Repo::open(root).unwrap();
922
    assert_eq!(
923
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
924
        FORMAT_LINE
925
    );
926
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
927
    let ops = repo.op_log().unwrap();
928
    assert_eq!(
929
        ops.iter()
930
            .map(|(_, o)| o.command.as_str())
931
            .collect::<Vec<_>>(),
932
        ["oxy commit", "oxy init"]
933
    );
934
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
935
    assert!(!repo.snapshot("status").unwrap().changed);
936
    // Reopening again is a no-op.
937
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
938
}
939
940
#[test]
941
fn undo_skips_snapshot_operations() {
942
    hermetic();
943
    let dir = tempfile::tempdir().unwrap();
944
    let root = dir.path();
945
    let repo = Repo::init(root).unwrap();
946
    write(root, "a.txt", b"a\n");
947
    let h1 = repo.commit("a", &[]).unwrap();
948
    // A later command snapshots new edits on top of the commit.
949
    write(root, "b.txt", b"b\n");
950
    let s = repo.snapshot("oxy status").unwrap();
951
    assert!(s.changed);
952
    assert!(repo.head_op().unwrap().1.is_snapshot());
953
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
954
    // Undo must undo the commit, not the snapshot.
955
    repo.undo().unwrap();
956
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
957
    let s = repo.snapshot("oxy status").unwrap();
958
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
959
    assert_eq!(
960
        paths,
961
        ["a.txt", "b.txt"],
962
        "both files are back in the working copy"
963
    );
964
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
965
    // Only snapshots remain above `init`, so there is nothing left to undo.
966
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
967
    assert!(repo.undo().is_err());
968
}
969
970
#[test]
971
fn independent_changes_commute_and_make_multiple_heads() {
972
    hermetic();
973
    let dir = tempfile::tempdir().unwrap();
974
    let root = dir.path();
975
    let repo = Repo::init(root).unwrap();
976
    write(root, "a.txt", b"a\n");
977
    let h1 = repo.commit("a", &[]).unwrap();
978
    write(root, "b.txt", b"b\n");
979
    let h2 = repo.commit("b", &[]).unwrap();
980
    let c2 = repo.store().get_change(&h2).unwrap();
981
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
982
    let mut heads = repo.bookmark_heads().unwrap();
983
    heads.sort();
984
    let mut want = vec![h1, h2];
985
    want.sort();
986
    assert_eq!(heads, want);
987
    // Editing a.txt depends on h1 only.
988
    write(root, "a.txt", b"a\na2\n");
989
    let h3 = repo.commit("a2", &[]).unwrap();
990
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
991
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
992
    assert_eq!(heads, [h2, h3].into_iter().collect());
993
    // Explicit dependency.
994
    write(root, "c.txt", b"c\n");
995
    let h4 = repo.commit("c", &[h2]).unwrap();
996
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
997
}
998
999
#[test]
1000
fn mode_change_and_text_binary_switch() {
1001
    hermetic();
1002
    let dir = tempfile::tempdir().unwrap();
1003
    let root = dir.path();
1004
    let repo = Repo::init(root).unwrap();
1005
    write(root, "run.sh", b"#!/bin/sh\n");
1006
    repo.commit("add script", &[]).unwrap();
1007
    #[cfg(unix)]
1008
    {
1009
        use std::os::unix::fs::PermissionsExt;
1010
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1011
        let s = repo.snapshot("status").unwrap();
1012
        assert_eq!(
1013
            statuses(&s),
1014
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
1015
        );
1016
        let h = repo.commit("exec", &[]).unwrap();
1017
        let snap = repo.load_state(&[h]).unwrap().materialize();
1018
        assert!(snap.files["run.sh"].mode.exec);
1019
    }
1020
    // Text → binary → text.
1021
    write(root, "run.sh", b"\0binary");
1022
    let h = repo.commit("binary", &[]).unwrap();
1023
    let snap = repo.load_state(&[h]).unwrap().materialize();
1024
    assert!(snap.files["run.sh"].mode.opaque);
1025
    write(root, "run.sh", b"text again\n");
1026
    let h = repo.commit("text", &[]).unwrap();
1027
    let snap = repo.load_state(&[h]).unwrap().materialize();
1028
    assert!(!snap.files["run.sh"].mode.opaque);
1029
    assert!(
1030
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
1031
    );
1032
    assert!(!snap.is_conflicted());
1033
}
1034
1035
#[test]
1036
fn trust_policy_governs_pushes_and_fetches() {
1037
    hermetic();
1038
    let dir = tempfile::tempdir().unwrap();
1039
    let root = dir.path();
1040
    let origin = Repo::init(&root.join("origin")).unwrap();
1041
    let url = root.join("origin").to_string_lossy().to_string();
1042
1043
    // A is the root. Before the policy, an unsigned push from B is fine.
1044
    let mut a = Repo::clone(&url, &root.join("a"))
1045
        .unwrap()
1046
        .with_home(root.join("home-a"));
1047
    let (key_a, _) = a
1048
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1049
        .unwrap();
1050
    let mut b = Repo::clone(&url, &root.join("b"))
1051
        .unwrap()
1052
        .with_home(root.join("home-b"));
1053
    write(&root.join("b"), "b.txt", b"b\n");
1054
    b.commit("unsigned before policy", &[]).unwrap();
1055
    assert!(b.push("origin", false).unwrap()[0].ok);
1056
1057
    // A creates the policy and pushes it; origin now enforces it.
1058
    write(&root.join("a"), "a.txt", b"a\n");
1059
    a.commit("a", &[]).unwrap();
1060
    let sp = a.policy_init().unwrap();
1061
    assert_eq!(sp.policy.serial, 1);
1062
    a.pull("origin").unwrap();
1063
    let results = a.push("origin", false).unwrap();
1064
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1065
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1066
1067
    // B pulls the policy. Without an identity B cannot push at all.
1068
    b.pull("origin").unwrap();
1069
    assert!(
1070
        b.current_policy().unwrap().is_some(),
1071
        "the policy arrived with the fetch"
1072
    );
1073
    assert!(b.push("origin", false).is_err());
1074
    // With an identity the policy does not list, the push is rejected by origin.
1075
    let (key_b, id_b) = b
1076
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1077
        .unwrap();
1078
    write(&root.join("b"), "b.txt", b"b2\n");
1079
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1080
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1081
    let r = b.push("origin", false).unwrap();
1082
    assert!(
1083
        !r[0].ok && r[0].reason.contains("may not update"),
1084
        "{:?}",
1085
        r
1086
    );
1087
1088
    // A grants B (identity handed over as a file) and publishes the policy.
1089
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1090
    assert_eq!(sp.policy.serial, 2);
1091
    let r = a.push("origin", false).unwrap();
1092
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1093
    // B must fetch the new policy before pushing.
1094
    assert!(b
1095
        .push("origin", false)
1096
        .unwrap_or_else(|e| vec![RefResult {
1097
            name: "main".into(),
1098
            ok: false,
1099
            reason: e.to_string()
1100
        }])
1101
        .iter()
1102
        .all(|x| !x.ok));
1103
    b.pull("origin").unwrap();
1104
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1105
    let r = b.push("origin", false).unwrap();
1106
    assert!(r[0].ok, "{:?}", r);
1107
    // Origin verified B's change under the policy.
1108
    let heads = origin.bookmark_heads().unwrap();
1109
    for h in &heads {
1110
        let c = origin.store().get_change(h).unwrap();
1111
        if c.author == key_b {
1112
            origin
1113
                .change_allowed(
1114
                    h,
1115
                    &origin.current_policy().unwrap().unwrap().1.policy,
1116
                    "main",
1117
                )
1118
                .unwrap();
1119
        }
1120
    }
1121
1122
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1123
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1124
    forged.serial = 3;
1125
    forged.roots = vec![key_b];
1126
    let fh = forged.hash();
1127
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
1128
    let forged = SignedPolicy {
1129
        policy: forged,
1130
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1131
    };
1132
    let r = origin
1133
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1134
        .unwrap();
1135
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1136
    let stale = a.current_policy().unwrap().unwrap().1;
1137
    let mut old = stale.clone();
1138
    old.policy.serial = 1;
1139
    let r = origin
1140
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1141
        .unwrap();
1142
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1143
1144
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1145
    a.pull("origin").unwrap();
1146
    a.policy_revoke(&key_b).unwrap();
1147
    let r = a.push("origin", false).unwrap();
1148
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1149
    b.pull("origin").unwrap();
1150
    write(&root.join("b"), "b.txt", b"b3\n");
1151
    b.commit("b3", &[]).unwrap();
1152
    let r = b.push("origin", false).unwrap();
1153
    assert!(!r[0].ok, "{:?}", r);
1154
1155
    // A clone by a third party receives and verifies everything.
1156
    let c = Repo::clone(&url, &root.join("c"))
1157
        .unwrap()
1158
        .with_home(root.join("home-c"));
1159
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
1160
    assert!(c
1161
        .current_policy()
1162
        .unwrap()
1163
        .unwrap()
1164
        .1
1165
        .policy
1166
        .roots
1167
        .contains(&key_a));
1168
    assert!(!c.snapshot("status").unwrap().changed);
1169
}
1170
1171
#[test]
1172
fn gc_packs_objects_and_history_still_works() {
1173
    hermetic();
1174
    let dir = tempfile::tempdir().unwrap();
1175
    let root = dir.path();
1176
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1177
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1178
        .unwrap();
1179
    repo.set_user_config("core.sign", "change").unwrap();
1180
    write(root, "a.txt", b"one\n");
1181
    let h1 = repo.commit("one", &[]).unwrap();
1182
    write(root, "a.txt", b"two\n");
1183
    write(root, "big.bin", &vec![0u8; 100_000]);
1184
    let h2 = repo.commit("two", &[]).unwrap();
1185
    // Several snapshots leave superseded working-copy versions behind.
1186
    for i in 0..5 {
1187
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1188
        repo.snapshot("status").unwrap();
1189
    }
1190
    write(root, "a.txt", b"two\n");
1191
    repo.snapshot("status").unwrap();
1192
    let before = repo.store().list().unwrap();
1193
    assert!(repo.store().loose_count().unwrap() > 0);
1194
1195
    // With the default retention every operation's view is a root: nothing prunes.
1196
    let r = repo.gc(true).unwrap();
1197
    assert_eq!(r.packed.objects, before.len());
1198
    assert_eq!(r.pruned.objects, 0);
1199
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1200
    assert_eq!(repo.store().list().unwrap(), before);
1201
1202
    // With zero retention only the current view is a root: superseded
1203
    // working copies go, everything reachable stays.
1204
    repo.config.set("core.op-retention", "0").unwrap();
1205
    repo.save_config().unwrap();
1206
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
1207
    let r = repo.gc(true).unwrap();
1208
    assert!(r.pruned.objects >= 5, "{r:?}");
1209
    let after = repo.store().list().unwrap();
1210
    assert!(after.len() < before.len());
1211
    assert!(after.contains(&h1) && after.contains(&h2));
1212
    for (_, op) in repo.op_log().unwrap() {
1213
        assert!(!op.command.is_empty(), "operation objects are all kept");
1214
    }
1215
    // Everything still works from the pruned, packed store.
1216
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1217
    assert!(matches!(
1218
        repo.verify_change(&h2).unwrap(),
1219
        SignatureStatus::Valid { .. }
1220
    ));
1221
    assert_eq!(repo.log().unwrap().len(), 3);
1222
    repo.checkout(&[h1], false, "checkout").unwrap();
1223
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1224
    repo.checkout(&[h2], false, "checkout").unwrap();
1225
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1226
    assert!(!repo.snapshot("status").unwrap().changed);
1227
    // Grace period defers pruning of young garbage.
1228
    write(root, "a.txt", b"three\n");
1229
    repo.commit("three", &[]).unwrap();
1230
    let r = repo.gc(false).unwrap();
1231
    assert_eq!(r.pruned.objects, 0);
1232
    assert!(r.pruned.deferred > 0);
1233
    let r = repo.gc(true).unwrap();
1234
    assert!(r.pruned.objects > 0);
1235
    assert_eq!(repo.log().unwrap().len(), 4);
1236
    // Restoring the default retention makes the old views roots again; the
1237
    // working copies they name were pruned, which gc tolerates.
1238
    repo.config.set("core.op-retention", "90").unwrap();
1239
    repo.save_config().unwrap();
1240
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1241
    let r = repo.gc(false).unwrap();
1242
    assert_eq!(r.pruned.objects, 0);
1243
    assert_eq!(repo.log().unwrap().len(), 4);
1244
}
1245
1246
#[test]
1247
fn describe_amend_abandon_heads() {
1248
    hermetic();
1249
    let dir = tempfile::tempdir().unwrap();
1250
    let root = dir.path();
1251
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1252
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1253
        .unwrap();
1254
    repo.set_user_config("core.sign", "change").unwrap();
1255
    write(root, "a.txt", b"one\n");
1256
    let h1 = repo.commit("first", &[]).unwrap();
1257
    write(root, "a.txt", b"one\ntwo\n");
1258
    let h2 = repo.commit("secnod", &[]).unwrap();
1259
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1260
1261
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1262
    let h2b = repo.describe(&h2, "second").unwrap();
1263
    assert_ne!(h2b, h2);
1264
    let c = repo.store().get_change(&h2b).unwrap();
1265
    assert_eq!(
1266
        (c.change_id, c.message.as_str(), c.deps.clone()),
1267
        (id2, "second", vec![h1])
1268
    );
1269
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
1270
    assert!(matches!(
1271
        repo.verify_change(&h2b).unwrap(),
1272
        SignatureStatus::Valid { .. }
1273
    ));
1274
    let s = repo.snapshot("status").unwrap();
1275
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
1276
    assert_eq!(
1277
        repo.resolve_change(&id2.short(8)).unwrap(),
1278
        h2b,
1279
        "the old object is no longer reachable from the log"
1280
    );
1281
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1282
    let h1b = repo.describe(&h1, "first, described").unwrap();
1283
    assert_ne!(h1b, h1);
1284
    let heads = repo.bookmark_heads().unwrap();
1285
    assert_eq!(heads.len(), 1);
1286
    let top = repo.store().get_change(&heads[0]).unwrap();
1287
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
1288
    assert!(
1289
        matches!(
1290
            repo.verify_change(&heads[0]).unwrap(),
1291
            SignatureStatus::Valid { .. }
1292
        ),
1293
        "rewritten own change is re-signed"
1294
    );
1295
    let (_, wc) = repo.working_copy().unwrap();
1296
    assert_eq!(
1297
        wc.deps,
1298
        vec![heads[0]],
1299
        "the working copy follows the rewrite"
1300
    );
1301
    assert!(!repo.snapshot("status").unwrap().changed);
1302
    let snap = repo.load_state(&heads).unwrap().materialize();
1303
    assert!(
1304
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1305
    );
1306
1307
    // amend: fold an edit into the head; the result is one change from h1.
1308
    write(root, "a.txt", b"one\ntwo\nthree\n");
1309
    write(root, "b.txt", b"b\n");
1310
    let h2c = repo.amend(None).unwrap();
1311
    let c = repo.store().get_change(&h2c).unwrap();
1312
    assert_eq!(c.change_id, id2);
1313
    assert_eq!(c.message, "second");
1314
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
1315
    assert_eq!(
1316
        repo.log().unwrap().len(),
1317
        3,
1318
        "working copy, amended head, first"
1319
    );
1320
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
1321
    assert!(
1322
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1323
    );
1324
    assert!(snap.files.contains_key("b.txt"));
1325
    assert!(!repo.snapshot("status").unwrap().changed);
1326
    assert!(
1327
        repo.amend(None).is_err(),
1328
        "clean working copy and no message"
1329
    );
1330
    let h2d = repo.amend(Some("second, amended")).unwrap();
1331
    assert_eq!(
1332
        repo.store().get_change(&h2d).unwrap().message,
1333
        "second, amended"
1334
    );
1335
1336
    // abandon: the head goes, its content stays as uncommitted work.
1337
    repo.abandon(&h2d).unwrap();
1338
    assert_eq!(
1339
        repo.bookmark_heads().unwrap(),
1340
        vec![h1b],
1341
        "the described first change is the head again"
1342
    );
1343
    let s = repo.snapshot("status").unwrap();
1344
    let paths: Vec<_> = s
1345
        .statuses
1346
        .iter()
1347
        .map(|p| (p.path.as_str(), p.status))
1348
        .collect();
1349
    assert_eq!(
1350
        paths,
1351
        vec![
1352
            ("a.txt", ChangeStatus::Modified),
1353
            ("b.txt", ChangeStatus::Added)
1354
        ]
1355
    );
1356
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1357
    let h3 = repo.commit("recommitted", &[]).unwrap();
1358
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1359
    // undo brings the abandoned head back.
1360
    repo.undo().unwrap();
1361
    repo.undo().unwrap();
1362
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
1363
1364
    // Abandoning a non-head whose dependent references its atoms reifies
1365
    // the references (here: a.txt vanishes with it, so the dependent's edit
1366
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
1367
    let base = repo.bookmark_heads().unwrap()[0];
1368
    let base_change = repo.store().get_change(&base).unwrap();
1369
    let h1_now = base_change.deps[0];
1370
    let notes = repo.abandon(&h1_now).unwrap();
1371
    assert!(
1372
        !notes.is_empty(),
1373
        "the dependent's edit of a.txt was reified"
1374
    );
1375
    let heads = repo.bookmark_heads().unwrap();
1376
    let after = repo.load_state(&heads).unwrap().materialize();
1377
    assert!(
1378
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1379
        "{:?}",
1380
        after.files.keys()
1381
    );
1382
    repo.undo().unwrap();
1383
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
1384
    write(root, "c.txt", b"c\n");
1385
    let hc = repo.commit("c", &[]).unwrap();
1386
    write(root, "d.txt", b"d\n");
1387
    let hd = repo.commit("d", &[hc]).unwrap();
1388
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1389
    repo.abandon(&hc).unwrap();
1390
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1391
    assert!(!heads.contains(&hc));
1392
    let d_now = heads
1393
        .iter()
1394
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1395
        .copied()
1396
        .unwrap();
1397
    assert!(
1398
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1399
        "d inherited c's (empty) dependencies"
1400
    );
1401
    let s = repo.snapshot("status").unwrap();
1402
    assert_eq!(
1403
        s.statuses
1404
            .iter()
1405
            .map(|p| p.path.as_str())
1406
            .collect::<Vec<_>>(),
1407
        vec!["c.txt"],
1408
        "c's content is now uncommitted work"
1409
    );
1410
}
1411
1412
#[test]
1413
fn git_export_mirrors_history() {
1414
    hermetic();
1415
    if std::process::Command::new("git")
1416
        .arg("--version")
1417
        .output()
1418
        .is_err()
1419
    {
1420
        eprintln!("git not installed; skipping");
1421
        return;
1422
    }
1423
    let dir = tempfile::tempdir().unwrap();
1424
    let root = dir.path();
1425
    let mut repo = Repo::init(&root.join("r"))
1426
        .unwrap()
1427
        .with_home(root.join("home"));
1428
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1429
        .unwrap();
1430
    let r = root.join("r");
1431
    write(&r, "README.md", b"hello\n");
1432
    write(&r, "src/main.rs", b"fn main() {}\n");
1433
    let h1 = repo.commit("first", &[]).unwrap();
1434
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1435
    write(&r, "logo.png", b"\x89PNG\0\0");
1436
    let h2 = repo.commit("second", &[]).unwrap();
1437
1438
    let git_dir = root.join("mirror.git");
1439
    let rep = repo.git_export(&git_dir).unwrap();
1440
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1441
    let git = |args: &[&str]| -> String {
1442
        let out = std::process::Command::new("git")
1443
            .arg("-C")
1444
            .arg(&git_dir)
1445
            .args(args)
1446
            .output()
1447
            .unwrap();
1448
        assert!(
1449
            out.status.success(),
1450
            "{}",
1451
            String::from_utf8_lossy(&out.stderr)
1452
        );
1453
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1454
    };
1455
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1456
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1457
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1458
    let body = git(&["log", "-1", "--format=%B", "main"]);
1459
    assert!(
1460
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1461
        "{body}"
1462
    );
1463
    assert!(body.contains("Change-Id: "), "{body}");
1464
    assert_eq!(
1465
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1466
        "Ada Lovelace <[email protected]>"
1467
    );
1468
    assert_eq!(
1469
        git(&["ls-tree", "--name-only", "main"]),
1470
        "README.md\nlogo.png\nsrc"
1471
    );
1472
1473
    // Re-export is incremental.
1474
    let rep = repo.git_export(&git_dir).unwrap();
1475
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1476
1477
    // An independent change makes two heads; the next state is one more
1478
    // commit on the linear branch whose tree is the union.
1479
    repo.checkout(&[h1], false, "checkout").unwrap();
1480
    write(&r, "other.txt", b"o\n");
1481
    let h3 = repo.commit("third", &[]).unwrap();
1482
    let rep = repo.git_export(&git_dir).unwrap();
1483
    assert_eq!((rep.exported, rep.heads), (1, 2));
1484
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1485
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1486
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1487
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1488
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1489
    assert_eq!(
1490
        git(&["ls-tree", "--name-only", "main"]),
1491
        "README.md\nlogo.png\nother.txt\nsrc"
1492
    );
1493
    let body = git(&["log", "-1", "--format=%B", "main"]);
1494
    assert!(
1495
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1496
        "{body}"
1497
    );
1498
    // A rewrite is a new state whose one new change is the rewritten one.
1499
    repo.describe(&h3, "third, described").unwrap();
1500
    let rep = repo.git_export(&git_dir).unwrap();
1501
    assert_eq!(rep.exported, 1);
1502
    assert_eq!(
1503
        git(&["log", "-1", "--format=%s", "main"]),
1504
        "third, described"
1505
    );
1506
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1507
    let _ = h2;
1508
}
1509
1510
#[test]
1511
fn git_import_reproduces_trees() {
1512
    hermetic();
1513
    if std::process::Command::new("git")
1514
        .arg("--version")
1515
        .output()
1516
        .is_err()
1517
    {
1518
        eprintln!("git not installed; skipping");
1519
        return;
1520
    }
1521
    let dir = tempfile::tempdir().unwrap();
1522
    let root = dir.path();
1523
    let g = root.join("src.git");
1524
    fs::create_dir_all(&g).unwrap();
1525
    let git = |args: &[&str]| -> String {
1526
        let out = std::process::Command::new("git")
1527
            .arg("-C")
1528
            .arg(&g)
1529
            .args([
1530
                "-c",
1531
                "user.name=Grace",
1532
                "-c",
1533
                "[email protected]",
1534
                "-c",
1535
                "commit.gpgsign=false",
1536
            ])
1537
            .args(args)
1538
            .output()
1539
            .unwrap();
1540
        assert!(
1541
            out.status.success(),
1542
            "git {args:?}: {}",
1543
            String::from_utf8_lossy(&out.stderr)
1544
        );
1545
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1546
    };
1547
    git(&["init", "-q", "-b", "main"]);
1548
    write(&g, "README.md", b"# Hi\n");
1549
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1550
    git(&["add", "."]);
1551
    git(&["commit", "-q", "-m", "initial"]);
1552
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1553
    write(&g, "run.sh", b"#!/bin/sh\n");
1554
    #[cfg(unix)]
1555
    {
1556
        use std::os::unix::fs::PermissionsExt;
1557
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1558
    }
1559
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1560
    git(&["add", "."]);
1561
    git(&[
1562
        "commit",
1563
        "-q",
1564
        "-m",
1565
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1566
    ]);
1567
    // A branch that edits README, merged back with a conflict-free merge.
1568
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1569
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1570
    git(&["commit", "-q", "-am", "readme"]);
1571
    git(&["checkout", "-q", "main"]);
1572
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1573
    // A branch from the initial commit inserting at the same place as
1574
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1575
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1576
    git(&["checkout", "-q", "-b", "clash", &initial]);
1577
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1578
    git(&["commit", "-q", "-am", "clash"]);
1579
    git(&["checkout", "-q", "main"]);
1580
    let _ = std::process::Command::new("git")
1581
        .arg("-C")
1582
        .arg(&g)
1583
        .args(["merge", "-q", "clash"])
1584
        .output();
1585
    write(
1586
        &g,
1587
        "src/lib.rs",
1588
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1589
    );
1590
    git(&["add", "."]);
1591
    git(&["commit", "-q", "-m", "resolve clash"]);
1592
    git(&["rm", "-q", "logo.png"]);
1593
    git(&["commit", "-q", "-m", "drop logo"]);
1594
    // A rename with a small edit is imported as a move of the same node.
1595
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
1596
    write(
1597
        &g,
1598
        "src/lib2.rs",
1599
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1600
    );
1601
    git(&["add", "."]);
1602
    git(&["commit", "-q", "-m", "rename lib"]);
1603
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1604
    // run.sh is the same as in the first parent's tree, but the merged
1605
    // change touched it, so the importer must compare it, not skip it.
1606
    git(&["checkout", "-q", "-b", "discarded"]);
1607
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1608
    git(&["commit", "-q", "-am", "discarded edit"]);
1609
    git(&["checkout", "-q", "main"]);
1610
    git(&[
1611
        "merge",
1612
        "-q",
1613
        "-s",
1614
        "ours",
1615
        "-m",
1616
        "merge discarded, keeping ours",
1617
        "discarded",
1618
    ]);
1619
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1620
1621
    let dest = root.join("oxy");
1622
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1623
    let rep = repo.import_git(&g, "main").unwrap();
1624
    assert_eq!(rep.commits, expected_count);
1625
    assert_eq!(rep.merges, 3);
1626
    assert_eq!(
1627
        fs::read(dest.join("run.sh")).unwrap(),
1628
        b"#!/bin/sh\n",
1629
        "the ours merge kept main's run.sh"
1630
    );
1631
    let v = repo.verify_git_import(&g, "main").unwrap();
1632
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1633
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
1634
    // The working copy equals the Git tree at main.
1635
    assert_eq!(
1636
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1637
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1638
    );
1639
    assert!(!dest.join("src/lib.rs").exists());
1640
    assert_eq!(
1641
        fs::read(dest.join("README.md")).unwrap(),
1642
        b"# Hi\n\nMore.\n"
1643
    );
1644
    assert!(!dest.join("logo.png").exists());
1645
    #[cfg(unix)]
1646
    {
1647
        use std::os::unix::fs::PermissionsExt;
1648
        assert!(
1649
            fs::metadata(dest.join("run.sh"))
1650
                .unwrap()
1651
                .permissions()
1652
                .mode()
1653
                & 0o111
1654
                != 0
1655
        );
1656
    }
1657
    assert!(
1658
        !repo.snapshot("status").unwrap().changed,
1659
        "clean after import"
1660
    );
1661
    let heads = repo.bookmark_heads().unwrap();
1662
    let st = repo.load_state(&heads).unwrap();
1663
    assert!(!st.materialize().is_conflicted());
1664
    assert_eq!(st.len(), expected_count);
1665
    let tip = repo
1666
        .log()
1667
        .unwrap()
1668
        .into_iter()
1669
        .find(|e| e.change.message.starts_with("rename lib"))
1670
        .unwrap();
1671
    let c = repo.store().get_change(&tip.hash).unwrap();
1672
    assert!(
1673
        c.tree_ops
1674
            .iter()
1675
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1676
        "{:?}",
1677
        c.tree_ops
1678
    );
1679
    assert!(!c
1680
        .tree_ops
1681
        .iter()
1682
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
1683
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1684
    let log = repo.log().unwrap();
1685
    let second = log
1686
        .iter()
1687
        .find(|e| e.change.message.starts_with("second"))
1688
        .unwrap();
1689
    assert_eq!(
1690
        second.change.change_id,
1691
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1692
    );
1693
    assert!(second
1694
        .change
1695
        .message
1696
        .contains("Git-Author: Grace <[email protected]>"));
1697
    let resolve = log
1698
        .iter()
1699
        .find(|e| e.change.message.starts_with("resolve clash"))
1700
        .unwrap();
1701
    assert_eq!(
1702
        resolve.change.kind,
1703
        ChangeKind::Resolution,
1704
        "a conflicting Git merge becomes a resolution"
1705
    );
1706
    // Re-importing into another fresh repository gives the same ChangeIds.
1707
    let repo2 = Repo::init(&root.join("oxy2"))
1708
        .unwrap()
1709
        .with_home(root.join("home"));
1710
    repo2.import_git(&g, "main").unwrap();
1711
    // New nodes' identifiers derive from the commit (spec §23), so the
1712
    // re-import is not just the same ChangeIds but the same changes.
1713
    assert_eq!(
1714
        repo2.bookmark_heads().unwrap(),
1715
        repo.bookmark_heads().unwrap()
1716
    );
1717
    let ids: BTreeSet<ChangeId> = repo
1718
        .log()
1719
        .unwrap()
1720
        .iter()
1721
        .filter(|e| !e.is_working_copy)
1722
        .map(|e| e.change.change_id)
1723
        .collect();
1724
    let ids2: BTreeSet<ChangeId> = repo2
1725
        .log()
1726
        .unwrap()
1727
        .iter()
1728
        .filter(|e| !e.is_working_copy)
1729
        .map(|e| e.change.change_id)
1730
        .collect();
1731
    assert_eq!(ids, ids2);
1732
    // Round trip back out to Git reproduces the tip tree.
1733
    let mirror = root.join("mirror.git");
1734
    repo.git_export(&mirror).unwrap();
1735
    let out = std::process::Command::new("git")
1736
        .arg("-C")
1737
        .arg(&mirror)
1738
        .args(["show", "main:src/lib2.rs"])
1739
        .output()
1740
        .unwrap();
1741
    assert_eq!(
1742
        String::from_utf8_lossy(&out.stdout),
1743
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1744
    );
1745
    let out = std::process::Command::new("git")
1746
        .arg("-C")
1747
        .arg(&mirror)
1748
        .args(["show", "main:src/lib.rs"])
1749
        .output()
1750
        .unwrap();
1751
    assert!(
1752
        !out.status.success(),
1753
        "the old path is gone from the export"
1754
    );
1755
}
1756
1757
#[test]
1758
fn checkpoints_accelerate_loading_and_stay_correct() {
1759
    hermetic();
1760
    let dir = tempfile::tempdir().unwrap();
1761
    let root = dir.path();
1762
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1763
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1764
    repo.save_config().unwrap();
1765
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1766
    let mut hashes = Vec::new();
1767
    for i in 0..12 {
1768
        write(
1769
            root,
1770
            "a.txt",
1771
            format!(
1772
                "{}\n",
1773
                (0..=i)
1774
                    .map(|k| k.to_string())
1775
                    .collect::<Vec<_>>()
1776
                    .join("\n")
1777
            )
1778
            .as_bytes(),
1779
        );
1780
        write(root, &format!("f{i}.txt"), b"x\n");
1781
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1782
    }
1783
    let (_, cp) = repo
1784
        .latest_checkpoint("main")
1785
        .unwrap()
1786
        .expect("automatic checkpoint");
1787
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1788
    // Loading through the checkpoint equals loading everything.
1789
    let heads = repo.bookmark_heads().unwrap();
1790
    let fast = repo.load_state(&heads).unwrap();
1791
    let full = repo.load_state_full(&heads).unwrap();
1792
    assert_eq!(fast.len(), full.len());
1793
    assert_eq!(fast.heads(), full.heads());
1794
    let (a, b) = (fast.materialize(), full.materialize());
1795
    assert_eq!(
1796
        a.files.keys().collect::<Vec<_>>(),
1797
        b.files.keys().collect::<Vec<_>>()
1798
    );
1799
    for (p, f) in &a.files {
1800
        assert_eq!(f.content, b.files[p].content, "{p}");
1801
    }
1802
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1803
    // A head set that does not contain the checkpoint's heads falls back.
1804
    assert!(repo
1805
        .load_state_checkpointed(&[hashes[0]])
1806
        .unwrap()
1807
        .is_none());
1808
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1809
    // Everything else keeps working on top of the checkpoint.
1810
    assert!(!repo.snapshot("status").unwrap().changed);
1811
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1812
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1813
    let (r, n, bytes) = repo.checkpoint().unwrap();
1814
    assert!(n >= 12 && bytes > 0);
1815
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1816
    write(root, "a.txt", b"after\n");
1817
    let h_after = repo.commit("after", &[]).unwrap();
1818
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1819
    assert!(st.contains(&h_after));
1820
    assert!(
1821
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1822
    );
1823
    assert_eq!(repo.log().unwrap().len(), 14);
1824
    // Checkpoints survive gc.
1825
    repo.gc(true).unwrap();
1826
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
1827
    assert!(repo
1828
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1829
        .unwrap()
1830
        .is_some());
1831
}
1832
1833
#[test]
1834
fn quick_status_for_prompts() {
1835
    hermetic();
1836
    let dir = tempfile::tempdir().unwrap();
1837
    let root = dir.path();
1838
    let origin = Repo::init(&root.join("origin")).unwrap();
1839
    let url = root.join("origin").to_string_lossy().to_string();
1840
    let a = Repo::clone(&url, &root.join("a"))
1841
        .unwrap()
1842
        .with_home(root.join("home"));
1843
    let ops_before = a.op_log().unwrap().len();
1844
    let info = a.quick_status().unwrap();
1845
    assert_eq!(
1846
        (
1847
            info.bookmark.as_str(),
1848
            info.heads,
1849
            info.dirty,
1850
            info.conflicted,
1851
            info.ahead,
1852
            info.behind
1853
        ),
1854
        ("main", 0, false, false, Some(0), Some(0))
1855
    );
1856
    write(&root.join("a"), "f.txt", b"f\n");
1857
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
1858
    assert_eq!(
1859
        a.op_log().unwrap().len(),
1860
        ops_before,
1861
        "quick_status records nothing"
1862
    );
1863
    // A snapshotted but uncommitted change is still dirty.
1864
    a.snapshot("status").unwrap();
1865
    assert!(a.quick_status().unwrap().dirty);
1866
    a.commit("f", &[]).unwrap();
1867
    let info = a.quick_status().unwrap();
1868
    assert!(!info.dirty, "clean right after a commit");
1869
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
1870
    assert_eq!(
1871
        info.format("%b %c%d%x%A%D"),
1872
        format!("main {}+1", info.change_id)
1873
    );
1874
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1875
    // Touching a file without changing it is not dirty; changing content of
1876
    // the same size is.
1877
    let p = root.join("a/f.txt");
1878
    let content = fs::read(&p).unwrap();
1879
    fs::write(&p, &content).unwrap();
1880
    assert!(!a.quick_status().unwrap().dirty);
1881
    fs::write(&p, b"g\n").unwrap();
1882
    assert!(a.quick_status().unwrap().dirty);
1883
    fs::write(&p, b"f\n").unwrap();
1884
    // Push, then a second clone commits and pushes: we are behind.
1885
    assert!(a.push("origin", false).unwrap()[0].ok);
1886
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
1887
    let b = Repo::clone(&url, &root.join("b"))
1888
        .unwrap()
1889
        .with_home(root.join("home-b"));
1890
    write(&root.join("b"), "g.txt", b"g\n");
1891
    b.commit("g", &[]).unwrap();
1892
    b.push("origin", false).unwrap();
1893
    a.fetch("origin").unwrap();
1894
    let info = a.quick_status().unwrap();
1895
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1896
    assert_eq!(info.format("%A%D"), "-1");
1897
    let _ = origin;
1898
}
1899
1900
#[test]
1901
fn lazy_blobs_are_fetched_on_first_read() {
1902
    hermetic();
1903
    let dir = tempfile::tempdir().unwrap();
1904
    let root = dir.path();
1905
    let origin_dir = root.join("origin");
1906
    let origin = Repo::init(&origin_dir)
1907
        .unwrap()
1908
        .with_home(root.join("home"));
1909
    let url = origin_dir.to_string_lossy().to_string();
1910
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1911
    write(&origin_dir, "big.bin", &big);
1912
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1913
    write(&origin_dir, "t.txt", b"t\n");
1914
    let h = origin.commit("blobs", &[]).unwrap();
1915
    let big_ref = Repo::blob_ref(&big);
1916
1917
    // Fetch only (no checkout) with a filter: the big blob stays absent.
1918
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1919
        .unwrap()
1920
        .with_home(root.join("home"));
1921
    let a = {
1922
        let mut a = a;
1923
        a.config.set("remote.origin.url", &url).unwrap();
1924
        a.config.set("filter.max-blob", "100K").unwrap();
1925
        a.save_config().unwrap();
1926
        a
1927
    };
1928
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1929
    a.fetch("origin").unwrap();
1930
    assert!(a.store().has(&h));
1931
    assert!(!a.store().has(&big_ref), "withheld");
1932
    assert!(
1933
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1934
        "small blob came along"
1935
    );
1936
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1937
1938
    // status and commit do not need it: adopt the state, edit a text file, commit.
1939
    let (op_ref, op) = a.head_op().unwrap();
1940
    let mut view = op.view.clone();
1941
    view.bookmarks.insert(
1942
        "main".into(),
1943
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1944
    );
1945
    a.record_op(&[op_ref], "adopt", view).unwrap();
1946
    // Checkout reads the blob lazily, which fetches it.
1947
    a.checkout(&[h], true, "checkout").unwrap();
1948
    assert!(a.store().has(&big_ref), "fetched on first read");
1949
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1950
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1951
    write(&root.join("a"), "t.txt", b"t2\n");
1952
    a.commit("text edit", &[]).unwrap();
1953
1954
    // clone --max-blob records the filter; the checkout fetches lazily.
1955
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
1956
    assert_eq!(b.config.max_blob, Some(1024));
1957
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1958
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1959
    assert!(parse_size("lots").is_err());
1960
}
1961
1962
#[test]
1963
fn sparse_checkout_materializes_only_chosen_paths() {
1964
    hermetic();
1965
    let dir = tempfile::tempdir().unwrap();
1966
    let root = dir.path();
1967
    let origin_dir = root.join("origin");
1968
    let origin = Repo::init(&origin_dir)
1969
        .unwrap()
1970
        .with_home(root.join("home"));
1971
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1972
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1973
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1974
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1975
    write(&origin_dir, "docs/logo.png", &logo);
1976
    write(&origin_dir, "README.md", b"# top\n");
1977
    let h1 = origin.commit("tree", &[]).unwrap();
1978
    let url = origin_dir.to_string_lossy().to_string();
1979
1980
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
1981
        .unwrap()
1982
        .with_home(root.join("home"));
1983
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1984
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1985
    assert!(root.join("a/src/main.rs").exists());
1986
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
1987
    assert!(
1988
        !a.store().has(&Repo::blob_ref(&logo)),
1989
        "out-of-scope blob never fetched"
1990
    );
1991
    assert!(
1992
        !a.snapshot("status").unwrap().changed,
1993
        "out-of-scope files are not removals"
1994
    );
1995
    assert!(!a.quick_status().unwrap().dirty);
1996
1997
    // Edits in scope commit normally and keep the rest of the tree intact.
1998
    write(
1999
        &root.join("a"),
2000
        "src/lib.rs",
2001
        b"pub fn a() {}\npub fn b() {}\n",
2002
    );
2003
    let h2 = a.commit("edit lib", &[]).unwrap();
2004
    let st = a.load_state(&[h2]).unwrap().materialize();
2005
    assert!(
2006
        st.files.contains_key("docs/guide.md"),
2007
        "the state still has everything"
2008
    );
2009
    assert!(a.push("origin", false).unwrap()[0].ok);
2010
    // Files created outside the scope are ignored by status.
2011
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2012
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2013
2014
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2015
    let mut a = a;
2016
    a.config.set("filter.paths", "src,docs").unwrap();
2017
    a.save_config().unwrap();
2018
    let r = a
2019
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2020
        .unwrap();
2021
    assert!(r.written >= 2);
2022
    assert_eq!(
2023
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2024
        logo,
2025
        "now fetched lazily"
2026
    );
2027
    assert!(!root.join("a/README.md").exists());
2028
    // Origin sees the change made under a sparse checkout with the full tree intact.
2029
    origin.pull("origin").err();
2030
    let full = origin
2031
        .load_state(&origin.bookmark_heads().unwrap())
2032
        .unwrap()
2033
        .materialize();
2034
    assert!(
2035
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2036
    );
2037
    assert!(full.files.contains_key("README.md"));
2038
    let _ = h1;
2039
}
2040
2041
#[test]
2042
fn shallow_clone_and_deepen() {
2043
    hermetic();
2044
    let dir = tempfile::tempdir().unwrap();
2045
    let root = dir.path();
2046
    let origin_dir = root.join("origin");
2047
    let origin = Repo::init(&origin_dir)
2048
        .unwrap()
2049
        .with_home(root.join("home"));
2050
    let mut hashes = Vec::new();
2051
    for i in 0..8 {
2052
        write(
2053
            &origin_dir,
2054
            "a.txt",
2055
            format!(
2056
                "{}\n",
2057
                (0..=i)
2058
                    .map(|k| k.to_string())
2059
                    .collect::<Vec<_>>()
2060
                    .join("\n")
2061
            )
2062
            .as_bytes(),
2063
        );
2064
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2065
    }
2066
    let url = origin_dir.to_string_lossy().to_string();
2067
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2068
        .unwrap()
2069
        .with_home(root.join("home"));
2070
    assert!(a.is_shallow());
2071
    assert_eq!(
2072
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2073
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2074
    );
2075
    assert!(
2076
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2077
        "three levels present"
2078
    );
2079
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2080
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
2081
    assert_eq!(
2082
        a.log().unwrap().len(),
2083
        9,
2084
        "the log shows every change from the checkpoint's metadata"
2085
    );
2086
    assert!(!a.snapshot("status").unwrap().changed);
2087
    assert_eq!(a.quick_status().unwrap().heads, 1);
2088
2089
    // Work continues on top of the shallow history and pushes back.
2090
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2091
    let h_new = a.commit("c8", &[]).unwrap();
2092
    assert!(a.push("origin", false).unwrap()[0].ok);
2093
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2094
    // Fetching new work from origin into the shallow clone works too.
2095
    write(&origin_dir, "b.txt", b"b\n");
2096
    origin.pull("origin").err();
2097
    let (_, wc) = origin.working_copy().unwrap();
2098
    let _ = wc;
2099
    origin
2100
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2101
        .unwrap();
2102
    write(&origin_dir, "b.txt", b"b\n");
2103
    let h_b = origin.commit("b", &[]).unwrap();
2104
    let pr = a.pull("origin").unwrap();
2105
    assert!(pr.changed);
2106
    assert!(a.store().has(&h_b));
2107
    assert!(root.join("a/b.txt").exists());
2108
2109
    // Deepening fetches older history until the boundary is gone.
2110
    // Every commit also depends on the change that created the file, so two
2111
    // levels below the boundary hold h4, h3, and the root.
2112
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2113
    assert!(a.store().has(&hashes[3]));
2114
    assert!(a.is_shallow());
2115
    a.deepen("origin", 100).unwrap();
2116
    assert!(!a.is_shallow(), "boundary reached the root");
2117
    assert!(a.store().has(&hashes[0]));
2118
    assert_eq!(
2119
        a.load_state_full(&a.bookmark_heads().unwrap())
2120
            .unwrap()
2121
            .len(),
2122
        10
2123
    );
2124
}
2125
2126
#[test]
2127
fn tags_are_immutable_named_states_and_travel() {
2128
    hermetic();
2129
    let dir = tempfile::tempdir().unwrap();
2130
    let root = dir.path();
2131
    let origin = Repo::init(&root.join("origin")).unwrap();
2132
    let url = root.join("origin").to_string_lossy().to_string();
2133
    let mut a = Repo::clone(&url, &root.join("a"))
2134
        .unwrap()
2135
        .with_home(root.join("home-a"));
2136
    let (key_a, _) = a
2137
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2138
        .unwrap();
2139
    write(&root.join("a"), "f.txt", b"1\n");
2140
    let h1 = a.commit("one", &[]).unwrap();
2141
    write(&root.join("a"), "f.txt", b"1\n2\n");
2142
    let h2 = a.commit("two", &[]).unwrap();
2143
2144
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
2145
    assert_eq!(
2146
        (t.heads.clone(), t.signer.as_deref()),
2147
        (vec![h1], Some("Ada"))
2148
    );
2149
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2150
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2151
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2152
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2153
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2154
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2155
    assert_eq!(sa.sigs[0].key, key_a);
2156
    // Checkout by tag.
2157
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2158
        .unwrap();
2159
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
2160
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2161
        .unwrap();
2162
2163
    // Push carries the tag; a second attestation for the name is refused.
2164
    let r = a.push("origin", false).unwrap();
2165
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2166
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
2167
    let mut forged = a
2168
        .tag_refs()
2169
        .unwrap()
2170
        .into_iter()
2171
        .find(|t| t.name == "v1")
2172
        .unwrap();
2173
    forged.state = origin
2174
        .store()
2175
        .put_state(&StateObject::new(vec![h2]))
2176
        .unwrap();
2177
    forged.heads = vec![h2];
2178
    forged.attestation = None;
2179
    let r = origin
2180
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2181
        .unwrap();
2182
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2183
2184
    // A clone gets the tag; a later tag arrives on fetch.
2185
    let b = Repo::clone(&url, &root.join("b"))
2186
        .unwrap()
2187
        .with_home(root.join("home-b"));
2188
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2189
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2190
    a.tag_create("v2", &[h2], "second").unwrap();
2191
    a.push("origin", false).unwrap();
2192
    let rep = b.fetch("origin").unwrap();
2193
    assert_eq!(rep.new_tags, 1);
2194
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2195
2196
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2197
    a.policy_init().unwrap();
2198
    a.push("origin", false).unwrap();
2199
    let unattested = crate::protocol::TagRef {
2200
        name: "v3".into(),
2201
        state: origin
2202
            .store()
2203
            .put_state(&StateObject::new(vec![h2]))
2204
            .unwrap(),
2205
        heads: vec![h2],
2206
        attestation: None,
2207
    };
2208
    let r = origin
2209
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2210
        .unwrap();
2211
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2212
    a.tag_create("v3", &[h2], "").unwrap();
2213
    let r = a.push("origin", false).unwrap();
2214
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2215
    assert!(a.gc(true).is_ok());
2216
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2217
}
2218
2219
#[test]
2220
fn multiple_workspaces_share_a_repository() {
2221
    hermetic();
2222
    let dir = tempfile::tempdir().unwrap();
2223
    let root = dir.path();
2224
    let main_dir = root.join("main");
2225
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2226
    write(&main_dir, "a.txt", b"a\n");
2227
    let h1 = repo.commit("a", &[]).unwrap();
2228
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2229
2230
    // A second workspace elsewhere, checked out on the bookmark.
2231
    let ws_dir = root.join("ws2");
2232
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2233
    assert!(ws_dir.join(".oxy").is_file());
2234
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2235
    assert_ne!(ws.workspace(), repo.workspace());
2236
    let list = repo.workspaces().unwrap();
2237
    assert_eq!(list.len(), 2);
2238
    assert!(list
2239
        .iter()
2240
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
2241
    assert!(!ws.snapshot("status").unwrap().changed);
2242
2243
    // Work in the second workspace: its own working copy, shared bookmark.
2244
    write(&ws_dir, "b.txt", b"b\n");
2245
    let s = ws.snapshot("status").unwrap();
2246
    assert_eq!(s.statuses.len(), 1);
2247
    assert!(
2248
        !repo.snapshot("status").unwrap().changed,
2249
        "the first workspace is untouched"
2250
    );
2251
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2252
    let mut heads = repo.bookmark_heads().unwrap();
2253
    heads.sort();
2254
    let mut want = vec![h1, h2];
2255
    want.sort();
2256
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2257
    assert!(!main_dir.join("b.txt").exists());
2258
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2259
        .unwrap();
2260
    assert!(main_dir.join("b.txt").exists());
2261
2262
    // Reopening from inside the second workspace finds the shared repository.
2263
    let reopened = Repo::open(&ws_dir).unwrap();
2264
    assert_eq!(reopened.workspace(), ws.workspace());
2265
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2266
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2267
2268
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2269
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2270
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2271
    repo.workspace_forget(&ws.workspace()).unwrap();
2272
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2273
    assert!(ws_dir.join("b.txt").exists());
2274
    assert!(
2275
        ws.snapshot("status").is_err(),
2276
        "a forgotten workspace is no longer in the view"
2277
    );
2278
2279
    // The working-copy lock: re-entrant in a thread; a lock whose process
2280
    // is gone is taken over, and a live process's is not, however old.
2281
    let lock = repo.lock_snapshot().unwrap();
2282
    let again = repo.lock_working_copy().unwrap();
2283
    drop(again);
2284
    drop(lock);
2285
    let lock_path = main_dir
2286
        .join(".oxy/workspaces")
2287
        .join(repo.workspace().to_hex())
2288
        .join("lock");
2289
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
2290
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2291
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2292
    age(&lock_path);
2293
    assert!(
2294
        !super::workspace::lock_is_stale(&lock_path),
2295
        "a live process keeps its lock"
2296
    );
2297
    fs::write(&lock_path, "4294967295").unwrap();
2298
    age(&lock_path);
2299
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2300
}
2301
2302
#[test]
2303
fn attributes_binary_eol_nocompress_lockable() {
2304
    hermetic();
2305
    let dir = tempfile::tempdir().unwrap();
2306
    let root = dir.path();
2307
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2308
    write(
2309
        root,
2310
        ".oxyattributes",
2311
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2312
    );
2313
    write(root, "plain.dat", b"no nul bytes here\n");
2314
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2315
    write(root, "assets/model.bin", b"\0model");
2316
    let h = repo.commit("attrs", &[]).unwrap();
2317
    let snap = repo.load_state(&[h]).unwrap().materialize();
2318
    assert!(
2319
        snap.files["plain.dat"].mode.opaque,
2320
        "binary attribute forces opaque without NUL bytes"
2321
    );
2322
    assert!(
2323
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2324
        "stored with LF"
2325
    );
2326
    assert!(
2327
        !repo.snapshot("status").unwrap().changed,
2328
        "CRLF on disk equals LF in the state"
2329
    );
2330
    // nocompress chunks pack raw.
2331
    let r = repo.gc(true).unwrap();
2332
    assert!(r.packed.objects > 0);
2333
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2334
    fs::remove_file(root.join("notes.txt")).unwrap();
2335
    repo.checkout(&[h], true, "co").unwrap();
2336
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
2337
    assert!(fs::metadata(root.join("assets/model.bin"))
2338
        .unwrap()
2339
        .permissions()
2340
        .readonly());
2341
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2342
    repo.lock_path("assets/model.bin").unwrap();
2343
    assert!(!fs::metadata(root.join("assets/model.bin"))
2344
        .unwrap()
2345
        .permissions()
2346
        .readonly());
2347
    assert!(repo.is_locked("assets/model.bin"));
2348
    write(root, "assets/model.bin", b"\0model2");
2349
    repo.commit("edit model", &[]).unwrap();
2350
    repo.unlock_path("assets/model.bin").unwrap();
2351
    assert!(fs::metadata(root.join("assets/model.bin"))
2352
        .unwrap()
2353
        .permissions()
2354
        .readonly());
2355
    // A later checkout can still overwrite a read-only lockable file.
2356
    repo.checkout(&[h], true, "co").unwrap();
2357
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2358
}
2359
2360
#[cfg(unix)]
2361
#[test]
2362
fn hooks_can_veto_observe_and_add_dependencies() {
2363
    use std::os::unix::fs::PermissionsExt;
2364
    hermetic();
2365
    let dir = tempfile::tempdir().unwrap();
2366
    let root = dir.path();
2367
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2368
    let hooks = root.join(".oxy/hooks");
2369
    fs::create_dir_all(&hooks).unwrap();
2370
    let hook = |name: &str, body: &str| {
2371
        let p = hooks.join(name);
2372
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2373
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2374
    };
2375
    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");
2376
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2377
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2378
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2379
    write(root, ".oxyignore", b".last-*\n");
2380
    write(root, "a.txt", b"a\n");
2381
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2382
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2383
    let h1 = repo.commit("first", &[]).unwrap();
2384
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
2385
    assert!(
2386
        pre.contains("\"event\":\"pre-commit\"")
2387
            && pre.contains("\"path\":\"a.txt\"")
2388
            && pre.contains("\"message\":\"first\""),
2389
        "{pre}"
2390
    );
2391
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2392
    assert!(post.contains(&h1.to_hex()), "{post}");
2393
    repo.checkout(&[h1], false, "co").unwrap();
2394
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2395
        .unwrap()
2396
        .contains("post-checkout"));
2397
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2398
    repo.save_config().unwrap();
2399
    let err = repo.push("origin", false).unwrap_err().to_string();
2400
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2401
2402
    // semantic-deps: only when enabled; adds an explicit dependency.
2403
    write(root, "b.txt", b"b\n");
2404
    hook(
2405
        "semantic-deps",
2406
        &format!(
2407
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2408
            h1.to_hex()
2409
        ),
2410
    );
2411
    let h2 = repo.commit("b without hook", &[]).unwrap();
2412
    assert!(
2413
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2414
        "hook disabled by default"
2415
    );
2416
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2417
    repo.save_config().unwrap();
2418
    write(root, "c.txt", b"c\n");
2419
    let h3 = repo.commit("c with hook", &[]).unwrap();
2420
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2421
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
2422
    assert!(
2423
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2424
        "{sem}"
2425
    );
2426
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2427
}
2428
2429
#[test]
2430
fn amend_into_older_change_and_split() {
2431
    hermetic();
2432
    let dir = tempfile::tempdir().unwrap();
2433
    let root = dir.path();
2434
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2435
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2436
        .unwrap();
2437
    repo.set_user_config("core.sign", "change").unwrap();
2438
    write(root, "a.txt", b"one\ntwo\n");
2439
    let h0 = repo.commit("base", &[]).unwrap();
2440
    write(root, "a.txt", b"one\nTWO\n");
2441
    let h1 = repo.commit("edit two", &[]).unwrap();
2442
    write(root, "a.txt", b"one\nTWO\nthree\n");
2443
    let h2 = repo.commit("add three", &[]).unwrap();
2444
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2445
2446
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2447
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2448
    let h1b = repo.amend_into(&h1, None).unwrap();
2449
    assert_ne!(h1b, h1);
2450
    let c1b = repo.store().get_change(&h1b).unwrap();
2451
    assert_eq!(c1b.change_id, id1);
2452
    assert_eq!(c1b.deps, vec![h0]);
2453
    assert!(matches!(
2454
        repo.verify_change(&h1b).unwrap(),
2455
        SignatureStatus::Valid { .. }
2456
    ));
2457
    let heads = repo.bookmark_heads().unwrap();
2458
    assert_eq!(heads.len(), 1);
2459
    let top = repo.store().get_change(&heads[0]).unwrap();
2460
    assert_eq!(top.message, "add three");
2461
    assert_eq!(
2462
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2463
        [h0, h1b].into_iter().collect(),
2464
        "depends on the file's creator and the rewritten line"
2465
    );
2466
    let snap = repo.load_state(&heads).unwrap().materialize();
2467
    assert!(
2468
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2469
    );
2470
    assert!(
2471
        !repo.snapshot("status").unwrap().changed,
2472
        "the working copy is clean after folding"
2473
    );
2474
    // Only h1b's own state shows the fix without "three".
2475
    let only = repo.load_state(&[h1b]).unwrap().materialize();
2476
    assert!(
2477
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2478
    );
2479
    assert_eq!(repo.log().unwrap().len(), 4);
2480
2481
    // An edit to a line introduced by h2 cannot fold into h1.
2482
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2483
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2484
    assert!(err.contains("introduced after"), "{err}");
2485
    assert!(
2486
        repo.snapshot("status").unwrap().statuses.len() == 1,
2487
        "nothing was changed by the refusal"
2488
    );
2489
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2490
2491
    // Split the head that touches two files.
2492
    write(root, "b.txt", b"b\n");
2493
    write(root, "c.txt", b"c\n");
2494
    let h3 = repo.commit("b and c", &[]).unwrap();
2495
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2496
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2497
    let c_1 = repo.store().get_change(&p1).unwrap();
2498
    let c_2 = repo.store().get_change(&p2).unwrap();
2499
    assert!(c_1.message.contains("part 1: b.txt"));
2500
    assert_eq!(c_2.change_id, id3);
2501
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2502
    assert!(
2503
        heads.contains(&p1) && heads.contains(&p2),
2504
        "independent parts are both heads"
2505
    );
2506
    let snap = repo
2507
        .load_state(&repo.bookmark_heads().unwrap())
2508
        .unwrap()
2509
        .materialize();
2510
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2511
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2512
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2513
    assert!(!repo.snapshot("status").unwrap().changed);
2514
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2515
    let _ = h2;
2516
}
2517
2518
#[test]
2519
fn identity_lifecycle() {
2520
    hermetic();
2521
    let dir = tempfile::tempdir().unwrap();
2522
    let root = dir.path();
2523
    let origin = Repo::init(&root.join("origin")).unwrap();
2524
    let url = root.join("origin").to_string_lossy().to_string();
2525
    let mut a = Repo::clone(&url, &root.join("a"))
2526
        .unwrap()
2527
        .with_home(root.join("home-a"));
2528
    a.set_user_config("core.sign", "change").unwrap();
2529
    let (key_a, _) = a
2530
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2531
        .unwrap();
2532
    write(&root.join("a"), "a.txt", b"a\n");
2533
    let h1 = a.commit("one", &[]).unwrap();
2534
    assert!(a.policy_init().unwrap().applied);
2535
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2536
2537
    // Expiry: an identity that had expired when the change was made does not authenticate it.
2538
    let mut e = Repo::init(&root.join("e"))
2539
        .unwrap()
2540
        .with_home(root.join("home-e"));
2541
    e.set_user_config("core.sign", "change").unwrap();
2542
    e.create_identity_with(
2543
        "Eve",
2544
        "[email protected]",
2545
        IdentityScope::User,
2546
        Some(Hlc::now().wall_ms - 1),
2547
    )
2548
    .unwrap();
2549
    write(&root.join("e"), "e.txt", b"e\n");
2550
    let he = e.commit("late", &[]).unwrap();
2551
    assert!(
2552
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2553
    );
2554
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
2555
    let r = e
2556
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2557
        .unwrap();
2558
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2559
    write(&root.join("e"), "e.txt", b"e2\n");
2560
    let he2 = e.commit("in time", &[]).unwrap();
2561
    assert!(
2562
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2563
    );
2564
2565
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2566
    let r = a.rotate_identity().unwrap();
2567
    assert_eq!(r.old, key_a);
2568
    assert_eq!(a.config.author_key, Some(r.new));
2569
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2570
    assert!(r.policy.as_ref().unwrap().applied);
2571
    let (_, sp) = a.current_policy().unwrap().unwrap();
2572
    assert_eq!(
2573
        (sp.policy.serial, sp.policy.roots.clone()),
2574
        (2, vec![r.new])
2575
    );
2576
    assert!(
2577
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2578
        "superseded, not revoked"
2579
    );
2580
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
2581
    assert!(
2582
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2583
    );
2584
    write(&root.join("a"), "a.txt", b"a2\n");
2585
    let h2 = a.commit("two", &[]).unwrap();
2586
    assert!(
2587
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2588
    );
2589
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2590
    let res = a.push("origin", false).unwrap();
2591
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2592
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2593
    let key_a = r.new;
2594
2595
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2596
    // identity object, so Ada's KeyId changes while her keys stay the same.
2597
    let mut b = Repo::clone(&url, &root.join("b"))
2598
        .unwrap()
2599
        .with_home(root.join("home-b"));
2600
    let (key_b, id_b) = b
2601
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2602
        .unwrap();
2603
    let r = a.delegate_add(id_b.clone()).unwrap();
2604
    assert_eq!(r.old, key_a);
2605
    let key_a2 = r.new;
2606
    assert_eq!(a.identity(&key_a2).unwrap().delegates, vec![key_b]);
2607
    assert_eq!(
2608
        a.identity(&key_a2).unwrap().ed25519_pk,
2609
        a.identity(&key_a).unwrap().ed25519_pk
2610
    );
2611
    assert!(a.delegate_add(id_b.clone()).is_err(), "already a delegate");
2612
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2613
    write(&root.join("a"), "a.txt", b"a3\n");
2614
    let h3 = a.commit("three", &[]).unwrap();
2615
    assert!(
2616
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2617
        "the same secret signs under the new KeyId"
2618
    );
2619
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2620
    a.set_user_config("core.sign", "seal").unwrap();
2621
    write(&root.join("a"), "a.txt", b"a4\n");
2622
    let h4 = a.commit("four", &[]).unwrap();
2623
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2624
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2625
    a.store()
2626
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2627
        .unwrap();
2628
    assert!(
2629
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2630
    );
2631
    a.set_user_config("core.sign", "change").unwrap();
2632
    // Withdrawing the delegation re-issues the identity again.
2633
    let r = a.delegate_remove(&key_b).unwrap();
2634
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2635
    assert!(a.delegate_remove(&key_b).is_err());
2636
    let key_a3 = r.new;
2637
    let res = a.push("origin", false).unwrap();
2638
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2639
2640
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2641
    // both applied under the old threshold of 1. A grant then needs Bob too.
2642
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2643
    assert!(a.policy_root_add(id_b.clone()).is_err());
2644
    assert!(a.policy_set_threshold(3).is_err());
2645
    assert!(a.policy_set_threshold(2).unwrap().applied);
2646
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2647
    b.pull("origin").unwrap();
2648
    assert_eq!(
2649
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2650
        2
2651
    );
2652
    let mut c = Repo::init(&root.join("c"))
2653
        .unwrap()
2654
        .with_home(root.join("home-c"));
2655
    let (key_c, id_c) = c
2656
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2657
        .unwrap();
2658
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2659
    let proposal = a.policy_grant(id_c, None).unwrap();
2660
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2661
    assert_eq!(proposal.policy.serial, serial_before + 1);
2662
    assert_eq!(
2663
        a.current_policy().unwrap().unwrap().1.policy.serial,
2664
        serial_before,
2665
        "a proposal changes nothing yet"
2666
    );
2667
    // Bob signs the proposal, handed over as a file, and it applies for him.
2668
    let bytes = proposal.signed().encode();
2669
    let signed = b
2670
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2671
        .unwrap();
2672
    assert!(signed.applied && signed.sigs.len() == 2);
2673
    assert!(b
2674
        .current_policy()
2675
        .unwrap()
2676
        .unwrap()
2677
        .1
2678
        .policy
2679
        .authorizes(&key_c, "main"));
2680
    assert!(
2681
        b.policy_sign(signed.signed()).is_err(),
2682
        "a stale proposal is refused"
2683
    );
2684
    // Bob publishes it and Ada picks it up.
2685
    assert!(b
2686
        .push("origin", false)
2687
        .unwrap()
2688
        .iter()
2689
        .any(|x| x.name == "policy" && x.ok));
2690
    a.pull("origin").unwrap();
2691
    assert_eq!(
2692
        a.current_policy().unwrap().unwrap().1.policy.serial,
2693
        serial_before + 1
2694
    );
2695
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2696
    assert!(a.policy_revoke(&key_a3).is_err());
2697
    let u = a
2698
        .revoke_identity(&key_c, "left the project")
2699
        .unwrap()
2700
        .unwrap();
2701
    assert!(!u.applied);
2702
    assert!(a.is_revoked(&key_c).unwrap());
2703
    assert!(!b.is_revoked(&key_c).unwrap());
2704
    let u = b.policy_sign(u.signed()).unwrap();
2705
    assert!(u.applied && u.policy.is_revoked(&key_c));
2706
    assert!(b.is_revoked(&key_c).unwrap());
2707
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
2708
    assert!(
2709
        b.policy_revoke(&key_a3).is_err(),
2710
        "would leave one root for a threshold of 2"
2711
    );
2712
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2713
    let key_c_own = c.config.author_key.unwrap();
2714
    assert!(c
2715
        .revoke_identity(&key_c_own, "lost laptop")
2716
        .unwrap()
2717
        .is_none());
2718
    assert!(c.is_revoked(&key_c_own).unwrap());
2719
    assert_eq!(key_c_own, key_c);
2720
}
2721
2722
#[test]
2723
fn renames_are_detected_and_tracked_as_moves() {
2724
    hermetic();
2725
    let dir = tempfile::tempdir().unwrap();
2726
    let root = dir.path();
2727
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
2728
    write(
2729
        root,
2730
        "src/old.rs",
2731
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2732
    );
2733
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2734
    write(root, "tiny.txt", b"x\n");
2735
    let h1 = repo.commit("base", &[]).unwrap();
2736
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2737
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2738
2739
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2740
    // that shares nothing with the removed file.
2741
    fs::remove_file(root.join("src/old.rs")).unwrap();
2742
    write(
2743
        root,
2744
        "lib/new.rs",
2745
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2746
    );
2747
    fs::remove_file(root.join("img.bin")).unwrap();
2748
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2749
    fs::remove_file(root.join("tiny.txt")).unwrap();
2750
    write(root, "other.txt", b"completely different\n");
2751
    let snap = repo.snapshot("status").unwrap();
2752
    let statuses: Vec<(&str, ChangeStatus)> = snap
2753
        .statuses
2754
        .iter()
2755
        .map(|s| (s.path.as_str(), s.status))
2756
        .collect();
2757
    assert_eq!(
2758
        statuses,
2759
        vec![
2760
            ("assets/img.bin", ChangeStatus::Renamed),
2761
            ("lib/new.rs", ChangeStatus::Renamed),
2762
            ("other.txt", ChangeStatus::Added),
2763
            ("src", ChangeStatus::Removed),
2764
            ("tiny.txt", ChangeStatus::Removed)
2765
        ]
2766
    );
2767
    let h2 = repo.commit("move things", &[]).unwrap();
2768
    let c = repo.store().get_change(&h2).unwrap();
2769
    let moves: Vec<_> = c
2770
        .tree_ops
2771
        .iter()
2772
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2773
        .collect();
2774
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
2775
    assert!(c.tree_ops.iter().any(
2776
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2777
    ));
2778
    assert!(c.tree_ops.iter().any(
2779
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2780
    ));
2781
    let snap = repo.load_state(&[h2]).unwrap().materialize();
2782
    assert_eq!(
2783
        snap.files["lib/new.rs"].node, node_old,
2784
        "the node survives the rename"
2785
    );
2786
    assert!(
2787
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2788
    );
2789
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
2790
    assert!(render_change(
2791
        &c,
2792
        &repo.load_state(&[h1]).unwrap(),
2793
        &repo.load_state(&[h1]).unwrap().materialize()
2794
    )
2795
    .contains("R "));
2796
    // A fresh checkout reproduces the tree.
2797
    let other = tempfile::tempdir().unwrap();
2798
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
2799
    assert_eq!(
2800
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2801
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2802
    );
2803
    assert!(!other.path().join("src").exists());
2804
    assert!(!clone.snapshot("status").unwrap().changed);
2805
    // Similarity is line based, byte weighted.
2806
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2807
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2808
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2809
    assert_eq!(similarity(b"", b"x\n"), 0);
2810
}
2811
2812
#[test]
2813
fn git_fetch_and_push_round_trip() {
2814
    hermetic();
2815
    if std::process::Command::new("git")
2816
        .arg("--version")
2817
        .output()
2818
        .is_err()
2819
    {
2820
        eprintln!("git not installed; skipping");
2821
        return;
2822
    }
2823
    let dir = tempfile::tempdir().unwrap();
2824
    let root = dir.path();
2825
    let git_in = |d: &Path, args: &[&str]| -> String {
2826
        let out = std::process::Command::new("git")
2827
            .arg("-C")
2828
            .arg(d)
2829
            .args([
2830
                "-c",
2831
                "user.name=Grace",
2832
                "-c",
2833
                "[email protected]",
2834
                "-c",
2835
                "commit.gpgsign=false",
2836
            ])
2837
            .args(args)
2838
            .output()
2839
            .unwrap();
2840
        assert!(
2841
            out.status.success(),
2842
            "git {args:?}: {}",
2843
            String::from_utf8_lossy(&out.stderr)
2844
        );
2845
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2846
    };
2847
    // A bare "remote" and a work tree that pushes to it.
2848
    let remote = root.join("remote.git");
2849
    fs::create_dir_all(&remote).unwrap();
2850
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2851
    let work = root.join("work");
2852
    git_in(
2853
        root,
2854
        &[
2855
            "clone",
2856
            "-q",
2857
            remote.to_str().unwrap(),
2858
            work.to_str().unwrap(),
2859
        ],
2860
    );
2861
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2862
    write(&work, "README.md", b"# Project\n");
2863
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2864
    git_in(&work, &["add", "."]);
2865
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2866
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2867
    git_in(&work, &["commit", "-q", "-am", "second"]);
2868
    git_in(&work, &["push", "-q", "origin", "main"]);
2869
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2870
2871
    // Fetch into a fresh oxy repository.
2872
    let o = root.join("oxy");
2873
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
2874
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2875
        .unwrap();
2876
    let url = remote.to_string_lossy().to_string();
2877
    let r = repo.git_fetch(&url, "main").unwrap();
2878
    assert_eq!((r.commits, r.heads), (2, 1));
2879
    assert_eq!(
2880
        fs::read(o.join("src/lib.rs")).unwrap(),
2881
        b"pub fn a() {}\npub fn b() {}\n"
2882
    );
2883
    assert!(!repo.snapshot("status").unwrap().changed);
2884
    assert_eq!(
2885
        repo.git_fetch(&url, "main").unwrap().commits,
2886
        0,
2887
        "nothing new"
2888
    );
2889
2890
    // An oxy change, pushed back: one commit on top of the Git tip.
2891
    write(
2892
        &o,
2893
        "src/lib.rs",
2894
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2895
    );
2896
    write(&o, "NOTES.md", b"from oxy\n");
2897
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2898
    let r = repo.git_push(&url, "main").unwrap();
2899
    assert_eq!(r.exported, 1, "{r:?}");
2900
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2901
    assert_eq!(
2902
        git_in(&work, &["log", "--format=%s", "main"]),
2903
        "add c and notes\nsecond\ninitial"
2904
    );
2905
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2906
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2907
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
2908
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2909
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2910
    assert_eq!(
2911
        repo.git_push(&url, "main").unwrap().exported,
2912
        0,
2913
        "already pushed"
2914
    );
2915
2916
    // Git moves on; pushing without fetching is refused, fetching brings
2917
    // the commit in and the working copy follows.
2918
    write(&work, "README.md", b"# Project\n\nMore.\n");
2919
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2920
    git_in(&work, &["push", "-q", "origin", "main"]);
2921
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
2922
    assert!(repo
2923
        .git_push(&url, "main")
2924
        .unwrap_err()
2925
        .to_string()
2926
        .contains("fetch"));
2927
    let r = repo.git_fetch(&url, "main").unwrap();
2928
    assert_eq!(
2929
        (r.commits, r.heads),
2930
        (1, 2),
2931
        "the Git change and the oxy change commute"
2932
    );
2933
    assert_eq!(
2934
        fs::read(o.join("README.md")).unwrap(),
2935
        b"# Project\n\nMore.\n"
2936
    );
2937
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2938
    assert!(!repo.snapshot("status").unwrap().changed);
2939
    // Another oxy change pushes on top of Git's newest commit.
2940
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2941
    repo.commit("notes again", &[]).unwrap();
2942
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2943
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2944
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
2945
    assert_eq!(
2946
        fs::read(work.join("NOTES.md")).unwrap(),
2947
        b"from oxy\nagain\n"
2948
    );
2949
    assert_eq!(
2950
        git_in(&work, &["log", "--format=%s", "main"])
2951
            .lines()
2952
            .count(),
2953
        5
2954
    );
2955
}
2956
2957
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2958
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2959
#[test]
2960
#[ignore]
2961
fn bench_one_gibibyte_file() {
2962
    hermetic();
2963
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2964
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2965
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2966
        None => tempfile::tempdir().unwrap(),
2967
    };
2968
    let root = dir.path();
2969
    let repo = Repo::init(&root.join("r"))
2970
        .unwrap()
2971
        .with_home(root.join("home"));
2972
    let size = 1usize << 30;
2973
    let mut data = vec![0u8; size];
2974
    let mut x = 0x9e3779b97f4a7c15u64;
2975
    for chunk in data.chunks_mut(8) {
2976
        x ^= x << 13;
2977
        x ^= x >> 7;
2978
        x ^= x << 17;
2979
        let b = x.to_le_bytes();
2980
        chunk.copy_from_slice(&b[..chunk.len()]);
2981
    }
2982
    let t = std::time::Instant::now();
2983
    write(&root.join("r"), "big.bin", &data);
2984
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
2985
    let t = std::time::Instant::now();
2986
    let h = repo.commit("big", &[]).unwrap();
2987
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
2988
    let t = std::time::Instant::now();
2989
    assert!(!repo.snapshot("status").unwrap().changed);
2990
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
2991
    let t = std::time::Instant::now();
2992
    let objects = repo.store().list().unwrap().len();
2993
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
2994
    let t = std::time::Instant::now();
2995
    let g = repo.gc(true).unwrap();
2996
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
2997
    let t = std::time::Instant::now();
2998
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
2999
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3000
    let t = std::time::Instant::now();
3001
    let back = fs::read(root.join("c/big.bin")).unwrap();
3002
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3003
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3004
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3005
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
3006
    eprintln!(
3007
        "store size: {:.1} MiB for 1 GiB of data",
3008
        store_bytes as f64 / (1024.0 * 1024.0)
3009
    );
3010
}
3011
3012
fn walkdir_size(p: &Path) -> u64 {
3013
    let mut total = 0;
3014
    if let Ok(rd) = fs::read_dir(p) {
3015
        for e in rd.flatten() {
3016
            let path = e.path();
3017
            if path.is_dir() {
3018
                total += walkdir_size(&path);
3019
            } else if let Ok(m) = fs::metadata(&path) {
3020
                total += m.len();
3021
            }
3022
        }
3023
    }
3024
    total
3025
}
3026
3027
/// An opaque file whose size and mtime match the manifest is not read on
3028
/// the next snapshot: its blob comes from the manifest's stat cache.
3029
#[cfg(unix)]
3030
#[test]
3031
fn stat_cache_skips_reading_unchanged_opaque_files() {
3032
    use std::os::unix::fs::PermissionsExt;
3033
    hermetic();
3034
    let dir = tempfile::tempdir().unwrap();
3035
    let root = dir.path();
3036
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3037
    let mut big = vec![0u8; 300 * 1024];
3038
    for (i, b) in big.iter_mut().enumerate() {
3039
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3040
    }
3041
    big[0] = 0;
3042
    write(root, "big.bin", &big);
3043
    write(root, "a.txt", b"text\n");
3044
    let h1 = repo.commit("base", &[]).unwrap();
3045
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3046
    assert!(
3047
        m.entries["big.bin"].blob.is_some(),
3048
        "opaque files record their blob"
3049
    );
3050
    assert!(m.entries["a.txt"].blob.is_none());
3051
    let blob = m.entries["big.bin"].blob.unwrap();
3052
    assert!(repo.store().has(&blob));
3053
3054
    // Files modified within two seconds of the manifest are racy and still
3055
    // read; age the file so the cache applies, then snapshot to record it.
3056
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
3057
    fs::File::options()
3058
        .write(true)
3059
        .open(root.join("big.bin"))
3060
        .unwrap()
3061
        .set_modified(old)
3062
        .unwrap();
3063
    assert!(!repo.snapshot("status").unwrap().changed);
3064
    // Now the file cannot be read at all; the snapshot succeeds without it.
3065
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3066
    let snap = repo.snapshot("status").unwrap();
3067
    assert!(
3068
        !snap.changed && snap.statuses.is_empty(),
3069
        "{:?}",
3070
        snap.statuses
3071
    );
3072
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3073
    // A real change (new mtime, new content) is seen and committed correctly.
3074
    let mut big2 = big.clone();
3075
    big2[10] ^= 0xff;
3076
    write(root, "big.bin", &big2);
3077
    let snap = repo.snapshot("status").unwrap();
3078
    assert_eq!(
3079
        snap.statuses
3080
            .iter()
3081
            .map(|s| (s.path.as_str(), s.status))
3082
            .collect::<Vec<_>>(),
3083
        vec![("big.bin", ChangeStatus::Modified)]
3084
    );
3085
    let h2 = repo.commit("edit", &[]).unwrap();
3086
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3087
    assert_eq!(
3088
        files["big.bin"].content,
3089
        FileContent::Opaque {
3090
            blobs: vec![Repo::blob_ref(&big2)]
3091
        }
3092
    );
3093
    // Checkout writes a manifest with blobs too, so the next status is cached.
3094
    repo.checkout(&[h1], false, "checkout").unwrap();
3095
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3096
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3097
    assert!(!repo.snapshot("status").unwrap().changed);
3098
}
3099
3100
#[test]
3101
fn status_json_lists_conflicts_with_contributors() {
3102
    hermetic();
3103
    let dir = tempfile::tempdir().unwrap();
3104
    let root = dir.path();
3105
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3106
    write(root, "a.txt", b"one\n");
3107
    let h1 = repo.commit("base", &[]).unwrap();
3108
    write(root, "a.txt", b"one\nleft\n");
3109
    let ha = repo.commit("left", &[]).unwrap();
3110
    repo.checkout(&[h1], true, "checkout").unwrap();
3111
    write(root, "a.txt", b"one\nright\n");
3112
    let hb = repo.commit("right", &[]).unwrap();
3113
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3114
    let snap = repo.snapshot("status").unwrap();
3115
    assert!(snap.base_snapshot.is_conflicted());
3116
    let json = repo.status_json(&snap).unwrap();
3117
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3118
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3119
    assert!(json.contains("\"conflicted\":true"), "{json}");
3120
    assert!(
3121
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3122
        "{json}"
3123
    );
3124
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3125
    assert!(json.contains("\"resolved\":false"), "{json}");
3126
    assert!(json.starts_with('{') && json.ends_with('}'));
3127
    // Resolve and the report says so; a clean copy has no conflicts.
3128
    write(root, "a.txt", b"one\nleft\nright\n");
3129
    let snap = repo.snapshot("status").unwrap();
3130
    let json = repo.status_json(&snap).unwrap();
3131
    assert!(json.contains("\"resolved\":true"), "{json}");
3132
    repo.commit("resolve", &[]).unwrap();
3133
    let snap = repo.snapshot("status").unwrap();
3134
    let json = repo.status_json(&snap).unwrap();
3135
    assert!(
3136
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3137
        "{json}"
3138
    );
3139
}
3140
3141
#[test]
3142
fn ignore_rules_do_not_untrack_files() {
3143
    hermetic();
3144
    let dir = tempfile::tempdir().unwrap();
3145
    let root = dir.path();
3146
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3147
    write(root, "src.c", b"int x;\n");
3148
    write(root, "build/out.o", b"\0obj");
3149
    write(root, "sub/keep.log", b"keep\n");
3150
    write(root, "sub/junk.log", b"junk\n");
3151
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3152
    let snap = repo.snapshot("status").unwrap();
3153
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3154
    assert_eq!(
3155
        added,
3156
        vec![".oxyignore", "src.c", "sub/keep.log"],
3157
        "anchored, glob, and negated rules"
3158
    );
3159
    let h1 = repo.commit("base", &[]).unwrap();
3160
    // Ignoring a tracked file changes nothing about it.
3161
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3162
    let snap = repo.snapshot("status").unwrap();
3163
    assert_eq!(
3164
        snap.statuses
3165
            .iter()
3166
            .map(|s| s.path.as_str())
3167
            .collect::<Vec<_>>(),
3168
        vec![".oxyignore"]
3169
    );
3170
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
3171
    assert!(repo
3172
        .load_state(&[h2])
3173
        .unwrap()
3174
        .materialize()
3175
        .files
3176
        .contains_key("src.c"));
3177
    // Its edits are still seen, by status and by the prompt.
3178
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3179
    write(root, "src.c", b"int x, y;\n");
3180
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3181
    let snap = repo.snapshot("status").unwrap();
3182
    assert_eq!(
3183
        snap.statuses
3184
            .iter()
3185
            .map(|s| (s.path.as_str(), s.status))
3186
            .collect::<Vec<_>>(),
3187
        vec![("src.c", ChangeStatus::Modified)]
3188
    );
3189
    let h3 = repo.commit("edit src.c", &[]).unwrap();
3190
    assert!(
3191
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3192
    );
3193
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3194
    fs::remove_file(root.join("src.c")).unwrap();
3195
    let snap = repo.snapshot("status").unwrap();
3196
    assert_eq!(
3197
        snap.statuses
3198
            .iter()
3199
            .map(|s| (s.path.as_str(), s.status))
3200
            .collect::<Vec<_>>(),
3201
        vec![("src.c", ChangeStatus::Removed)]
3202
    );
3203
    repo.checkout(&[h3], true, "checkout").unwrap();
3204
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3205
    assert!(!repo.snapshot("status").unwrap().changed);
3206
    let _ = h1;
3207
}
3208
3209
#[test]
3210
fn split_works_on_non_heads_by_node() {
3211
    hermetic();
3212
    let dir = tempfile::tempdir().unwrap();
3213
    let root = dir.path();
3214
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3215
    write(root, "a.txt", b"one\n");
3216
    write(root, "junk/x.lock", b"lock\n");
3217
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3218
    write(root, "a.txt", b"one\ntwo\n");
3219
    let h2 = repo.commit("more work", &[]).unwrap();
3220
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3221
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3222
    // h1 is not a head: split it by node.
3223
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3224
    assert_ne!(h1b, h1);
3225
    assert_eq!(
3226
        repo.store().get_change(&h1b).unwrap().change_id,
3227
        id1,
3228
        "the rest keeps the ChangeId"
3229
    );
3230
    let junk = repo.store().get_change(&hj).unwrap();
3231
    assert!(junk.tree_ops.iter().all(
3232
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3233
    ));
3234
    let heads = repo.bookmark_heads().unwrap();
3235
    assert!(
3236
        heads.contains(&hj),
3237
        "the split-off part is a head of its own"
3238
    );
3239
    let snap = repo.load_state(&heads).unwrap().materialize();
3240
    assert!(
3241
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3242
        "the dependent was rewritten onto the new hash"
3243
    );
3244
    assert!(snap.files.contains_key("junk/x.lock"));
3245
    let h2b = heads
3246
        .iter()
3247
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3248
        .copied()
3249
        .unwrap();
3250
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3251
    assert!(!repo.snapshot("status").unwrap().changed);
3252
    // Abandoning the split-off head removes the junk from history.
3253
    repo.abandon(&hj).unwrap();
3254
    let heads = repo.bookmark_heads().unwrap();
3255
    let snap = repo.load_state(&heads).unwrap().materialize();
3256
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3257
    assert!(snap.files.contains_key("a.txt"));
3258
    // A dependent that touches the split-off paths blocks the split.
3259
    write(root, "junk/y.lock", b"y\n");
3260
    let hb = repo.commit("junk base", &[]).unwrap();
3261
    write(root, "junk/y.lock", b"yy\n");
3262
    write(root, "b.txt", b"b\n");
3263
    repo.commit("touches junk", &[]).unwrap();
3264
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3265
    assert!(err.contains("depends on the split-off paths"), "{err}");
3266
}
3267
3268
#[test]
3269
fn bookmarks_switch_merge_and_push() {
3270
    hermetic();
3271
    let dir = tempfile::tempdir().unwrap();
3272
    let root = dir.path();
3273
    let origin = Repo::init(&root.join("origin")).unwrap();
3274
    let url = root.join("origin").to_string_lossy().to_string();
3275
    let mut repo = Repo::clone(&url, &root.join("r"))
3276
        .unwrap()
3277
        .with_home(root.join("home"));
3278
    let r = root.join("r");
3279
    write(&r, "a.txt", b"a\n");
3280
    let h_a = repo.commit("a", &[]).unwrap();
3281
    assert!(repo.push("origin", false).unwrap()[0].ok);
3282
3283
    // A bookmark at the working copy's base, then work on it.
3284
    assert!(repo.bookmark_create("bad name..", None).is_err());
3285
    assert!(repo.bookmark_create("-x", None).is_err());
3286
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3287
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3288
    repo.bookmark_switch("feature", false).unwrap();
3289
    assert_eq!(repo.config.bookmark, "feature");
3290
    write(&r, "a.txt", b"a\nb\n");
3291
    write(&r, "b.txt", b"b\n");
3292
    let h_b = repo.commit("b on feature", &[]).unwrap();
3293
    assert_eq!(
3294
        repo.bookmark_heads().unwrap(),
3295
        vec![h_b],
3296
        "b edits a.txt, so it depends on a"
3297
    );
3298
    assert_eq!(
3299
        repo.resolve_heads("main").unwrap(),
3300
        vec![h_a],
3301
        "main is untouched"
3302
    );
3303
    assert_eq!(
3304
        repo.resolve_change("feature").unwrap(),
3305
        h_b,
3306
        "a one-head bookmark names its change"
3307
    );
3308
    // Reopening keeps the workspace's bookmark.
3309
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3310
    assert_eq!(reopened.config.bookmark, "feature");
3311
    // Back to main: b.txt goes away; work there.
3312
    repo.bookmark_switch("main", false).unwrap();
3313
    assert!(!r.join("b.txt").exists());
3314
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3315
    write(&r, "c.txt", b"c\n");
3316
    let h_c = repo.commit("c on main", &[]).unwrap();
3317
    let list = repo.bookmarks().unwrap();
3318
    assert_eq!(
3319
        list.iter()
3320
            .map(|b| (b.name.as_str(), b.current))
3321
            .collect::<Vec<_>>(),
3322
        vec![("feature", false), ("main", true)]
3323
    );
3324
    assert_eq!(
3325
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3326
        Some(1),
3327
        "c is not on origin yet"
3328
    );
3329
    // Merge feature into main: the union, both heads, no merge change.
3330
    let m = repo.merge("feature").unwrap();
3331
    assert!(m.changed && m.checked_out);
3332
    let mut want = vec![h_b, h_c];
3333
    want.sort();
3334
    assert_eq!(m.heads, want);
3335
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3336
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3337
    assert!(repo.merge("main").is_err());
3338
    // The other bookmark can be pushed by name and appears at origin.
3339
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3340
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3341
    assert!(repo.push("origin", false).unwrap()[0].ok);
3342
    assert_eq!(
3343
        repo.bookmarks()
3344
            .unwrap()
3345
            .iter()
3346
            .find(|b| b.name == "main")
3347
            .unwrap()
3348
            .ahead,
3349
        Some(0)
3350
    );
3351
    // A second workspace inherits the current bookmark and can switch independently.
3352
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3353
    assert_eq!(ws.config.bookmark, "main");
3354
    let mut ws = ws;
3355
    ws.bookmark_switch("feature", false).unwrap();
3356
    assert_eq!(
3357
        Repo::open(&r).unwrap().config.bookmark,
3358
        "main",
3359
        "the first workspace is unaffected"
3360
    );
3361
    assert!(
3362
        repo.bookmark_delete("feature").is_err(),
3363
        "current bookmark of another workspace"
3364
    );
3365
    ws.bookmark_switch("main", false).unwrap();
3366
    // Set and delete.
3367
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3368
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3369
    repo.bookmark_delete("feature").unwrap();
3370
    assert!(repo.resolve_heads("feature").is_err());
3371
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
3372
    assert!(
3373
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3374
        "changes of a deleted bookmark remain"
3375
    );
3376
}
3377
3378
#[test]
3379
fn oxygen_subrepos_pin_follow_and_update() {
3380
    hermetic();
3381
    let dir = tempfile::tempdir().unwrap();
3382
    let root = dir.path();
3383
    // A library repository with two commits, and a bare-ish origin for it.
3384
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3385
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
3386
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3387
        .unwrap()
3388
        .with_home(root.join("home"));
3389
    write(&root.join("lib"), "lib.txt", b"v1\n");
3390
    let l1 = lib.commit("lib v1", &[]).unwrap();
3391
    assert!(lib.push("origin", false).unwrap()[0].ok);
3392
    let _ = lib_origin;
3393
3394
    // The application (a clone of its own origin) adds it as a subrepo.
3395
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3396
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3397
    let _ = app_origin;
3398
    let app_dir = root.join("app");
3399
    let app = Repo::clone(&app_url, &app_dir)
3400
        .unwrap()
3401
        .with_home(root.join("home"));
3402
    write(&app_dir, "main.txt", b"app\n");
3403
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3404
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3405
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3406
    let snap = app.snapshot("status").unwrap();
3407
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
3408
    assert_eq!(
3409
        paths,
3410
        vec![".oxymodules", "libs/lib", "main.txt"],
3411
        "the nested files are not walked"
3412
    );
3413
    let a1 = app.commit("app with lib", &[]).unwrap();
3414
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3415
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3416
    assert!(!files.contains_key("libs/lib/lib.txt"));
3417
    assert!(!app.snapshot("status").unwrap().changed);
3418
    let subs = app.subrepos().unwrap();
3419
    assert_eq!(subs.len(), 1);
3420
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3421
3422
    // Advance the nested repository: the parent sees a modified pin.
3423
    let nested = Repo::open(&app_dir.join("libs/lib"))
3424
        .unwrap()
3425
        .with_home(root.join("home"));
3426
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3427
    let l2 = nested.commit("lib v2", &[]).unwrap();
3428
    assert!(nested.push("origin", false).unwrap()[0].ok);
3429
    let snap = app.snapshot("status").unwrap();
3430
    assert_eq!(
3431
        snap.statuses
3432
            .iter()
3433
            .map(|s| (s.path.as_str(), s.status))
3434
            .collect::<Vec<_>>(),
3435
        vec![("libs/lib", ChangeStatus::Modified)]
3436
    );
3437
    let a2 = app.commit("bump lib", &[]).unwrap();
3438
    // Checking out the older app state brings the nested working copy back
3439
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
3440
    let r = app.checkout(&[a1], false, "checkout").unwrap();
3441
    assert!(
3442
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3443
        "{:?}",
3444
        r.notes
3445
    );
3446
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3447
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3448
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3449
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
3450
    assert!(!app.snapshot("status").unwrap().changed);
3451
    // A dirty nested repository is left alone and reported.
3452
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3453
    let r = app.checkout(&[a2], false, "checkout").unwrap();
3454
    assert!(
3455
        r.notes.iter().any(|n| n.contains("uncommitted")),
3456
        "{:?}",
3457
        r.notes
3458
    );
3459
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3460
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3461
    let r = app.submodule_update(false, &[]).unwrap();
3462
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3463
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3464
    let _ = l2;
3465
3466
    // A fresh clone of the app has the pin but no nested repository until update --init.
3467
    assert!(app.push("origin", false).unwrap()[0].ok);
3468
    let clone_dir = root.join("app-clone");
3469
    let clone = Repo::clone(&app_url, &clone_dir)
3470
        .unwrap()
3471
        .with_home(root.join("home"));
3472
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
3473
    assert_eq!(
3474
        clone.submodule_update(false, &[]).unwrap(),
3475
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3476
    );
3477
    assert_eq!(
3478
        clone.submodule_update(true, &[]).unwrap(),
3479
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3480
    );
3481
    assert_eq!(
3482
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3483
        b"v2\n"
3484
    );
3485
    assert!(!clone.snapshot("status").unwrap().changed);
3486
    // Removing the subrepo leaves the directory and drops the node.
3487
    clone.submodule_remove("libs/lib").unwrap();
3488
    let snap = clone.snapshot("status").unwrap();
3489
    assert!(
3490
        snap.statuses
3491
            .iter()
3492
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3493
        "{:?}",
3494
        snap.statuses
3495
    );
3496
    let c = clone.commit("drop lib", &[]).unwrap();
3497
    assert!(!clone
3498
        .load_state(&[c])
3499
        .unwrap()
3500
        .materialize()
3501
        .files
3502
        .contains_key("libs/lib"));
3503
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
3504
    assert!(
3505
        !clone.snapshot("status").unwrap().changed,
3506
        "an unregistered nested repository is ignored"
3507
    );
3508
}
3509
3510
#[test]
3511
fn git_submodules_import_and_export_as_gitlinks() {
3512
    hermetic();
3513
    if std::process::Command::new("git")
3514
        .arg("--version")
3515
        .output()
3516
        .is_err()
3517
    {
3518
        eprintln!("git not installed; skipping");
3519
        return;
3520
    }
3521
    let dir = tempfile::tempdir().unwrap();
3522
    let root = dir.path();
3523
    let git_in = |d: &Path, args: &[&str]| -> String {
3524
        let out = std::process::Command::new("git")
3525
            .arg("-C")
3526
            .arg(d)
3527
            .args([
3528
                "-c",
3529
                "user.name=Grace",
3530
                "-c",
3531
                "[email protected]",
3532
                "-c",
3533
                "commit.gpgsign=false",
3534
                "-c",
3535
                "protocol.file.allow=always",
3536
            ])
3537
            .args(args)
3538
            .output()
3539
            .unwrap();
3540
        assert!(
3541
            out.status.success(),
3542
            "git {args:?}: {}",
3543
            String::from_utf8_lossy(&out.stderr)
3544
        );
3545
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3546
    };
3547
    let sub = root.join("sub");
3548
    fs::create_dir_all(&sub).unwrap();
3549
    git_in(&sub, &["init", "-q", "-b", "main"]);
3550
    write(&sub, "s.txt", b"sub\n");
3551
    git_in(&sub, &["add", "."]);
3552
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3553
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3554
    let g = root.join("main.git");
3555
    fs::create_dir_all(&g).unwrap();
3556
    git_in(&g, &["init", "-q", "-b", "main"]);
3557
    write(&g, "README.md", b"# app\n");
3558
    git_in(&g, &["add", "."]);
3559
    git_in(&g, &["commit", "-q", "-m", "initial"]);
3560
    git_in(
3561
        &g,
3562
        &[
3563
            "submodule",
3564
            "add",
3565
            "-q",
3566
            sub.to_str().unwrap(),
3567
            "vendor/sub",
3568
        ],
3569
    );
3570
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3571
3572
    let dest = root.join("oxy");
3573
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3574
    let rep = repo.import_git(&g, "main").unwrap();
3575
    assert_eq!((rep.commits, rep.submodules), (2, 1));
3576
    let files = repo
3577
        .load_state(&repo.bookmark_heads().unwrap())
3578
        .unwrap()
3579
        .materialize()
3580
        .files;
3581
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
3582
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3583
        panic!()
3584
    };
3585
    assert_eq!(
3586
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3587
        crate::subrepo::Pin::Git {
3588
            sha: sub_sha.clone(),
3589
            branch: "HEAD".into()
3590
        }
3591
    );
3592
    let modules =
3593
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
3594
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3595
    assert!(modules.entries["vendor/sub"].git);
3596
    assert!(
3597
        files.contains_key(".gitmodules"),
3598
        "the Git file is kept for round trips"
3599
    );
3600
    assert!(
3601
        !dest.join("vendor/sub/.git").exists(),
3602
        "not cloned until update --init"
3603
    );
3604
    assert!(!repo.snapshot("status").unwrap().changed);
3605
    // update --init clones it at the pinned commit; status is unchanged.
3606
    assert_eq!(
3607
        repo.submodule_update(true, &[]).unwrap(),
3608
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3609
    );
3610
    assert_eq!(
3611
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3612
        sub_sha
3613
    );
3614
    assert!(!repo.snapshot("status").unwrap().changed);
3615
    // Export writes the gitlink and .gitmodules back.
3616
    let mirror = root.join("mirror.git");
3617
    let rep = repo.git_export(&mirror).unwrap();
3618
    assert_eq!(rep.skipped_subrepos, 0);
3619
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
3620
    assert!(
3621
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3622
        "{ls}"
3623
    );
3624
    assert_eq!(
3625
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3626
        ".gitmodules\nREADME.md\nvendor"
3627
    );
3628
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
3629
    assert_eq!(
3630
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3631
        orig_tree,
3632
        "tree round trip"
3633
    );
3634
}
3635
3636
#[test]
3637
fn partial_commits_by_path_and_by_hunk() {
3638
    hermetic();
3639
    let dir = tempfile::tempdir().unwrap();
3640
    let root = dir.path();
3641
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3642
    write(root, "a.txt", b"1\n2\n3\n");
3643
    write(root, "b.txt", b"b\n");
3644
    let h0 = repo.commit("base", &[]).unwrap();
3645
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3646
    write(root, "b.txt", b"b\nbb\n");
3647
    write(root, "c.txt", b"c\n");
3648
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
3649
    let h1 = repo
3650
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3651
        .unwrap();
3652
    let c1 = repo.store().get_change(&h1).unwrap();
3653
    assert!(
3654
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3655
        "{:?}",
3656
        c1.tree_ops
3657
    );
3658
    assert_eq!(c1.deps, vec![h0]);
3659
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
3660
    assert!(
3661
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3662
    );
3663
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3664
    assert!(!files.contains_key("c.txt"));
3665
    let snap = repo.snapshot("status").unwrap();
3666
    assert_eq!(
3667
        snap.statuses
3668
            .iter()
3669
            .map(|s| (s.path.as_str(), s.status))
3670
            .collect::<Vec<_>>(),
3671
        vec![
3672
            ("b.txt", ChangeStatus::Modified),
3673
            ("c.txt", ChangeStatus::Added)
3674
        ]
3675
    );
3676
    assert_eq!(
3677
        fs::read(root.join("b.txt")).unwrap(),
3678
        b"b\nbb\n",
3679
        "disk untouched"
3680
    );
3681
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3682
    let (_, hunks) = repo.hunks().unwrap();
3683
    let b_hunk = hunks
3684
        .iter()
3685
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3686
        .unwrap()
3687
        .index;
3688
    let h2 = repo
3689
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3690
        .unwrap();
3691
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
3692
    assert!(
3693
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3694
    );
3695
    assert!(!files.contains_key("c.txt"));
3696
    let snap = repo.snapshot("status").unwrap();
3697
    assert_eq!(
3698
        snap.statuses
3699
            .iter()
3700
            .map(|s| s.path.as_str())
3701
            .collect::<Vec<_>>(),
3702
        vec!["c.txt"]
3703
    );
3704
    // Choosing only the content hunk of a file in a new directory pulls in
3705
    // the directory and file additions it needs.
3706
    write(root, "d/e.txt", b"e\n");
3707
    let (_, hunks) = repo.hunks().unwrap();
3708
    let e_insert = hunks
3709
        .iter()
3710
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3711
        .unwrap()
3712
        .index;
3713
    let h3 = repo
3714
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3715
        .unwrap();
3716
    let c3 = repo.store().get_change(&h3).unwrap();
3717
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3718
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3719
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
3720
    // Choosing a new file's addition hunk brings its content along.
3721
    write(root, "f/g.txt", b"g\n");
3722
    let (_, hunks) = repo.hunks().unwrap();
3723
    let g_add = hunks
3724
        .iter()
3725
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3726
        .unwrap()
3727
        .index;
3728
    let h4 = repo
3729
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3730
        .unwrap();
3731
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
3732
    assert!(
3733
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3734
    );
3735
    assert!(!repo
3736
        .snapshot("status")
3737
        .unwrap()
3738
        .statuses
3739
        .iter()
3740
        .any(|s| s.path == "f/g.txt"));
3741
    // Everything left commits normally; the working copy is then clean.
3742
    repo.commit("the rest", &[]).unwrap();
3743
    assert!(!repo.snapshot("status").unwrap().changed);
3744
    let files = repo
3745
        .load_state(&repo.bookmark_heads().unwrap())
3746
        .unwrap()
3747
        .materialize()
3748
        .files;
3749
    assert!(files.contains_key("c.txt"));
3750
}
3751
3752
#[test]
3753
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3754
    hermetic();
3755
    let dir = tempfile::tempdir().unwrap();
3756
    let root = dir.path();
3757
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3758
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3759
        .unwrap();
3760
    write(root, "a.txt", b"one\n");
3761
    let h1 = repo.commit("first", &[]).unwrap();
3762
    write(root, "a.txt", b"one\ntwo\n");
3763
    let h2 = repo.commit("second", &[]).unwrap();
3764
    let b = repo.blame("a.txt").unwrap();
3765
    assert_eq!(
3766
        b.iter()
3767
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3768
            .collect::<Vec<_>>(),
3769
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3770
    );
3771
    assert!(b.iter().all(|l| l.author == "Ada"));
3772
    assert_eq!(
3773
        b[0].change_id,
3774
        repo.store().get_change(&h1).unwrap().change_id
3775
    );
3776
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3777
    repo.commit("rename", &[]).unwrap();
3778
    let b = repo.blame("b.txt").unwrap();
3779
    assert_eq!(
3780
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3781
        vec![h1, h2],
3782
        "the node survives the rename"
3783
    );
3784
    assert!(repo.blame("a.txt").is_err());
3785
}
3786
3787
#[test]
3788
fn bisect_finds_the_first_bad_change() {
3789
    hermetic();
3790
    let dir = tempfile::tempdir().unwrap();
3791
    let root = dir.path();
3792
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3793
    let mut content = String::new();
3794
    let mut hashes = Vec::new();
3795
    for i in 1..=8 {
3796
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3797
        write(root, "f.txt", content.as_bytes());
3798
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3799
    }
3800
    // Each step appends after the previous line, so the chain is linear.
3801
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3802
    repo.bisect_start().unwrap();
3803
    assert!(matches!(
3804
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3805
        BisectStep::NeedMarks { good: 1, bad: 0 }
3806
    ));
3807
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3808
    assert!(
3809
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3810
        "{step:?}"
3811
    );
3812
    // Automated: bad when the bug line is present.
3813
    let step = repo
3814
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3815
        .unwrap();
3816
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3817
    assert_eq!(
3818
        repo.bisect_status().unwrap(),
3819
        Some(BisectStep::Found { culprit: hashes[4] })
3820
    );
3821
    repo.bisect_reset().unwrap();
3822
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3823
    assert!(repo.bisect_status().unwrap().is_none());
3824
    assert!(!repo.snapshot("status").unwrap().changed);
3825
    // Manual marks and a skip.
3826
    repo.bisect_start().unwrap();
3827
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3828
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3829
    let mut skipped_once = false;
3830
    let mut guard = 0;
3831
    while let BisectStep::Testing { .. } = step {
3832
        guard += 1;
3833
        assert!(guard < 20);
3834
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3835
        if !skipped_once && text.contains("line 6") {
3836
            // An untestable state away from the boundary: the search routes around it.
3837
            skipped_once = true;
3838
            step = repo.bisect_mark(None, &[]).unwrap();
3839
            continue;
3840
        }
3841
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3842
    }
3843
    assert!(skipped_once);
3844
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3845
    repo.bisect_reset().unwrap();
3846
    // Skipping the culprit itself leaves it among the candidates reported.
3847
    repo.bisect_start().unwrap();
3848
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3849
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3850
    let mut guard = 0;
3851
    while let BisectStep::Testing { heads, .. } = &step {
3852
        guard += 1;
3853
        assert!(guard < 20);
3854
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3855
        let is_culprit_state =
3856
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3857
        step = if is_culprit_state {
3858
            repo.bisect_mark(None, &[]).unwrap()
3859
        } else {
3860
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3861
        };
3862
    }
3863
    match step {
3864
        BisectStep::Inconclusive { candidates } => assert!(
3865
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3866
            "{candidates:?}"
3867
        ),
3868
        other => panic!("{other:?}"),
3869
    }
3870
    repo.bisect_reset().unwrap();
3871
}
3872
3873
#[test]
3874
fn squash_folds_a_change_into_its_dependency() {
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\n");
3880
    let a = repo.commit("A", &[]).unwrap();
3881
    write(root, "a.txt", b"1\n2\n");
3882
    let c = repo.commit("C", &[]).unwrap();
3883
    write(root, "a.txt", b"1\n2\n3\n");
3884
    let e = repo.commit("E", &[]).unwrap();
3885
    write(root, "b.txt", b"b\n");
3886
    let b = repo.commit("B", &[]).unwrap();
3887
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3888
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3889
    // E depends on C which A lacks: refused, naming it.
3890
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3891
    assert!(err.contains(&c.short(12)), "{err}");
3892
    // C into A: A' has both, C is gone, E follows and still reads the same.
3893
    let a2 = repo.squash(&c, &a).unwrap();
3894
    let a2c = repo.store().get_change(&a2).unwrap();
3895
    assert_eq!(a2c.change_id, id_a);
3896
    assert!(a2c.deps.is_empty());
3897
    let heads = repo.bookmark_heads().unwrap();
3898
    let st = repo.load_state(&heads).unwrap();
3899
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
3900
    let e2 = st
3901
        .changes()
3902
        .find(|(_, m)| m.change_id == id_e)
3903
        .map(|(h, _)| *h)
3904
        .unwrap();
3905
    assert_eq!(
3906
        repo.store().get_change(&e2).unwrap().deps,
3907
        vec![a2],
3908
        "E now depends on A' alone"
3909
    );
3910
    let files = st.materialize().files;
3911
    assert!(
3912
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3913
    );
3914
    assert!(files.contains_key("b.txt"));
3915
    assert!(st.contains(&b));
3916
    assert!(!repo.snapshot("status").unwrap().changed);
3917
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3918
    // Undo restores the three original changes.
3919
    repo.undo().unwrap();
3920
    repo.undo().unwrap();
3921
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3922
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3923
}
3924
3925
#[test]
3926
fn rebase_re_expresses_a_change_against_another_base() {
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"1\n2\n");
3932
    let a = repo.commit("A", &[]).unwrap();
3933
    write(root, "a.txt", b"1\n2\n3\n");
3934
    let c = repo.commit("C: append 3", &[]).unwrap();
3935
    write(root, "a.txt", b"1\n2\n3\n4\n");
3936
    let e = repo.commit("E: append 4", &[]).unwrap();
3937
    // A different base: A plus a change that prepends a line.
3938
    repo.checkout(&[a], true, "checkout").unwrap();
3939
    write(root, "a.txt", b"0\n1\n2\n");
3940
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3941
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3942
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3943
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3944
    let c2 = repo.rebase(&c, &[d]).unwrap();
3945
    let c2c = repo.store().get_change(&c2).unwrap();
3946
    assert_eq!(c2c.change_id, id_c);
3947
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3948
    let heads = repo.bookmark_heads().unwrap();
3949
    let st = repo.load_state(&heads).unwrap();
3950
    assert!(!st.contains(&c) && st.contains(&d));
3951
    let e2 = st
3952
        .changes()
3953
        .find(|(_, m)| m.change_id == id_e)
3954
        .map(|(h, _)| *h)
3955
        .unwrap();
3956
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
3957
    assert!(
3958
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3959
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3960
    );
3961
    let files = st.materialize().files;
3962
    assert!(
3963
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3964
        "{:?}",
3965
        files["a.txt"].content
3966
    );
3967
    assert!(!files["a.txt"].is_conflicted());
3968
    // Rebasing onto a state that already contains the change is refused.
3969
    assert!(repo.rebase(&c2, &[c2]).is_err());
3970
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
3971
    assert!(
3972
        err.contains("lacks dependencies"),
3973
        "E needs C, which D's state does not have: {err}"
3974
    );
3975
}
3976
3977
#[test]
3978
fn unsigned_tags_keep_their_message() {
3979
    hermetic();
3980
    let dir = tempfile::tempdir().unwrap();
3981
    let root = dir.path();
3982
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3983
    write(root, "a.txt", b"a\n");
3984
    repo.commit("a", &[]).unwrap();
3985
    assert!(repo.secret_key().unwrap().is_none());
3986
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
3987
        .unwrap();
3988
    let tags = repo.tags().unwrap();
3989
    assert_eq!(
3990
        (
3991
            tags[0].name.as_str(),
3992
            tags[0].message.as_str(),
3993
            tags[0].signer.as_deref()
3994
        ),
3995
        ("v1", "first release", None)
3996
    );
3997
    assert!(
3998
        repo.tag_refs().unwrap()[0].attestation.is_none(),
3999
        "an unsigned attestation is not advertised"
4000
    );
4001
}
4002
4003
#[test]
4004
fn fsck_passes_a_sound_repository_and_names_each_fault() {
4005
    hermetic();
4006
    let dir = tempfile::tempdir().unwrap();
4007
    let root = dir.path();
4008
    let origin_path = root.join("origin");
4009
    let origin = Repo::init(&origin_path).unwrap();
4010
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4011
        .unwrap()
4012
        .with_home(root.join("home-a"));
4013
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4014
        .unwrap();
4015
    write(&root.join("a"), "f.txt", b"one\n");
4016
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4017
    let h1 = a.commit("first", &[]).unwrap();
4018
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4019
    let h2 = a.commit("second", &[]).unwrap();
4020
    a.tag_create("v1", &[h2], "first release").unwrap();
4021
    a.checkpoint().unwrap();
4022
    assert!(a.push("origin", false).unwrap()[0].ok);
4023
4024
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4025
    for repo in [&a, &origin] {
4026
        let rep = repo.fsck().unwrap();
4027
        assert_eq!(rep.problems, vec![], "{rep:?}");
4028
        // The two commits, plus the working copy's change in `a`.
4029
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4030
        assert!(rep.ops > 1 && rep.objects > 5);
4031
    }
4032
    assert!(origin.fsck().unwrap().attestations >= 1);
4033
4034
    // A flipped byte in a stored object is corruption, named by hash.
4035
    let c1 = a.store().path_for(&h1);
4036
    let pristine = fs::read(&c1).unwrap();
4037
    let mut bytes = pristine.clone();
4038
    *bytes.last_mut().unwrap() ^= 1;
4039
    fs::write(&c1, &bytes).unwrap();
4040
    let rep = a.fsck().unwrap();
4041
    assert!(rep.errors() >= 1);
4042
    assert!(
4043
        rep.problems
4044
            .iter()
4045
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4046
        "{rep:?}"
4047
    );
4048
    fs::write(&c1, &pristine).unwrap();
4049
    assert_eq!(a.fsck().unwrap().errors(), 0);
4050
4051
    // A missing change is named with what needed it.
4052
    fs::remove_file(&c1).unwrap();
4053
    let rep = a.fsck().unwrap();
4054
    assert!(
4055
        rep.problems.iter().any(|p| p.severity == Severity::Error
4056
            && p.object == Some(h1)
4057
            && p.what.contains("change missing, needed by change")),
4058
        "{rep:?}"
4059
    );
4060
    fs::write(&c1, &pristine).unwrap();
4061
4062
    // A missing blob is an error in a full clone.
4063
    let c2 = a.store().get_change(&h1).unwrap();
4064
    let blob = c2
4065
        .edits
4066
        .iter()
4067
        .find_map(|e| match e {
4068
            Edit::Replace { new: Some(b), .. } => Some(*b),
4069
            _ => None,
4070
        })
4071
        .expect("the binary file is a blob");
4072
    let bp = a.store().path_for(&blob);
4073
    let blob_bytes = fs::read(&bp).unwrap();
4074
    fs::remove_file(&bp).unwrap();
4075
    let rep = a.fsck().unwrap();
4076
    assert!(
4077
        rep.problems
4078
            .iter()
4079
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4080
        "{rep:?}"
4081
    );
4082
    fs::write(&bp, &blob_bytes).unwrap();
4083
4084
    // A broken op log head is reported, not a crash.
4085
    let head = root.join("a/.oxy/ops/head");
4086
    let saved = fs::read(&head).unwrap();
4087
    fs::write(&head, b"not a hash").unwrap();
4088
    let rep = a.fsck().unwrap();
4089
    assert!(
4090
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4091
        "{rep:?}"
4092
    );
4093
    fs::write(&head, saved).unwrap();
4094
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4095
}
4096
4097
/// Copy a directory tree (for restoring a pristine repository).
4098
fn copy_tree(from: &Path, to: &Path) {
4099
    fs::create_dir_all(to).unwrap();
4100
    for e in fs::read_dir(from).unwrap() {
4101
        let e = e.unwrap();
4102
        let target = to.join(e.file_name());
4103
        if e.file_type().unwrap().is_dir() {
4104
            copy_tree(&e.path(), &target);
4105
        } else {
4106
            fs::copy(e.path(), &target).unwrap();
4107
        }
4108
    }
4109
}
4110
4111
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4112
/// would, and check that both repositories still open, pass `fsck`, and
4113
/// accept the same operation again.
4114
#[test]
4115
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
4116
    use crate::durable::failpoint;
4117
    hermetic();
4118
    let dir = tempfile::tempdir().unwrap();
4119
    let pristine = dir.path().join("pristine");
4120
    let origin_path = pristine.join("origin");
4121
    Repo::init(&origin_path).unwrap();
4122
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4123
        .unwrap()
4124
        .with_home(dir.path().join("home"));
4125
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4126
        .unwrap();
4127
    write(&pristine.join("a"), "f.txt", b"one\n");
4128
    a.commit("first", &[]).unwrap();
4129
    assert!(a.push("origin", false).unwrap()[0].ok);
4130
    drop(a);
4131
4132
    type Op = fn(&Repo) -> Result<()>;
4133
    let edit_and_commit: Op = |r| {
4134
        write(r.root(), "f.txt", b"one\ntwo\n");
4135
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4136
        r.commit("second", &[]).map(|_| ())
4137
    };
4138
    let push: Op = |r| {
4139
        let res = r.push("origin", false)?;
4140
        if res.iter().all(|x| x.ok) {
4141
            Ok(())
4142
        } else {
4143
            Err(RepoError::Msg(format!("{res:?}")))
4144
        }
4145
    };
4146
4147
    for (name, prepare, op) in [
4148
        ("commit", None, edit_and_commit),
4149
        ("push", Some(edit_and_commit), push),
4150
    ] {
4151
        let mut steps = 0;
4152
        for n in 1.. {
4153
            let run = dir.path().join(format!("{name}-{n}"));
4154
            copy_tree(&pristine, &run);
4155
            // Clones record their remote by path; point it at this copy.
4156
            let open = |p: &Path| {
4157
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4158
                r.config
4159
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4160
                    .unwrap();
4161
                r.save_config().unwrap();
4162
                r
4163
            };
4164
            let a = open(&run.join("a"));
4165
            if let Some(prep) = prepare {
4166
                prep(&a).unwrap();
4167
            }
4168
            failpoint::crash_after(n);
4169
            let outcome = op(&a);
4170
            let crashed = failpoint::disarm();
4171
            drop(a);
4172
            if !crashed {
4173
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4174
                steps = n - 1;
4175
                break;
4176
            }
4177
            assert!(
4178
                outcome.is_err(),
4179
                "{name}: a crash at step {n} was swallowed"
4180
            );
4181
            for repo in ["a", "origin"] {
4182
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4183
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4184
                });
4185
                let rep = r.fsck().unwrap();
4186
                assert_eq!(
4187
                    rep.errors(),
4188
                    0,
4189
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4190
                    rep.problems
4191
                );
4192
            }
4193
            // The interrupted operation can simply be run again.
4194
            let a = open(&run.join("a"));
4195
            // A crash after the commit point leaves the commit done.
4196
            let landed = a
4197
                .bookmark_heads()
4198
                .unwrap()
4199
                .iter()
4200
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4201
            let again = match (name, landed) {
4202
                ("commit", true) => Ok(()),
4203
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4204
                _ => op(&a),
4205
            };
4206
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4207
            assert_eq!(a.fsck().unwrap().errors(), 0);
4208
            fs::remove_dir_all(&run).unwrap();
4209
        }
4210
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4211
    }
4212
}
4213
4214
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4215
/// running at the same time lose nothing: every commit ends up on the
4216
/// bookmark, locally and on the remote, and the repository passes fsck.
4217
#[test]
4218
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4219
    hermetic();
4220
    let dir = tempfile::tempdir().unwrap();
4221
    let root = dir.path();
4222
    let origin = root.join("origin");
4223
    Repo::init_bare_unbound(&origin).unwrap();
4224
    let main = root.join("main");
4225
    let mut repo = Repo::init(&main).unwrap();
4226
    repo.config
4227
        .set("remote.origin.url", &origin.to_string_lossy())
4228
        .unwrap();
4229
    repo.save_config().unwrap();
4230
    write(&main, "seed.txt", b"seed\n");
4231
    repo.commit("seed", &[]).unwrap();
4232
    let second = root.join("second");
4233
    repo.workspace_add(&second, None).unwrap();
4234
    drop(repo);
4235
4236
    const EACH: usize = 15;
4237
    std::thread::scope(|s| {
4238
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4239
            s.spawn(move || {
4240
                let r = Repo::open(&dir).unwrap();
4241
                for i in 0..EACH {
4242
                    write(
4243
                        &dir,
4244
                        &format!("{tag}-{i}.txt"),
4245
                        format!("{tag} {i}\n").as_bytes(),
4246
                    );
4247
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4248
                    if push && i % 5 == 4 {
4249
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4250
                        let _ = r.push("origin", false);
4251
                    }
4252
                }
4253
            });
4254
        }
4255
    });
4256
4257
    let repo = Repo::open(&main).unwrap();
4258
    let heads = repo.bookmark_heads().unwrap();
4259
    let state = repo.load_state(&heads).unwrap();
4260
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4261
    for tag in ["a", "b"] {
4262
        for i in 0..EACH {
4263
            assert!(
4264
                messages.contains(&format!("{tag} {i}")),
4265
                "lost commit {tag} {i}; have {messages:?}"
4266
            );
4267
        }
4268
    }
4269
    let rep = repo.fsck().unwrap();
4270
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4271
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4272
    let hosted = Repo::open(&origin).unwrap();
4273
    let hosted_heads = hosted.bookmark_heads().unwrap();
4274
    assert_eq!(
4275
        hosted.load_state(&hosted_heads).unwrap().len(),
4276
        state.len(),
4277
        "the remote has every commit"
4278
    );
4279
}
4280
4281
/// Two operations recorded from the same parent (what two processes do
4282
/// when they race) are merged: both bookmarks' heads survive, and a
4283
/// change made on one side only is kept.
4284
#[test]
4285
fn operations_from_the_same_parent_are_merged() {
4286
    hermetic();
4287
    let dir = tempfile::tempdir().unwrap();
4288
    let root = dir.path();
4289
    let repo = Repo::init(root).unwrap();
4290
    write(root, "a.txt", b"a\n");
4291
    let a = repo.commit("a", &[]).unwrap();
4292
    write(root, "b.txt", b"b\n");
4293
    let b = repo.commit("b", &[]).unwrap();
4294
    let (x, op) = repo.head_op().unwrap();
4295
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4296
4297
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4298
    let mut one = op.view.clone();
4299
    one.bookmarks.insert("main".into(), state(vec![a]));
4300
    one.bookmarks.insert("topic".into(), state(vec![a]));
4301
    let mut two = op.view.clone();
4302
    two.bookmarks.insert("main".into(), state(vec![b]));
4303
    repo.record_op(&[x], "one", one).unwrap();
4304
    let merged = repo.record_op(&[x], "two", two).unwrap();
4305
4306
    let (head, op) = repo.head_op().unwrap();
4307
    assert_eq!(head, merged);
4308
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4309
    assert!(op.command.contains("merged with a concurrent operation"));
4310
    let mut main = repo
4311
        .store()
4312
        .get_state(&op.view.bookmarks["main"])
4313
        .unwrap()
4314
        .heads;
4315
    main.sort();
4316
    let mut want = vec![a, b];
4317
    want.sort();
4318
    assert_eq!(main, want, "both sides' heads are kept");
4319
    assert!(
4320
        op.view.bookmarks.contains_key("topic"),
4321
        "a one-sided change survives"
4322
    );
4323
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4324
}
4325
4326
#[test]
4327
fn failed_requests_come_with_a_next_step() {
4328
    use crate::protocol::hint_for;
4329
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4330
        .unwrap()
4331
        .contains("token"));
4332
    assert!(hint_for("…: HTTP 403: forbidden")
4333
        .unwrap()
4334
        .contains("repo:write"));
4335
    assert!(hint_for("…: HTTP 404: no such repository")
4336
        .unwrap()
4337
        .contains("owner and repository name"));
4338
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4339
        .unwrap()
4340
        .contains("oxyhub-ca.pem"));
4341
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4342
        .unwrap()
4343
        .contains("running"));
4344
    assert!(hint_for("Dns Failed: failed to lookup address information")
4345
        .unwrap()
4346
        .contains("resolve"));
4347
    assert_eq!(hint_for("something else entirely"), None);
4348
}
4349
4350
#[test]
4351
fn doctor_names_problems_and_what_to_do() {
4352
    hermetic();
4353
    let dir = tempfile::tempdir().unwrap();
4354
    let root = dir.path();
4355
    let origin = root.join("origin");
4356
    Repo::init_bare_unbound(&origin).unwrap();
4357
    let mut repo = Repo::init(&root.join("r"))
4358
        .unwrap()
4359
        .with_home(root.join("home"));
4360
    let find = |r: &DoctorReport, area: &str, h: Health| {
4361
        r.checks
4362
            .iter()
4363
            .find(|c| c.area == area && c.health == h)
4364
            .cloned()
4365
    };
4366
4367
    let r = repo.doctor(true);
4368
    assert!(find(&r, "identity", Health::Warn)
4369
        .unwrap()
4370
        .hint
4371
        .unwrap()
4372
        .contains("oxy identity create"));
4373
    assert!(find(&r, "repository", Health::Ok).is_some());
4374
4375
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4376
        .unwrap();
4377
    repo.config.set("author.name", "Ada").unwrap();
4378
    repo.config.set("author.email", "[email protected]").unwrap();
4379
    repo.config
4380
        .set("remote.origin.url", &origin.to_string_lossy())
4381
        .unwrap();
4382
    repo.config
4383
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4384
        .unwrap();
4385
    repo.config.set("remote.down.token", "t").unwrap();
4386
    repo.config
4387
        .set("remote.badca.url", "https://example.invalid/a/b")
4388
        .unwrap();
4389
    repo.config
4390
        .set(
4391
            "remote.badca.ca",
4392
            &root.join("missing.pem").to_string_lossy(),
4393
        )
4394
        .unwrap();
4395
    repo.save_config().unwrap();
4396
4397
    let r = repo.doctor(true);
4398
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4399
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4400
    assert!(find(&r, "remote origin", Health::Ok)
4401
        .unwrap()
4402
        .message
4403
        .contains("first push binds it"));
4404
    let down = find(&r, "remote down", Health::Fail).unwrap();
4405
    assert!(
4406
        down.hint.as_deref().unwrap_or("").contains("running"),
4407
        "{down:?}"
4408
    );
4409
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4410
    assert!(
4411
        badca.hint.unwrap().contains("remote.badca.ca"),
4412
        "the remote's own name is in the hint"
4413
    );
4414
    assert_eq!(r.worst(), Health::Fail);
4415
4416
    // Offline, nothing is contacted.
4417
    let r = repo.doctor(false);
4418
    assert!(find(&r, "remote down", Health::Fail).is_none());
4419
    assert!(find(&r, "remote down", Health::Ok)
4420
        .unwrap()
4421
        .message
4422
        .contains("not contacted"));
4423
}
4424
4425
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4426
/// after it. Inserting after `b` and then deleting `b`, one commit after
4427
/// the other, must not leave a delete/insert conflict.
4428
#[test]
4429
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4430
    hermetic();
4431
    let dir = tempfile::tempdir().unwrap();
4432
    let root = dir.path();
4433
    let repo = Repo::init(root).unwrap();
4434
    write(root, "f", b"a\nb\nc\n");
4435
    repo.commit("base", &[]).unwrap();
4436
    write(root, "f", b"a\nb\nx\nc\n");
4437
    let insert = repo.commit("insert x after b", &[]).unwrap();
4438
    write(root, "f", b"a\nx\nc\n");
4439
    let delete = repo.commit("delete b", &[]).unwrap();
4440
    assert!(
4441
        repo.store()
4442
            .get_change(&delete)
4443
            .unwrap()
4444
            .deps
4445
            .contains(&insert),
4446
        "the deletion depends on the insertion below the deleted line"
4447
    );
4448
    let heads = repo.bookmark_heads().unwrap();
4449
    assert_eq!(heads, vec![delete]);
4450
    let snap = repo.load_state(&heads).unwrap().materialize();
4451
    assert!(!snap.is_conflicted());
4452
    assert!(
4453
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4454
    );
4455
}
4456
4457
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4458
/// replacement depends on the change that set the blob it replaces.
4459
#[test]
4460
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4461
    hermetic();
4462
    let dir = tempfile::tempdir().unwrap();
4463
    let root = dir.path();
4464
    let repo = Repo::init(root).unwrap();
4465
    write(root, "bin", b"\0A");
4466
    let v1 = repo.commit("v1", &[]).unwrap();
4467
    write(root, "bin", b"\0B");
4468
    let v2 = repo.commit("v2", &[]).unwrap();
4469
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4470
    write(root, "bin", b"\0A");
4471
    let v3 = repo.commit("back to A", &[]).unwrap();
4472
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4473
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4474
    let state = repo.load_state(&[v3]).unwrap();
4475
    let snap = state.materialize();
4476
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4477
        panic!("opaque")
4478
    };
4479
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4480
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4481
}
4482
4483
/// Spec §23: a binary file changed on two branches and merged in Git to
4484
/// one side's version comes back as that version at the merge, and the
4485
/// import verifies commit by commit.
4486
#[test]
4487
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4488
    hermetic();
4489
    if std::process::Command::new("git")
4490
        .arg("--version")
4491
        .output()
4492
        .is_err()
4493
    {
4494
        eprintln!("git not installed; skipping");
4495
        return;
4496
    }
4497
    let dir = tempfile::tempdir().unwrap();
4498
    let root = dir.path();
4499
    let g = root.join("src.git");
4500
    fs::create_dir_all(&g).unwrap();
4501
    let git = |args: &[&str]| -> String {
4502
        let out = std::process::Command::new("git")
4503
            .arg("-C")
4504
            .arg(&g)
4505
            .args([
4506
                "-c",
4507
                "user.name=Grace",
4508
                "-c",
4509
                "[email protected]",
4510
                "-c",
4511
                "commit.gpgsign=false",
4512
            ])
4513
            .args(args)
4514
            .output()
4515
            .unwrap();
4516
        assert!(
4517
            out.status.success(),
4518
            "git {args:?}: {}",
4519
            String::from_utf8_lossy(&out.stderr)
4520
        );
4521
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4522
    };
4523
    git(&["init", "-q", "-b", "main"]);
4524
    write(&g, "logo.bin", b"\0base");
4525
    write(&g, "notes.txt", b"a\nb\nc\n");
4526
    git(&["add", "."]);
4527
    git(&["commit", "-qm", "base"]);
4528
    git(&["checkout", "-qb", "side"]);
4529
    write(&g, "logo.bin", b"\0side");
4530
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4531
    git(&["commit", "-qam", "side"]);
4532
    git(&["checkout", "-q", "main"]);
4533
    write(&g, "logo.bin", b"\0main");
4534
    git(&["commit", "-qam", "main"]);
4535
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4536
    let _ = std::process::Command::new("git")
4537
        .arg("-C")
4538
        .arg(&g)
4539
        .args([
4540
            "-c",
4541
            "user.name=G",
4542
            "-c",
4543
            "user.email=g@e",
4544
            "merge",
4545
            "-q",
4546
            "side",
4547
        ])
4548
        .output();
4549
    write(&g, "logo.bin", b"\0main");
4550
    git(&["add", "."]);
4551
    git(&["commit", "-qm", "merge side"]);
4552
    // Then a revert of the binary to its first version.
4553
    write(&g, "logo.bin", b"\0base");
4554
    git(&["commit", "-qam", "back to base"]);
4555
4556
    let repo = Repo::init(&root.join("o")).unwrap();
4557
    let rep = repo.import_git(&g, "main").unwrap();
4558
    assert_eq!(rep.merges, 1);
4559
    let v = repo.verify_git_import(&g, "main").unwrap();
4560
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4561
    assert_eq!(v.commits, 5);
4562
    let snap = repo
4563
        .load_state(&repo.bookmark_heads().unwrap())
4564
        .unwrap()
4565
        .materialize();
4566
    assert!(!snap.is_conflicted());
4567
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4568
        panic!("opaque")
4569
    };
4570
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4571
}
4572
4573
/// Spec §7.7 on a file system without executable bits or symlinks: the
4574
/// recorded bit is kept, and a symlink checked out as a plain file holding
4575
/// its target is still that symlink.
4576
#[cfg(unix)]
4577
#[test]
4578
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4579
    use crate::portable::Platform;
4580
    use std::os::unix::fs::PermissionsExt;
4581
    hermetic();
4582
    let dir = tempfile::tempdir().unwrap();
4583
    let root = dir.path();
4584
    let repo = Repo::init(root).unwrap();
4585
    write(root, "run.sh", b"#!/bin/sh\n");
4586
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4587
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4588
    repo.commit("script and link", &[]).unwrap();
4589
    drop(repo);
4590
4591
    // What checking out on Windows leaves: no exec bit, the link as a file.
4592
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4593
    fs::remove_file(root.join("link")).unwrap();
4594
    write(root, "link", b"run.sh");
4595
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4596
    let s = win.snapshot("oxy status").unwrap();
4597
    assert!(
4598
        s.statuses.is_empty(),
4599
        "nothing changed on Windows: {:?}",
4600
        statuses(&s)
4601
    );
4602
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4603
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4604
    write(root, "link", b"other");
4605
    let h = win.commit("edit on Windows", &[]).unwrap();
4606
    let snap = win.load_state(&[h]).unwrap().materialize();
4607
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4608
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4609
    // The same working copy read as Linux sees the lost bit and the plain file.
4610
    let linux = Repo::open(root).unwrap();
4611
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4612
}
4613
4614
/// Paths that collide on case-insensitive or Windows file systems are
4615
/// named at checkout there, and by doctor everywhere.
4616
#[test]
4617
fn paths_other_platforms_cannot_hold_are_reported() {
4618
    use crate::portable::Platform;
4619
    hermetic();
4620
    let dir = tempfile::tempdir().unwrap();
4621
    let root = dir.path();
4622
    let repo = Repo::init(root).unwrap();
4623
    write(root, "README.md", b"a\n");
4624
    write(root, "readme.md", b"b\n");
4625
    write(root, "src/aux.c", b"int x;\n");
4626
    let h = repo.commit("unportable", &[]).unwrap();
4627
    let r = repo.doctor(false);
4628
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4629
    assert_eq!(port.health, Health::Warn);
4630
    assert!(
4631
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4632
        "{}",
4633
        port.message
4634
    );
4635
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4636
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4637
    assert!(
4638
        rep.notes
4639
            .iter()
4640
            .any(|n| n.contains("README.md and readme.md")),
4641
        "{:?}",
4642
        rep.notes
4643
    );
4644
    assert!(
4645
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4646
        "macOS allows aux.c"
4647
    );
4648
}
4649
4650
#[test]
4651
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4652
    hermetic();
4653
    let dir = tempfile::tempdir().unwrap();
4654
    let repo = Repo::init(dir.path()).unwrap();
4655
    write(dir.path(), "a.txt", b"one\n");
4656
    write(dir.path(), "other.txt", b"x\n");
4657
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4658
    repo.snapshot("t").unwrap();
4659
    let c1 = repo.commit("first", &[]).unwrap();
4660
    write(dir.path(), "other.txt", b"y\n");
4661
    repo.snapshot("t").unwrap();
4662
    repo.commit("other only", &[]).unwrap();
4663
    write(dir.path(), "a.txt", b"one\ntwo\n");
4664
    repo.snapshot("t").unwrap();
4665
    let c3 = repo.commit("second line", &[]).unwrap();
4666
    write(dir.path(), "other.txt", b"z\n");
4667
    repo.snapshot("t").unwrap();
4668
    repo.commit("other again", &[]).unwrap();
4669
4670
    let heads = repo.bookmark_heads().unwrap();
4671
    let state = repo.load_state(&heads).unwrap();
4672
    let full: Vec<ChangeHash> = repo
4673
        .log_for_path_in("a.txt", &heads)
4674
        .unwrap()
4675
        .iter()
4676
        .map(|e| e.hash)
4677
        .collect();
4678
    assert_eq!(
4679
        full,
4680
        vec![c3, c1],
4681
        "newest first, only changes touching the path"
4682
    );
4683
    let newest: Vec<ChangeHash> = repo
4684
        .log_for_path_of(&state, "a.txt", Some(1))
4685
        .unwrap()
4686
        .iter()
4687
        .map(|e| e.hash)
4688
        .collect();
4689
    assert_eq!(newest, vec![c3], "stops at the first");
4690
    assert_eq!(
4691
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4692
        2
4693
    );
4694
    assert!(repo
4695
        .log_for_path_of(&state, "missing.txt", Some(1))
4696
        .is_err());
4697
    assert_eq!(
4698
        repo.log_state(&heads).unwrap().len(),
4699
        repo.log_of(&state).len()
4700
    );
4701
4702
    let tree = state.tree().view();
4703
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4704
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4705
    assert_eq!(
4706
        via_state
4707
            .iter()
4708
            .map(|l| (l.hash, l.text.clone()))
4709
            .collect::<Vec<_>>(),
4710
        via_heads
4711
            .iter()
4712
            .map(|l| (l.hash, l.text.clone()))
4713
            .collect::<Vec<_>>()
4714
    );
4715
    assert_eq!(
4716
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4717
        vec![c1, c3]
4718
    );
4719
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4720
}
4721
4722
/// A text file whose stat matches the manifest and whose recorded hash is
4723
/// the base's content is taken from the base without reading it; anything
4724
/// else is read, so no edit is missed (spec §12.3).
4725
#[cfg(unix)]
4726
#[test]
4727
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4728
    use std::os::unix::fs::PermissionsExt;
4729
    hermetic();
4730
    let dir = tempfile::tempdir().unwrap();
4731
    let root = dir.path();
4732
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4733
    write(root, "a.txt", b"one\ntwo\n");
4734
    write(root, "b.txt", b"bee\n");
4735
    repo.commit("base", &[]).unwrap();
4736
    let age = |p: &str| {
4737
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4738
        fs::File::options()
4739
            .write(true)
4740
            .open(root.join(p))
4741
            .unwrap()
4742
            .set_modified(old)
4743
            .unwrap();
4744
    };
4745
    age("a.txt");
4746
    age("b.txt");
4747
    assert!(
4748
        !repo.snapshot("status").unwrap().changed,
4749
        "records the aged stat"
4750
    );
4751
4752
    // Clean and equal to the base: not read at all.
4753
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4754
    let snap = repo.snapshot("status").unwrap();
4755
    assert!(
4756
        !snap.changed && snap.statuses.is_empty(),
4757
        "{:?}",
4758
        snap.statuses
4759
    );
4760
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4761
4762
    // An uncommitted edit that is older than the manifest: stat-clean, but
4763
    // its hash is not the base's, so it is read and stays visible.
4764
    write(root, "b.txt", b"bee edited\n");
4765
    age("b.txt");
4766
    let first = repo.snapshot("status").unwrap();
4767
    assert_eq!(
4768
        statuses(&first),
4769
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4770
    );
4771
    let again = repo.snapshot("status").unwrap();
4772
    assert_eq!(
4773
        statuses(&again),
4774
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4775
        "still seen once stat-clean"
4776
    );
4777
    assert!(!again.changed, "and the working copy hashes the same");
4778
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4779
    assert!(
4780
        repo.snapshot("status").is_err(),
4781
        "an edited file must be read, never taken from the base"
4782
    );
4783
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4784
4785
    // A same-size edit made just now is racy and read.
4786
    write(root, "a.txt", b"one\nTWO\n");
4787
    assert_eq!(
4788
        statuses(&repo.snapshot("status").unwrap()),
4789
        vec![
4790
            ("a.txt".to_string(), ChangeStatus::Modified),
4791
            ("b.txt".to_string(), ChangeStatus::Modified)
4792
        ]
4793
    );
4794
    // Committing makes the edits the base: both are clean and served from it again.
4795
    repo.commit("edits", &[]).unwrap();
4796
    age("a.txt");
4797
    age("b.txt");
4798
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4799
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4800
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4801
    let snap = repo.snapshot("status").unwrap();
4802
    assert!(!snap.changed && snap.statuses.is_empty());
4803
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4804
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4805
}
4806
4807
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4808
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4809
/// file is unchanged, and loading through the checkpoint equals a full load.
4810
#[test]
4811
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4812
    hermetic();
4813
    let dir = tempfile::tempdir().unwrap();
4814
    let root = dir.path();
4815
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4816
    let long: String = (0..300)
4817
        .map(|i| format!("line {i} of a long file\n"))
4818
        .collect();
4819
    write(root, "long.txt", long.as_bytes());
4820
    write(root, "short.txt", b"short\n");
4821
    repo.commit("base", &[]).unwrap();
4822
    let (r1, _, _) = repo.checkpoint().unwrap();
4823
    let cp1 = crate::objects::Checkpoint::decode(
4824
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4825
    )
4826
    .unwrap();
4827
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4828
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4829
4830
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4831
    repo.gc(true).unwrap();
4832
    assert!(repo.store().has(&graphs1[0]));
4833
    let report = repo.fsck().unwrap();
4834
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4835
4836
    // Loading through the checkpoint equals a full load.
4837
    write(root, "short.txt", b"short, edited\n");
4838
    repo.commit("edit the short file", &[]).unwrap();
4839
    let heads = repo.bookmark_heads().unwrap();
4840
    let fast = repo.load_state(&heads).unwrap();
4841
    let full = repo.load_state_full(&heads).unwrap();
4842
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4843
4844
    // The next checkpoint shares the unchanged long file's graph.
4845
    let (r2, _, _) = repo.checkpoint().unwrap();
4846
    let cp2 = crate::objects::Checkpoint::decode(
4847
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
4848
    )
4849
    .unwrap();
4850
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
4851
4852
    // A shallow clone's bundle carries the graph blob with the checkpoint.
4853
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
4854
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
4855
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
4856
4857
    // A version 1 checkpoint written by an older oxy still loads.
4858
    let state = repo.load_state_full(&heads).unwrap();
4859
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
4860
    let cp_old = crate::objects::Checkpoint {
4861
        heads: cp2.heads.clone(),
4862
        count: cp2.count,
4863
        payload: old,
4864
    };
4865
    let r_old = repo
4866
        .store()
4867
        .put(ObjectType::Checkpoint, &cp_old.encode())
4868
        .unwrap();
4869
    repo.install_checkpoint("main", &r_old).unwrap();
4870
    assert_eq!(
4871
        repo.load_state(&heads).unwrap().checkpoint_payload(),
4872
        full.checkpoint_payload()
4873
    );
4874
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4875
4876
    // A lost graph blob fails the load loudly rather than dropping the
4877
    // file, and fsck reports it (a fresh repository, objects still loose).
4878
    let dir2 = tempfile::tempdir().unwrap();
4879
    let root2 = dir2.path();
4880
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
4881
    write(root2, "long.txt", long.as_bytes());
4882
    repo2.commit("base", &[]).unwrap();
4883
    let (r, _, _) = repo2.checkpoint().unwrap();
4884
    let cp = crate::objects::Checkpoint::decode(
4885
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
4886
    )
4887
    .unwrap();
4888
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
4889
    fs::remove_file(repo2.store().path_for(&graph)).unwrap();
4890
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
4891
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
4892
}
4893
4894
/// A new repository has not stored the user's identity yet (that happens
4895
/// at the first signed change); looking it up falls back to the key
4896
/// directory, and a file there that does not hash to the key is refused.
4897
#[test]
4898
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
4899
    hermetic();
4900
    let dir = tempfile::tempdir().unwrap();
4901
    let home = dir.path().join("home");
4902
    let mut first = Repo::init(&dir.path().join("a"))
4903
        .unwrap()
4904
        .with_home(home.clone());
4905
    let (key, _) = first
4906
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4907
        .unwrap();
4908
    let fresh = Repo::init(&dir.path().join("b"))
4909
        .unwrap()
4910
        .with_home(home.clone());
4911
    assert!(!fresh.store().has(&key), "nothing stored yet");
4912
    let id = fresh.identity(&key).unwrap();
4913
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
4914
    // A key file that is not this identity is an error, not a wrong answer.
4915
    let keys = fresh.keys_dir.clone();
4916
    let (other, _) = first
4917
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4918
        .unwrap();
4919
    fs::copy(
4920
        keys.join(format!("{}.identity", other.to_hex())),
4921
        keys.join(format!("{}.identity", key.to_hex())),
4922
    )
4923
    .unwrap();
4924
    assert!(fresh
4925
        .identity(&key)
4926
        .unwrap_err()
4927
        .to_string()
4928
        .contains("does not hold identity"));
4929
}
4930
4931
/// Status snapshots (spec §12.3): a text file whose stat matches the
4932
/// manifest, and whose base graph key is the one the manifest recorded it
4933
/// equal to, is neither read nor rendered; any edit, and any change to the
4934
/// file's graph in the base, brings it back.
4935
#[cfg(unix)]
4936
#[test]
4937
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
4938
    use std::os::unix::fs::PermissionsExt;
4939
    hermetic();
4940
    let dir = tempfile::tempdir().unwrap();
4941
    let root = dir.path();
4942
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4943
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
4944
        write(root, p, c.as_bytes());
4945
    }
4946
    repo.commit("base", &[]).unwrap();
4947
    let age = |p: &str| {
4948
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4949
        fs::File::options()
4950
            .write(true)
4951
            .open(root.join(p))
4952
            .unwrap()
4953
            .set_modified(old)
4954
            .unwrap();
4955
    };
4956
    let lock = |p: &str, mode: u32| {
4957
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
4958
    };
4959
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4960
        age(p);
4961
    }
4962
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4963
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4964
    assert!(
4965
        m.entries.values().all(|e| e.graph.is_some()),
4966
        "keys recorded"
4967
    );
4968
4969
    // Unreadable files prove they are not read; the status snapshot does
4970
    // not render them either, and its base lacks their graphs.
4971
    lock("a.txt", 0o000);
4972
    lock("b.txt", 0o000);
4973
    let snap = repo.snapshot_status("status").unwrap();
4974
    assert!(!snap.changed && snap.statuses.is_empty());
4975
    assert_eq!(
4976
        snap.base_snapshot
4977
            .unrendered
4978
            .iter()
4979
            .cloned()
4980
            .collect::<Vec<_>>(),
4981
        vec!["a.txt", "b.txt", "d/c.txt"]
4982
    );
4983
    assert!(!snap.base.is_full());
4984
    assert!(!snap.base_snapshot.is_conflicted());
4985
    // A full snapshot does not read them either, but renders everything.
4986
    let full = repo.snapshot("status").unwrap();
4987
    assert!(full.statuses.is_empty() && full.base.is_full());
4988
    assert!(full.base_snapshot.unrendered.is_empty());
4989
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
4990
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
4991
4992
    // An edit is seen; the file is rendered, the others still are not.
4993
    write(root, "d/c.txt", b"sea edited\n");
4994
    let snap = repo.snapshot_status("status").unwrap();
4995
    assert_eq!(
4996
        statuses(&snap),
4997
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
4998
    );
4999
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5000
    // So is a mode change of an unread file.
5001
    lock("b.txt", 0o100);
5002
    assert_eq!(
5003
        statuses(&repo.snapshot_status("status").unwrap()),
5004
        vec![
5005
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5006
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5007
        ]
5008
    );
5009
    lock("b.txt", 0o000);
5010
5011
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5012
    // stays unread, c.txt is read once and then skipped too.
5013
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5014
        .unwrap();
5015
    age("d/c.txt");
5016
    let snap = repo.snapshot_status("status").unwrap();
5017
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5018
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5019
    lock("d/c.txt", 0o000);
5020
    let snap = repo.snapshot_status("status").unwrap();
5021
    assert!(snap.statuses.is_empty());
5022
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5023
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5024
        lock(p, 0o644);
5025
    }
5026
}
5027
5028
/// Attributes decide how a file compares with the base, so a changed
5029
/// `.oxyattributes` makes every text file be compared again.
5030
#[cfg(unix)]
5031
#[test]
5032
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5033
    hermetic();
5034
    let dir = tempfile::tempdir().unwrap();
5035
    let root = dir.path();
5036
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5037
    write(root, "a.txt", b"crlf\r\n");
5038
    repo.commit("base", &[]).unwrap();
5039
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5040
    fs::File::options()
5041
        .write(true)
5042
        .open(root.join("a.txt"))
5043
        .unwrap()
5044
        .set_modified(old)
5045
        .unwrap();
5046
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5047
    assert!(repo
5048
        .snapshot_status("status")
5049
        .unwrap()
5050
        .base_snapshot
5051
        .unrendered
5052
        .contains("a.txt"));
5053
    // With eol=lf, a.txt as stored no longer equals the base.
5054
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5055
    let snap = repo.snapshot_status("status").unwrap();
5056
    assert_eq!(
5057
        statuses(&snap),
5058
        vec![
5059
            (".oxyattributes".to_string(), ChangeStatus::Added),
5060
            ("a.txt".to_string(), ChangeStatus::Modified)
5061
        ]
5062
    );
5063
}
5064
5065
/// Bookmarks with `/` in their names: pushing records their
5066
/// attestations, and checkpoints are kept for them, beside `feature`
5067
/// itself.
5068
#[test]
5069
fn bookmarks_with_slashes_push_and_checkpoint() {
5070
    hermetic();
5071
    let dir = tempfile::tempdir().unwrap();
5072
    let root = dir.path();
5073
    let origin = Repo::init(&root.join("origin")).unwrap();
5074
    let url = root.join("origin").to_string_lossy().to_string();
5075
    let mut repo = Repo::clone(&url, &root.join("r"))
5076
        .unwrap()
5077
        .with_home(root.join("home"));
5078
    // With an identity, pushes carry reference attestations: the case
5079
    // that failed, since the attestation is a file named after the bookmark.
5080
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5081
        .unwrap();
5082
    let r = root.join("r");
5083
    write(&r, "a.txt", b"a\n");
5084
    let h_a = repo.commit("a", &[]).unwrap();
5085
    assert!(repo.push("origin", false).unwrap()[0].ok);
5086
    repo.bookmark_create("feature", None).unwrap();
5087
    repo.bookmark_create("feature/x", None).unwrap();
5088
    repo.bookmark_switch("feature/x", false).unwrap();
5089
    write(&r, "b.txt", b"b\n");
5090
    let h_b = repo.commit("b", &[]).unwrap();
5091
    for name in ["feature", "feature/x"] {
5092
        let res = repo.push_bookmark("origin", name, false).unwrap();
5093
        assert!(res[0].ok, "{name}: {res:?}");
5094
    }
5095
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5096
    assert_eq!(
5097
        origin.resolve_heads("feature/x").unwrap(),
5098
        repo.resolve_heads("feature/x").unwrap()
5099
    );
5100
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5101
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5102
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5103
5104
    // A checkpoint of feature/x is found again when loading its state.
5105
    let (cp, _, _) = repo.checkpoint().unwrap();
5106
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5107
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5108
    let heads = repo.resolve_heads("feature/x").unwrap();
5109
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
5110
}
5111
5112
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5113
/// never the remote's own bookmark, and a bookmark created again later is
5114
/// accepted although the deletion's attestation stays the latest.
5115
#[test]
5116
fn bookmarks_are_deleted_on_a_remote() {
5117
    hermetic();
5118
    let dir = tempfile::tempdir().unwrap();
5119
    let root = dir.path();
5120
    let origin = Repo::init(&root.join("origin")).unwrap();
5121
    let url = root.join("origin").to_string_lossy().to_string();
5122
    let mut repo = Repo::clone(&url, &root.join("r"))
5123
        .unwrap()
5124
        .with_home(root.join("home"));
5125
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5126
        .unwrap();
5127
    let r = root.join("r");
5128
    write(&r, "a.txt", b"a\n");
5129
    repo.commit("a", &[]).unwrap();
5130
    assert!(repo.push("origin", false).unwrap()[0].ok);
5131
    repo.bookmark_create("feature/x", None).unwrap();
5132
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5133
    assert!(origin.resolve_heads("feature/x").is_ok());
5134
5135
    let res = repo.push_delete("origin", "feature/x").unwrap();
5136
    assert!(res[0].ok, "{res:?}");
5137
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5138
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5139
    assert!(
5140
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5141
        "the deletion is attested"
5142
    );
5143
    assert!(
5144
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5145
        "the local bookmark stays"
5146
    );
5147
    assert!(!repo
5148
        .view()
5149
        .unwrap()
5150
        .remotes
5151
        .get("origin")
5152
        .is_some_and(|m| m.contains_key("feature/x")));
5153
5154
    // Pushing it again creates it again, past the deletion's serial.
5155
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5156
    assert!(res[0].ok, "{res:?}");
5157
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5158
5159
    // Nothing to delete, and never the remote's own bookmark.
5160
    assert!(repo.push_delete("origin", "nope").is_err());
5161
    let res = repo.push_delete("origin", "main").unwrap();
5162
    assert!(
5163
        !res[0].ok && res[0].reason.contains("default bookmark"),
5164
        "{res:?}"
5165
    );
5166
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
5167
}
5168
5169
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5170
/// when the target has the same versions of the files it touches, and is
5171
/// refused, untouched, when it has others.
5172
#[test]
5173
fn switching_bookmarks_carries_uncommitted_work() {
5174
    hermetic();
5175
    let dir = tempfile::tempdir().unwrap();
5176
    let root = dir.path();
5177
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5178
    write(root, "a.txt", b"a\n");
5179
    write(root, "b.txt", b"b\n");
5180
    write(root, "gone.txt", b"gone\n");
5181
    repo.commit("base", &[]).unwrap();
5182
    repo.bookmark_create("feature", None).unwrap();
5183
    // Started on main, belongs on feature: edit, add, remove.
5184
    write(root, "a.txt", b"a\nmore\n");
5185
    write(root, "new.txt", b"new\n");
5186
    fs::remove_file(root.join("gone.txt")).unwrap();
5187
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5188
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5189
    assert_eq!(repo.config.bookmark, "feature");
5190
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5191
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5192
    assert!(!root.join("gone.txt").exists());
5193
    let snap = repo.snapshot("status").unwrap();
5194
    assert_eq!(
5195
        statuses(&snap),
5196
        vec![
5197
            ("a.txt".to_string(), ChangeStatus::Modified),
5198
            ("gone.txt".to_string(), ChangeStatus::Removed),
5199
            ("new.txt".to_string(), ChangeStatus::Added)
5200
        ]
5201
    );
5202
    repo.commit("the work", &[]).unwrap();
5203
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5204
5205
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5206
    repo.bookmark_switch("main", false).unwrap();
5207
    write(root, "b.txt", b"b on main\n");
5208
    repo.commit("b on main", &[]).unwrap();
5209
    repo.bookmark_switch("feature", false).unwrap();
5210
    write(root, "b.txt", b"b edited\n");
5211
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5212
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5213
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5214
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5215
}
5216
5217
/// Merging and checking out (feedback 3): a working copy without changes
5218
/// follows a merge whichever state it sat on; a refused checkout names
5219
/// what is in the way; `checkout --carry` takes the work along.
5220
#[test]
5221
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5222
    hermetic();
5223
    let dir = tempfile::tempdir().unwrap();
5224
    let root = dir.path();
5225
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5226
    write(root, "a.txt", b"a\n");
5227
    let h1 = repo.commit("a", &[]).unwrap();
5228
    write(root, "b.txt", b"b\n");
5229
    repo.commit("b", &[]).unwrap();
5230
    repo.bookmark_create("feature", None).unwrap();
5231
    repo.bookmark_switch("feature", false).unwrap();
5232
    write(root, "c.txt", b"c\n");
5233
    repo.commit("c on feature", &[]).unwrap();
5234
    repo.bookmark_switch("main", false).unwrap();
5235
    // The working copy sits on an older state than main's heads.
5236
    repo.checkout(&[h1], false, "checkout").unwrap();
5237
    assert!(!root.join("b.txt").exists());
5238
    let m = repo.merge("feature").unwrap();
5239
    assert!(m.checked_out, "a clean working copy follows the merge");
5240
    for f in ["a.txt", "b.txt", "c.txt"] {
5241
        assert!(root.join(f).exists(), "{f}");
5242
    }
5243
5244
    // A refusal says which paths are in the way and what to do.
5245
    fs::remove_file(root.join("b.txt")).unwrap();
5246
    write(root, "a.txt", b"a edited\n");
5247
    let err = repo
5248
        .checkout(&[h1], false, "checkout")
5249
        .unwrap_err()
5250
        .to_string();
5251
    assert!(
5252
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5253
        "{err}"
5254
    );
5255
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5256
    // is carried as absent (h1 has none either, so that is refused).
5257
    let err = repo
5258
        .checkout_carry(&[h1], "the first change", "checkout")
5259
        .unwrap_err()
5260
        .to_string();
5261
    assert!(
5262
        err.contains("b.txt") && err.contains("the first change"),
5263
        "{err}"
5264
    );
5265
    write(root, "b.txt", b"b\n");
5266
    let (_, carried) = repo
5267
        .checkout_carry(&[h1], "the first change", "checkout")
5268
        .unwrap();
5269
    assert_eq!(carried, vec!["a.txt"]);
5270
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5271
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5272
}
5273
5274
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5275
/// user identity not stored in a new repository yet is fine while its
5276
/// secret key is there; an added subrepo is listed as not committed yet.
5277
#[test]
5278
fn a_new_repository_is_healthy_before_its_first_commit() {
5279
    hermetic();
5280
    let dir = tempfile::tempdir().unwrap();
5281
    let root = dir.path();
5282
    let home = root.join("home");
5283
    let mut first = Repo::init(&root.join("first"))
5284
        .unwrap()
5285
        .with_home(home.clone());
5286
    let (key, _) = first
5287
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5288
        .unwrap();
5289
    let repo = Repo::init(&root.join("second"))
5290
        .unwrap()
5291
        .with_home(home.clone());
5292
    // Only the secret key: no identity object anywhere this repository sees.
5293
    let keys = repo.keys_dir.clone();
5294
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5295
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5296
    let r = repo.doctor(true);
5297
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5298
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5299
    assert!(id.message.contains("first signed change"), "{}", id.message);
5300
5301
    // A subrepo added and not committed yet is listed, pinned where it is.
5302
    let lib = root.join("lib");
5303
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5304
    write(&lib, "x.txt", b"x\n");
5305
    l.commit("x", &[]).unwrap();
5306
    let second = root.join("second");
5307
    write(&second, "a.txt", b"a\n");
5308
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5309
        .unwrap();
5310
    let subs = repo.subrepos().unwrap();
5311
    assert_eq!(subs.len(), 1);
5312
    assert_eq!(
5313
        (subs[0].path.as_str(), subs[0].committed),
5314
        ("deps/lib", false)
5315
    );
5316
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5317
    repo.commit("add lib", &[]).unwrap();
5318
    let subs = repo.subrepos().unwrap();
5319
    assert!(subs[0].committed, "committed now");
5320
}
5321
5322
/// Commit, diff, hunks and discard use the partial snapshot: a file
5323
/// unchanged since the manifest is neither read nor rendered, and showing
5324
/// a change renders only what it edits, the same as from a full base.
5325
#[cfg(unix)]
5326
#[test]
5327
fn commits_and_diffs_leave_unchanged_files_alone() {
5328
    use std::os::unix::fs::PermissionsExt;
5329
    hermetic();
5330
    let dir = tempfile::tempdir().unwrap();
5331
    let root = dir.path();
5332
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5333
    write(root, "big.txt", b"lots\nof\nlines\n");
5334
    write(root, "a.txt", b"one\ntwo\n");
5335
    repo.commit("base", &[]).unwrap();
5336
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5337
    for f in ["big.txt", "a.txt"] {
5338
        fs::File::options()
5339
            .write(true)
5340
            .open(root.join(f))
5341
            .unwrap()
5342
            .set_modified(old)
5343
            .unwrap();
5344
    }
5345
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5346
    // big.txt cannot be read at all from here on.
5347
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5348
5349
    write(root, "a.txt", b"one\nTWO\nthree\n");
5350
    let diff = repo.diff_files(None).unwrap();
5351
    assert_eq!(
5352
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5353
        ["a.txt"]
5354
    );
5355
    let (_, hunks) = repo.hunks().unwrap();
5356
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5357
    let h = repo.commit("edit a", &[]).unwrap();
5358
5359
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5360
    let c = repo.store().get_change(&h).unwrap();
5361
    let full = repo.load_state(&c.deps).unwrap();
5362
    let want = render_change(&c, &full, &full.materialize());
5363
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5364
    let (base, snap) = repo.change_base(&c).unwrap();
5365
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5366
5367
    // Discarding works the same way.
5368
    write(root, "a.txt", b"scratch\n");
5369
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5370
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5371
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5372
}
5373
5374
/// A replace conflict (spec §9.3) is settled by a change that writes one
5375
/// candidate, or new bytes, at the path when the caller names it; a plain
5376
/// snapshot of a checkout never settles it on its own.
5377
#[test]
5378
fn replace_conflicts_are_settled_when_asked() {
5379
    hermetic();
5380
    let dir = tempfile::tempdir().unwrap();
5381
    let root = dir.path();
5382
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5383
    let blob = |n: u8| {
5384
        let mut v = vec![0u8; 64];
5385
        v[1] = n;
5386
        v
5387
    };
5388
    write(root, "img.bin", &blob(1));
5389
    repo.commit("add img", &[]).unwrap();
5390
    repo.bookmark_create("other", None).unwrap();
5391
    write(root, "img.bin", &blob(2));
5392
    repo.commit("img two", &[]).unwrap();
5393
    repo.bookmark_switch("other", false).unwrap();
5394
    write(root, "img.bin", &blob(3));
5395
    repo.commit("img three", &[]).unwrap();
5396
    repo.bookmark_switch("main", false).unwrap();
5397
    repo.merge("other").unwrap();
5398
    let heads = repo.bookmark_heads().unwrap();
5399
    let merged = repo.load_state(&heads).unwrap().materialize();
5400
    assert!(
5401
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5402
        "a replace conflict"
5403
    );
5404
    // A snapshot of the checkout records nothing.
5405
    assert!(repo
5406
        .snapshot("status")
5407
        .unwrap()
5408
        .statuses
5409
        .iter()
5410
        .all(|s| s.path != "img.bin"));
5411
5412
    // Keeping candidate 3 settles it.
5413
    let author = repo.author();
5414
    let edits = [FileEdit {
5415
        path: "img.bin".into(),
5416
        content: Some(blob(3)),
5417
    }];
5418
    let c = repo
5419
        .build_change(&heads, &edits, "keep three", author)
5420
        .unwrap();
5421
    assert_eq!(c.kind, ChangeKind::Resolution);
5422
    let mut st = repo.load_state(&heads).unwrap();
5423
    for d in &c.deps {
5424
        assert!(st.contains(d));
5425
    }
5426
    assert!(
5427
        heads.iter().all(|h| c.deps.contains(h)),
5428
        "depends on both contributors"
5429
    );
5430
    st.add(c).unwrap();
5431
    let after = st.materialize();
5432
    assert!(!after.is_conflicted());
5433
    assert_eq!(
5434
        after.files["img.bin"].content,
5435
        FileContent::Opaque {
5436
            blobs: vec![Repo::blob_ref(&blob(3))]
5437
        }
5438
    );
5439
5440
    // New bytes settle it too.
5441
    let edits = [FileEdit {
5442
        path: "img.bin".into(),
5443
        content: Some(blob(9)),
5444
    }];
5445
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5446
    let mut st = repo.load_state(&heads).unwrap();
5447
    st.add(c).unwrap();
5448
    assert_eq!(
5449
        st.materialize().files["img.bin"].content,
5450
        FileContent::Opaque {
5451
            blobs: vec![Repo::blob_ref(&blob(9))]
5452
        }
5453
    );
5454
}
5455
5456
/// The history of a range of lines (spec §27): the changes that wrote
5457
/// or deleted its atoms, or deleted atoms from between them; edits outside
5458
/// the range and changes the range's lines survived are not in it.
5459
#[test]
5460
fn line_ranges_have_exact_histories() {
5461
    hermetic();
5462
    let dir = tempfile::tempdir().unwrap();
5463
    let root = dir.path();
5464
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5465
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5466
    let base = repo.commit("add f", &[]).unwrap();
5467
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5468
    let outside = repo.commit("change the import", &[]).unwrap();
5469
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5470
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5471
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5472
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5473
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5474
    let after = repo.commit("add b after a", &[]).unwrap();
5475
    let heads = repo.bookmark_heads().unwrap();
5476
5477
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5478
    let hist: Vec<ChangeHash> = repo
5479
        .line_history(&heads, "f.rs", 2, 4)
5480
        .unwrap()
5481
        .iter()
5482
        .map(|e| e.hash)
5483
        .collect();
5484
    for (h, what) in [
5485
        (base, "wrote it"),
5486
        (inside, "edited a line"),
5487
        (deleted, "deleted a line from inside"),
5488
    ] {
5489
        assert!(hist.contains(&h), "{what}");
5490
    }
5491
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5492
        assert!(!hist.contains(&h), "{what}");
5493
    }
5494
    assert_eq!(hist[0], deleted, "newest first");
5495
    // One line: only what touched it.
5496
    let one: Vec<ChangeHash> = repo
5497
        .line_history(&heads, "f.rs", 1, 1)
5498
        .unwrap()
5499
        .iter()
5500
        .map(|e| e.hash)
5501
        .collect();
5502
    assert!(one.contains(&outside) && !one.contains(&inside));
5503
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5504
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5505
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5506
}
5507
5508
#[test]
5509
fn receipts_are_kept_with_their_state_and_verified() {
5510
    use crate::receipt::{Receipt, SignedReceipt};
5511
    hermetic();
5512
    let dir = tempfile::tempdir().unwrap();
5513
    let root = dir.path();
5514
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5515
    write(root, "a.txt", b"1\n");
5516
    repo.commit("A", &[]).unwrap();
5517
    let heads = repo.bookmark_heads().unwrap();
5518
    let state = repo
5519
        .store()
5520
        .put_state(&StateObject::new(heads.clone()))
5521
        .unwrap();
5522
    let out = repo.store_blob(b"built\n").unwrap();
5523
    let receipt = Receipt {
5524
        job_name: "build".into(),
5525
        pipeline_hash: ObjectRef([1; 32]),
5526
        scope_tree_hash: ObjectRef([2; 32]),
5527
        inputs: vec![],
5528
        environment: ObjectRef([3; 32]),
5529
        outputs: vec![out],
5530
        exit_code: 0,
5531
        duration_ms: 42,
5532
    };
5533
    let sk = SecretKey::generate();
5534
    let runner = sk.identity("earth-1", "runner@earth", 1);
5535
    let sr = SignedReceipt::sign(
5536
        receipt.clone(),
5537
        repo.id().unwrap(),
5538
        state,
5539
        "demo#1",
5540
        &runner,
5541
        &sk,
5542
    );
5543
5544
    let r = repo.add_receipt(&sr).unwrap();
5545
    let found = repo.receipts(&heads).unwrap();
5546
    assert_eq!(found.len(), 1);
5547
    assert_eq!(found[0].attest, r);
5548
    assert_eq!(found[0].signed, sr);
5549
    assert!(found[0].problem.is_none() && !found[0].revoked);
5550
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5551
5552
    // Another repository's receipt, or a forged one, is refused.
5553
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5554
    assert!(repo
5555
        .add_receipt(&elsewhere)
5556
        .unwrap_err()
5557
        .to_string()
5558
        .contains("another repository"));
5559
    let mut forged = sr.clone();
5560
    forged.receipt.exit_code = 1;
5561
    assert!(repo
5562
        .add_receipt(&forged)
5563
        .unwrap_err()
5564
        .to_string()
5565
        .contains("does not verify"));
5566
5567
    // gc keeps the receipt, its runner and its output while the state lives.
5568
    repo.gc(true).unwrap();
5569
    assert_eq!(repo.receipts(&heads).unwrap().len(), 1);
5570
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5571
    assert!(repo.fsck().unwrap().problems.is_empty());
5572
}
5573
5574
#[test]
5575
fn status_leaves_an_unchanged_manifest_alone() {
5576
    hermetic();
5577
    let dir = tempfile::tempdir().unwrap();
5578
    let root = dir.path();
5579
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5580
    write(root, "a.txt", b"1\n");
5581
    write(root, "b.txt", b"2\n");
5582
    repo.commit("A", &[]).unwrap();
5583
    // Files last touched well outside the racy window.
5584
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5585
    for f in ["a.txt", "b.txt"] {
5586
        fs::File::options()
5587
            .write(true)
5588
            .open(root.join(f))
5589
            .unwrap()
5590
            .set_modified(old)
5591
            .unwrap();
5592
    }
5593
    repo.snapshot_status("status").unwrap();
5594
    let path = repo.manifest_path();
5595
    let first = fs::read(&path).unwrap();
5596
    repo.snapshot_status("status").unwrap();
5597
    assert_eq!(
5598
        fs::read(&path).unwrap(),
5599
        first,
5600
        "an unchanged tree does not rewrite the manifest"
5601
    );
5602
    // A change rewrites it.
5603
    write(root, "a.txt", b"1\n2\n");
5604
    repo.snapshot_status("status").unwrap();
5605
    assert_ne!(fs::read(&path).unwrap(), first);
5606
}
5607
5608
#[test]
5609
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5610
    hermetic();
5611
    let dir = tempfile::tempdir().unwrap();
5612
    let root = dir.path();
5613
    let origin_path = root.join("origin");
5614
    Repo::init(&origin_path).unwrap();
5615
    let origin_url = origin_path.to_string_lossy().to_string();
5616
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5617
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5618
    write(&root.join("a"), "big.txt", big.as_bytes());
5619
    write(&root.join("a"), "small.txt", b"small\n");
5620
    let h1 = a.commit("large", &[]).unwrap();
5621
    let (_, body) = a.store().get(&h1).unwrap();
5622
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5623
    assert!(a.push("origin", false).unwrap()[0].ok);
5624
5625
    // A clone reads the text from the blobs that came with the change.
5626
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5627
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5628
    // An edit in the middle of the stored insert is an ordinary change.
5629
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5630
    write(&root.join("b"), "big.txt", edited.as_bytes());
5631
    let h2 = b.commit("edit", &[]).unwrap();
5632
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5633
    assert!(b.push("origin", false).unwrap()[0].ok);
5634
    assert!(a.pull("origin").unwrap().checked_out);
5635
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5636
    assert_eq!(
5637
        a.fsck().unwrap().errors(),
5638
        0,
5639
        "{:?}",
5640
        a.fsck().unwrap().problems
5641
    );
5642
5643
    // With zero retention gc keeps the text blobs of every kept change.
5644
    let mut a = Repo::open(&root.join("a")).unwrap();
5645
    a.config.set("core.op-retention", "0").unwrap();
5646
    a.save_config().unwrap();
5647
    let a = Repo::open(&root.join("a")).unwrap();
5648
    a.gc(true).unwrap();
5649
    let a = Repo::open(&root.join("a")).unwrap();
5650
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5651
    assert_eq!(
5652
        a.fsck().unwrap().errors(),
5653
        0,
5654
        "{:?}",
5655
        a.fsck().unwrap().problems
5656
    );
5657
    // And a clone of the packed repository reads them from its packs.
5658
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5659
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5660
    drop(c);
5661
}
5662
5663
#[test]
5664
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5665
    hermetic();
5666
    let dir = tempfile::tempdir().unwrap();
5667
    let root = dir.path();
5668
    let repo = Repo::init(root).unwrap();
5669
    write(root, "a.txt", b"a\n");
5670
    let a = repo.commit("a", &[]).unwrap();
5671
    write(root, "b.txt", b"b\n");
5672
    repo.commit("b", &[]).unwrap();
5673
    let (x, op) = repo.head_op().unwrap();
5674
    let ws = *op.view.workspaces.keys().next().unwrap();
5675
    let mut one = op.view.clone();
5676
    one.workspaces.insert(ws, a);
5677
    let mut two = op.view.clone();
5678
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5679
    let first = repo.record_op(&[x], "one", one).unwrap();
5680
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5681
    assert!(
5682
        e.to_string()
5683
            .contains("changed this working copy at the same time"),
5684
        "{e}"
5685
    );
5686
    assert_eq!(
5687
        repo.head_op().unwrap().0,
5688
        first,
5689
        "the second is not recorded"
5690
    );
5691
}
5692
5693
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5694
/// rewrote the working copy recorded the half-written files as edits, and
5695
/// its view replaced the switch's.
5696
#[test]
5697
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5698
    hermetic();
5699
    let dir = tempfile::tempdir().unwrap();
5700
    let root = dir.path().to_path_buf();
5701
    let mut repo = Repo::init(&root).unwrap();
5702
    write(&root, "keep.txt", b"keep\n");
5703
    repo.commit("base", &[]).unwrap();
5704
    repo.bookmark_create("small", None).unwrap();
5705
    for i in 0..300 {
5706
        write(
5707
            &root,
5708
            &format!("many/f{i}.txt"),
5709
            format!("file {i}\n").as_bytes(),
5710
        );
5711
    }
5712
    repo.commit("many", &[]).unwrap();
5713
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5714
    let watcher = {
5715
        let (root, stop) = (root.clone(), stop.clone());
5716
        std::thread::spawn(move || {
5717
            let r = Repo::open(&root).unwrap();
5718
            let mut ran = 0;
5719
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
5720
                if r.snapshot_status("oxy status").is_ok() {
5721
                    ran += 1;
5722
                }
5723
            }
5724
            ran
5725
        })
5726
    };
5727
    for i in 0..20 {
5728
        let to = if i % 2 == 0 { "small" } else { "main" };
5729
        repo.bookmark_switch(to, false).unwrap();
5730
    }
5731
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
5732
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
5733
    // Back on main, clean, with every file where main has it.
5734
    let repo = Repo::open(&root).unwrap();
5735
    let s = repo.snapshot_status("oxy status").unwrap();
5736
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
5737
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
5738
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
5739
    assert!(root.join("many/f299.txt").exists());
5740
}
5741
5742
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
5743
/// put a subrepo that was ahead of its pin back at the pin and moved the
5744
/// subrepo's own bookmark backwards.
5745
#[test]
5746
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
5747
    hermetic();
5748
    let dir = tempfile::tempdir().unwrap();
5749
    let root = dir.path();
5750
    Repo::init(&root.join("lib-origin")).unwrap();
5751
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5752
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
5753
    write(&root.join("lib"), "lib.txt", b"v1\n");
5754
    lib.commit("lib v1", &[]).unwrap();
5755
    assert!(lib.push("origin", false).unwrap()[0].ok);
5756
5757
    let app_dir = root.join("app");
5758
    let mut app = Repo::init(&app_dir).unwrap();
5759
    write(&app_dir, "main.txt", b"app\n");
5760
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5761
    app.commit("app with lib", &[]).unwrap();
5762
    app.bookmark_create("feature", None).unwrap();
5763
5764
    // New work in the subrepo, not yet pinned by the parent.
5765
    let nested_dir = app_dir.join("libs/lib");
5766
    let nested = Repo::open(&nested_dir).unwrap();
5767
    write(&nested_dir, "new.txt", b"new\n");
5768
    let l2 = nested.commit("lib: new file", &[]).unwrap();
5769
    drop(nested);
5770
5771
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
5772
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
5773
    let nested = Repo::open(&nested_dir).unwrap();
5774
    assert!(
5775
        nested.bookmark_heads().unwrap().contains(&l2),
5776
        "its bookmark kept its work"
5777
    );
5778
    assert!(nested_dir.join("new.txt").exists(), "and its files");
5779
    let s = app.snapshot("status").unwrap();
5780
    assert_eq!(
5781
        statuses(&s),
5782
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
5783
    );
5784
}
5785
5786
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
5787
/// moving `main` to a change this clone had pushed on another bookmark,
5788
/// the first `pull` said "Already up to date" while `main` was behind.
5789
#[test]
5790
fn pull_takes_a_remote_move_to_changes_already_here() {
5791
    hermetic();
5792
    let dir = tempfile::tempdir().unwrap();
5793
    let root = dir.path();
5794
    let origin_path = root.join("origin");
5795
    let origin = Repo::init(&origin_path).unwrap();
5796
    let url = origin_path.to_string_lossy().to_string();
5797
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
5798
    write(&root.join("b"), "base.txt", b"base\n");
5799
    b.commit("base", &[]).unwrap();
5800
    assert!(b.push("origin", false).unwrap()[0].ok);
5801
5802
    // A feature bookmark with one change, pushed.
5803
    b.bookmark_create("feat", None).unwrap();
5804
    b.bookmark_switch("feat", false).unwrap();
5805
    write(&root.join("b"), "x.txt", b"x\n");
5806
    let x = b.commit("x", &[]).unwrap();
5807
    assert!(b.push("origin", false).unwrap()[0].ok);
5808
    b.bookmark_switch("main", false).unwrap();
5809
5810
    // The remote lands it: its main moves to the feature's state.
5811
    let feat = origin
5812
        .store()
5813
        .get_state(&origin.view().unwrap().bookmarks["feat"])
5814
        .unwrap()
5815
        .heads;
5816
    origin.bookmark_set("main", &feat).unwrap();
5817
5818
    let r = b.pull("origin").unwrap();
5819
    assert!(r.changed, "{r:?}");
5820
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
5821
    let main = b
5822
        .bookmarks()
5823
        .unwrap()
5824
        .into_iter()
5825
        .find(|m| m.name == "main")
5826
        .unwrap();
5827
    assert_eq!(main.behind, Some(0), "{main:?}");
5828
}
5829
5830
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
5831
/// to one only the remote has makes a local bookmark from it; a pull moves
5832
/// every local bookmark the remote has too; a clone checks out the remote's
5833
/// default bookmark.
5834
#[test]
5835
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
5836
    hermetic();
5837
    let dir = tempfile::tempdir().unwrap();
5838
    let root = dir.path();
5839
    let origin_path = root.join("origin");
5840
    let mut origin = Repo::init(&origin_path).unwrap();
5841
    let url = origin_path.to_string_lossy().to_string();
5842
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
5843
    write(&root.join("a"), "base.txt", b"base\n");
5844
    a.commit("base", &[]).unwrap();
5845
    assert!(a.push("origin", false).unwrap()[0].ok);
5846
    a.bookmark_create("develop", None).unwrap();
5847
    a.bookmark_switch("develop", false).unwrap();
5848
    write(&root.join("a"), "base.txt", b"base\nd1\n");
5849
    let d1 = a.commit("d1", &[]).unwrap();
5850
    assert!(a.push("origin", false).unwrap()[0].ok);
5851
5852
    // A clone has main only; origin/develop is a name all the same.
5853
    let c_root = root.join("c");
5854
    let mut c = Repo::clone(&url, &c_root).unwrap();
5855
    assert_eq!(c.config.bookmark, "main");
5856
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
5857
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
5858
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
5859
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
5860
5861
    // Switching makes the local bookmark from origin's.
5862
    c.bookmark_switch("develop", false).unwrap();
5863
    assert_eq!(c.config.bookmark, "develop");
5864
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
5865
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
5866
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
5867
    assert!(c.bookmark_switch("nowhere", false).is_err());
5868
5869
    // Both bookmarks move on the remote; one pull takes both.
5870
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
5871
    let d2 = a.commit("d2", &[]).unwrap();
5872
    assert!(a.push("origin", false).unwrap()[0].ok);
5873
    a.bookmark_switch("main", false).unwrap();
5874
    write(&root.join("a"), "m.txt", b"m\n");
5875
    let m = a.commit("m", &[]).unwrap();
5876
    assert!(a.push("origin", false).unwrap()[0].ok);
5877
    let r = c.pull("origin").unwrap();
5878
    assert!(r.changed && r.checked_out, "{r:?}");
5879
    assert_eq!(r.heads, vec![d2]);
5880
    assert_eq!(r.others, vec!["main".to_string()]);
5881
    assert!(c.resolve_heads("main").unwrap().contains(&m));
5882
    assert_eq!(
5883
        fs::read(c_root.join("base.txt")).unwrap(),
5884
        b"base\nd1\nd2\n"
5885
    );
5886
    let again = c.pull("origin").unwrap();
5887
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
5888
5889
    // A clone checks out the remote's default bookmark.
5890
    origin.config.set("workspace.bookmark", "develop").unwrap();
5891
    origin.save_config().unwrap();
5892
    let e = Repo::clone(&url, &root.join("e")).unwrap();
5893
    assert_eq!(e.config.bookmark, "develop");
5894
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
5895
    let reopened = Repo::open(&root.join("e")).unwrap();
5896
    assert_eq!(reopened.config.bookmark, "develop");
5897
    // REMOTE/NAME names the remote's bookmark to switch to.
5898
    let mut e = reopened;
5899
    e.bookmark_switch("origin/main", false).unwrap();
5900
    assert_eq!(e.config.bookmark, "main");
5901
    assert!(e.bookmark_heads().unwrap().contains(&m));
5902
}
5903
5904
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
5905
/// op restore goes back to an operation, files included, and undo takes
5906
/// the restore back whole; op revert undoes one operation alone; each
5907
/// operation's changes are described from the views.
5908
#[test]
5909
fn operations_can_be_read_restored_and_reverted() {
5910
    hermetic();
5911
    let dir = tempfile::tempdir().unwrap();
5912
    let root = dir.path();
5913
    let repo = Repo::init(root).unwrap();
5914
    write(root, "a.txt", b"a\n");
5915
    let first = repo.commit("first", &[]).unwrap();
5916
    write(root, "a.txt", b"a\nb\n");
5917
    let second = repo.commit("second", &[]).unwrap();
5918
    let at_second = repo.head_op().unwrap().0.to_hex();
5919
    repo.bookmark_create("keep", None).unwrap();
5920
    let created = repo.head_op().unwrap().0.to_hex();
5921
    write(root, "n.txt", b"n\n");
5922
    let third = repo.commit("third", &[]).unwrap();
5923
5924
    // What each operation changed.
5925
    let ops = repo.op_log().unwrap();
5926
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
5927
    assert!(
5928
        changes
5929
            .iter()
5930
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
5931
        "{changes:?}"
5932
    );
5933
    assert!(changes
5934
        .iter()
5935
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
5936
5937
    // Reading at an earlier operation.
5938
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
5939
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
5940
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
5941
    write(root, "z.txt", b"z\n");
5942
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
5943
    fs::remove_file(root.join("z.txt")).unwrap();
5944
    assert!(repo.resolve_op("zz").is_err());
5945
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
5946
5947
    // Restore goes back, files and all; undo takes it back whole.
5948
    repo.op_restore(&at_second, false).unwrap();
5949
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
5950
    assert!(!root.join("n.txt").exists());
5951
    repo.undo().unwrap();
5952
    let mut heads = repo.bookmark_heads().unwrap();
5953
    heads.sort();
5954
    let mut want = vec![second, third];
5955
    want.sort();
5956
    assert_eq!(heads, want);
5957
    assert!(
5958
        root.join("n.txt").exists(),
5959
        "the files came back with the undo"
5960
    );
5961
5962
    // Revert the bookmark's creation alone: the commit after it stays.
5963
    let r = repo.op_revert(&created).unwrap();
5964
    assert_eq!(r.reverted, vec!["keep".to_string()]);
5965
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
5966
    assert!(repo
5967
        .load_state(&repo.bookmark_heads().unwrap())
5968
        .unwrap()
5969
        .contains(&third));
5970
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
5971
    let _ = first;
5972
}
5973
5974
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
5975
/// from the status cache while every file is as the snapshot left it, and
5976
/// from a snapshot again as soon as one is not.
5977
#[test]
5978
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
5979
    hermetic();
5980
    let dir = tempfile::tempdir().unwrap();
5981
    let root = dir.path();
5982
    let repo = Repo::init(root).unwrap();
5983
    write(root, "a.txt", b"a\n");
5984
    write(root, "b.txt", b"b\n");
5985
    repo.commit("base", &[]).unwrap();
5986
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
5987
5988
    write(root, "a.txt", b"a\nmore\n");
5989
    assert_eq!(
5990
        repo.status_by_manifest().unwrap(),
5991
        None,
5992
        "no snapshot of the edit yet"
5993
    );
5994
    let snap = repo.snapshot_status("oxy status").unwrap();
5995
    assert_eq!(snap.statuses.len(), 1);
5996
    let cached = repo
5997
        .status_by_manifest()
5998
        .unwrap()
5999
        .expect("answered from the cache");
6000
    assert_eq!(cached.len(), 1);
6001
    assert_eq!(
6002
        (cached[0].path.as_str(), cached[0].status),
6003
        ("a.txt", ChangeStatus::Modified)
6004
    );
6005
6006
    // Any further change sends status back to a snapshot.
6007
    write(root, "a.txt", b"a\nmore\nand more\n");
6008
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6009
    repo.snapshot_status("oxy status").unwrap();
6010
    assert!(repo.status_by_manifest().unwrap().is_some());
6011
    write(root, "new.txt", b"n\n");
6012
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6013
    fs::remove_file(root.join("new.txt")).unwrap();
6014
    assert!(
6015
        repo.status_by_manifest().unwrap().is_some(),
6016
        "back as it was"
6017
    );
6018
    fs::remove_file(root.join("b.txt")).unwrap();
6019
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6020
    write(root, "b.txt", b"b\n");
6021
6022
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6023
    repo.snapshot_status("oxy status").unwrap();
6024
    repo.commit("more", &[]).unwrap();
6025
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6026
}
6027
6028
/// oxygen#41: while the status cache holds, the working copy's diff is
6029
/// rendered from the stored working-copy change, and says exactly what a
6030
/// snapshot's diff says.
6031
#[test]
6032
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6033
    hermetic();
6034
    let dir = tempfile::tempdir().unwrap();
6035
    let root = dir.path();
6036
    let repo = Repo::init(root).unwrap();
6037
    write(root, "a.txt", b"one\ntwo\nthree\n");
6038
    write(root, "gone.txt", b"bye\n");
6039
    repo.commit("base", &[]).unwrap();
6040
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6041
    write(root, "new.txt", b"hello\n");
6042
    fs::remove_file(root.join("gone.txt")).unwrap();
6043
    let snap = repo.snapshot_status("oxy status").unwrap();
6044
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6045
    assert!(
6046
        repo.status_by_manifest().unwrap().is_some(),
6047
        "the cache holds"
6048
    );
6049
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6050
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6051
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6052
}
6053
6054
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6055
/// while none has moved, the check stats the tracked files without listing
6056
/// the tree, and a file added or removed anywhere moves its directory's
6057
/// time, so the tree is listed again.
6058
#[test]
6059
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6060
    hermetic();
6061
    let dir = tempfile::tempdir().unwrap();
6062
    let root = dir.path();
6063
    let repo = Repo::init(root).unwrap();
6064
    write(root, "a.txt", b"a\n");
6065
    write(root, "sub/deep/b.txt", b"b\n");
6066
    repo.commit("base", &[]).unwrap();
6067
    // Out of the racy window: every file and directory a minute old.
6068
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6069
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6070
        fs::File::open(root.join(p))
6071
            .unwrap()
6072
            .set_modified(old)
6073
            .unwrap();
6074
    }
6075
    repo.snapshot_status("oxy status").unwrap();
6076
    repo.write_manifest(false, false).unwrap();
6077
    let m = repo.read_manifest().unwrap().unwrap().2;
6078
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6079
    assert_eq!(
6080
        repo.disk_differs_by_dirs(&m),
6081
        Some(false),
6082
        "no listing needed"
6083
    );
6084
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6085
6086
    // A same-size edit with a new time: found by its stat.
6087
    write(root, "sub/deep/b.txt", b"c\n");
6088
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6089
    write(root, "sub/deep/b.txt", b"b\n");
6090
    fs::File::open(root.join("sub/deep/b.txt"))
6091
        .unwrap()
6092
        .set_modified(old)
6093
        .unwrap();
6094
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6095
6096
    // A new file moves its directory's time: the tree must be listed.
6097
    write(root, "sub/deep/new.txt", b"n\n");
6098
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6099
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6100
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6101
    // A removed one too.
6102
    fs::remove_file(root.join("a.txt")).unwrap();
6103
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6104
}
6105
6106
/// oxygen#41: a commit right after a status takes the snapshot the status
6107
/// left (the status cache holds) rather than walking again, and commits
6108
/// exactly what a snapshot would have.
6109
#[test]
6110
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6111
    hermetic();
6112
    let dir = tempfile::tempdir().unwrap();
6113
    let root = dir.path();
6114
    let repo = Repo::init(root).unwrap();
6115
    write(root, "a.txt", b"a\nb\n");
6116
    write(root, ".oxyattributes", b"*.bin binary\n");
6117
    repo.commit("base", &[]).unwrap();
6118
    write(root, "a.txt", b"a\nB\n");
6119
    write(root, "new.txt", b"new\n");
6120
    let snap = repo.snapshot_status("oxy status").unwrap();
6121
    let cached = repo
6122
        .snapshot_from_cache()
6123
        .unwrap()
6124
        .expect("the cache holds");
6125
    assert_eq!(cached.wc_hash, snap.wc_hash);
6126
    assert_eq!(cached.statuses, snap.statuses);
6127
    assert!(
6128
        !cached.attributes.is_empty(),
6129
        "the .oxyattributes file was read"
6130
    );
6131
    let h = repo.commit("edit", &[]).unwrap();
6132
    let c = repo.store().get_change(&h).unwrap();
6133
    assert_eq!(
6134
        c.tree_ops.len() + c.edits.len(),
6135
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6136
    );
6137
    assert_eq!(
6138
        repo.status_by_manifest().unwrap(),
6139
        Some(vec![]),
6140
        "clean after the commit"
6141
    );
6142
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6143
}
6144
6145
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6146
/// stored insert's text blob only when it builds that file's graph, and
6147
/// builds the same graph a full load does.
6148
#[test]
6149
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6150
    hermetic();
6151
    let dir = tempfile::tempdir().unwrap();
6152
    let root = dir.path();
6153
    let repo = Repo::init(root).unwrap();
6154
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6155
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6156
    write(root, "big.txt", big.as_bytes());
6157
    write(root, "other.txt", other.as_bytes());
6158
    let h = repo.commit("two large files", &[]).unwrap();
6159
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6160
    let h2 = repo.commit("append", &[]).unwrap();
6161
6162
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6163
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6164
        FileContent::Text { bytes, .. } => bytes.clone(),
6165
        other => panic!("{other:?}"),
6166
    };
6167
    // Built on demand, every graph renders as the full load's.
6168
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6169
    let big_node = full.files["big.txt"].node;
6170
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6171
    repo.load_all_graphs(&mut hist).unwrap();
6172
    let rendered = hist.materialize();
6173
    for p in ["big.txt", "other.txt"] {
6174
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6175
    }
6176
6177
    // Without other.txt's text blob, history still loads and big.txt still
6178
    // builds: nothing read the other text.
6179
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6180
    assert_eq!(texts.len(), 2);
6181
    let content = |r: &ObjectRef| -> Vec<u8> {
6182
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6183
        blob.chunks
6184
            .iter()
6185
            .flat_map(|c| repo.store().get(c).unwrap().1)
6186
            .collect()
6187
    };
6188
    let other_text = texts
6189
        .iter()
6190
        .filter_map(|t| match t {
6191
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
6192
            _ => None,
6193
        })
6194
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6195
        .unwrap();
6196
    fs::remove_file(repo.store().path_for(&other_text)).unwrap();
6197
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6198
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6199
    assert!(repo
6200
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6201
        .is_err());
6202
}
6203
6204
/// oxygen#35: the first status after a commit read and rendered every
6205
/// file (79 s and more than 14 GB on the Linux tree), because the
6206
/// manifest had no graph keys for files the commit added.
6207
#[test]
6208
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6209
    use std::os::unix::fs::PermissionsExt;
6210
    hermetic();
6211
    let dir = tempfile::tempdir().unwrap();
6212
    let root = dir.path();
6213
    let repo = Repo::init(root).unwrap();
6214
    let files = ["a.txt", "b.txt", "d/c.txt"];
6215
    for p in files {
6216
        write(root, p, format!("{p}\n").as_bytes());
6217
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6218
        fs::File::options()
6219
            .write(true)
6220
            .open(root.join(p))
6221
            .unwrap()
6222
            .set_modified(old)
6223
            .unwrap();
6224
    }
6225
    repo.commit("added", &[]).unwrap();
6226
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6227
    assert!(
6228
        m.entries.values().all(|e| e.graph.is_some()),
6229
        "keys recorded at commit"
6230
    );
6231
    // Unreadable files prove the next status reads none of them.
6232
    for p in files {
6233
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6234
    }
6235
    let snap = repo.snapshot_status("status").unwrap();
6236
    for p in files {
6237
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6238
    }
6239
    assert!(!snap.changed && snap.statuses.is_empty());
6240
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6241
}
6242
6243
/// oxygen#35: a checkout reads, renders and writes only the files whose
6244
/// graphs differ, and renders the rest a batch at a time.
6245
#[test]
6246
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6247
    use std::os::unix::fs::PermissionsExt;
6248
    hermetic();
6249
    let dir = tempfile::tempdir().unwrap();
6250
    let root = dir.path();
6251
    let origin = root.join("origin");
6252
    let mut repo = Repo::init(&origin).unwrap();
6253
    // More files than one batch holds.
6254
    let n = 2100;
6255
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6256
    for i in 0..n {
6257
        let p = format!("f/{i:04}.txt");
6258
        write(&origin, &p, format!("file {i}\n").as_bytes());
6259
        fs::File::options()
6260
            .write(true)
6261
            .open(origin.join(&p))
6262
            .unwrap()
6263
            .set_modified(old)
6264
            .unwrap();
6265
    }
6266
    repo.commit("many", &[]).unwrap();
6267
    repo.bookmark_create("feature", None).unwrap();
6268
    repo.bookmark_switch("feature", false).unwrap();
6269
    write(&origin, "f/0007.txt", b"changed\n");
6270
    repo.commit("one change", &[]).unwrap();
6271
6272
    // Switching back to main must not read the unchanged files.
6273
    for i in 0..n {
6274
        if i != 7 {
6275
            let p = origin.join(format!("f/{i:04}.txt"));
6276
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6277
        }
6278
    }
6279
    let r = repo.bookmark_switch("main", false).unwrap();
6280
    for i in 0..n {
6281
        let p = origin.join(format!("f/{i:04}.txt"));
6282
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6283
    }
6284
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6285
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6286
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6287
6288
    // A clone renders every file, across batches.
6289
    let c = root.join("clone");
6290
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6291
    for i in [0, 2047, 2048, n - 1] {
6292
        assert_eq!(
6293
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6294
            format!("file {i}\n").as_bytes()
6295
        );
6296
    }
6297
    let cloned = Repo::open(&c).unwrap();
6298
    assert!(cloned
6299
        .snapshot_status("status")
6300
        .unwrap()
6301
        .statuses
6302
        .is_empty());
6303
}
6304
6305
/// A file written just before the manifest (inside the racy window) is
6306
/// checked by its hash: trusted when equal, caught when edited in place
6307
/// with the same size and time.
6308
#[test]
6309
fn a_racy_manifest_entry_is_checked_by_hash() {
6310
    hermetic();
6311
    let dir = tempfile::tempdir().unwrap();
6312
    let root = dir.path();
6313
    let repo = Repo::init(root).unwrap();
6314
    write(root, "a.txt", b"one\n");
6315
    repo.commit("fresh", &[]).unwrap();
6316
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6317
    let t = fs::metadata(root.join("a.txt"))
6318
        .unwrap()
6319
        .modified()
6320
        .unwrap();
6321
    write(root, "a.txt", b"two\n");
6322
    fs::File::options()
6323
        .write(true)
6324
        .open(root.join("a.txt"))
6325
        .unwrap()
6326
        .set_modified(t)
6327
        .unwrap();
6328
    assert!(
6329
        !repo.clean_by_manifest().unwrap(),
6330
        "same size and time, other bytes"
6331
    );
6332
    assert_eq!(
6333
        statuses(&repo.snapshot_status("status").unwrap()),
6334
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6335
    );
6336
}
6337
6338
/// A fetch on one machine moves changes as stored, text blobs among the
6339
/// objects; a change whose text blob did not come is refused, not stored.
6340
#[test]
6341
fn a_raw_bundle_without_a_changes_text_is_refused() {
6342
    hermetic();
6343
    let dir = tempfile::tempdir().unwrap();
6344
    let root = dir.path();
6345
    let a = Repo::init(&root.join("a")).unwrap();
6346
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6347
    write(&root.join("a"), "big.txt", big.as_bytes());
6348
    let h = a.commit("big", &[]).unwrap();
6349
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6350
    assert_eq!(bundle.raw_changes.len(), 1);
6351
    assert!(bundle.changes.is_empty());
6352
    let b = Repo::init(&root.join("b")).unwrap();
6353
    let mut without = bundle.clone();
6354
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6355
    let e = b.import_bundle(&without, false).unwrap_err();
6356
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6357
    assert!(!b.store().has(&h));
6358
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6359
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6360
}
6361
6362
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6363
/// again was a second node for one Git path, so a file moved into it on
6364
/// another line, where the first node still stood, ended up in two places.
6365
/// An import now brings the directory back rather than make a new one.
6366
#[test]
6367
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6368
    hermetic();
6369
    if std::process::Command::new("git")
6370
        .arg("--version")
6371
        .output()
6372
        .is_err()
6373
    {
6374
        eprintln!("git not installed; skipping");
6375
        return;
6376
    }
6377
    let dir = tempfile::tempdir().unwrap();
6378
    let root = dir.path();
6379
    let g = root.join("src.git");
6380
    fs::create_dir_all(&g).unwrap();
6381
    let git = |args: &[&str]| -> String {
6382
        let out = std::process::Command::new("git")
6383
            .arg("-C")
6384
            .arg(&g)
6385
            .args([
6386
                "-c",
6387
                "user.name=Grace",
6388
                "-c",
6389
                "[email protected]",
6390
                "-c",
6391
                "commit.gpgsign=false",
6392
            ])
6393
            .args(args)
6394
            .output()
6395
            .unwrap();
6396
        assert!(
6397
            out.status.success(),
6398
            "git {args:?}: {}",
6399
            String::from_utf8_lossy(&out.stderr)
6400
        );
6401
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6402
    };
6403
    git(&["init", "-q", "-b", "main"]);
6404
    write(&g, "d/a.txt", b"a\n");
6405
    write(&g, "c/x.txt", b"x\n");
6406
    git(&["add", "."]);
6407
    git(&["commit", "-qm", "base"]);
6408
    // One line: move x into d while d still stands.
6409
    git(&["checkout", "-qb", "side"]);
6410
    git(&["mv", "c/x.txt", "d/x.txt"]);
6411
    git(&["commit", "-qm", "x into d"]);
6412
    // The other: d goes, comes back, and x moves into it too.
6413
    git(&["checkout", "-q", "main"]);
6414
    git(&["rm", "-q", "d/a.txt"]);
6415
    git(&["commit", "-qm", "d goes"]);
6416
    write(&g, "d/b.txt", b"b\n");
6417
    git(&["add", "."]);
6418
    git(&["commit", "-qm", "d comes back"]);
6419
    git(&["mv", "c/x.txt", "d/x.txt"]);
6420
    git(&["commit", "-qm", "x into d again"]);
6421
    git(&["merge", "-q", "--no-edit", "side"]);
6422
6423
    let repo = Repo::init(&root.join("o")).unwrap();
6424
    repo.import_git(&g, "main").unwrap();
6425
    let v = repo.verify_git_import(&g, "main").unwrap();
6426
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6427
    let st = repo
6428
        .load_state_history(&repo.bookmark_heads().unwrap())
6429
        .unwrap();
6430
    let view = st.tree().view();
6431
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6432
    // The directory is the one the first commit made.
6433
    // Commits made in one second tie on time: find the first by its message.
6434
    let first = repo
6435
        .log()
6436
        .unwrap()
6437
        .into_iter()
6438
        .find(|e| e.change.message.starts_with("base"))
6439
        .unwrap();
6440
    let base = repo
6441
        .load_state_history(&[first.hash])
6442
        .unwrap()
6443
        .tree()
6444
        .view();
6445
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6446
}
6447
6448
/// oxygen#30, the rest: a placement left under a directory another line
6449
/// removed is out of sight, so no diff reaches it; the merge that settles
6450
/// where the file is retires it.
6451
#[test]
6452
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6453
    hermetic();
6454
    if std::process::Command::new("git")
6455
        .arg("--version")
6456
        .output()
6457
        .is_err()
6458
    {
6459
        eprintln!("git not installed; skipping");
6460
        return;
6461
    }
6462
    let dir = tempfile::tempdir().unwrap();
6463
    let root = dir.path();
6464
    let g = root.join("src.git");
6465
    fs::create_dir_all(&g).unwrap();
6466
    let run = |args: &[&str]| {
6467
        std::process::Command::new("git")
6468
            .arg("-C")
6469
            .arg(&g)
6470
            .args([
6471
                "-c",
6472
                "user.name=Grace",
6473
                "-c",
6474
                "[email protected]",
6475
                "-c",
6476
                "commit.gpgsign=false",
6477
            ])
6478
            .args(args)
6479
            .output()
6480
            .unwrap()
6481
    };
6482
    let git = |args: &[&str]| {
6483
        let out = run(args);
6484
        assert!(
6485
            out.status.success(),
6486
            "git {args:?}: {}",
6487
            String::from_utf8_lossy(&out.stderr)
6488
        );
6489
    };
6490
    git(&["init", "-q", "-b", "main"]);
6491
    write(&g, "c/x.txt", b"x\n");
6492
    write(&g, "keep.txt", b"k\n");
6493
    git(&["add", "."]);
6494
    git(&["commit", "-qm", "base"]);
6495
    // One line renames the file within c; the other moves it out of c,
6496
    // which goes.
6497
    git(&["checkout", "-qb", "side"]);
6498
    git(&["mv", "c/x.txt", "c/y.txt"]);
6499
    git(&["commit", "-qm", "rename within c"]);
6500
    git(&["checkout", "-q", "main"]);
6501
    fs::create_dir_all(g.join("n")).unwrap();
6502
    git(&["mv", "c/x.txt", "n/x.txt"]);
6503
    git(&["commit", "-qm", "move out of c"]);
6504
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6505
    let _ = run(&["merge", "-q", "side"]);
6506
    let _ = run(&[
6507
        "rm",
6508
        "-q",
6509
        "--cached",
6510
        "--ignore-unmatch",
6511
        "c/y.txt",
6512
        "c/x.txt",
6513
    ]);
6514
    let _ = std::fs::remove_dir_all(g.join("c"));
6515
    write(&g, "n/x.txt", b"x\n");
6516
    git(&["add", "-A"]);
6517
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6518
6519
    let repo = Repo::init(&root.join("o")).unwrap();
6520
    repo.import_git(&g, "main").unwrap();
6521
    let v = repo.verify_git_import(&g, "main").unwrap();
6522
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6523
    let st = repo
6524
        .load_state_history(&repo.bookmark_heads().unwrap())
6525
        .unwrap();
6526
    let view = st.tree().view();
6527
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6528
    assert!(view.entries.contains_key("n/x.txt"));
6529
}
6530
6531
/// oxygen#30, orphans: a file added on one line into a directory the other
6532
/// line removed is placed where the tree cannot show it; Git's merge keeps
6533
/// the file, and the import's merge leaves exactly one of it.
6534
#[test]
6535
fn git_import_merge_leaves_no_orphan_behind() {
6536
    hermetic();
6537
    if std::process::Command::new("git")
6538
        .arg("--version")
6539
        .output()
6540
        .is_err()
6541
    {
6542
        eprintln!("git not installed; skipping");
6543
        return;
6544
    }
6545
    let dir = tempfile::tempdir().unwrap();
6546
    let root = dir.path();
6547
    let g = root.join("src.git");
6548
    fs::create_dir_all(&g).unwrap();
6549
    let git = |args: &[&str]| {
6550
        let out = std::process::Command::new("git")
6551
            .arg("-C")
6552
            .arg(&g)
6553
            .args([
6554
                "-c",
6555
                "user.name=Grace",
6556
                "-c",
6557
                "[email protected]",
6558
                "-c",
6559
                "commit.gpgsign=false",
6560
            ])
6561
            .args(args)
6562
            .output()
6563
            .unwrap();
6564
        assert!(
6565
            out.status.success(),
6566
            "git {args:?}: {}",
6567
            String::from_utf8_lossy(&out.stderr)
6568
        );
6569
    };
6570
    git(&["init", "-q", "-b", "main"]);
6571
    write(&g, "d/f.txt", b"f\n");
6572
    write(&g, "keep.txt", b"k\n");
6573
    git(&["add", "."]);
6574
    git(&["commit", "-qm", "base"]);
6575
    git(&["checkout", "-qb", "side"]);
6576
    write(&g, "d/new.txt", b"new\n");
6577
    git(&["add", "."]);
6578
    git(&["commit", "-qm", "add into d"]);
6579
    git(&["checkout", "-q", "main"]);
6580
    git(&["rm", "-q", "d/f.txt"]);
6581
    git(&["commit", "-qm", "d goes"]);
6582
    git(&["merge", "-q", "--no-edit", "side"]);
6583
6584
    let repo = Repo::init(&root.join("o")).unwrap();
6585
    repo.import_git(&g, "main").unwrap();
6586
    let v = repo.verify_git_import(&g, "main").unwrap();
6587
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6588
    let st = repo
6589
        .load_state_history(&repo.bookmark_heads().unwrap())
6590
        .unwrap();
6591
    let view = st.tree().view();
6592
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6593
    assert!(view.entries.contains_key("d/new.txt"));
6594
}
6595
6596
/// fsck checks a change's text as the blobs it is stored in, without
6597
/// decoding it: a missing text blob is an error named for the change.
6598
#[test]
6599
fn fsck_names_a_missing_text_blob() {
6600
    hermetic();
6601
    let dir = tempfile::tempdir().unwrap();
6602
    let root = dir.path();
6603
    let repo = Repo::init(root).unwrap();
6604
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6605
    write(root, "big.txt", big.as_bytes());
6606
    let h = repo.commit("big", &[]).unwrap();
6607
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6608
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6609
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6610
        panic!("a stored text")
6611
    };
6612
    fs::remove_file(repo.store().path_for(&b)).unwrap();
6613
    let rep = repo.fsck().unwrap();
6614
    assert!(rep.errors() > 0);
6615
    assert!(
6616
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6617
        "{:?}",
6618
        rep.problems
6619
    );
6620
}
6621
6622
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6623
/// reached with that remote's token and CA (a private subrepo then clones
6624
/// for anyone who can read the parent); another hub gets none of them.
6625
#[test]
6626
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6627
    hermetic();
6628
    let dir = tempfile::tempdir().unwrap();
6629
    let mut repo = Repo::init(dir.path()).unwrap();
6630
    repo.config
6631
        .set(
6632
            "remote.origin.url",
6633
            "https://Hub.example:7343/doomsdayone/metalgear",
6634
        )
6635
        .unwrap();
6636
    repo.config.set("remote.origin.token", "secret").unwrap();
6637
    repo.config
6638
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6639
        .unwrap();
6640
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6641
    assert_eq!(same.token.as_deref(), Some("secret"));
6642
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6643
    for other in [
6644
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6645
        "https://hub.example/doomsdayone/rstar-api",
6646
        "http://hub.example:7343/doomsdayone/rstar-api",
6647
    ] {
6648
        let o = repo.credentials_for(other);
6649
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6650
    }
6651
}
6652
6653
/// oxygen#47: a remote with no token of its own uses the user's credential
6654
/// store for its hub, and a nested checkout finds its parent's remote
6655
/// token there instead of keeping a copy.
6656
#[test]
6657
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
6658
    hermetic();
6659
    let home = tempfile::tempdir().unwrap();
6660
    let dir = tempfile::tempdir().unwrap();
6661
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
6662
    parent
6663
        .config
6664
        .set("remote.origin.url", "https://hub.example/o/parent")
6665
        .unwrap();
6666
    parent.save_config().unwrap();
6667
    assert_eq!(parent.remote_options("origin").token, None);
6668
    crate::credentials::Credentials::at(home.path())
6669
        .save("https://hub.example", "stored", Some("andy"), None)
6670
        .unwrap();
6671
    assert_eq!(
6672
        parent.remote_options("origin").token.as_deref(),
6673
        Some("stored")
6674
    );
6675
6676
    let empty_home = tempfile::tempdir().unwrap();
6677
    let nested = dir.path().join("deps").join("child");
6678
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
6679
    child
6680
        .config
6681
        .set("remote.origin.url", "https://hub.example/o/child")
6682
        .unwrap();
6683
    child.save_config().unwrap();
6684
    assert_eq!(child.remote_options("origin").token, None);
6685
    parent
6686
        .config
6687
        .set("remote.origin.token", "checkout")
6688
        .unwrap();
6689
    parent.save_config().unwrap();
6690
    assert_eq!(
6691
        child.remote_options("origin").token.as_deref(),
6692
        Some("checkout")
6693
    );
6694
    // Another hub's checkout token is not borrowed.
6695
    child
6696
        .config
6697
        .set("remote.origin.url", "https://other.example/o/child")
6698
        .unwrap();
6699
    assert_eq!(child.remote_options("origin").token, None);
6700
}
6701
6702
#[test]
6703
fn the_metadata_cache_survives_a_torn_tail() {
6704
    hermetic();
6705
    let dir = tempfile::tempdir().unwrap();
6706
    let root = dir.path();
6707
    let repo = Repo::init(root).unwrap();
6708
    write(root, "a.txt", b"1\n");
6709
    let h = repo.commit("first", &[]).unwrap();
6710
    let meta = repo.store().get_change_meta(&h).unwrap();
6711
    let cache = repo.store().dir().join("metas");
6712
    let len = fs::metadata(&cache).unwrap().len();
6713
    assert!(len > 0, "a change read is cached");
6714
    // A torn record at the end: the cache reads up to it and cuts it off.
6715
    fs::OpenOptions::new()
6716
        .append(true)
6717
        .open(&cache)
6718
        .unwrap()
6719
        .write_all(&[7; 20])
6720
        .unwrap();
6721
    let again = Repo::open(root).unwrap();
6722
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
6723
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
6724
}
6725
6726
#[test]
6727
fn a_manifest_that_does_not_check_reads_as_none() {
6728
    hermetic();
6729
    let dir = tempfile::tempdir().unwrap();
6730
    let root = dir.path();
6731
    let repo = Repo::init(root).unwrap();
6732
    write(root, "a.txt", b"1\n");
6733
    repo.commit("first", &[]).unwrap();
6734
    let path = repo.manifest_path();
6735
    let mut bytes = fs::read(&path).unwrap();
6736
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
6737
    let last = bytes.len() - 1;
6738
    bytes[last] ^= 1;
6739
    fs::write(&path, &bytes).unwrap();
6740
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
6741
    // The next status reads the files and writes it again.
6742
    let again = Repo::open(root).unwrap();
6743
    assert!(!again.snapshot("status").unwrap().changed);
6744
    assert!(again.read_manifest().unwrap().is_some());
6745
}
6746
6747
#[test]
6748
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
6749
    hermetic();
6750
    let dir = tempfile::tempdir().unwrap();
6751
    let root = dir.path();
6752
    let repo = Repo::init(root).unwrap();
6753
    write(root, "a.txt", b"1\n");
6754
    write(root, "b.txt", b"2\n");
6755
    // b.txt outside the racy window, so snapshots take it as unchanged.
6756
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6757
    fs::File::options()
6758
        .write(true)
6759
        .open(root.join("b.txt"))
6760
        .unwrap()
6761
        .set_modified(old)
6762
        .unwrap();
6763
    repo.commit("first", &[]).unwrap();
6764
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
6765
    repo.snapshot_status("status").unwrap();
6766
    write(root, "a.txt", b"1\n2\n");
6767
    repo.commit("second", &[]).unwrap();
6768
    assert!(
6769
        repo.clean_by_manifest().unwrap(),
6770
        "after a commit of one file"
6771
    );
6772
    // Edited, seen by a status, edited again, then committed: the status
6773
    // left the first edit's stat, which the commit must not keep.
6774
    write(root, "a.txt", b"1\n2\n3\n");
6775
    repo.snapshot_status("status").unwrap();
6776
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
6777
    repo.commit("third", &[]).unwrap();
6778
    assert!(
6779
        repo.clean_by_manifest().unwrap(),
6780
        "after an edit a status saw"
6781
    );
6782
}
6783
6784
#[test]
6785
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
6786
    hermetic();
6787
    let dir = tempfile::tempdir().unwrap();
6788
    let root = dir.path();
6789
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6790
    write(root, "a.txt", b"1\n2\n");
6791
    let a = repo.commit("A", &[]).unwrap();
6792
    repo.bookmark_create("develop", Some(&[a])).unwrap();
6793
    write(root, "a.txt", b"1\nX\n");
6794
    let c = repo.commit("C: 2 to X", &[]).unwrap();
6795
    repo.bookmark_switch("develop", false).unwrap();
6796
    write(root, "a.txt", b"1\nY\n");
6797
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
6798
    repo.bookmark_switch("main", false).unwrap();
6799
6800
    let err = repo.rebase(&c, &[d]).unwrap_err();
6801
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
6802
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
6803
    assert!(r.changed && r.checked_out);
6804
    let snap = repo.snapshot_status("status").unwrap();
6805
    assert!(
6806
        snap.base_snapshot.is_conflicted(),
6807
        "the conflict is in the working copy"
6808
    );
6809
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
6810
    assert!(text.contains('X') && text.contains('Y'), "{text}");
6811
6812
    write(root, "a.txt", b"1\nXY\n");
6813
    repo.commit("Resolve", &[]).unwrap();
6814
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
6815
    assert!(st.contains(&c) && st.contains(&d));
6816
    let files = st.materialize().files;
6817
    assert!(!files["a.txt"].is_conflicted());
6818
    assert!(
6819
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
6820
    );
6821
6822
    // A change the current bookmark does not hold is refused.
6823
    repo.bookmark_switch("develop", false).unwrap();
6824
    write(root, "b.txt", b"b\n");
6825
    let e = repo.commit("E", &[]).unwrap();
6826
    repo.bookmark_switch("main", false).unwrap();
6827
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
6828
    assert!(
6829
        err.to_string().contains("not on the current bookmark"),
6830
        "{err}"
6831
    );
6832
}
6833
6834
#[test]
6835
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
6836
    hermetic();
6837
    let dir = tempfile::tempdir().unwrap();
6838
    let root = dir.path();
6839
    let repo = Repo::init(root).unwrap();
6840
    write(root, "a.txt", b"a\n");
6841
    write(root, "kept.log", b"tracked\n");
6842
    repo.commit("first", &[]).unwrap();
6843
    write(root, "build.log", b"made\n");
6844
    let snap = repo.snapshot_status("status").unwrap();
6845
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
6846
    // A rule written afterwards leaves the added file out again, while the
6847
    // committed one stays tracked.
6848
    write(root, ".gitignore", b"*.log\n");
6849
    let snap = repo.snapshot_status("status").unwrap();
6850
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
6851
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
6852
    write(root, "kept.log", b"tracked, edited\n");
6853
    let snap = repo.snapshot_status("status").unwrap();
6854
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
6855
}
6856
6857
#[test]
6858
fn shed_graphs_come_back_the_same() {
6859
    hermetic();
6860
    let dir = tempfile::tempdir().unwrap();
6861
    let root = dir.path();
6862
    let repo = Repo::init(root).unwrap();
6863
    write(root, "a.txt", b"1\n2\n3\n");
6864
    write(root, "b.txt", b"x\n");
6865
    repo.commit("first", &[]).unwrap();
6866
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
6867
    repo.commit("second", &[]).unwrap();
6868
    let heads = repo.bookmark_heads().unwrap();
6869
    let mut st = repo.load_state_history(&heads).unwrap();
6870
    let view = st.tree().view();
6871
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
6872
        .iter()
6873
        .map(|p| view.entries[*p].node)
6874
        .collect();
6875
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6876
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6877
    assert_eq!(st.built_count(), 2);
6878
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
6879
    assert_eq!((shed, st.built_count()), (2, 0));
6880
    // A later change applies on top of the shed history.
6881
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
6882
    let h3 = repo.commit("third", &[]).unwrap();
6883
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
6884
    st.add_known(h3, skeleton, texts);
6885
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6886
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6887
    assert_eq!(after[1], before[1]);
6888
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
6889
}
6890
6891
#[test]
6892
fn many_edited_files_diff_in_parallel() {
6893
    // Enough edited files that the builder diffs them in parallel; the
6894
    // commit must hold exactly what is on disk, and a second snapshot
6895
    // must find nothing left to commit.
6896
    hermetic();
6897
    let dir = tempfile::tempdir().unwrap();
6898
    let root = dir.path();
6899
    let repo = Repo::init(root).unwrap();
6900
    let text = |i: usize, round: usize| {
6901
        let mut s = String::new();
6902
        for line in 0..50 {
6903
            if round > 0 && line % 7 == i % 7 {
6904
                s.push_str(&format!("edited {round} {i} {line}\n"));
6905
            } else {
6906
                s.push_str(&format!("file {i} line {line}\n"));
6907
            }
6908
        }
6909
        if round > 0 && i.is_multiple_of(3) {
6910
            s.push_str("appended\n");
6911
        }
6912
        s
6913
    };
6914
    for i in 0..40 {
6915
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
6916
    }
6917
    repo.commit("first", &[]).unwrap();
6918
    for i in 0..40 {
6919
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
6920
    }
6921
    let h = repo.commit("edit every file", &[]).unwrap();
6922
    let snap = repo.load_state(&[h]).unwrap().materialize();
6923
    for i in 0..40 {
6924
        let want = text(i, 1);
6925
        assert!(
6926
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
6927
            "d/f{i}.txt as committed"
6928
        );
6929
    }
6930
    assert!(
6931
        repo.commit("nothing", &[]).is_err(),
6932
        "nothing left to commit"
6933
    );
6934
}
6935
6936
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
6937
/// is known (fetch printed "up to date" while main was behind), a change
6938
/// only fetched resolves and says where it is, and a checkout whose only
6939
/// remote is not `origin` uses that one.
6940
#[test]
6941
fn a_fetched_change_shows_as_behind_and_resolves() {
6942
    hermetic();
6943
    let dir = tempfile::tempdir().unwrap();
6944
    let root = dir.path();
6945
    let origin = Repo::init(&root.join("origin")).unwrap();
6946
    drop(origin);
6947
    let url = root.join("origin").to_string_lossy().to_string();
6948
    let a = Repo::clone(&url, &root.join("a"))
6949
        .unwrap()
6950
        .with_home(root.join("home-a"));
6951
    write(&root.join("a"), "f.txt", b"one\n");
6952
    a.commit("one", &[]).unwrap();
6953
    a.push("origin", false).unwrap();
6954
    let b = Repo::clone(&url, &root.join("b"))
6955
        .unwrap()
6956
        .with_home(root.join("home-b"));
6957
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
6958
6959
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
6960
    let h2 = a.commit("two", &[]).unwrap();
6961
    a.push("origin", false).unwrap();
6962
    b.fetch("origin").unwrap();
6963
    // Fetched, not pulled: one behind, the change found and placed.
6964
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
6965
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
6966
    assert_eq!(
6967
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
6968
            .unwrap(),
6969
        h2
6970
    );
6971
    assert_eq!(
6972
        b.remote_only_location(&h2).unwrap().as_deref(),
6973
        Some("origin/main")
6974
    );
6975
    // Fetching again changes nothing: still behind, which is what the
6976
    // CLI now says rather than "up to date".
6977
    b.fetch("origin").unwrap();
6978
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
6979
    b.pull("origin").unwrap();
6980
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
6981
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
6982
6983
    // One remote, not called origin: it is the default.
6984
    let mut c = Repo::init(&root.join("c")).unwrap();
6985
    assert_eq!(c.default_remote(), "origin");
6986
    c.config.set("remote.earth.url", &url).unwrap();
6987
    assert_eq!(c.default_remote(), "earth");
6988
    c.config.set("remote.origin.url", &url).unwrap();
6989
    assert_eq!(c.default_remote(), "origin");
6990
}
6991
6992
/// oxygen#57: a clone from a relative local path records the remote as an
6993
/// absolute path, so fetch still finds it from inside the clone.
6994
#[test]
6995
fn a_clone_from_a_relative_path_records_it_absolute() {
6996
    hermetic();
6997
    let dir = tempfile::tempdir().unwrap();
6998
    let root = dir.path();
6999
    Repo::init(&root.join("origin")).unwrap();
7000
    let rel = crate::protocol::stored_url("relative/repo");
7001
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7002
    assert_eq!(
7003
        crate::protocol::stored_url("https://hub.example/o/n"),
7004
        "https://hub.example/o/n"
7005
    );
7006
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
7007
    let url = root.join("origin").to_string_lossy().to_string();
7008
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7009
    assert_eq!(b.config.remotes["origin"], url);
7010
    b.fetch("origin").unwrap();
7011
}
7012
7013
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7014
/// and gets its subrepos at their pins from this workspace's copies, with
7015
/// their remotes pointing where the subrepos come from.
7016
#[test]
7017
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7018
    hermetic();
7019
    let dir = tempfile::tempdir().unwrap();
7020
    let root = dir.path();
7021
    Repo::init(&root.join("lib-origin")).unwrap();
7022
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7023
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7024
        .unwrap()
7025
        .with_home(root.join("home"));
7026
    write(&root.join("lib"), "lib.txt", b"v1\n");
7027
    let l1 = lib.commit("lib v1", &[]).unwrap();
7028
    assert!(lib.push("origin", false).unwrap()[0].ok);
7029
7030
    let app_dir = root.join("app");
7031
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7032
    write(&app_dir, "main.txt", b"app\n");
7033
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7034
    app.commit("app with lib", &[]).unwrap();
7035
    // A second bookmark, and the main workspace on another.
7036
    app.bookmark_create("develop", None).unwrap();
7037
    app.bookmark_create("feature", None).unwrap();
7038
    let mut app = app;
7039
    app.bookmark_switch("feature", false).unwrap();
7040
    assert_eq!(app.config.bookmark, "feature");
7041
7042
    // The library's origin goes away: the subrepo must come from here.
7043
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7044
    let heads = app.resolve_heads("develop").unwrap();
7045
    let ws = app
7046
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7047
        .unwrap();
7048
    assert_eq!(
7049
        ws.config.bookmark, "develop",
7050
        "the new workspace is on develop"
7051
    );
7052
    assert_eq!(
7053
        app.config.bookmark, "feature",
7054
        "and this one stays on its own"
7055
    );
7056
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7057
    assert_eq!(
7058
        sub.config.remotes["origin"], lib_url,
7059
        "its origin is the subrepo's URL"
7060
    );
7061
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7062
    assert_eq!(
7063
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7064
        b"v1\n"
7065
    );
7066
}
7067
7068
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7069
/// operators and the predicates, over a small graph with two heads and
7070
/// a rename.
7071
#[test]
7072
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7073
    hermetic();
7074
    let dir = tempfile::tempdir().unwrap();
7075
    let root = dir.path();
7076
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7077
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7078
        .unwrap();
7079
    write(root, "src/a.rs", b"one\n");
7080
    let a = repo.commit("first: add a", &[]).unwrap();
7081
    write(root, "src/a.rs", b"one\ntwo\n");
7082
    let b = repo.commit("second: grow a", &[]).unwrap();
7083
    // A second head, independent of b: a new file on top of a.
7084
    repo.checkout(&[a], false, "checkout a").unwrap();
7085
    write(root, "docs/notes.md", b"notes\n");
7086
    let c = repo.commit("third: notes", &[]).unwrap();
7087
    // Back to both heads, then rename a.rs: the node keeps its identity.
7088
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7089
        .unwrap();
7090
    fs::remove_file(root.join("src/a.rs")).unwrap();
7091
    write(root, "src/z.rs", b"one\ntwo\n");
7092
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7093
    let wc = repo.working_copy().unwrap().0;
7094
    // A saved revset is checked when set.
7095
    repo.set_user_config("revset.mine", "author(me) & ::main")
7096
        .unwrap();
7097
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7098
    let set = |src: &str| -> Vec<ChangeHash> {
7099
        let mut v = repo.revset(src).unwrap().hashes;
7100
        v.sort();
7101
        v
7102
    };
7103
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7104
        let mut v = hs.to_vec();
7105
        v.sort();
7106
        v
7107
    };
7108
7109
    // Changes commute: a new file depends on nothing and the rename on the
7110
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7111
    // copy on the three heads b, c, d.
7112
    let heads = sorted(&repo.bookmark_heads().unwrap());
7113
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7114
    assert!(heads.contains(&d) && heads.contains(&c));
7115
    // Symbols and closures.
7116
    assert_eq!(set("main"), heads);
7117
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7118
    assert_eq!(set("@"), vec![wc]);
7119
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7120
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7121
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7122
    assert_eq!(
7123
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7124
        sorted(&[a, b])
7125
    );
7126
    // Ranges: what main has beyond b, and `..` forms.
7127
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7128
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7129
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7130
    // Operators and precedence: ~ binds tighter than &, & than |.
7131
    assert_eq!(
7132
        set(&format!("::main ~ #{}", d.short(12))),
7133
        sorted(&[a, b, c])
7134
    );
7135
    assert_eq!(
7136
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7137
        sorted(&[b, c])
7138
    );
7139
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7140
    // Relations.
7141
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7142
    head_deps.sort();
7143
    head_deps.dedup();
7144
    assert_eq!(set("deps(main)"), head_deps);
7145
    let on_a: Vec<ChangeHash> = [b, c, d]
7146
        .into_iter()
7147
        .filter(|h| meta(h).deps.contains(&a))
7148
        .collect();
7149
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7150
    assert_eq!(set("heads(::main)"), heads);
7151
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7152
    assert_eq!(
7153
        set(&format!(
7154
            "heads(#{} | #{} | #{})",
7155
            a.short(12),
7156
            b.short(12),
7157
            c.short(12)
7158
        )),
7159
        sorted(&[b, c])
7160
    );
7161
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7162
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7163
    assert_eq!(set("none()"), vec![]);
7164
    // Predicates: author by name, email, key prefix and `me`.
7165
    let key = repo.config.author_key.unwrap();
7166
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7167
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7168
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7169
    assert_eq!(set("author(me) & ::main").len(), 4);
7170
    assert_eq!(set("author(nobody)"), vec![]);
7171
    assert_eq!(set("description(notes)"), vec![c]);
7172
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7173
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7174
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7175
    // touches follows the node through the rename, in the current state.
7176
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7177
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7178
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7179
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7180
    // Newest first in the result order.
7181
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7182
    // The saved revset, and errors that say what is wrong.
7183
    assert_eq!(set("mine()").len(), 4);
7184
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7185
    assert!(e.contains("unknown function nosuch()"), "{e}");
7186
    let e = repo.revset("main &").unwrap_err().to_string();
7187
    assert!(e.contains("at character"), "{e}");
7188
    let e = repo.revset("zzzz").unwrap_err().to_string();
7189
    assert!(e.contains("no change matches"), "{e}");
7190
    let e = repo
7191
        .revset_with_budget("::main", std::time::Duration::ZERO)
7192
        .unwrap_err()
7193
        .to_string();
7194
    assert!(e.contains("budget"), "{e}");
7195
    // The log entries carry the bookmark's heads and the working copy.
7196
    let entries = repo.log_revset("::@").unwrap();
7197
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
7198
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7199
    // push); then a signed change, a tag, and a revocation.
7200
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7201
    assert_eq!(set("signed_by(me)"), vec![]);
7202
    repo.sign_change(&d).unwrap();
7203
    assert_eq!(set("signed_by(me)"), vec![d]);
7204
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7205
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7206
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7207
    assert_eq!(set("delegated()"), vec![]);
7208
    assert_eq!(set("revoked()"), vec![]);
7209
    assert_eq!(set("attested(tag)"), vec![]);
7210
    repo.tag_create("v1", &[b], "first").unwrap();
7211
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7212
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7213
    assert_eq!(set("attested(receipt)"), vec![]);
7214
    assert_eq!(set("built(test)"), vec![]);
7215
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7216
    assert!(e.contains("tag, receipt or ref"), "{e}");
7217
    repo.revoke_identity(&key, "test").unwrap();
7218
    assert_eq!(set("revoked()"), vec![d]);
7219
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
7220
}