OXYGENHUB
◆ v0.4.4 oxygen / crates / oxy-core / src / repo / tests.rs
325.9 KiB · Rust · last changed Log takes the state index's changes in order; a clean diff loads no base 19 days ago source blame history raw
98286406 Andy McCall ↶ 1
//! Tests for the repository layer.
2
3
use super::*;
75167672 Andy McCall 4
use crate::protocol::SignedPolicy;
957fee30 Andy McCall ↶ 5
use crate::repo::{BisectStep, Selection};
98286406 Andy McCall ↶ 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)> {
75167672 Andy McCall 26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
98286406 Andy McCall ↶ 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.
75167672 Andy McCall 80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
98286406 Andy McCall ↶ 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();
75167672 Andy McCall 103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
98286406 Andy McCall ↶ 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());
75167672 Andy McCall 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
    );
98286406 Andy McCall ↶ 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}");
0912a033 Andy McCall ↶ 137
    assert!(
138
        d.lines()
139
            .any(|l| l.starts_with("M ") && l.ends_with("main.rs")),
140
        "a modified file is in the summary too: {d}"
141
    );
98286406 Andy McCall ↶ 142
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
143
    assert!(d.contains("-fn main() {}"), "{d}");
144
145
    // Resolution by prefix.
146
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
75167672 Andy McCall 147
    assert_eq!(
148
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
149
        h1
150
    );
98286406 Andy McCall ↶ 151
    assert!(repo.resolve_change("zzzz").is_err());
152
153
    // Undo the commit: bookmark and working copy go back.
154
    repo.undo().unwrap();
155
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
156
    let s = repo.snapshot("oxy status").unwrap();
75167672 Andy McCall 157
    assert!(
158
        !s.changed,
159
        "files on disk still match the pre-commit working copy"
160
    );
98286406 Andy McCall ↶ 161
    assert_eq!(s.statuses.len(), 3);
162
}
163
164
/// Make `main` conflicted: two commits on the same base that edit the same line.
165
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
166
    let dir = tempfile::tempdir().unwrap();
167
    let root = dir.path();
168
    let repo = Repo::init(root).unwrap();
169
    write(root, "f.txt", b"a\nb\nc\n");
170
    let h1 = repo.commit("base", &[]).unwrap();
171
    write(root, "f.txt", b"a\nB\nc\n");
172
    let h2 = repo.commit("upper", &[]).unwrap();
173
    repo.checkout(&[h1], false, "checkout").unwrap();
174
    write(root, "f.txt", b"a\nX\nc\n");
175
    let h3 = repo.commit("ex", &[]).unwrap();
176
    (dir, repo, h1, h2, h3)
177
}
178
179
#[test]
180
fn concurrent_edits_conflict_and_can_be_resolved() {
181
    hermetic();
182
    let (dir, repo, h1, h2, h3) = conflicted_repo();
183
    let root = dir.path();
184
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
185
    assert_eq!(heads, [h2, h3].into_iter().collect());
186
    let st = repo.load_state(&[h2, h3]).unwrap();
187
    assert!(st.materialize().is_conflicted());
188
189
    // Checking out main writes markers.
75167672 Andy McCall 190
    let r = repo
191
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
192
        .unwrap();
98286406 Andy McCall ↶ 193
    assert!(r.conflicted);
194
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 195
    assert!(
196
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
197
        "{marked}"
198
    );
199
    assert!(
200
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
201
        "{marked}"
202
    );
98286406 Andy McCall ↶ 203
    assert!(has_conflict_markers(marked.as_bytes()));
204
    // Untouched markers: clean working copy; commit has nothing to do.
205
    let s = repo.snapshot("status").unwrap();
206
    assert!(s.statuses.is_empty());
207
    assert!(!s.resolves);
208
209
    // Partially edited file that still has markers cannot be committed.
210
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
211
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 212
    assert_eq!(
213
        statuses(&s),
214
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
215
    );
98286406 Andy McCall ↶ 216
    assert!(repo.commit("no", &[]).is_err());
217
218
    // Resolve by keeping one side and adding a line elsewhere.
219
    write(root, "f.txt", b"a\nX\nc\nd\n");
220
    let s = repo.snapshot("status").unwrap();
221
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
222
    assert!(s.resolves);
223
    let h4 = repo.commit("resolve", &[]).unwrap();
224
    let c4 = repo.store().get_change(&h4).unwrap();
225
    assert_eq!(c4.kind, ChangeKind::Resolution);
226
    let mut want = vec![h1, h2, h3];
227
    want.sort();
75167672 Andy McCall 228
    assert_eq!(
229
        c4.deps, want,
230
        "a resolution depends on exactly the contributors and what it references"
231
    );
98286406 Andy McCall ↶ 232
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
233
    let snap = repo.load_state(&[h4]).unwrap().materialize();
234
    assert!(!snap.is_conflicted());
75167672 Andy McCall 235
    assert!(
236
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
237
    );
98286406 Andy McCall ↶ 238
    assert!(!repo.snapshot("status").unwrap().changed);
239
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
240
    // whatever order the changes arrive in.
241
    let mut st = State::new();
242
    for h in [h4, h3, h1, h2] {
243
        st.add_unchecked(repo.store().get_change(&h).unwrap());
244
    }
245
    st.validate().unwrap();
75167672 Andy McCall 246
    assert!(
247
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
248
    );
98286406 Andy McCall ↶ 249
}
250
251
#[test]
252
fn resolution_may_keep_both_sides_or_neither() {
253
    hermetic();
254
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
255
    let root = dir.path();
75167672 Andy McCall 256
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
257
        .unwrap();
98286406 Andy McCall ↶ 258
    // Keep both sides in a chosen order.
259
    write(root, "f.txt", b"a\nX\nB\nc\n");
260
    let h = repo.commit("both", &[]).unwrap();
261
    let snap = repo.load_state(&[h]).unwrap().materialize();
262
    assert!(!snap.is_conflicted());
75167672 Andy McCall 263
    assert!(
264
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
265
    );
98286406 Andy McCall ↶ 266
    // Undo and instead drop the whole region.
267
    repo.undo().unwrap();
268
    write(root, "f.txt", b"a\nc\n");
269
    let h = repo.commit("neither", &[]).unwrap();
270
    let snap = repo.load_state(&[h]).unwrap().materialize();
271
    assert!(!snap.is_conflicted());
75167672 Andy McCall 272
    assert!(
273
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
274
    );
98286406 Andy McCall ↶ 275
}
276
277
#[test]
278
fn name_conflict_resolved_by_removing_a_candidate() {
279
    hermetic();
280
    let dir = tempfile::tempdir().unwrap();
281
    let root = dir.path();
282
    let repo = Repo::init(root).unwrap();
283
    write(root, "keep.txt", b"k\n");
284
    let h1 = repo.commit("base", &[]).unwrap();
285
    write(root, "new.txt", b"one\n");
286
    repo.commit("one", &[]).unwrap();
287
    repo.checkout(&[h1], false, "checkout").unwrap();
288
    write(root, "new.txt", b"two\n");
289
    repo.commit("two", &[]).unwrap();
75167672 Andy McCall 290
    let r = repo
291
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
292
        .unwrap();
98286406 Andy McCall ↶ 293
    assert!(r.conflicted);
75167672 Andy McCall 294
    assert!(
295
        root.join("new.txt.oxy-conflict-1").exists()
296
            && root.join("new.txt.oxy-conflict-2").exists()
297
    );
98286406 Andy McCall ↶ 298
    assert!(!root.join("new.txt").exists());
299
    // Candidate numbering follows change-hash order, so pick by content:
300
    // keep the "two" candidate under the real name and drop the other.
75167672 Andy McCall 301
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
302
        (1, 2)
303
    } else {
304
        (2, 1)
305
    };
98286406 Andy McCall ↶ 306
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
75167672 Andy McCall 307
    fs::rename(
308
        root.join(format!("new.txt.oxy-conflict-{keep}")),
309
        root.join("new.txt"),
310
    )
311
    .unwrap();
98286406 Andy McCall ↶ 312
    let h = repo.commit("pick two", &[]).unwrap();
75167672 Andy McCall 313
    assert_eq!(
314
        repo.store().get_change(&h).unwrap().kind,
315
        ChangeKind::Resolution
316
    );
98286406 Andy McCall ↶ 317
    // The resolution does not touch keep.txt, so it does not depend on h1;
318
    // the bookmark keeps both as heads and their union is the state.
319
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
320
    assert_eq!(heads, [h1, h].into_iter().collect());
75167672 Andy McCall 321
    let snap = repo
322
        .load_state(&repo.bookmark_heads().unwrap())
323
        .unwrap()
324
        .materialize();
98286406 Andy McCall ↶ 325
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
75167672 Andy McCall 326
    assert_eq!(
327
        snap.files.keys().cloned().collect::<Vec<_>>(),
328
        ["keep.txt", "new.txt"]
329
    );
330
    assert!(
331
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
332
    );
98286406 Andy McCall ↶ 333
}
334
335
#[test]
336
fn identities_and_signed_commits() {
337
    hermetic();
338
    let dir = tempfile::tempdir().unwrap();
339
    let root = dir.path();
340
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
341
    write(root, "a.txt", b"a\n");
342
    let h0 = repo.commit("unsigned", &[]).unwrap();
343
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
75167672 Andy McCall 344
    assert_eq!(
345
        repo.store().get_change(&h0).unwrap().author,
346
        ObjectRef::ZERO
347
    );
98286406 Andy McCall ↶ 348
75167672 Andy McCall 349
    let (key, id) = repo
350
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
351
        .unwrap();
98286406 Andy McCall ↶ 352
    assert_eq!(id.hash(), key);
353
    assert_eq!(repo.config.author_key, Some(key));
354
    // Config survives reopen; the secret key is found again.
355
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
356
    assert_eq!(reopened.config.author_key, Some(key));
357
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
358
359
    // Default core.sign = seal: commits carry the author but no signature.
360
    write(root, "a.txt", b"a\nb\n");
361
    let h1 = repo.commit("authored", &[]).unwrap();
362
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
363
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
364
    // Signing later works too.
365
    repo.sign_change(&h1).unwrap();
75167672 Andy McCall 366
    assert!(
367
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
368
    );
98286406 Andy McCall ↶ 369
370
    repo.config.set("core.sign", "change").unwrap();
371
    repo.save_config().unwrap();
372
    write(root, "a.txt", b"a\nb\nc\n");
373
    let h2 = repo.commit("signed", &[]).unwrap();
75167672 Andy McCall 374
    assert_eq!(
375
        repo.verify_change(&h2).unwrap(),
376
        SignatureStatus::Valid {
377
            key,
378
            name: "Ada".into(),
379
            email: "[email protected]".into(),
380
            sealed: false,
381
            revoked: false
382
        }
383
    );
98286406 Andy McCall ↶ 384
05e71ed6 Andy McCall ↶ 385
    // A signature by a key that is not the author or a delegate is rejected
386
    // when the change names an author; an anonymous change (made before any
387
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
98286406 Andy McCall ↶ 388
    let other = SecretKey::generate();
389
    let other_id = other.identity("Mallory", "[email protected]", 0);
390
    let other_key = repo.store().put_identity(&other_id).unwrap();
05e71ed6 Andy McCall ↶ 391
    write(root, "a.txt", b"a\nb\nc\nd\n");
392
    repo.config.set("core.sign", "seal").unwrap();
393
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
394
    let forged = other.sign(Domain::Change, &other_key, &h3);
395
    repo.store().put_signature(&h3, &forged).unwrap();
75167672 Andy McCall 396
    assert!(
05e71ed6 Andy McCall ↶ 397
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
75167672 Andy McCall 398
    );
05e71ed6 Andy McCall ↶ 399
    let adopted = other.sign(Domain::Change, &other_key, &h0);
400
    repo.store().put_signature(&h0, &adopted).unwrap();
401
    assert!(
402
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
403
    );
98286406 Andy McCall ↶ 404
405
    // Tampering with the stored signature invalidates it.
406
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
407
    sig.ed[0] ^= 1;
408
    repo.store().put_signature(&h2, &sig).unwrap();
75167672 Andy McCall 409
    assert!(matches!(
410
        repo.verify_change(&h2).unwrap(),
411
        SignatureStatus::Invalid(_)
412
    ));
98286406 Andy McCall ↶ 413
414
    // Without the secret key, signing at commit fails cleanly.
415
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
416
    write(root, "a.txt", b"z\n");
417
    assert!(no_keys.commit("cannot sign", &[]).is_err());
418
}
419
420
#[test]
421
fn checkout_moves_the_working_copy() {
422
    hermetic();
423
    let dir = tempfile::tempdir().unwrap();
424
    let root = dir.path();
425
    let repo = Repo::init(root).unwrap();
426
    write(root, "a.txt", b"one\n");
427
    write(root, "sub/deep/b.txt", b"b\n");
428
    let h1 = repo.commit("first", &[]).unwrap();
429
    write(root, "a.txt", b"two\n");
430
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
431
    write(root, "bin.dat", &[0, 1, 2, 3]);
432
    let h2 = repo.commit("second", &[]).unwrap();
433
434
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
75167672 Andy McCall 435
    assert_eq!(
436
        r,
437
        CheckoutReport {
438
            written: 2,
439
            removed: 1,
9b723f69 Andy McCall ↶ 440
            removed_paths: vec!["bin.dat".into()],
75167672 Andy McCall 441
            conflicted: false,
d3cd7ef9 Andy McCall ↶ 442
            notes: vec![],
443
            lacks: 1,
75167672 Andy McCall 444
        }
445
    );
98286406 Andy McCall ↶ 446
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
447
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
448
    assert!(!root.join("bin.dat").exists());
449
    let (_, wc) = repo.working_copy().unwrap();
450
    assert_eq!(wc.deps, vec![h1]);
75167672 Andy McCall 451
    assert!(
452
        !repo.snapshot("status").unwrap().changed,
453
        "checkout leaves a clean working copy"
454
    );
98286406 Andy McCall ↶ 455
    // The bookmark still points at h2.
456
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
457
458
    // Dirty working copy refuses without --discard.
459
    write(root, "a.txt", b"dirty\n");
460
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
75167672 Andy McCall 461
    let r = repo
462
        .checkout(&[h2], true, "oxy checkout --discard")
463
        .unwrap();
98286406 Andy McCall ↶ 464
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
465
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
466
    assert!(!root.join("sub").exists(), "empty directories are pruned");
467
    assert_eq!(r.removed, 1);
468
    assert!(!repo.snapshot("status").unwrap().changed);
469
470
    // Refuses to write through a symlinked directory.
471
    #[cfg(unix)]
472
    {
473
        fs::remove_dir_all(root.join("sub")).ok();
474
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
475
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
476
    }
477
}
478
479
#[test]
480
fn large_files_are_chunked_and_read_back() {
481
    hermetic();
482
    let dir = tempfile::tempdir().unwrap();
483
    let repo = Repo::init(dir.path()).unwrap();
484
    let mut big = vec![0u8; 700 * 1024];
485
    for (i, b) in big.iter_mut().enumerate() {
486
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
487
    }
488
    let r = repo.store_blob(&big).unwrap();
489
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
490
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
491
    assert_eq!(repo.read_blob(&r).unwrap(), big);
492
    assert_eq!(Repo::blob_ref(&big), r);
493
}
494
495
#[test]
496
fn clone_push_pull_with_seals_and_attestations() {
497
    hermetic();
498
    let dir = tempfile::tempdir().unwrap();
499
    let root = dir.path();
500
    let origin_path = root.join("origin");
501
    let origin = Repo::init(&origin_path).unwrap();
502
    let origin_url = origin_path.to_string_lossy().to_string();
503
504
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
75167672 Andy McCall 505
    let mut a = Repo::clone(&origin_url, &root.join("a"))
506
        .unwrap()
507
        .with_home(root.join("home-a"));
98286406 Andy McCall ↶ 508
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
75167672 Andy McCall 509
    let (key_a, _) = a
510
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
511
        .unwrap();
98286406 Andy McCall ↶ 512
    write(&root.join("a"), "f.txt", b"a\n");
513
    let h1 = a.commit("first", &[]).unwrap();
514
    let results = a.push("origin", false).unwrap();
515
    assert!(results[0].ok, "{}", results[0].reason);
516
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
517
    // The change was sealed at push and the reference attested.
75167672 Andy McCall 518
    assert!(
519
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
520
    );
521
    assert_eq!(
522
        origin.verify_change(&h1).unwrap(),
523
        SignatureStatus::Unsigned
524
    );
f8c69576 Andy McCall ↶ 525
    let serial_of = |att: &SignedAttest| match att.attest.body {
526
        AttestBody::Ref { serial, .. } => serial,
527
        _ => unreachable!(),
528
    };
98286406 Andy McCall ↶ 529
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 530
    // A bookmark new to the remote starts at the clock (past any deleted
531
    // namesake's serial); later updates count up from there.
532
    let first = serial_of(&att);
533
    assert!(first > 1_000_000_000_000, "{first}");
98286406 Andy McCall ↶ 534
    let again = a.push("origin", false).unwrap();
535
    assert!(again[0].ok && again[0].reason.contains("up to date"));
536
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 537
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
98286406 Andy McCall ↶ 538
539
    // B clones and sees the file and the seal.
540
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
541
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
542
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
75167672 Andy McCall 543
    assert!(matches!(
544
        b.authenticate_change(&h1).unwrap(),
545
        SignatureStatus::Valid { sealed: true, .. }
546
    ));
98286406 Andy McCall ↶ 547
548
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
549
    write(&root.join("b"), "f.txt", b"a\nb\n");
550
    let h2 = b.commit("second", &[]).unwrap();
551
    assert!(b.push("origin", false).unwrap()[0].ok);
552
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
553
554
    // A commits an independent change; push is refused until A pulls.
555
    write(&root.join("a"), "g.txt", b"g\n");
556
    let h3 = a.commit("third", &[]).unwrap();
557
    assert!(a.push("origin", false).is_err());
558
    let pr = a.pull("origin").unwrap();
559
    assert!(pr.changed && pr.checked_out);
560
    let mut want = vec![h2, h3];
561
    want.sort();
562
    assert_eq!(pr.heads, want);
563
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
564
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
565
    let results = a.push("origin", false).unwrap();
566
    assert!(results[0].ok, "{}", results[0].reason);
567
    let mut origin_heads = origin.bookmark_heads().unwrap();
568
    origin_heads.sort();
569
    assert_eq!(origin_heads, want);
570
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 571
    assert_eq!(serial_of(&att), first + 1);
98286406 Andy McCall ↶ 572
573
    // B pulls and ends up identical.
574
    let pr = b.pull("origin").unwrap();
575
    assert_eq!(pr.heads, want);
576
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
577
    assert!(!b.snapshot("status").unwrap().changed);
578
579
    // Concurrent edits of the same line: the union is a reified conflict.
580
    write(&root.join("a"), "f.txt", b"a\nA\n");
581
    a.commit("a-edit", &[]).unwrap();
582
    a.push("origin", false).unwrap();
583
    write(&root.join("b"), "f.txt", b"a\nB\n");
584
    b.commit("b-edit", &[]).unwrap();
585
    let pr = b.pull("origin").unwrap();
586
    assert!(pr.changed && pr.checked_out);
587
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
588
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
589
    write(&root.join("b"), "f.txt", b"a\nAB\n");
590
    let hr = b.commit("resolve", &[]).unwrap();
75167672 Andy McCall 591
    assert_eq!(
592
        b.store().get_change(&hr).unwrap().kind,
593
        ChangeKind::Resolution
594
    );
98286406 Andy McCall ↶ 595
    assert!(b.push("origin", false).unwrap()[0].ok);
596
    a.pull("origin").unwrap();
597
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
598
    // The resolution depends on the conflicting edits, but nothing depends
599
    // on "third" (it only added g.txt), so it stays a head beside it.
600
    let mut want = vec![hr, h3];
601
    want.sort();
602
    assert_eq!(a.bookmark_heads().unwrap(), want);
603
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
604
}
605
606
#[test]
607
fn receive_push_rejects_bad_updates() {
608
    hermetic();
609
    let dir = tempfile::tempdir().unwrap();
610
    let root = dir.path();
611
    let origin = Repo::init(&root.join("origin")).unwrap();
612
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 613
    let mut a = Repo::clone(&url, &root.join("a"))
614
        .unwrap()
615
        .with_home(root.join("home"));
616
    let (key, _) = a
617
        .create_identity("Ada", "a@b", IdentityScope::Repo)
618
        .unwrap();
98286406 Andy McCall ↶ 619
    write(&root.join("a"), "f.txt", b"x\n");
620
    let h1 = a.commit("one", &[]).unwrap();
621
    assert!(a.push("origin", false).unwrap()[0].ok);
622
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
75167672 Andy McCall 623
    let s1 = origin
624
        .store()
625
        .put_state(&StateObject::new(vec![h1]))
626
        .unwrap();
98286406 Andy McCall ↶ 627
628
    // Missing head.
75167672 Andy McCall 629
    let ghost = origin
630
        .store()
631
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
632
        .unwrap();
633
    let r = origin
634
        .receive_push(
635
            Bundle::default(),
636
            vec![RefUpdate {
637
                name: "main".into(),
638
                old_state: s1,
639
                new_state: ghost,
640
                force: false,
641
                attestation: None,
642
            }],
643
            None,
644
            vec![],
645
        )
646
        .unwrap();
647
    assert!(
648
        !r[0].ok && r[0].reason.contains("missing"),
649
        "{}",
650
        r[0].reason
651
    );
98286406 Andy McCall ↶ 652
653
    // Stale old_state.
75167672 Andy McCall 654
    let r = origin
655
        .receive_push(
656
            Bundle::default(),
657
            vec![RefUpdate {
658
                name: "main".into(),
659
                old_state: empty,
660
                new_state: s1,
661
                force: false,
662
                attestation: None,
663
            }],
664
            None,
665
            vec![],
666
        )
667
        .unwrap();
98286406 Andy McCall ↶ 668
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
669
670
    // Non-fast-forward without force is refused; with force it passes.
75167672 Andy McCall 671
    let r = origin
672
        .receive_push(
673
            Bundle::default(),
674
            vec![RefUpdate {
675
                name: "main".into(),
676
                old_state: s1,
677
                new_state: empty,
678
                force: false,
679
                attestation: None,
680
            }],
681
            None,
682
            vec![],
683
        )
684
        .unwrap();
685
    assert!(
686
        !r[0].ok && r[0].reason.contains("fast-forward"),
687
        "{}",
688
        r[0].reason
689
    );
690
    let r = origin
691
        .receive_push(
692
            Bundle::default(),
693
            vec![RefUpdate {
694
                name: "main".into(),
695
                old_state: s1,
696
                new_state: empty,
697
                force: true,
698
                attestation: None,
699
            }],
700
            None,
701
            vec![],
702
        )
703
        .unwrap();
98286406 Andy McCall ↶ 704
    assert!(r[0].ok);
705
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
706
707
    // Attestation with a stale serial is a rollback and is refused.
75167672 Andy McCall 708
    let sa = a
709
        .sign_attest(&Attest {
710
            repo: a.id().unwrap(),
711
            hlc: Hlc::now(),
712
            body: AttestBody::Ref {
713
                name: "main".into(),
714
                old_state: empty,
715
                new_state: s1,
716
                serial: 1,
717
            },
718
        })
719
        .unwrap();
720
    let r = origin
721
        .receive_push(
722
            Bundle::default(),
723
            vec![RefUpdate {
724
                name: "main".into(),
725
                old_state: empty,
726
                new_state: s1,
727
                force: false,
728
                attestation: Some(sa.clone()),
729
            }],
730
            None,
731
            vec![],
732
        )
733
        .unwrap();
734
    assert!(
735
        !r[0].ok && r[0].reason.contains("serial"),
736
        "{}",
737
        r[0].reason
738
    );
98286406 Andy McCall ↶ 739
    // An attestation for a different update is refused too.
75167672 Andy McCall 740
    let sa2 = a
741
        .sign_attest(&Attest {
742
            repo: a.id().unwrap(),
743
            hlc: Hlc::now(),
744
            body: AttestBody::Ref {
745
                name: "main".into(),
746
                old_state: s1,
747
                new_state: empty,
748
                serial: 5,
749
            },
750
        })
751
        .unwrap();
752
    let r = origin
753
        .receive_push(
754
            Bundle::default(),
755
            vec![RefUpdate {
756
                name: "main".into(),
757
                old_state: empty,
758
                new_state: s1,
759
                force: false,
760
                attestation: Some(sa2),
761
            }],
762
            None,
763
            vec![],
764
        )
765
        .unwrap();
766
    assert!(
767
        !r[0].ok && r[0].reason.contains("describe"),
768
        "{}",
769
        r[0].reason
770
    );
98286406 Andy McCall ↶ 771
    let _ = key;
772
}
773
774
#[test]
775
fn user_config_supplies_defaults_and_clones_sign() {
776
    hermetic();
777
    let dir = tempfile::tempdir().unwrap();
778
    let root = dir.path();
779
    let home = root.join("home");
780
    let origin = Repo::init(&root.join("origin")).unwrap();
781
    let url = root.join("origin").to_string_lossy().to_string();
782
783
    // Identity at user scope: the repository file stays free of author keys.
784
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
75167672 Andy McCall 785
    let (key, _) = a
786
        .create_identity("Ada", "[email protected]", IdentityScope::User)
787
        .unwrap();
98286406 Andy McCall ↶ 788
    assert!(!a.config.repo_layer().contains_key("author.key"));
789
    assert_eq!(a.config.author_key, Some(key));
790
    assert!(home.join("config.toml").exists());
791
    a.set_user_config("core.sign", "change").unwrap();
792
    assert!(a.config.sign_changes);
793
794
    // Repository settings override user settings and are the only ones saved.
795
    a.config.set("core.sign", "seal").unwrap();
796
    a.save_config().unwrap();
797
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
798
    assert!(!again.config.sign_changes);
799
    assert_eq!(again.config.author_key, Some(key));
75167672 Andy McCall 800
    assert_eq!(
801
        read_config_file(&root.join("a/.oxy/config"))
802
            .unwrap()
803
            .get("core.sign")
804
            .map(String::as_str),
805
        Some("seal")
806
    );
98286406 Andy McCall ↶ 807
808
    // A fresh clone made by this user signs with the user-level identity,
809
    // even though the clone's store has never seen the identity object.
810
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
811
    assert!(b.config.sign_changes);
812
    write(&root.join("b"), "f.txt", b"f\n");
813
    let h = b.commit("signed from a clone", &[]).unwrap();
75167672 Andy McCall 814
    assert!(
815
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
816
    );
98286406 Andy McCall ↶ 817
    assert!(b.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 818
    assert!(matches!(
819
        origin.verify_change(&h).unwrap(),
820
        SignatureStatus::Valid { .. }
821
    ));
98286406 Andy McCall ↶ 822
}
823
824
#[test]
825
fn format1_repositories_are_migrated_on_open() {
826
    hermetic();
827
    use crate::oplog::{Format1Op, Format1View};
828
    let dir = tempfile::tempdir().unwrap();
829
    let root = dir.path();
830
    let repo = Repo::init(root).unwrap();
831
    write(root, "a.txt", b"a\n");
832
    let h1 = repo.commit("one", &[]).unwrap();
833
    let (wc_hash, _) = repo.working_copy().unwrap();
834
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
835
    let mut v1 = Format1View::default();
836
    v1.bookmarks.insert("main".into(), vec![]);
837
    v1.workspaces.insert(repo.workspace(), wc_hash);
75167672 Andy McCall 838
    let init = Format1Op {
839
        parents: vec![],
840
        hlc: Hlc::default(),
841
        command: "oxy init".into(),
842
        view: v1.clone(),
843
    };
98286406 Andy McCall ↶ 844
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
845
    v1.bookmarks.insert("main".into(), vec![h1]);
75167672 Andy McCall 846
    let commit = Format1Op {
847
        parents: vec![init_ref],
848
        hlc: Hlc::default(),
849
        command: "oxy commit".into(),
850
        view: v1,
851
    };
98286406 Andy McCall ↶ 852
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
853
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
854
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
855
    drop(repo);
856
857
    let repo = Repo::open(root).unwrap();
75167672 Andy McCall 858
    assert_eq!(
859
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
860
        FORMAT_LINE
861
    );
98286406 Andy McCall ↶ 862
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
863
    let ops = repo.op_log().unwrap();
75167672 Andy McCall 864
    assert_eq!(
865
        ops.iter()
866
            .map(|(_, o)| o.command.as_str())
867
            .collect::<Vec<_>>(),
868
        ["oxy commit", "oxy init"]
869
    );
98286406 Andy McCall ↶ 870
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
871
    assert!(!repo.snapshot("status").unwrap().changed);
872
    // Reopening again is a no-op.
873
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
874
}
875
876
#[test]
877
fn undo_skips_snapshot_operations() {
878
    hermetic();
879
    let dir = tempfile::tempdir().unwrap();
880
    let root = dir.path();
881
    let repo = Repo::init(root).unwrap();
882
    write(root, "a.txt", b"a\n");
883
    let h1 = repo.commit("a", &[]).unwrap();
884
    // A later command snapshots new edits on top of the commit.
885
    write(root, "b.txt", b"b\n");
886
    let s = repo.snapshot("oxy status").unwrap();
887
    assert!(s.changed);
888
    assert!(repo.head_op().unwrap().1.is_snapshot());
889
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
890
    // Undo must undo the commit, not the snapshot.
891
    repo.undo().unwrap();
892
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
893
    let s = repo.snapshot("oxy status").unwrap();
894
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
75167672 Andy McCall 895
    assert_eq!(
896
        paths,
897
        ["a.txt", "b.txt"],
898
        "both files are back in the working copy"
899
    );
98286406 Andy McCall ↶ 900
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
901
    // Only snapshots remain above `init`, so there is nothing left to undo.
902
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
903
    assert!(repo.undo().is_err());
904
}
905
906
#[test]
907
fn independent_changes_commute_and_make_multiple_heads() {
908
    hermetic();
909
    let dir = tempfile::tempdir().unwrap();
910
    let root = dir.path();
911
    let repo = Repo::init(root).unwrap();
912
    write(root, "a.txt", b"a\n");
913
    let h1 = repo.commit("a", &[]).unwrap();
914
    write(root, "b.txt", b"b\n");
915
    let h2 = repo.commit("b", &[]).unwrap();
916
    let c2 = repo.store().get_change(&h2).unwrap();
917
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
918
    let mut heads = repo.bookmark_heads().unwrap();
919
    heads.sort();
920
    let mut want = vec![h1, h2];
921
    want.sort();
922
    assert_eq!(heads, want);
923
    // Editing a.txt depends on h1 only.
924
    write(root, "a.txt", b"a\na2\n");
925
    let h3 = repo.commit("a2", &[]).unwrap();
926
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
927
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
928
    assert_eq!(heads, [h2, h3].into_iter().collect());
929
    // Explicit dependency.
930
    write(root, "c.txt", b"c\n");
931
    let h4 = repo.commit("c", &[h2]).unwrap();
932
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
933
}
934
935
#[test]
936
fn mode_change_and_text_binary_switch() {
937
    hermetic();
938
    let dir = tempfile::tempdir().unwrap();
939
    let root = dir.path();
940
    let repo = Repo::init(root).unwrap();
941
    write(root, "run.sh", b"#!/bin/sh\n");
942
    repo.commit("add script", &[]).unwrap();
943
    #[cfg(unix)]
944
    {
945
        use std::os::unix::fs::PermissionsExt;
946
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
947
        let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 948
        assert_eq!(
949
            statuses(&s),
950
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
951
        );
98286406 Andy McCall ↶ 952
        let h = repo.commit("exec", &[]).unwrap();
953
        let snap = repo.load_state(&[h]).unwrap().materialize();
954
        assert!(snap.files["run.sh"].mode.exec);
955
    }
956
    // Text → binary → text.
957
    write(root, "run.sh", b"\0binary");
958
    let h = repo.commit("binary", &[]).unwrap();
959
    let snap = repo.load_state(&[h]).unwrap().materialize();
960
    assert!(snap.files["run.sh"].mode.opaque);
961
    write(root, "run.sh", b"text again\n");
962
    let h = repo.commit("text", &[]).unwrap();
963
    let snap = repo.load_state(&[h]).unwrap().materialize();
964
    assert!(!snap.files["run.sh"].mode.opaque);
75167672 Andy McCall 965
    assert!(
966
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
967
    );
98286406 Andy McCall ↶ 968
    assert!(!snap.is_conflicted());
969
}
83e0677b Andy McCall ↶ 970
6eae06b6 Andy McCall ↶ 971
/// oxygen#87: a binary file given new contents and the executable bit in
972
/// one commit kept the contents and lost the bit.
973
#[cfg(unix)]
974
#[test]
975
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
976
    use std::os::unix::fs::PermissionsExt;
977
    hermetic();
978
    let dir = tempfile::tempdir().unwrap();
979
    let root = dir.path();
980
    let repo = Repo::init(root).unwrap();
981
    write(root, "tool.exe", b"MZ\0one");
982
    repo.commit("add", &[]).unwrap();
983
    write(root, "tool.exe", b"MZ\0two");
984
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
985
    let h = repo.commit("update and +x", &[]).unwrap();
986
    let snap = repo.load_state(&[h]).unwrap().materialize();
987
    let f = &snap.files["tool.exe"];
988
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
989
    assert!(
990
        repo.snapshot("status").unwrap().statuses.is_empty(),
991
        "nothing left to commit"
992
    );
993
}
994
83e0677b Andy McCall ↶ 995
#[test]
996
fn trust_policy_governs_pushes_and_fetches() {
997
    hermetic();
998
    let dir = tempfile::tempdir().unwrap();
999
    let root = dir.path();
1000
    let origin = Repo::init(&root.join("origin")).unwrap();
1001
    let url = root.join("origin").to_string_lossy().to_string();
1002
1003
    // A is the root. Before the policy, an unsigned push from B is fine.
75167672 Andy McCall 1004
    let mut a = Repo::clone(&url, &root.join("a"))
1005
        .unwrap()
1006
        .with_home(root.join("home-a"));
1007
    let (key_a, _) = a
1008
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1009
        .unwrap();
1010
    let mut b = Repo::clone(&url, &root.join("b"))
1011
        .unwrap()
1012
        .with_home(root.join("home-b"));
83e0677b Andy McCall ↶ 1013
    write(&root.join("b"), "b.txt", b"b\n");
1014
    b.commit("unsigned before policy", &[]).unwrap();
1015
    assert!(b.push("origin", false).unwrap()[0].ok);
1016
1017
    // A creates the policy and pushes it; origin now enforces it.
1018
    write(&root.join("a"), "a.txt", b"a\n");
1019
    a.commit("a", &[]).unwrap();
1020
    let sp = a.policy_init().unwrap();
1021
    assert_eq!(sp.policy.serial, 1);
1022
    a.pull("origin").unwrap();
1023
    let results = a.push("origin", false).unwrap();
1024
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1025
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1026
1027
    // B pulls the policy. Without an identity B cannot push at all.
1028
    b.pull("origin").unwrap();
75167672 Andy McCall 1029
    assert!(
1030
        b.current_policy().unwrap().is_some(),
1031
        "the policy arrived with the fetch"
1032
    );
83e0677b Andy McCall ↶ 1033
    assert!(b.push("origin", false).is_err());
1034
    // With an identity the policy does not list, the push is rejected by origin.
75167672 Andy McCall 1035
    let (key_b, id_b) = b
1036
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1037
        .unwrap();
83e0677b Andy McCall ↶ 1038
    write(&root.join("b"), "b.txt", b"b2\n");
1039
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1040
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1041
    let r = b.push("origin", false).unwrap();
75167672 Andy McCall 1042
    assert!(
1043
        !r[0].ok && r[0].reason.contains("may not update"),
1044
        "{:?}",
1045
        r
1046
    );
83e0677b Andy McCall ↶ 1047
1048
    // A grants B (identity handed over as a file) and publishes the policy.
1049
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1050
    assert_eq!(sp.policy.serial, 2);
1051
    let r = a.push("origin", false).unwrap();
1052
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1053
    // B must fetch the new policy before pushing.
75167672 Andy McCall 1054
    assert!(b
1055
        .push("origin", false)
1056
        .unwrap_or_else(|e| vec![RefResult {
1057
            name: "main".into(),
1058
            ok: false,
1059
            reason: e.to_string()
1060
        }])
1061
        .iter()
1062
        .all(|x| !x.ok));
83e0677b Andy McCall ↶ 1063
    b.pull("origin").unwrap();
1064
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1065
    let r = b.push("origin", false).unwrap();
1066
    assert!(r[0].ok, "{:?}", r);
1067
    // Origin verified B's change under the policy.
1068
    let heads = origin.bookmark_heads().unwrap();
1069
    for h in &heads {
1070
        let c = origin.store().get_change(h).unwrap();
1071
        if c.author == key_b {
75167672 Andy McCall 1072
            origin
1073
                .change_allowed(
1074
                    h,
1075
                    &origin.current_policy().unwrap().unwrap().1.policy,
1076
                    "main",
1077
                )
1078
                .unwrap();
83e0677b Andy McCall ↶ 1079
        }
1080
    }
1081
1082
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1083
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1084
    forged.serial = 3;
1085
    forged.roots = vec![key_b];
1086
    let fh = forged.hash();
1087
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 1088
    let forged = SignedPolicy {
1089
        policy: forged,
1090
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1091
    };
1092
    let r = origin
1093
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1094
        .unwrap();
83e0677b Andy McCall ↶ 1095
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1096
    let stale = a.current_policy().unwrap().unwrap().1;
1097
    let mut old = stale.clone();
1098
    old.policy.serial = 1;
75167672 Andy McCall 1099
    let r = origin
1100
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1101
        .unwrap();
83e0677b Andy McCall ↶ 1102
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1103
1104
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1105
    a.pull("origin").unwrap();
1106
    a.policy_revoke(&key_b).unwrap();
1107
    let r = a.push("origin", false).unwrap();
1108
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1109
    b.pull("origin").unwrap();
1110
    write(&root.join("b"), "b.txt", b"b3\n");
1111
    b.commit("b3", &[]).unwrap();
1112
    let r = b.push("origin", false).unwrap();
1113
    assert!(!r[0].ok, "{:?}", r);
1114
1115
    // A clone by a third party receives and verifies everything.
75167672 Andy McCall 1116
    let c = Repo::clone(&url, &root.join("c"))
1117
        .unwrap()
1118
        .with_home(root.join("home-c"));
83e0677b Andy McCall ↶ 1119
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
75167672 Andy McCall 1120
    assert!(c
1121
        .current_policy()
1122
        .unwrap()
1123
        .unwrap()
1124
        .1
1125
        .policy
1126
        .roots
1127
        .contains(&key_a));
83e0677b Andy McCall ↶ 1128
    assert!(!c.snapshot("status").unwrap().changed);
1129
}
d02e545d Andy McCall ↶ 1130
9ae4d15a Andy McCall ↶ 1131
/// oxygen#66: a gc says what it is doing, phase by phase.
d02e545d Andy McCall ↶ 1132
#[test]
9ae4d15a Andy McCall ↶ 1133
fn gc_reports_its_phases() {
1134
    hermetic();
1135
    let dir = tempfile::tempdir().unwrap();
1136
    let repo = Repo::init(dir.path()).unwrap();
1137
    for i in 0..3 {
1138
        write(
1139
            dir.path(),
1140
            &format!("f{i}.txt"),
1141
            format!("{i}\n").as_bytes(),
1142
        );
1143
        repo.commit(&format!("c{i}"), &[]).unwrap();
1144
    }
1145
    let mut phases = Vec::new();
1146
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1147
        .unwrap();
1148
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1149
    assert!(
1150
        phases.iter().any(|p| p.starts_with("pruning")),
1151
        "{phases:?}"
1152
    );
1153
    assert!(
1154
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1155
        "{phases:?}"
1156
    );
1157
    assert!(
1158
        phases
1159
            .iter()
1160
            .any(|p| p.starts_with("writing the index of ")),
1161
        "{phases:?}"
1162
    );
1163
}
1164
1165
#[test]
d02e545d Andy McCall ↶ 1166
fn gc_packs_objects_and_history_still_works() {
1167
    hermetic();
1168
    let dir = tempfile::tempdir().unwrap();
1169
    let root = dir.path();
1170
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1171
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1172
        .unwrap();
d02e545d Andy McCall ↶ 1173
    repo.set_user_config("core.sign", "change").unwrap();
1174
    write(root, "a.txt", b"one\n");
1175
    let h1 = repo.commit("one", &[]).unwrap();
1176
    write(root, "a.txt", b"two\n");
1177
    write(root, "big.bin", &vec![0u8; 100_000]);
1178
    let h2 = repo.commit("two", &[]).unwrap();
ba160f60 Andy McCall ↶ 1179
    // Several snapshots leave superseded working-copy versions behind.
1180
    for i in 0..5 {
1181
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1182
        repo.snapshot("status").unwrap();
1183
    }
1184
    write(root, "a.txt", b"two\n");
1185
    repo.snapshot("status").unwrap();
d02e545d Andy McCall ↶ 1186
    let before = repo.store().list().unwrap();
1187
    assert!(repo.store().loose_count().unwrap() > 0);
ba160f60 Andy McCall ↶ 1188
1189
    // With the default retention every operation's view is a root: nothing prunes.
1190
    let r = repo.gc(true).unwrap();
1191
    assert_eq!(r.packed.objects, before.len());
1192
    assert_eq!(r.pruned.objects, 0);
d02e545d Andy McCall ↶ 1193
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1194
    assert_eq!(repo.store().list().unwrap(), before);
ba160f60 Andy McCall ↶ 1195
1196
    // With zero retention only the current view is a root: superseded
1197
    // working copies go, everything reachable stays.
1198
    repo.config.set("core.op-retention", "0").unwrap();
1199
    repo.save_config().unwrap();
21b2aec2 Andy McCall ↶ 1200
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
ba160f60 Andy McCall ↶ 1201
    let r = repo.gc(true).unwrap();
1202
    assert!(r.pruned.objects >= 5, "{r:?}");
1203
    let after = repo.store().list().unwrap();
1204
    assert!(after.len() < before.len());
1205
    assert!(after.contains(&h1) && after.contains(&h2));
1206
    for (_, op) in repo.op_log().unwrap() {
1207
        assert!(!op.command.is_empty(), "operation objects are all kept");
1208
    }
1209
    // Everything still works from the pruned, packed store.
d02e545d Andy McCall ↶ 1210
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
75167672 Andy McCall 1211
    assert!(matches!(
1212
        repo.verify_change(&h2).unwrap(),
1213
        SignatureStatus::Valid { .. }
1214
    ));
d02e545d Andy McCall ↶ 1215
    assert_eq!(repo.log().unwrap().len(), 3);
1216
    repo.checkout(&[h1], false, "checkout").unwrap();
1217
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1218
    repo.checkout(&[h2], false, "checkout").unwrap();
1219
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1220
    assert!(!repo.snapshot("status").unwrap().changed);
ba160f60 Andy McCall ↶ 1221
    // Grace period defers pruning of young garbage.
d02e545d Andy McCall ↶ 1222
    write(root, "a.txt", b"three\n");
1223
    repo.commit("three", &[]).unwrap();
ba160f60 Andy McCall ↶ 1224
    let r = repo.gc(false).unwrap();
1225
    assert_eq!(r.pruned.objects, 0);
1226
    assert!(r.pruned.deferred > 0);
1227
    let r = repo.gc(true).unwrap();
1228
    assert!(r.pruned.objects > 0);
1229
    assert_eq!(repo.log().unwrap().len(), 4);
21b2aec2 Andy McCall ↶ 1230
    // Restoring the default retention makes the old views roots again; the
1231
    // working copies they name were pruned, which gc tolerates.
1232
    repo.config.set("core.op-retention", "90").unwrap();
1233
    repo.save_config().unwrap();
1234
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1235
    let r = repo.gc(false).unwrap();
1236
    assert_eq!(r.pruned.objects, 0);
1237
    assert_eq!(repo.log().unwrap().len(), 4);
d02e545d Andy McCall ↶ 1238
}
614541c3 Andy McCall ↶ 1239
1240
#[test]
1241
fn describe_amend_abandon_heads() {
1242
    hermetic();
1243
    let dir = tempfile::tempdir().unwrap();
1244
    let root = dir.path();
1245
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1246
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1247
        .unwrap();
614541c3 Andy McCall ↶ 1248
    repo.set_user_config("core.sign", "change").unwrap();
1249
    write(root, "a.txt", b"one\n");
1250
    let h1 = repo.commit("first", &[]).unwrap();
1251
    write(root, "a.txt", b"one\ntwo\n");
1252
    let h2 = repo.commit("secnod", &[]).unwrap();
1253
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1254
1255
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1256
    let h2b = repo.describe(&h2, "second").unwrap();
1257
    assert_ne!(h2b, h2);
1258
    let c = repo.store().get_change(&h2b).unwrap();
75167672 Andy McCall 1259
    assert_eq!(
1260
        (c.change_id, c.message.as_str(), c.deps.clone()),
1261
        (id2, "second", vec![h1])
1262
    );
614541c3 Andy McCall ↶ 1263
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
75167672 Andy McCall 1264
    assert!(matches!(
1265
        repo.verify_change(&h2b).unwrap(),
1266
        SignatureStatus::Valid { .. }
1267
    ));
614541c3 Andy McCall ↶ 1268
    let s = repo.snapshot("status").unwrap();
1269
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
75167672 Andy McCall 1270
    assert_eq!(
1271
        repo.resolve_change(&id2.short(8)).unwrap(),
1272
        h2b,
1273
        "the old object is no longer reachable from the log"
1274
    );
c07e0e7d Andy McCall ↶ 1275
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1276
    let h1b = repo.describe(&h1, "first, described").unwrap();
1277
    assert_ne!(h1b, h1);
1278
    let heads = repo.bookmark_heads().unwrap();
1279
    assert_eq!(heads.len(), 1);
1280
    let top = repo.store().get_change(&heads[0]).unwrap();
1281
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
75167672 Andy McCall 1282
    assert!(
1283
        matches!(
1284
            repo.verify_change(&heads[0]).unwrap(),
1285
            SignatureStatus::Valid { .. }
1286
        ),
1287
        "rewritten own change is re-signed"
1288
    );
c07e0e7d Andy McCall ↶ 1289
    let (_, wc) = repo.working_copy().unwrap();
75167672 Andy McCall 1290
    assert_eq!(
1291
        wc.deps,
1292
        vec![heads[0]],
1293
        "the working copy follows the rewrite"
1294
    );
c07e0e7d Andy McCall ↶ 1295
    assert!(!repo.snapshot("status").unwrap().changed);
1296
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 1297
    assert!(
1298
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1299
    );
614541c3 Andy McCall ↶ 1300
1301
    // amend: fold an edit into the head; the result is one change from h1.
1302
    write(root, "a.txt", b"one\ntwo\nthree\n");
1303
    write(root, "b.txt", b"b\n");
1304
    let h2c = repo.amend(None).unwrap();
1305
    let c = repo.store().get_change(&h2c).unwrap();
1306
    assert_eq!(c.change_id, id2);
1307
    assert_eq!(c.message, "second");
1308
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
75167672 Andy McCall 1309
    assert_eq!(
1310
        repo.log().unwrap().len(),
1311
        3,
1312
        "working copy, amended head, first"
1313
    );
614541c3 Andy McCall ↶ 1314
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
75167672 Andy McCall 1315
    assert!(
1316
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1317
    );
614541c3 Andy McCall ↶ 1318
    assert!(snap.files.contains_key("b.txt"));
1319
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 1320
    assert!(
1321
        repo.amend(None).is_err(),
1322
        "clean working copy and no message"
1323
    );
614541c3 Andy McCall ↶ 1324
    let h2d = repo.amend(Some("second, amended")).unwrap();
75167672 Andy McCall 1325
    assert_eq!(
1326
        repo.store().get_change(&h2d).unwrap().message,
1327
        "second, amended"
1328
    );
614541c3 Andy McCall ↶ 1329
1330
    // abandon: the head goes, its content stays as uncommitted work.
1331
    repo.abandon(&h2d).unwrap();
75167672 Andy McCall 1332
    assert_eq!(
1333
        repo.bookmark_heads().unwrap(),
1334
        vec![h1b],
1335
        "the described first change is the head again"
1336
    );
614541c3 Andy McCall ↶ 1337
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 1338
    let paths: Vec<_> = s
1339
        .statuses
1340
        .iter()
1341
        .map(|p| (p.path.as_str(), p.status))
1342
        .collect();
1343
    assert_eq!(
1344
        paths,
1345
        vec![
1346
            ("a.txt", ChangeStatus::Modified),
1347
            ("b.txt", ChangeStatus::Added)
1348
        ]
1349
    );
614541c3 Andy McCall ↶ 1350
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1351
    let h3 = repo.commit("recommitted", &[]).unwrap();
1352
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1353
    // undo brings the abandoned head back.
1354
    repo.undo().unwrap();
1355
    repo.undo().unwrap();
1356
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
c07e0e7d Andy McCall ↶ 1357
6706bdcf Andy McCall ↶ 1358
    // Abandoning a non-head whose dependent references its atoms reifies
1359
    // the references (here: a.txt vanishes with it, so the dependent's edit
1360
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
c07e0e7d Andy McCall ↶ 1361
    let base = repo.bookmark_heads().unwrap()[0];
1362
    let base_change = repo.store().get_change(&base).unwrap();
1363
    let h1_now = base_change.deps[0];
6706bdcf Andy McCall ↶ 1364
    let notes = repo.abandon(&h1_now).unwrap();
75167672 Andy McCall 1365
    assert!(
1366
        !notes.is_empty(),
1367
        "the dependent's edit of a.txt was reified"
1368
    );
6706bdcf Andy McCall ↶ 1369
    let heads = repo.bookmark_heads().unwrap();
1370
    let after = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 1371
    assert!(
1372
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1373
        "{:?}",
1374
        after.files.keys()
1375
    );
6706bdcf Andy McCall ↶ 1376
    repo.undo().unwrap();
1377
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
c07e0e7d Andy McCall ↶ 1378
    write(root, "c.txt", b"c\n");
1379
    let hc = repo.commit("c", &[]).unwrap();
1380
    write(root, "d.txt", b"d\n");
1381
    let hd = repo.commit("d", &[hc]).unwrap();
1382
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1383
    repo.abandon(&hc).unwrap();
1384
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1385
    assert!(!heads.contains(&hc));
75167672 Andy McCall 1386
    let d_now = heads
1387
        .iter()
1388
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1389
        .copied()
1390
        .unwrap();
1391
    assert!(
1392
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1393
        "d inherited c's (empty) dependencies"
1394
    );
c07e0e7d Andy McCall ↶ 1395
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 1396
    assert_eq!(
1397
        s.statuses
1398
            .iter()
1399
            .map(|p| p.path.as_str())
1400
            .collect::<Vec<_>>(),
1401
        vec!["c.txt"],
1402
        "c's content is now uncommitted work"
1403
    );
614541c3 Andy McCall ↶ 1404
}
79ab8528 Andy McCall ↶ 1405
1406
#[test]
1407
fn git_export_mirrors_history() {
1408
    hermetic();
75167672 Andy McCall 1409
    if std::process::Command::new("git")
1410
        .arg("--version")
1411
        .output()
1412
        .is_err()
1413
    {
79ab8528 Andy McCall ↶ 1414
        eprintln!("git not installed; skipping");
1415
        return;
1416
    }
1417
    let dir = tempfile::tempdir().unwrap();
1418
    let root = dir.path();
75167672 Andy McCall 1419
    let mut repo = Repo::init(&root.join("r"))
1420
        .unwrap()
1421
        .with_home(root.join("home"));
1422
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1423
        .unwrap();
79ab8528 Andy McCall ↶ 1424
    let r = root.join("r");
1425
    write(&r, "README.md", b"hello\n");
1426
    write(&r, "src/main.rs", b"fn main() {}\n");
1427
    let h1 = repo.commit("first", &[]).unwrap();
1428
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1429
    write(&r, "logo.png", b"\x89PNG\0\0");
1430
    let h2 = repo.commit("second", &[]).unwrap();
1431
1432
    let git_dir = root.join("mirror.git");
1433
    let rep = repo.git_export(&git_dir).unwrap();
1434
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1435
    let git = |args: &[&str]| -> String {
75167672 Andy McCall 1436
        let out = std::process::Command::new("git")
1437
            .arg("-C")
1438
            .arg(&git_dir)
1439
            .args(args)
1440
            .output()
1441
            .unwrap();
1442
        assert!(
1443
            out.status.success(),
1444
            "{}",
1445
            String::from_utf8_lossy(&out.stderr)
1446
        );
79ab8528 Andy McCall ↶ 1447
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1448
    };
1449
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1450
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1451
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1452
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 1453
    assert!(
1454
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1455
        "{body}"
1456
    );
79ab8528 Andy McCall ↶ 1457
    assert!(body.contains("Change-Id: "), "{body}");
75167672 Andy McCall 1458
    assert_eq!(
1459
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1460
        "Ada Lovelace <[email protected]>"
1461
    );
1462
    assert_eq!(
1463
        git(&["ls-tree", "--name-only", "main"]),
1464
        "README.md\nlogo.png\nsrc"
1465
    );
79ab8528 Andy McCall ↶ 1466
1467
    // Re-export is incremental.
1468
    let rep = repo.git_export(&git_dir).unwrap();
1469
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1470
1471
    // An independent change makes two heads; the next state is one more
1472
    // commit on the linear branch whose tree is the union.
1473
    repo.checkout(&[h1], false, "checkout").unwrap();
1474
    write(&r, "other.txt", b"o\n");
1475
    let h3 = repo.commit("third", &[]).unwrap();
1476
    let rep = repo.git_export(&git_dir).unwrap();
1477
    assert_eq!((rep.exported, rep.heads), (1, 2));
1478
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1479
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1480
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1481
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1482
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
75167672 Andy McCall 1483
    assert_eq!(
1484
        git(&["ls-tree", "--name-only", "main"]),
1485
        "README.md\nlogo.png\nother.txt\nsrc"
1486
    );
79ab8528 Andy McCall ↶ 1487
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 1488
    assert!(
1489
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1490
        "{body}"
1491
    );
79ab8528 Andy McCall ↶ 1492
    // A rewrite is a new state whose one new change is the rewritten one.
1493
    repo.describe(&h3, "third, described").unwrap();
1494
    let rep = repo.git_export(&git_dir).unwrap();
1495
    assert_eq!(rep.exported, 1);
75167672 Andy McCall 1496
    assert_eq!(
1497
        git(&["log", "-1", "--format=%s", "main"]),
1498
        "third, described"
1499
    );
79ab8528 Andy McCall ↶ 1500
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1501
    let _ = h2;
1502
}
c3069537 Andy McCall ↶ 1503
1504
#[test]
1505
fn git_import_reproduces_trees() {
c3d2ef61 Andy McCall ↶ 1506
    git_import_reproduces_trees_with(None);
1507
}
1508
1509
/// The same import with every merge rendered in batches of one file
1510
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1511
#[test]
1512
fn git_import_reproduces_trees_in_batches() {
1513
    git_import_reproduces_trees_with(Some(1));
1514
}
1515
1516
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1517
    crate::repo::git::set_merge_batch_for_tests(batch);
c3069537 Andy McCall ↶ 1518
    hermetic();
75167672 Andy McCall 1519
    if std::process::Command::new("git")
1520
        .arg("--version")
1521
        .output()
1522
        .is_err()
1523
    {
c3069537 Andy McCall ↶ 1524
        eprintln!("git not installed; skipping");
1525
        return;
1526
    }
1527
    let dir = tempfile::tempdir().unwrap();
1528
    let root = dir.path();
1529
    let g = root.join("src.git");
1530
    fs::create_dir_all(&g).unwrap();
1531
    let git = |args: &[&str]| -> String {
1532
        let out = std::process::Command::new("git")
1533
            .arg("-C")
1534
            .arg(&g)
75167672 Andy McCall 1535
            .args([
1536
                "-c",
1537
                "user.name=Grace",
1538
                "-c",
1539
                "[email protected]",
1540
                "-c",
1541
                "commit.gpgsign=false",
1542
            ])
c3069537 Andy McCall ↶ 1543
            .args(args)
1544
            .output()
1545
            .unwrap();
75167672 Andy McCall 1546
        assert!(
1547
            out.status.success(),
1548
            "git {args:?}: {}",
1549
            String::from_utf8_lossy(&out.stderr)
1550
        );
c3069537 Andy McCall ↶ 1551
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1552
    };
1553
    git(&["init", "-q", "-b", "main"]);
1554
    write(&g, "README.md", b"# Hi\n");
1555
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1556
    git(&["add", "."]);
1557
    git(&["commit", "-q", "-m", "initial"]);
1558
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1559
    write(&g, "run.sh", b"#!/bin/sh\n");
1560
    #[cfg(unix)]
1561
    {
1562
        use std::os::unix::fs::PermissionsExt;
1563
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1564
    }
1565
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1566
    git(&["add", "."]);
75167672 Andy McCall 1567
    git(&[
1568
        "commit",
1569
        "-q",
1570
        "-m",
1571
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1572
    ]);
c3069537 Andy McCall ↶ 1573
    // A branch that edits README, merged back with a conflict-free merge.
1574
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1575
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1576
    git(&["commit", "-q", "-am", "readme"]);
1577
    git(&["checkout", "-q", "main"]);
1578
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1579
    // A branch from the initial commit inserting at the same place as
1580
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1581
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1582
    git(&["checkout", "-q", "-b", "clash", &initial]);
1583
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1584
    git(&["commit", "-q", "-am", "clash"]);
1585
    git(&["checkout", "-q", "main"]);
7df9007b Andy McCall ↶ 1586
    // Expected to stop at the conflict, so its status is ignored; the
1587
    // identity is passed as for every other git call here, or a machine
1588
    // without one refuses to start the merge at all.
75167672 Andy McCall 1589
    let _ = std::process::Command::new("git")
1590
        .arg("-C")
1591
        .arg(&g)
7df9007b Andy McCall ↶ 1592
        .args([
1593
            "-c",
1594
            "user.name=Grace",
1595
            "-c",
1596
            "[email protected]",
1597
            "merge",
1598
            "-q",
1599
            "clash",
1600
        ])
75167672 Andy McCall 1601
        .output();
7df9007b Andy McCall ↶ 1602
    assert!(
1603
        g.join(".git/MERGE_HEAD").exists(),
1604
        "the clash merge stopped at its conflict"
1605
    );
75167672 Andy McCall 1606
    write(
1607
        &g,
1608
        "src/lib.rs",
1609
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1610
    );
c3069537 Andy McCall ↶ 1611
    git(&["add", "."]);
1612
    git(&["commit", "-q", "-m", "resolve clash"]);
1613
    git(&["rm", "-q", "logo.png"]);
1614
    git(&["commit", "-q", "-m", "drop logo"]);
6e723b81 Andy McCall ↶ 1615
    // A rename with a small edit is imported as a move of the same node.
1616
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
75167672 Andy McCall 1617
    write(
1618
        &g,
1619
        "src/lib2.rs",
1620
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1621
    );
6e723b81 Andy McCall ↶ 1622
    git(&["add", "."]);
1623
    git(&["commit", "-q", "-m", "rename lib"]);
958fb27d Andy McCall ↶ 1624
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1625
    // run.sh is the same as in the first parent's tree, but the merged
1626
    // change touched it, so the importer must compare it, not skip it.
1627
    git(&["checkout", "-q", "-b", "discarded"]);
1628
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1629
    git(&["commit", "-q", "-am", "discarded edit"]);
1630
    git(&["checkout", "-q", "main"]);
314db9b4 Andy McCall ↶ 1631
    git(&[
1632
        "merge",
1633
        "-q",
1634
        "-s",
1635
        "ours",
1636
        "-m",
1637
        "merge discarded, keeping ours",
1638
        "discarded",
1639
    ]);
c3069537 Andy McCall ↶ 1640
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1641
1642
    let dest = root.join("oxy");
1643
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1644
    let rep = repo.import_git(&g, "main").unwrap();
1645
    assert_eq!(rep.commits, expected_count);
958fb27d Andy McCall ↶ 1646
    assert_eq!(rep.merges, 3);
314db9b4 Andy McCall ↶ 1647
    assert_eq!(
1648
        fs::read(dest.join("run.sh")).unwrap(),
1649
        b"#!/bin/sh\n",
1650
        "the ours merge kept main's run.sh"
1651
    );
958fb27d Andy McCall ↶ 1652
    let v = repo.verify_git_import(&g, "main").unwrap();
1653
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1654
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
c3069537 Andy McCall ↶ 1655
    // The working copy equals the Git tree at main.
75167672 Andy McCall 1656
    assert_eq!(
1657
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1658
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1659
    );
6e723b81 Andy McCall ↶ 1660
    assert!(!dest.join("src/lib.rs").exists());
75167672 Andy McCall 1661
    assert_eq!(
1662
        fs::read(dest.join("README.md")).unwrap(),
1663
        b"# Hi\n\nMore.\n"
1664
    );
c3069537 Andy McCall ↶ 1665
    assert!(!dest.join("logo.png").exists());
1666
    #[cfg(unix)]
1667
    {
1668
        use std::os::unix::fs::PermissionsExt;
75167672 Andy McCall 1669
        assert!(
1670
            fs::metadata(dest.join("run.sh"))
1671
                .unwrap()
1672
                .permissions()
1673
                .mode()
1674
                & 0o111
1675
                != 0
1676
        );
c3069537 Andy McCall ↶ 1677
    }
75167672 Andy McCall 1678
    assert!(
1679
        !repo.snapshot("status").unwrap().changed,
1680
        "clean after import"
1681
    );
c3069537 Andy McCall ↶ 1682
    let heads = repo.bookmark_heads().unwrap();
1683
    let st = repo.load_state(&heads).unwrap();
1684
    assert!(!st.materialize().is_conflicted());
1685
    assert_eq!(st.len(), expected_count);
75167672 Andy McCall 1686
    let tip = repo
1687
        .log()
1688
        .unwrap()
1689
        .into_iter()
1690
        .find(|e| e.change.message.starts_with("rename lib"))
1691
        .unwrap();
6e723b81 Andy McCall ↶ 1692
    let c = repo.store().get_change(&tip.hash).unwrap();
75167672 Andy McCall 1693
    assert!(
1694
        c.tree_ops
1695
            .iter()
1696
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1697
        "{:?}",
1698
        c.tree_ops
1699
    );
1700
    assert!(!c
1701
        .tree_ops
1702
        .iter()
1703
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
c3069537 Andy McCall ↶ 1704
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1705
    let log = repo.log().unwrap();
75167672 Andy McCall 1706
    let second = log
1707
        .iter()
1708
        .find(|e| e.change.message.starts_with("second"))
1709
        .unwrap();
1710
    assert_eq!(
1711
        second.change.change_id,
1712
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1713
    );
1714
    assert!(second
1715
        .change
1716
        .message
1717
        .contains("Git-Author: Grace <[email protected]>"));
1718
    let resolve = log
1719
        .iter()
1720
        .find(|e| e.change.message.starts_with("resolve clash"))
1721
        .unwrap();
1722
    assert_eq!(
1723
        resolve.change.kind,
1724
        ChangeKind::Resolution,
1725
        "a conflicting Git merge becomes a resolution"
1726
    );
c3069537 Andy McCall ↶ 1727
    // Re-importing into another fresh repository gives the same ChangeIds.
75167672 Andy McCall 1728
    let repo2 = Repo::init(&root.join("oxy2"))
1729
        .unwrap()
1730
        .with_home(root.join("home"));
c3069537 Andy McCall ↶ 1731
    repo2.import_git(&g, "main").unwrap();
dfb23a3a Andy McCall ↶ 1732
    // New nodes' identifiers derive from the commit (spec §23), so the
1733
    // re-import is not just the same ChangeIds but the same changes.
1734
    assert_eq!(
1735
        repo2.bookmark_heads().unwrap(),
1736
        repo.bookmark_heads().unwrap()
1737
    );
75167672 Andy McCall 1738
    let ids: BTreeSet<ChangeId> = repo
1739
        .log()
1740
        .unwrap()
1741
        .iter()
1742
        .filter(|e| !e.is_working_copy)
1743
        .map(|e| e.change.change_id)
1744
        .collect();
1745
    let ids2: BTreeSet<ChangeId> = repo2
1746
        .log()
1747
        .unwrap()
1748
        .iter()
1749
        .filter(|e| !e.is_working_copy)
1750
        .map(|e| e.change.change_id)
1751
        .collect();
c3069537 Andy McCall ↶ 1752
    assert_eq!(ids, ids2);
1753
    // Round trip back out to Git reproduces the tip tree.
1754
    let mirror = root.join("mirror.git");
1755
    repo.git_export(&mirror).unwrap();
75167672 Andy McCall 1756
    let out = std::process::Command::new("git")
1757
        .arg("-C")
1758
        .arg(&mirror)
1759
        .args(["show", "main:src/lib2.rs"])
1760
        .output()
1761
        .unwrap();
1762
    assert_eq!(
1763
        String::from_utf8_lossy(&out.stdout),
1764
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1765
    );
1766
    let out = std::process::Command::new("git")
1767
        .arg("-C")
1768
        .arg(&mirror)
1769
        .args(["show", "main:src/lib.rs"])
1770
        .output()
1771
        .unwrap();
1772
    assert!(
1773
        !out.status.success(),
1774
        "the old path is gone from the export"
1775
    );
c3069537 Andy McCall ↶ 1776
}
252e8cb2 Andy McCall ↶ 1777
1778
#[test]
1779
fn checkpoints_accelerate_loading_and_stay_correct() {
1780
    hermetic();
1781
    let dir = tempfile::tempdir().unwrap();
1782
    let root = dir.path();
1783
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1784
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1785
    repo.save_config().unwrap();
1786
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1787
    let mut hashes = Vec::new();
1788
    for i in 0..12 {
75167672 Andy McCall 1789
        write(
1790
            root,
1791
            "a.txt",
1792
            format!(
1793
                "{}\n",
1794
                (0..=i)
1795
                    .map(|k| k.to_string())
1796
                    .collect::<Vec<_>>()
1797
                    .join("\n")
1798
            )
1799
            .as_bytes(),
1800
        );
252e8cb2 Andy McCall ↶ 1801
        write(root, &format!("f{i}.txt"), b"x\n");
1802
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1803
    }
75167672 Andy McCall 1804
    let (_, cp) = repo
1805
        .latest_checkpoint("main")
1806
        .unwrap()
1807
        .expect("automatic checkpoint");
252e8cb2 Andy McCall ↶ 1808
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1809
    // Loading through the checkpoint equals loading everything.
1810
    let heads = repo.bookmark_heads().unwrap();
1811
    let fast = repo.load_state(&heads).unwrap();
1812
    let full = repo.load_state_full(&heads).unwrap();
1813
    assert_eq!(fast.len(), full.len());
1814
    assert_eq!(fast.heads(), full.heads());
1815
    let (a, b) = (fast.materialize(), full.materialize());
75167672 Andy McCall 1816
    assert_eq!(
1817
        a.files.keys().collect::<Vec<_>>(),
1818
        b.files.keys().collect::<Vec<_>>()
1819
    );
252e8cb2 Andy McCall ↶ 1820
    for (p, f) in &a.files {
1821
        assert_eq!(f.content, b.files[p].content, "{p}");
1822
    }
1823
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1824
    // A head set that does not contain the checkpoint's heads falls back.
75167672 Andy McCall 1825
    assert!(repo
1826
        .load_state_checkpointed(&[hashes[0]])
1827
        .unwrap()
1828
        .is_none());
252e8cb2 Andy McCall ↶ 1829
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1830
    // Everything else keeps working on top of the checkpoint.
1831
    assert!(!repo.snapshot("status").unwrap().changed);
1832
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1833
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1834
    let (r, n, bytes) = repo.checkpoint().unwrap();
1835
    assert!(n >= 12 && bytes > 0);
1836
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1837
    write(root, "a.txt", b"after\n");
1838
    let h_after = repo.commit("after", &[]).unwrap();
1839
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1840
    assert!(st.contains(&h_after));
75167672 Andy McCall 1841
    assert!(
1842
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1843
    );
252e8cb2 Andy McCall ↶ 1844
    assert_eq!(repo.log().unwrap().len(), 14);
1845
    // Checkpoints survive gc.
1846
    repo.gc(true).unwrap();
1847
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
75167672 Andy McCall 1848
    assert!(repo
1849
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1850
        .unwrap()
1851
        .is_some());
252e8cb2 Andy McCall ↶ 1852
}
135212de Andy McCall ↶ 1853
1854
#[test]
1855
fn quick_status_for_prompts() {
1856
    hermetic();
1857
    let dir = tempfile::tempdir().unwrap();
1858
    let root = dir.path();
1859
    let origin = Repo::init(&root.join("origin")).unwrap();
1860
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 1861
    let a = Repo::clone(&url, &root.join("a"))
1862
        .unwrap()
1863
        .with_home(root.join("home"));
135212de Andy McCall ↶ 1864
    let ops_before = a.op_log().unwrap().len();
1865
    let info = a.quick_status().unwrap();
75167672 Andy McCall 1866
    assert_eq!(
1867
        (
1868
            info.bookmark.as_str(),
1869
            info.heads,
1870
            info.dirty,
1871
            info.conflicted,
1872
            info.ahead,
1873
            info.behind
1874
        ),
1875
        ("main", 0, false, false, Some(0), Some(0))
1876
    );
135212de Andy McCall ↶ 1877
    write(&root.join("a"), "f.txt", b"f\n");
1878
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
75167672 Andy McCall 1879
    assert_eq!(
1880
        a.op_log().unwrap().len(),
1881
        ops_before,
1882
        "quick_status records nothing"
1883
    );
135212de Andy McCall ↶ 1884
    // A snapshotted but uncommitted change is still dirty.
1885
    a.snapshot("status").unwrap();
1886
    assert!(a.quick_status().unwrap().dirty);
1887
    a.commit("f", &[]).unwrap();
1888
    let info = a.quick_status().unwrap();
1889
    assert!(!info.dirty, "clean right after a commit");
1890
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
75167672 Andy McCall 1891
    assert_eq!(
1892
        info.format("%b %c%d%x%A%D"),
1893
        format!("main {}+1", info.change_id)
1894
    );
135212de Andy McCall ↶ 1895
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1896
    // Touching a file without changing it is not dirty; changing content of
1897
    // the same size is.
1898
    let p = root.join("a/f.txt");
1899
    let content = fs::read(&p).unwrap();
1900
    fs::write(&p, &content).unwrap();
1901
    assert!(!a.quick_status().unwrap().dirty);
1902
    fs::write(&p, b"g\n").unwrap();
1903
    assert!(a.quick_status().unwrap().dirty);
1904
    fs::write(&p, b"f\n").unwrap();
1905
    // Push, then a second clone commits and pushes: we are behind.
1906
    assert!(a.push("origin", false).unwrap()[0].ok);
1907
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
75167672 Andy McCall 1908
    let b = Repo::clone(&url, &root.join("b"))
1909
        .unwrap()
1910
        .with_home(root.join("home-b"));
135212de Andy McCall ↶ 1911
    write(&root.join("b"), "g.txt", b"g\n");
1912
    b.commit("g", &[]).unwrap();
1913
    b.push("origin", false).unwrap();
1914
    a.fetch("origin").unwrap();
1915
    let info = a.quick_status().unwrap();
1916
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1917
    assert_eq!(info.format("%A%D"), "-1");
1918
    let _ = origin;
1919
}
b3c5a59a Andy McCall ↶ 1920
1921
#[test]
1922
fn lazy_blobs_are_fetched_on_first_read() {
1923
    hermetic();
1924
    let dir = tempfile::tempdir().unwrap();
1925
    let root = dir.path();
1926
    let origin_dir = root.join("origin");
75167672 Andy McCall 1927
    let origin = Repo::init(&origin_dir)
1928
        .unwrap()
1929
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 1930
    let url = origin_dir.to_string_lossy().to_string();
1931
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1932
    write(&origin_dir, "big.bin", &big);
1933
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1934
    write(&origin_dir, "t.txt", b"t\n");
1935
    let h = origin.commit("blobs", &[]).unwrap();
1936
    let big_ref = Repo::blob_ref(&big);
1937
1938
    // Fetch only (no checkout) with a filter: the big blob stays absent.
75167672 Andy McCall 1939
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1940
        .unwrap()
1941
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 1942
    let a = {
1943
        let mut a = a;
1944
        a.config.set("remote.origin.url", &url).unwrap();
1945
        a.config.set("filter.max-blob", "100K").unwrap();
1946
        a.save_config().unwrap();
1947
        a
1948
    };
1949
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1950
    a.fetch("origin").unwrap();
1951
    assert!(a.store().has(&h));
1952
    assert!(!a.store().has(&big_ref), "withheld");
75167672 Andy McCall 1953
    assert!(
1954
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1955
        "small blob came along"
1956
    );
b3c5a59a Andy McCall ↶ 1957
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1958
1959
    // status and commit do not need it: adopt the state, edit a text file, commit.
1960
    let (op_ref, op) = a.head_op().unwrap();
1961
    let mut view = op.view.clone();
75167672 Andy McCall 1962
    view.bookmarks.insert(
1963
        "main".into(),
1964
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1965
    );
b3c5a59a Andy McCall ↶ 1966
    a.record_op(&[op_ref], "adopt", view).unwrap();
1967
    // Checkout reads the blob lazily, which fetches it.
1968
    a.checkout(&[h], true, "checkout").unwrap();
1969
    assert!(a.store().has(&big_ref), "fetched on first read");
1970
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1971
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1972
    write(&root.join("a"), "t.txt", b"t2\n");
1973
    a.commit("text edit", &[]).unwrap();
1974
1975
    // clone --max-blob records the filter; the checkout fetches lazily.
7421309f Andy McCall ↶ 1976
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
b3c5a59a Andy McCall ↶ 1977
    assert_eq!(b.config.max_blob, Some(1024));
1978
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1979
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1980
    assert!(parse_size("lots").is_err());
1981
}
7421309f Andy McCall ↶ 1982
1983
#[test]
1984
fn sparse_checkout_materializes_only_chosen_paths() {
1985
    hermetic();
1986
    let dir = tempfile::tempdir().unwrap();
1987
    let root = dir.path();
1988
    let origin_dir = root.join("origin");
75167672 Andy McCall 1989
    let origin = Repo::init(&origin_dir)
1990
        .unwrap()
1991
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 1992
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1993
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1994
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1995
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1996
    write(&origin_dir, "docs/logo.png", &logo);
1997
    write(&origin_dir, "README.md", b"# top\n");
1998
    let h1 = origin.commit("tree", &[]).unwrap();
1999
    let url = origin_dir.to_string_lossy().to_string();
2000
75167672 Andy McCall 2001
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2002
        .unwrap()
2003
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 2004
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2005
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2006
    assert!(root.join("a/src/main.rs").exists());
2007
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
75167672 Andy McCall 2008
    assert!(
2009
        !a.store().has(&Repo::blob_ref(&logo)),
2010
        "out-of-scope blob never fetched"
2011
    );
2012
    assert!(
2013
        !a.snapshot("status").unwrap().changed,
2014
        "out-of-scope files are not removals"
2015
    );
05e71ed6 Andy McCall ↶ 2016
    assert!(!a.quick_status().unwrap().dirty);
7421309f Andy McCall ↶ 2017
2018
    // Edits in scope commit normally and keep the rest of the tree intact.
75167672 Andy McCall 2019
    write(
2020
        &root.join("a"),
2021
        "src/lib.rs",
2022
        b"pub fn a() {}\npub fn b() {}\n",
2023
    );
7421309f Andy McCall ↶ 2024
    let h2 = a.commit("edit lib", &[]).unwrap();
2025
    let st = a.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 2026
    assert!(
2027
        st.files.contains_key("docs/guide.md"),
2028
        "the state still has everything"
2029
    );
7421309f Andy McCall ↶ 2030
    assert!(a.push("origin", false).unwrap()[0].ok);
2031
    // Files created outside the scope are ignored by status.
2032
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2033
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2034
2035
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2036
    let mut a = a;
2037
    a.config.set("filter.paths", "src,docs").unwrap();
2038
    a.save_config().unwrap();
75167672 Andy McCall 2039
    let r = a
2040
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2041
        .unwrap();
7421309f Andy McCall ↶ 2042
    assert!(r.written >= 2);
75167672 Andy McCall 2043
    assert_eq!(
2044
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2045
        logo,
2046
        "now fetched lazily"
2047
    );
7421309f Andy McCall ↶ 2048
    assert!(!root.join("a/README.md").exists());
2049
    // Origin sees the change made under a sparse checkout with the full tree intact.
2050
    origin.pull("origin").err();
75167672 Andy McCall 2051
    let full = origin
2052
        .load_state(&origin.bookmark_heads().unwrap())
2053
        .unwrap()
2054
        .materialize();
2055
    assert!(
2056
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2057
    );
7421309f Andy McCall ↶ 2058
    assert!(full.files.contains_key("README.md"));
2059
    let _ = h1;
2060
}
2863456a Andy McCall ↶ 2061
2062
#[test]
2063
fn shallow_clone_and_deepen() {
2064
    hermetic();
2065
    let dir = tempfile::tempdir().unwrap();
2066
    let root = dir.path();
2067
    let origin_dir = root.join("origin");
75167672 Andy McCall 2068
    let origin = Repo::init(&origin_dir)
2069
        .unwrap()
2070
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2071
    let mut hashes = Vec::new();
2072
    for i in 0..8 {
75167672 Andy McCall 2073
        write(
2074
            &origin_dir,
2075
            "a.txt",
2076
            format!(
2077
                "{}\n",
2078
                (0..=i)
2079
                    .map(|k| k.to_string())
2080
                    .collect::<Vec<_>>()
2081
                    .join("\n")
2082
            )
2083
            .as_bytes(),
2084
        );
2863456a Andy McCall ↶ 2085
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2086
    }
2087
    let url = origin_dir.to_string_lossy().to_string();
75167672 Andy McCall 2088
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2089
        .unwrap()
2090
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2091
    assert!(a.is_shallow());
75167672 Andy McCall 2092
    assert_eq!(
2093
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2094
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2095
    );
2096
    assert!(
2097
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2098
        "three levels present"
2099
    );
2863456a Andy McCall ↶ 2100
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2101
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
75167672 Andy McCall 2102
    assert_eq!(
2103
        a.log().unwrap().len(),
2104
        9,
2105
        "the log shows every change from the checkpoint's metadata"
2106
    );
2863456a Andy McCall ↶ 2107
    assert!(!a.snapshot("status").unwrap().changed);
2108
    assert_eq!(a.quick_status().unwrap().heads, 1);
2109
2110
    // Work continues on top of the shallow history and pushes back.
2111
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2112
    let h_new = a.commit("c8", &[]).unwrap();
2113
    assert!(a.push("origin", false).unwrap()[0].ok);
2114
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2115
    // Fetching new work from origin into the shallow clone works too.
2116
    write(&origin_dir, "b.txt", b"b\n");
2117
    origin.pull("origin").err();
2118
    let (_, wc) = origin.working_copy().unwrap();
2119
    let _ = wc;
75167672 Andy McCall 2120
    origin
2121
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2122
        .unwrap();
2863456a Andy McCall ↶ 2123
    write(&origin_dir, "b.txt", b"b\n");
2124
    let h_b = origin.commit("b", &[]).unwrap();
2125
    let pr = a.pull("origin").unwrap();
2126
    assert!(pr.changed);
2127
    assert!(a.store().has(&h_b));
2128
    assert!(root.join("a/b.txt").exists());
2129
2130
    // Deepening fetches older history until the boundary is gone.
2131
    // Every commit also depends on the change that created the file, so two
2132
    // levels below the boundary hold h4, h3, and the root.
2133
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2134
    assert!(a.store().has(&hashes[3]));
2135
    assert!(a.is_shallow());
2136
    a.deepen("origin", 100).unwrap();
2137
    assert!(!a.is_shallow(), "boundary reached the root");
2138
    assert!(a.store().has(&hashes[0]));
75167672 Andy McCall 2139
    assert_eq!(
2140
        a.load_state_full(&a.bookmark_heads().unwrap())
2141
            .unwrap()
2142
            .len(),
2143
        10
2144
    );
2863456a Andy McCall ↶ 2145
}
132b884b Andy McCall ↶ 2146
2147
#[test]
2148
fn tags_are_immutable_named_states_and_travel() {
2149
    hermetic();
2150
    let dir = tempfile::tempdir().unwrap();
2151
    let root = dir.path();
2152
    let origin = Repo::init(&root.join("origin")).unwrap();
2153
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2154
    let mut a = Repo::clone(&url, &root.join("a"))
2155
        .unwrap()
2156
        .with_home(root.join("home-a"));
2157
    let (key_a, _) = a
2158
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2159
        .unwrap();
132b884b Andy McCall ↶ 2160
    write(&root.join("a"), "f.txt", b"1\n");
2161
    let h1 = a.commit("one", &[]).unwrap();
2162
    write(&root.join("a"), "f.txt", b"1\n2\n");
2163
    let h2 = a.commit("two", &[]).unwrap();
2164
2165
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
75167672 Andy McCall 2166
    assert_eq!(
2167
        (t.heads.clone(), t.signer.as_deref()),
2168
        (vec![h1], Some("Ada"))
2169
    );
132b884b Andy McCall ↶ 2170
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2171
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2172
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2173
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2174
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2175
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2176
    assert_eq!(sa.sigs[0].key, key_a);
2177
    // Checkout by tag.
75167672 Andy McCall 2178
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2179
        .unwrap();
132b884b Andy McCall ↶ 2180
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
75167672 Andy McCall 2181
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2182
        .unwrap();
132b884b Andy McCall ↶ 2183
2184
    // Push carries the tag; a second attestation for the name is refused.
2185
    let r = a.push("origin", false).unwrap();
2186
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2187
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
75167672 Andy McCall 2188
    let mut forged = a
2189
        .tag_refs()
2190
        .unwrap()
2191
        .into_iter()
2192
        .find(|t| t.name == "v1")
2193
        .unwrap();
2194
    forged.state = origin
2195
        .store()
2196
        .put_state(&StateObject::new(vec![h2]))
2197
        .unwrap();
132b884b Andy McCall ↶ 2198
    forged.heads = vec![h2];
2199
    forged.attestation = None;
75167672 Andy McCall 2200
    let r = origin
2201
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2202
        .unwrap();
132b884b Andy McCall ↶ 2203
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2204
2205
    // A clone gets the tag; a later tag arrives on fetch.
75167672 Andy McCall 2206
    let b = Repo::clone(&url, &root.join("b"))
2207
        .unwrap()
2208
        .with_home(root.join("home-b"));
132b884b Andy McCall ↶ 2209
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2210
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2211
    a.tag_create("v2", &[h2], "second").unwrap();
2212
    a.push("origin", false).unwrap();
2213
    let rep = b.fetch("origin").unwrap();
2214
    assert_eq!(rep.new_tags, 1);
2215
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2216
2217
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2218
    a.policy_init().unwrap();
2219
    a.push("origin", false).unwrap();
75167672 Andy McCall 2220
    let unattested = crate::protocol::TagRef {
2221
        name: "v3".into(),
2222
        state: origin
2223
            .store()
2224
            .put_state(&StateObject::new(vec![h2]))
2225
            .unwrap(),
2226
        heads: vec![h2],
2227
        attestation: None,
2228
    };
2229
    let r = origin
2230
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2231
        .unwrap();
132b884b Andy McCall ↶ 2232
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2233
    a.tag_create("v3", &[h2], "").unwrap();
2234
    let r = a.push("origin", false).unwrap();
2235
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2236
    assert!(a.gc(true).is_ok());
2237
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
e5d9b051 Andy McCall ↶ 2238
2239
    // After a rotation the policy names only the new key, yet a fresh clone
2240
    // still takes the tags the old key made before it; the old key makes
2241
    // nothing new.
2242
    let rot = a.rotate_identity().unwrap();
2243
    let r = a.push("origin", false).unwrap();
2244
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2245
    let c = Repo::clone(&url, &root.join("c"))
2246
        .unwrap()
2247
        .with_home(root.join("home-c"));
2248
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
2249
    let (_, sp) = c.current_policy().unwrap().unwrap();
2250
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
2251
    let made = c.identity(&rot.new).unwrap().created;
2252
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
2253
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
2254
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
132b884b Andy McCall ↶ 2255
}
4e88e774 Andy McCall ↶ 2256
2257
#[test]
2258
fn multiple_workspaces_share_a_repository() {
2259
    hermetic();
2260
    let dir = tempfile::tempdir().unwrap();
2261
    let root = dir.path();
2262
    let main_dir = root.join("main");
2263
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2264
    write(&main_dir, "a.txt", b"a\n");
2265
    let h1 = repo.commit("a", &[]).unwrap();
2266
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2267
2268
    // A second workspace elsewhere, checked out on the bookmark.
2269
    let ws_dir = root.join("ws2");
2270
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2271
    assert!(ws_dir.join(".oxy").is_file());
2272
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2273
    assert_ne!(ws.workspace(), repo.workspace());
2274
    let list = repo.workspaces().unwrap();
2275
    assert_eq!(list.len(), 2);
75167672 Andy McCall 2276
    assert!(list
2277
        .iter()
2278
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
4e88e774 Andy McCall ↶ 2279
    assert!(!ws.snapshot("status").unwrap().changed);
2280
2281
    // Work in the second workspace: its own working copy, shared bookmark.
2282
    write(&ws_dir, "b.txt", b"b\n");
2283
    let s = ws.snapshot("status").unwrap();
2284
    assert_eq!(s.statuses.len(), 1);
75167672 Andy McCall 2285
    assert!(
2286
        !repo.snapshot("status").unwrap().changed,
2287
        "the first workspace is untouched"
2288
    );
4e88e774 Andy McCall ↶ 2289
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2290
    let mut heads = repo.bookmark_heads().unwrap();
2291
    heads.sort();
2292
    let mut want = vec![h1, h2];
2293
    want.sort();
2294
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2295
    assert!(!main_dir.join("b.txt").exists());
75167672 Andy McCall 2296
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2297
        .unwrap();
4e88e774 Andy McCall ↶ 2298
    assert!(main_dir.join("b.txt").exists());
2299
2300
    // Reopening from inside the second workspace finds the shared repository.
2301
    let reopened = Repo::open(&ws_dir).unwrap();
2302
    assert_eq!(reopened.workspace(), ws.workspace());
2303
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2304
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2305
2306
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2307
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2308
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2309
    repo.workspace_forget(&ws.workspace()).unwrap();
2310
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2311
    assert!(ws_dir.join("b.txt").exists());
75167672 Andy McCall 2312
    assert!(
2313
        ws.snapshot("status").is_err(),
2314
        "a forgotten workspace is no longer in the view"
2315
    );
4e88e774 Andy McCall ↶ 2316
6caacfff Andy McCall ↶ 2317
    // The working-copy lock: re-entrant in a thread; a lock whose process
2318
    // is gone is taken over, and a live process's is not, however old.
4e88e774 Andy McCall ↶ 2319
    let lock = repo.lock_snapshot().unwrap();
6caacfff Andy McCall ↶ 2320
    let again = repo.lock_working_copy().unwrap();
2321
    drop(again);
4e88e774 Andy McCall ↶ 2322
    drop(lock);
75167672 Andy McCall 2323
    let lock_path = main_dir
2324
        .join(".oxy/workspaces")
2325
        .join(repo.workspace().to_hex())
2326
        .join("lock");
4e88e774 Andy McCall ↶ 2327
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
6caacfff Andy McCall ↶ 2328
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2329
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2330
    age(&lock_path);
2331
    assert!(
2332
        !super::workspace::lock_is_stale(&lock_path),
2333
        "a live process keeps its lock"
2334
    );
2335
    fs::write(&lock_path, "4294967295").unwrap();
2336
    age(&lock_path);
4e88e774 Andy McCall ↶ 2337
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2338
}
cdb5beba Andy McCall ↶ 2339
2340
#[test]
2341
fn attributes_binary_eol_nocompress_lockable() {
2342
    hermetic();
2343
    let dir = tempfile::tempdir().unwrap();
2344
    let root = dir.path();
2345
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2346
    write(
2347
        root,
2348
        ".oxyattributes",
2349
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2350
    );
cdb5beba Andy McCall ↶ 2351
    write(root, "plain.dat", b"no nul bytes here\n");
2352
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2353
    write(root, "assets/model.bin", b"\0model");
2354
    let h = repo.commit("attrs", &[]).unwrap();
2355
    let snap = repo.load_state(&[h]).unwrap().materialize();
75167672 Andy McCall 2356
    assert!(
2357
        snap.files["plain.dat"].mode.opaque,
2358
        "binary attribute forces opaque without NUL bytes"
2359
    );
2360
    assert!(
2361
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2362
        "stored with LF"
2363
    );
2364
    assert!(
2365
        !repo.snapshot("status").unwrap().changed,
2366
        "CRLF on disk equals LF in the state"
2367
    );
cdb5beba Andy McCall ↶ 2368
    // nocompress chunks pack raw.
2369
    let r = repo.gc(true).unwrap();
2370
    assert!(r.packed.objects > 0);
2371
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2372
    fs::remove_file(root.join("notes.txt")).unwrap();
2373
    repo.checkout(&[h], true, "co").unwrap();
2374
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
75167672 Andy McCall 2375
    assert!(fs::metadata(root.join("assets/model.bin"))
2376
        .unwrap()
2377
        .permissions()
2378
        .readonly());
cdb5beba Andy McCall ↶ 2379
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2380
    repo.lock_path("assets/model.bin").unwrap();
75167672 Andy McCall 2381
    assert!(!fs::metadata(root.join("assets/model.bin"))
2382
        .unwrap()
2383
        .permissions()
2384
        .readonly());
cdb5beba Andy McCall ↶ 2385
    assert!(repo.is_locked("assets/model.bin"));
2386
    write(root, "assets/model.bin", b"\0model2");
2387
    repo.commit("edit model", &[]).unwrap();
2388
    repo.unlock_path("assets/model.bin").unwrap();
75167672 Andy McCall 2389
    assert!(fs::metadata(root.join("assets/model.bin"))
2390
        .unwrap()
2391
        .permissions()
2392
        .readonly());
cdb5beba Andy McCall ↶ 2393
    // A later checkout can still overwrite a read-only lockable file.
2394
    repo.checkout(&[h], true, "co").unwrap();
2395
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2396
}
6d3eefbc Andy McCall ↶ 2397
2398
#[cfg(unix)]
2399
#[test]
2400
fn hooks_can_veto_observe_and_add_dependencies() {
2401
    use std::os::unix::fs::PermissionsExt;
2402
    hermetic();
2403
    let dir = tempfile::tempdir().unwrap();
2404
    let root = dir.path();
2405
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2406
    let hooks = root.join(".oxy/hooks");
2407
    fs::create_dir_all(&hooks).unwrap();
2408
    let hook = |name: &str, body: &str| {
2409
        let p = hooks.join(name);
2410
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2411
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2412
    };
2413
    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");
2414
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2415
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2416
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2417
    write(root, ".oxyignore", b".last-*\n");
2418
    write(root, "a.txt", b"a\n");
2419
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2420
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2421
    let h1 = repo.commit("first", &[]).unwrap();
2422
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
75167672 Andy McCall 2423
    assert!(
2424
        pre.contains("\"event\":\"pre-commit\"")
2425
            && pre.contains("\"path\":\"a.txt\"")
2426
            && pre.contains("\"message\":\"first\""),
2427
        "{pre}"
2428
    );
6d3eefbc Andy McCall ↶ 2429
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2430
    assert!(post.contains(&h1.to_hex()), "{post}");
2431
    repo.checkout(&[h1], false, "co").unwrap();
75167672 Andy McCall 2432
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2433
        .unwrap()
2434
        .contains("post-checkout"));
6d3eefbc Andy McCall ↶ 2435
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2436
    repo.save_config().unwrap();
2437
    let err = repo.push("origin", false).unwrap_err().to_string();
2438
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2439
2440
    // semantic-deps: only when enabled; adds an explicit dependency.
2441
    write(root, "b.txt", b"b\n");
75167672 Andy McCall 2442
    hook(
2443
        "semantic-deps",
2444
        &format!(
2445
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2446
            h1.to_hex()
2447
        ),
2448
    );
6d3eefbc Andy McCall ↶ 2449
    let h2 = repo.commit("b without hook", &[]).unwrap();
75167672 Andy McCall 2450
    assert!(
2451
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2452
        "hook disabled by default"
2453
    );
6d3eefbc Andy McCall ↶ 2454
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2455
    repo.save_config().unwrap();
2456
    write(root, "c.txt", b"c\n");
2457
    let h3 = repo.commit("c with hook", &[]).unwrap();
2458
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2459
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
75167672 Andy McCall 2460
    assert!(
2461
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2462
        "{sem}"
2463
    );
6d3eefbc Andy McCall ↶ 2464
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2465
}
23b217d7 Andy McCall ↶ 2466
2467
#[test]
2468
fn amend_into_older_change_and_split() {
2469
    hermetic();
2470
    let dir = tempfile::tempdir().unwrap();
2471
    let root = dir.path();
2472
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2473
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2474
        .unwrap();
23b217d7 Andy McCall ↶ 2475
    repo.set_user_config("core.sign", "change").unwrap();
2476
    write(root, "a.txt", b"one\ntwo\n");
2477
    let h0 = repo.commit("base", &[]).unwrap();
2478
    write(root, "a.txt", b"one\nTWO\n");
2479
    let h1 = repo.commit("edit two", &[]).unwrap();
2480
    write(root, "a.txt", b"one\nTWO\nthree\n");
2481
    let h2 = repo.commit("add three", &[]).unwrap();
2482
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2483
2484
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2485
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2486
    let h1b = repo.amend_into(&h1, None).unwrap();
2487
    assert_ne!(h1b, h1);
2488
    let c1b = repo.store().get_change(&h1b).unwrap();
2489
    assert_eq!(c1b.change_id, id1);
2490
    assert_eq!(c1b.deps, vec![h0]);
75167672 Andy McCall 2491
    assert!(matches!(
2492
        repo.verify_change(&h1b).unwrap(),
2493
        SignatureStatus::Valid { .. }
2494
    ));
23b217d7 Andy McCall ↶ 2495
    let heads = repo.bookmark_heads().unwrap();
2496
    assert_eq!(heads.len(), 1);
2497
    let top = repo.store().get_change(&heads[0]).unwrap();
2498
    assert_eq!(top.message, "add three");
75167672 Andy McCall 2499
    assert_eq!(
2500
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2501
        [h0, h1b].into_iter().collect(),
2502
        "depends on the file's creator and the rewritten line"
2503
    );
23b217d7 Andy McCall ↶ 2504
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 2505
    assert!(
2506
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2507
    );
2508
    assert!(
2509
        !repo.snapshot("status").unwrap().changed,
2510
        "the working copy is clean after folding"
2511
    );
23b217d7 Andy McCall ↶ 2512
    // Only h1b's own state shows the fix without "three".
2513
    let only = repo.load_state(&[h1b]).unwrap().materialize();
75167672 Andy McCall 2514
    assert!(
2515
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2516
    );
23b217d7 Andy McCall ↶ 2517
    assert_eq!(repo.log().unwrap().len(), 4);
2518
2519
    // An edit to a line introduced by h2 cannot fold into h1.
2520
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2521
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2522
    assert!(err.contains("introduced after"), "{err}");
75167672 Andy McCall 2523
    assert!(
2524
        repo.snapshot("status").unwrap().statuses.len() == 1,
2525
        "nothing was changed by the refusal"
2526
    );
23b217d7 Andy McCall ↶ 2527
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2528
2529
    // Split the head that touches two files.
2530
    write(root, "b.txt", b"b\n");
2531
    write(root, "c.txt", b"c\n");
2532
    let h3 = repo.commit("b and c", &[]).unwrap();
2533
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2534
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2535
    let c_1 = repo.store().get_change(&p1).unwrap();
2536
    let c_2 = repo.store().get_change(&p2).unwrap();
2537
    assert!(c_1.message.contains("part 1: b.txt"));
2538
    assert_eq!(c_2.change_id, id3);
2539
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
75167672 Andy McCall 2540
    assert!(
2541
        heads.contains(&p1) && heads.contains(&p2),
2542
        "independent parts are both heads"
2543
    );
2544
    let snap = repo
2545
        .load_state(&repo.bookmark_heads().unwrap())
2546
        .unwrap()
2547
        .materialize();
23b217d7 Andy McCall ↶ 2548
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2549
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2550
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2551
    assert!(!repo.snapshot("status").unwrap().changed);
2552
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2553
    let _ = h2;
2554
}
28fc23d7 Andy McCall ↶ 2555
2556
#[test]
2557
fn identity_lifecycle() {
2558
    hermetic();
2559
    let dir = tempfile::tempdir().unwrap();
2560
    let root = dir.path();
2561
    let origin = Repo::init(&root.join("origin")).unwrap();
2562
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2563
    let mut a = Repo::clone(&url, &root.join("a"))
2564
        .unwrap()
2565
        .with_home(root.join("home-a"));
28fc23d7 Andy McCall ↶ 2566
    a.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 2567
    let (key_a, _) = a
2568
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2569
        .unwrap();
28fc23d7 Andy McCall ↶ 2570
    write(&root.join("a"), "a.txt", b"a\n");
2571
    let h1 = a.commit("one", &[]).unwrap();
2572
    assert!(a.policy_init().unwrap().applied);
2573
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2574
2575
    // Expiry: an identity that had expired when the change was made does not authenticate it.
75167672 Andy McCall 2576
    let mut e = Repo::init(&root.join("e"))
2577
        .unwrap()
2578
        .with_home(root.join("home-e"));
28fc23d7 Andy McCall ↶ 2579
    e.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 2580
    e.create_identity_with(
2581
        "Eve",
2582
        "[email protected]",
2583
        IdentityScope::User,
2584
        Some(Hlc::now().wall_ms - 1),
2585
    )
2586
    .unwrap();
28fc23d7 Andy McCall ↶ 2587
    write(&root.join("e"), "e.txt", b"e\n");
2588
    let he = e.commit("late", &[]).unwrap();
75167672 Andy McCall 2589
    assert!(
2590
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2591
    );
28fc23d7 Andy McCall ↶ 2592
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
75167672 Andy McCall 2593
    let r = e
2594
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2595
        .unwrap();
28fc23d7 Andy McCall ↶ 2596
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2597
    write(&root.join("e"), "e.txt", b"e2\n");
2598
    let he2 = e.commit("in time", &[]).unwrap();
75167672 Andy McCall 2599
    assert!(
2600
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2601
    );
28fc23d7 Andy McCall ↶ 2602
2603
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2604
    let r = a.rotate_identity().unwrap();
2605
    assert_eq!(r.old, key_a);
2606
    assert_eq!(a.config.author_key, Some(r.new));
2607
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2608
    assert!(r.policy.as_ref().unwrap().applied);
2609
    let (_, sp) = a.current_policy().unwrap().unwrap();
75167672 Andy McCall 2610
    assert_eq!(
2611
        (sp.policy.serial, sp.policy.roots.clone()),
2612
        (2, vec![r.new])
2613
    );
2614
    assert!(
2615
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2616
        "superseded, not revoked"
2617
    );
28fc23d7 Andy McCall ↶ 2618
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
75167672 Andy McCall 2619
    assert!(
2620
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2621
    );
28fc23d7 Andy McCall ↶ 2622
    write(&root.join("a"), "a.txt", b"a2\n");
2623
    let h2 = a.commit("two", &[]).unwrap();
75167672 Andy McCall 2624
    assert!(
2625
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2626
    );
28fc23d7 Andy McCall ↶ 2627
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2628
    let res = a.push("origin", false).unwrap();
2629
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2630
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2631
    let key_a = r.new;
2632
2633
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2634
    // identity object, so Ada's KeyId changes while her keys stay the same.
75167672 Andy McCall 2635
    let mut b = Repo::clone(&url, &root.join("b"))
2636
        .unwrap()
2637
        .with_home(root.join("home-b"));
2638
    let (key_b, id_b) = b
2639
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2640
        .unwrap();
7ba155f2 Andy McCall ↶ 2641
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
28fc23d7 Andy McCall ↶ 2642
    assert_eq!(r.old, key_a);
2643
    let key_a2 = r.new;
75167672 Andy McCall 2644
    assert_eq!(
7ba155f2 Andy McCall ↶ 2645
        a.identity(&key_a2).unwrap().delegates,
2646
        vec![Delegate::full(key_b)]
2647
    );
2648
    assert_eq!(
75167672 Andy McCall 2649
        a.identity(&key_a2).unwrap().ed25519_pk,
2650
        a.identity(&key_a).unwrap().ed25519_pk
7ba155f2 Andy McCall ↶ 2651
    );
2652
    assert!(
2653
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2654
        "already a delegate"
75167672 Andy McCall 2655
    );
28fc23d7 Andy McCall ↶ 2656
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2657
    write(&root.join("a"), "a.txt", b"a3\n");
2658
    let h3 = a.commit("three", &[]).unwrap();
75167672 Andy McCall 2659
    assert!(
2660
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2661
        "the same secret signs under the new KeyId"
2662
    );
28fc23d7 Andy McCall ↶ 2663
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2664
    a.set_user_config("core.sign", "seal").unwrap();
2665
    write(&root.join("a"), "a.txt", b"a4\n");
2666
    let h4 = a.commit("four", &[]).unwrap();
2667
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2668
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 2669
    a.store()
2670
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2671
        .unwrap();
2672
    assert!(
2673
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2674
    );
28fc23d7 Andy McCall ↶ 2675
    a.set_user_config("core.sign", "change").unwrap();
2676
    // Withdrawing the delegation re-issues the identity again.
2677
    let r = a.delegate_remove(&key_b).unwrap();
2678
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2679
    assert!(a.delegate_remove(&key_b).is_err());
2680
    let key_a3 = r.new;
2681
    let res = a.push("origin", false).unwrap();
2682
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2683
2684
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2685
    // both applied under the old threshold of 1. A grant then needs Bob too.
2686
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2687
    assert!(a.policy_root_add(id_b.clone()).is_err());
2688
    assert!(a.policy_set_threshold(3).is_err());
2689
    assert!(a.policy_set_threshold(2).unwrap().applied);
2690
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2691
    b.pull("origin").unwrap();
75167672 Andy McCall 2692
    assert_eq!(
2693
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2694
        2
2695
    );
2696
    let mut c = Repo::init(&root.join("c"))
2697
        .unwrap()
2698
        .with_home(root.join("home-c"));
2699
    let (key_c, id_c) = c
2700
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2701
        .unwrap();
28fc23d7 Andy McCall ↶ 2702
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2703
    let proposal = a.policy_grant(id_c, None).unwrap();
2704
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2705
    assert_eq!(proposal.policy.serial, serial_before + 1);
75167672 Andy McCall 2706
    assert_eq!(
2707
        a.current_policy().unwrap().unwrap().1.policy.serial,
2708
        serial_before,
2709
        "a proposal changes nothing yet"
2710
    );
28fc23d7 Andy McCall ↶ 2711
    // Bob signs the proposal, handed over as a file, and it applies for him.
2712
    let bytes = proposal.signed().encode();
75167672 Andy McCall 2713
    let signed = b
2714
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2715
        .unwrap();
28fc23d7 Andy McCall ↶ 2716
    assert!(signed.applied && signed.sigs.len() == 2);
75167672 Andy McCall 2717
    assert!(b
2718
        .current_policy()
2719
        .unwrap()
2720
        .unwrap()
2721
        .1
2722
        .policy
2723
        .authorizes(&key_c, "main"));
2724
    assert!(
2725
        b.policy_sign(signed.signed()).is_err(),
2726
        "a stale proposal is refused"
2727
    );
28fc23d7 Andy McCall ↶ 2728
    // Bob publishes it and Ada picks it up.
75167672 Andy McCall 2729
    assert!(b
2730
        .push("origin", false)
2731
        .unwrap()
2732
        .iter()
2733
        .any(|x| x.name == "policy" && x.ok));
28fc23d7 Andy McCall ↶ 2734
    a.pull("origin").unwrap();
75167672 Andy McCall 2735
    assert_eq!(
2736
        a.current_policy().unwrap().unwrap().1.policy.serial,
2737
        serial_before + 1
2738
    );
28fc23d7 Andy McCall ↶ 2739
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2740
    assert!(a.policy_revoke(&key_a3).is_err());
75167672 Andy McCall 2741
    let u = a
2742
        .revoke_identity(&key_c, "left the project")
2743
        .unwrap()
2744
        .unwrap();
28fc23d7 Andy McCall ↶ 2745
    assert!(!u.applied);
2746
    assert!(a.is_revoked(&key_c).unwrap());
2747
    assert!(!b.is_revoked(&key_c).unwrap());
2748
    let u = b.policy_sign(u.signed()).unwrap();
2749
    assert!(u.applied && u.policy.is_revoked(&key_c));
2750
    assert!(b.is_revoked(&key_c).unwrap());
2751
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
75167672 Andy McCall 2752
    assert!(
2753
        b.policy_revoke(&key_a3).is_err(),
2754
        "would leave one root for a threshold of 2"
2755
    );
28fc23d7 Andy McCall ↶ 2756
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2757
    let key_c_own = c.config.author_key.unwrap();
75167672 Andy McCall 2758
    assert!(c
2759
        .revoke_identity(&key_c_own, "lost laptop")
2760
        .unwrap()
2761
        .is_none());
28fc23d7 Andy McCall ↶ 2762
    assert!(c.is_revoked(&key_c_own).unwrap());
2763
    assert_eq!(key_c_own, key_c);
2764
}
2765
6e723b81 Andy McCall ↶ 2766
#[test]
2767
fn renames_are_detected_and_tracked_as_moves() {
2768
    hermetic();
2769
    let dir = tempfile::tempdir().unwrap();
2770
    let root = dir.path();
2771
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2772
    write(
2773
        root,
2774
        "src/old.rs",
2775
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2776
    );
6e723b81 Andy McCall ↶ 2777
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2778
    write(root, "tiny.txt", b"x\n");
2779
    let h1 = repo.commit("base", &[]).unwrap();
2780
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2781
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2782
2783
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2784
    // that shares nothing with the removed file.
2785
    fs::remove_file(root.join("src/old.rs")).unwrap();
75167672 Andy McCall 2786
    write(
2787
        root,
2788
        "lib/new.rs",
2789
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2790
    );
6e723b81 Andy McCall ↶ 2791
    fs::remove_file(root.join("img.bin")).unwrap();
2792
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2793
    fs::remove_file(root.join("tiny.txt")).unwrap();
2794
    write(root, "other.txt", b"completely different\n");
2795
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 2796
    let statuses: Vec<(&str, ChangeStatus)> = snap
2797
        .statuses
2798
        .iter()
2799
        .map(|s| (s.path.as_str(), s.status))
2800
        .collect();
6e723b81 Andy McCall ↶ 2801
    assert_eq!(
2802
        statuses,
75167672 Andy McCall 2803
        vec![
2804
            ("assets/img.bin", ChangeStatus::Renamed),
2805
            ("lib/new.rs", ChangeStatus::Renamed),
2806
            ("other.txt", ChangeStatus::Added),
2807
            ("src", ChangeStatus::Removed),
2808
            ("tiny.txt", ChangeStatus::Removed)
2809
        ]
6e723b81 Andy McCall ↶ 2810
    );
2811
    let h2 = repo.commit("move things", &[]).unwrap();
2812
    let c = repo.store().get_change(&h2).unwrap();
75167672 Andy McCall 2813
    let moves: Vec<_> = c
2814
        .tree_ops
2815
        .iter()
2816
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2817
        .collect();
6e723b81 Andy McCall ↶ 2818
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
75167672 Andy McCall 2819
    assert!(c.tree_ops.iter().any(
2820
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2821
    ));
2822
    assert!(c.tree_ops.iter().any(
2823
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2824
    ));
6e723b81 Andy McCall ↶ 2825
    let snap = repo.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 2826
    assert_eq!(
2827
        snap.files["lib/new.rs"].node, node_old,
2828
        "the node survives the rename"
2829
    );
2830
    assert!(
2831
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2832
    );
6e723b81 Andy McCall ↶ 2833
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
75167672 Andy McCall 2834
    assert!(render_change(
2835
        &c,
2836
        &repo.load_state(&[h1]).unwrap(),
2837
        &repo.load_state(&[h1]).unwrap().materialize()
2838
    )
0912a033 Andy McCall ↶ 2839
    .contains("R src/old.rs -> lib/new.rs"));
6e723b81 Andy McCall ↶ 2840
    // A fresh checkout reproduces the tree.
2841
    let other = tempfile::tempdir().unwrap();
2842
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
75167672 Andy McCall 2843
    assert_eq!(
2844
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2845
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2846
    );
6e723b81 Andy McCall ↶ 2847
    assert!(!other.path().join("src").exists());
2848
    assert!(!clone.snapshot("status").unwrap().changed);
2849
    // Similarity is line based, byte weighted.
2850
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2851
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2852
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2853
    assert_eq!(similarity(b"", b"x\n"), 0);
2854
}
2855
30ea9c1e Andy McCall ↶ 2856
#[test]
2857
fn git_fetch_and_push_round_trip() {
2858
    hermetic();
75167672 Andy McCall 2859
    if std::process::Command::new("git")
2860
        .arg("--version")
2861
        .output()
2862
        .is_err()
2863
    {
30ea9c1e Andy McCall ↶ 2864
        eprintln!("git not installed; skipping");
2865
        return;
2866
    }
2867
    let dir = tempfile::tempdir().unwrap();
2868
    let root = dir.path();
2869
    let git_in = |d: &Path, args: &[&str]| -> String {
2870
        let out = std::process::Command::new("git")
2871
            .arg("-C")
2872
            .arg(d)
75167672 Andy McCall 2873
            .args([
2874
                "-c",
2875
                "user.name=Grace",
2876
                "-c",
2877
                "[email protected]",
2878
                "-c",
2879
                "commit.gpgsign=false",
2880
            ])
30ea9c1e Andy McCall ↶ 2881
            .args(args)
2882
            .output()
2883
            .unwrap();
75167672 Andy McCall 2884
        assert!(
2885
            out.status.success(),
2886
            "git {args:?}: {}",
2887
            String::from_utf8_lossy(&out.stderr)
2888
        );
30ea9c1e Andy McCall ↶ 2889
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2890
    };
2891
    // A bare "remote" and a work tree that pushes to it.
2892
    let remote = root.join("remote.git");
2893
    fs::create_dir_all(&remote).unwrap();
2894
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2895
    let work = root.join("work");
75167672 Andy McCall 2896
    git_in(
2897
        root,
2898
        &[
2899
            "clone",
2900
            "-q",
2901
            remote.to_str().unwrap(),
2902
            work.to_str().unwrap(),
2903
        ],
2904
    );
30ea9c1e Andy McCall ↶ 2905
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2906
    write(&work, "README.md", b"# Project\n");
2907
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2908
    git_in(&work, &["add", "."]);
2909
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2910
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2911
    git_in(&work, &["commit", "-q", "-am", "second"]);
2912
    git_in(&work, &["push", "-q", "origin", "main"]);
2913
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2914
2915
    // Fetch into a fresh oxy repository.
2916
    let o = root.join("oxy");
2917
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2918
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2919
        .unwrap();
30ea9c1e Andy McCall ↶ 2920
    let url = remote.to_string_lossy().to_string();
2921
    let r = repo.git_fetch(&url, "main").unwrap();
2922
    assert_eq!((r.commits, r.heads), (2, 1));
75167672 Andy McCall 2923
    assert_eq!(
2924
        fs::read(o.join("src/lib.rs")).unwrap(),
2925
        b"pub fn a() {}\npub fn b() {}\n"
2926
    );
30ea9c1e Andy McCall ↶ 2927
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 2928
    assert_eq!(
2929
        repo.git_fetch(&url, "main").unwrap().commits,
2930
        0,
2931
        "nothing new"
2932
    );
30ea9c1e Andy McCall ↶ 2933
2934
    // An oxy change, pushed back: one commit on top of the Git tip.
75167672 Andy McCall 2935
    write(
2936
        &o,
2937
        "src/lib.rs",
2938
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2939
    );
30ea9c1e Andy McCall ↶ 2940
    write(&o, "NOTES.md", b"from oxy\n");
2941
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2942
    let r = repo.git_push(&url, "main").unwrap();
2943
    assert_eq!(r.exported, 1, "{r:?}");
2944
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
75167672 Andy McCall 2945
    assert_eq!(
2946
        git_in(&work, &["log", "--format=%s", "main"]),
2947
        "add c and notes\nsecond\ninitial"
2948
    );
30ea9c1e Andy McCall ↶ 2949
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2950
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2951
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
75167672 Andy McCall 2952
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2953
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2954
    assert_eq!(
2955
        repo.git_push(&url, "main").unwrap().exported,
2956
        0,
2957
        "already pushed"
2958
    );
30ea9c1e Andy McCall ↶ 2959
2960
    // Git moves on; pushing without fetching is refused, fetching brings
2961
    // the commit in and the working copy follows.
2962
    write(&work, "README.md", b"# Project\n\nMore.\n");
2963
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2964
    git_in(&work, &["push", "-q", "origin", "main"]);
2965
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
75167672 Andy McCall 2966
    assert!(repo
2967
        .git_push(&url, "main")
2968
        .unwrap_err()
2969
        .to_string()
2970
        .contains("fetch"));
30ea9c1e Andy McCall ↶ 2971
    let r = repo.git_fetch(&url, "main").unwrap();
75167672 Andy McCall 2972
    assert_eq!(
2973
        (r.commits, r.heads),
2974
        (1, 2),
2975
        "the Git change and the oxy change commute"
2976
    );
2977
    assert_eq!(
2978
        fs::read(o.join("README.md")).unwrap(),
2979
        b"# Project\n\nMore.\n"
2980
    );
30ea9c1e Andy McCall ↶ 2981
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2982
    assert!(!repo.snapshot("status").unwrap().changed);
2983
    // Another oxy change pushes on top of Git's newest commit.
2984
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2985
    repo.commit("notes again", &[]).unwrap();
2986
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2987
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2988
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
75167672 Andy McCall 2989
    assert_eq!(
2990
        fs::read(work.join("NOTES.md")).unwrap(),
2991
        b"from oxy\nagain\n"
2992
    );
2993
    assert_eq!(
2994
        git_in(&work, &["log", "--format=%s", "main"])
2995
            .lines()
2996
            .count(),
2997
        5
2998
    );
30ea9c1e Andy McCall ↶ 2999
}
3000
2b872d07 Andy McCall ↶ 3001
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3002
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3003
#[test]
3004
#[ignore]
3005
fn bench_one_gibibyte_file() {
3006
    hermetic();
3007
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3008
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3009
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3010
        None => tempfile::tempdir().unwrap(),
3011
    };
3012
    let root = dir.path();
75167672 Andy McCall 3013
    let repo = Repo::init(&root.join("r"))
3014
        .unwrap()
3015
        .with_home(root.join("home"));
2b872d07 Andy McCall ↶ 3016
    let size = 1usize << 30;
3017
    let mut data = vec![0u8; size];
3018
    let mut x = 0x9e3779b97f4a7c15u64;
3019
    for chunk in data.chunks_mut(8) {
3020
        x ^= x << 13;
3021
        x ^= x >> 7;
3022
        x ^= x << 17;
3023
        let b = x.to_le_bytes();
3024
        chunk.copy_from_slice(&b[..chunk.len()]);
3025
    }
3026
    let t = std::time::Instant::now();
3027
    write(&root.join("r"), "big.bin", &data);
3028
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3029
    let t = std::time::Instant::now();
3030
    let h = repo.commit("big", &[]).unwrap();
3031
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3032
    let t = std::time::Instant::now();
3033
    assert!(!repo.snapshot("status").unwrap().changed);
3034
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3035
    let t = std::time::Instant::now();
3036
    let objects = repo.store().list().unwrap().len();
3037
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3038
    let t = std::time::Instant::now();
3039
    let g = repo.gc(true).unwrap();
3040
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3041
    let t = std::time::Instant::now();
3042
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3043
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3044
    let t = std::time::Instant::now();
3045
    let back = fs::read(root.join("c/big.bin")).unwrap();
3046
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3047
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3048
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3049
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
75167672 Andy McCall 3050
    eprintln!(
3051
        "store size: {:.1} MiB for 1 GiB of data",
3052
        store_bytes as f64 / (1024.0 * 1024.0)
3053
    );
2b872d07 Andy McCall ↶ 3054
}
3055
3056
fn walkdir_size(p: &Path) -> u64 {
3057
    let mut total = 0;
3058
    if let Ok(rd) = fs::read_dir(p) {
3059
        for e in rd.flatten() {
3060
            let path = e.path();
3061
            if path.is_dir() {
3062
                total += walkdir_size(&path);
3063
            } else if let Ok(m) = fs::metadata(&path) {
3064
                total += m.len();
3065
            }
3066
        }
3067
    }
3068
    total
3069
}
3070
b7f102fc Andy McCall ↶ 3071
/// An opaque file whose size and mtime match the manifest is not read on
3072
/// the next snapshot: its blob comes from the manifest's stat cache.
3073
#[cfg(unix)]
3074
#[test]
3075
fn stat_cache_skips_reading_unchanged_opaque_files() {
3076
    use std::os::unix::fs::PermissionsExt;
3077
    hermetic();
3078
    let dir = tempfile::tempdir().unwrap();
3079
    let root = dir.path();
3080
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3081
    let mut big = vec![0u8; 300 * 1024];
3082
    for (i, b) in big.iter_mut().enumerate() {
3083
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3084
    }
3085
    big[0] = 0;
3086
    write(root, "big.bin", &big);
3087
    write(root, "a.txt", b"text\n");
3088
    let h1 = repo.commit("base", &[]).unwrap();
3089
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
75167672 Andy McCall 3090
    assert!(
3091
        m.entries["big.bin"].blob.is_some(),
3092
        "opaque files record their blob"
3093
    );
b7f102fc Andy McCall ↶ 3094
    assert!(m.entries["a.txt"].blob.is_none());
3095
    let blob = m.entries["big.bin"].blob.unwrap();
3096
    assert!(repo.store().has(&blob));
3097
3098
    // Files modified within two seconds of the manifest are racy and still
3099
    // read; age the file so the cache applies, then snapshot to record it.
3100
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
75167672 Andy McCall 3101
    fs::File::options()
3102
        .write(true)
3103
        .open(root.join("big.bin"))
3104
        .unwrap()
3105
        .set_modified(old)
3106
        .unwrap();
b7f102fc Andy McCall ↶ 3107
    assert!(!repo.snapshot("status").unwrap().changed);
3108
    // Now the file cannot be read at all; the snapshot succeeds without it.
3109
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3110
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3111
    assert!(
3112
        !snap.changed && snap.statuses.is_empty(),
3113
        "{:?}",
3114
        snap.statuses
3115
    );
b7f102fc Andy McCall ↶ 3116
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3117
    // A real change (new mtime, new content) is seen and committed correctly.
3118
    let mut big2 = big.clone();
3119
    big2[10] ^= 0xff;
3120
    write(root, "big.bin", &big2);
3121
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3122
    assert_eq!(
3123
        snap.statuses
3124
            .iter()
3125
            .map(|s| (s.path.as_str(), s.status))
3126
            .collect::<Vec<_>>(),
3127
        vec![("big.bin", ChangeStatus::Modified)]
3128
    );
b7f102fc Andy McCall ↶ 3129
    let h2 = repo.commit("edit", &[]).unwrap();
3130
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 3131
    assert_eq!(
3132
        files["big.bin"].content,
3133
        FileContent::Opaque {
3134
            blobs: vec![Repo::blob_ref(&big2)]
3135
        }
3136
    );
b7f102fc Andy McCall ↶ 3137
    // Checkout writes a manifest with blobs too, so the next status is cached.
3138
    repo.checkout(&[h1], false, "checkout").unwrap();
3139
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3140
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3141
    assert!(!repo.snapshot("status").unwrap().changed);
3142
}
3143
50a046e4 Andy McCall ↶ 3144
#[test]
3145
fn status_json_lists_conflicts_with_contributors() {
3146
    hermetic();
3147
    let dir = tempfile::tempdir().unwrap();
3148
    let root = dir.path();
3149
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3150
    write(root, "a.txt", b"one\n");
3151
    let h1 = repo.commit("base", &[]).unwrap();
3152
    write(root, "a.txt", b"one\nleft\n");
3153
    let ha = repo.commit("left", &[]).unwrap();
3154
    repo.checkout(&[h1], true, "checkout").unwrap();
3155
    write(root, "a.txt", b"one\nright\n");
3156
    let hb = repo.commit("right", &[]).unwrap();
3157
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3158
    let snap = repo.snapshot("status").unwrap();
3159
    assert!(snap.base_snapshot.is_conflicted());
3160
    let json = repo.status_json(&snap).unwrap();
3161
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3162
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3163
    assert!(json.contains("\"conflicted\":true"), "{json}");
75167672 Andy McCall 3164
    assert!(
3165
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3166
        "{json}"
3167
    );
50a046e4 Andy McCall ↶ 3168
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3169
    assert!(json.contains("\"resolved\":false"), "{json}");
3170
    assert!(json.starts_with('{') && json.ends_with('}'));
3171
    // Resolve and the report says so; a clean copy has no conflicts.
3172
    write(root, "a.txt", b"one\nleft\nright\n");
3173
    let snap = repo.snapshot("status").unwrap();
3174
    let json = repo.status_json(&snap).unwrap();
3175
    assert!(json.contains("\"resolved\":true"), "{json}");
3176
    repo.commit("resolve", &[]).unwrap();
3177
    let snap = repo.snapshot("status").unwrap();
3178
    let json = repo.status_json(&snap).unwrap();
75167672 Andy McCall 3179
    assert!(
3180
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3181
        "{json}"
3182
    );
50a046e4 Andy McCall ↶ 3183
}
3184
9ac1fbe2 Andy McCall ↶ 3185
#[test]
3186
fn ignore_rules_do_not_untrack_files() {
3187
    hermetic();
3188
    let dir = tempfile::tempdir().unwrap();
3189
    let root = dir.path();
3190
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3191
    write(root, "src.c", b"int x;\n");
3192
    write(root, "build/out.o", b"\0obj");
3193
    write(root, "sub/keep.log", b"keep\n");
3194
    write(root, "sub/junk.log", b"junk\n");
3195
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3196
    let snap = repo.snapshot("status").unwrap();
3197
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 3198
    assert_eq!(
3199
        added,
3200
        vec![".oxyignore", "src.c", "sub/keep.log"],
3201
        "anchored, glob, and negated rules"
3202
    );
9ac1fbe2 Andy McCall ↶ 3203
    let h1 = repo.commit("base", &[]).unwrap();
3204
    // Ignoring a tracked file changes nothing about it.
3205
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3206
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3207
    assert_eq!(
3208
        snap.statuses
3209
            .iter()
3210
            .map(|s| s.path.as_str())
3211
            .collect::<Vec<_>>(),
3212
        vec![".oxyignore"]
3213
    );
9ac1fbe2 Andy McCall ↶ 3214
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
75167672 Andy McCall 3215
    assert!(repo
3216
        .load_state(&[h2])
3217
        .unwrap()
3218
        .materialize()
3219
        .files
3220
        .contains_key("src.c"));
9ac1fbe2 Andy McCall ↶ 3221
    // Its edits are still seen, by status and by the prompt.
3222
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3223
    write(root, "src.c", b"int x, y;\n");
3224
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3225
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3226
    assert_eq!(
3227
        snap.statuses
3228
            .iter()
3229
            .map(|s| (s.path.as_str(), s.status))
3230
            .collect::<Vec<_>>(),
3231
        vec![("src.c", ChangeStatus::Modified)]
3232
    );
9ac1fbe2 Andy McCall ↶ 3233
    let h3 = repo.commit("edit src.c", &[]).unwrap();
75167672 Andy McCall 3234
    assert!(
3235
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3236
    );
9ac1fbe2 Andy McCall ↶ 3237
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3238
    fs::remove_file(root.join("src.c")).unwrap();
3239
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3240
    assert_eq!(
3241
        snap.statuses
3242
            .iter()
3243
            .map(|s| (s.path.as_str(), s.status))
3244
            .collect::<Vec<_>>(),
3245
        vec![("src.c", ChangeStatus::Removed)]
3246
    );
9ac1fbe2 Andy McCall ↶ 3247
    repo.checkout(&[h3], true, "checkout").unwrap();
3248
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3249
    assert!(!repo.snapshot("status").unwrap().changed);
3250
    let _ = h1;
3251
}
3252
b837d2b5 Andy McCall ↶ 3253
#[test]
3254
fn split_works_on_non_heads_by_node() {
3255
    hermetic();
3256
    let dir = tempfile::tempdir().unwrap();
3257
    let root = dir.path();
3258
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3259
    write(root, "a.txt", b"one\n");
3260
    write(root, "junk/x.lock", b"lock\n");
3261
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3262
    write(root, "a.txt", b"one\ntwo\n");
3263
    let h2 = repo.commit("more work", &[]).unwrap();
3264
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3265
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3266
    // h1 is not a head: split it by node.
3267
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3268
    assert_ne!(h1b, h1);
75167672 Andy McCall 3269
    assert_eq!(
3270
        repo.store().get_change(&h1b).unwrap().change_id,
3271
        id1,
3272
        "the rest keeps the ChangeId"
3273
    );
b837d2b5 Andy McCall ↶ 3274
    let junk = repo.store().get_change(&hj).unwrap();
75167672 Andy McCall 3275
    assert!(junk.tree_ops.iter().all(
3276
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3277
    ));
b837d2b5 Andy McCall ↶ 3278
    let heads = repo.bookmark_heads().unwrap();
75167672 Andy McCall 3279
    assert!(
3280
        heads.contains(&hj),
3281
        "the split-off part is a head of its own"
3282
    );
b837d2b5 Andy McCall ↶ 3283
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 3284
    assert!(
3285
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3286
        "the dependent was rewritten onto the new hash"
3287
    );
b837d2b5 Andy McCall ↶ 3288
    assert!(snap.files.contains_key("junk/x.lock"));
75167672 Andy McCall 3289
    let h2b = heads
3290
        .iter()
3291
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3292
        .copied()
3293
        .unwrap();
b837d2b5 Andy McCall ↶ 3294
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3295
    assert!(!repo.snapshot("status").unwrap().changed);
3296
    // Abandoning the split-off head removes the junk from history.
3297
    repo.abandon(&hj).unwrap();
3298
    let heads = repo.bookmark_heads().unwrap();
3299
    let snap = repo.load_state(&heads).unwrap().materialize();
3300
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3301
    assert!(snap.files.contains_key("a.txt"));
3302
    // A dependent that touches the split-off paths blocks the split.
3303
    write(root, "junk/y.lock", b"y\n");
3304
    let hb = repo.commit("junk base", &[]).unwrap();
3305
    write(root, "junk/y.lock", b"yy\n");
3306
    write(root, "b.txt", b"b\n");
3307
    repo.commit("touches junk", &[]).unwrap();
3308
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3309
    assert!(err.contains("depends on the split-off paths"), "{err}");
3310
}
3311
7b9809e6 Andy McCall ↶ 3312
#[test]
3313
fn bookmarks_switch_merge_and_push() {
3314
    hermetic();
3315
    let dir = tempfile::tempdir().unwrap();
3316
    let root = dir.path();
3317
    let origin = Repo::init(&root.join("origin")).unwrap();
3318
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3319
    let mut repo = Repo::clone(&url, &root.join("r"))
3320
        .unwrap()
3321
        .with_home(root.join("home"));
7b9809e6 Andy McCall ↶ 3322
    let r = root.join("r");
3323
    write(&r, "a.txt", b"a\n");
3324
    let h_a = repo.commit("a", &[]).unwrap();
3325
    assert!(repo.push("origin", false).unwrap()[0].ok);
3326
3327
    // A bookmark at the working copy's base, then work on it.
3328
    assert!(repo.bookmark_create("bad name..", None).is_err());
3329
    assert!(repo.bookmark_create("-x", None).is_err());
3330
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3331
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3332
    repo.bookmark_switch("feature", false).unwrap();
3333
    assert_eq!(repo.config.bookmark, "feature");
3334
    write(&r, "a.txt", b"a\nb\n");
3335
    write(&r, "b.txt", b"b\n");
3336
    let h_b = repo.commit("b on feature", &[]).unwrap();
75167672 Andy McCall 3337
    assert_eq!(
3338
        repo.bookmark_heads().unwrap(),
3339
        vec![h_b],
3340
        "b edits a.txt, so it depends on a"
3341
    );
3342
    assert_eq!(
3343
        repo.resolve_heads("main").unwrap(),
3344
        vec![h_a],
3345
        "main is untouched"
3346
    );
3347
    assert_eq!(
3348
        repo.resolve_change("feature").unwrap(),
3349
        h_b,
3350
        "a one-head bookmark names its change"
3351
    );
7b9809e6 Andy McCall ↶ 3352
    // Reopening keeps the workspace's bookmark.
3353
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3354
    assert_eq!(reopened.config.bookmark, "feature");
3355
    // Back to main: b.txt goes away; work there.
3356
    repo.bookmark_switch("main", false).unwrap();
3357
    assert!(!r.join("b.txt").exists());
3358
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3359
    write(&r, "c.txt", b"c\n");
3360
    let h_c = repo.commit("c on main", &[]).unwrap();
3361
    let list = repo.bookmarks().unwrap();
75167672 Andy McCall 3362
    assert_eq!(
3363
        list.iter()
3364
            .map(|b| (b.name.as_str(), b.current))
3365
            .collect::<Vec<_>>(),
3366
        vec![("feature", false), ("main", true)]
3367
    );
3368
    assert_eq!(
3369
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3370
        Some(1),
3371
        "c is not on origin yet"
3372
    );
7b9809e6 Andy McCall ↶ 3373
    // Merge feature into main: the union, both heads, no merge change.
3374
    let m = repo.merge("feature").unwrap();
3375
    assert!(m.changed && m.checked_out);
3376
    let mut want = vec![h_b, h_c];
3377
    want.sort();
3378
    assert_eq!(m.heads, want);
3379
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3380
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3381
    assert!(repo.merge("main").is_err());
3382
    // The other bookmark can be pushed by name and appears at origin.
3383
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3384
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3385
    assert!(repo.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 3386
    assert_eq!(
3387
        repo.bookmarks()
3388
            .unwrap()
3389
            .iter()
3390
            .find(|b| b.name == "main")
3391
            .unwrap()
3392
            .ahead,
3393
        Some(0)
3394
    );
7b9809e6 Andy McCall ↶ 3395
    // A second workspace inherits the current bookmark and can switch independently.
3396
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3397
    assert_eq!(ws.config.bookmark, "main");
3398
    let mut ws = ws;
3399
    ws.bookmark_switch("feature", false).unwrap();
75167672 Andy McCall 3400
    assert_eq!(
3401
        Repo::open(&r).unwrap().config.bookmark,
3402
        "main",
3403
        "the first workspace is unaffected"
3404
    );
3405
    assert!(
3406
        repo.bookmark_delete("feature").is_err(),
3407
        "current bookmark of another workspace"
3408
    );
7b9809e6 Andy McCall ↶ 3409
    ws.bookmark_switch("main", false).unwrap();
3410
    // Set and delete.
3411
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3412
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3413
    repo.bookmark_delete("feature").unwrap();
3414
    assert!(repo.resolve_heads("feature").is_err());
3415
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
75167672 Andy McCall 3416
    assert!(
3417
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3418
        "changes of a deleted bookmark remain"
3419
    );
7b9809e6 Andy McCall ↶ 3420
}
3421
4dee277c Andy McCall ↶ 3422
#[test]
3423
fn oxygen_subrepos_pin_follow_and_update() {
3424
    hermetic();
3425
    let dir = tempfile::tempdir().unwrap();
3426
    let root = dir.path();
3427
    // A library repository with two commits, and a bare-ish origin for it.
3428
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3429
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
75167672 Andy McCall 3430
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3431
        .unwrap()
3432
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3433
    write(&root.join("lib"), "lib.txt", b"v1\n");
3434
    let l1 = lib.commit("lib v1", &[]).unwrap();
3435
    assert!(lib.push("origin", false).unwrap()[0].ok);
3436
    let _ = lib_origin;
3437
3438
    // The application (a clone of its own origin) adds it as a subrepo.
3439
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3440
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3441
    let _ = app_origin;
3442
    let app_dir = root.join("app");
75167672 Andy McCall 3443
    let app = Repo::clone(&app_url, &app_dir)
3444
        .unwrap()
3445
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3446
    write(&app_dir, "main.txt", b"app\n");
3447
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3448
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3449
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3450
    let snap = app.snapshot("status").unwrap();
3451
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 3452
    assert_eq!(
3453
        paths,
3454
        vec![".oxymodules", "libs/lib", "main.txt"],
3455
        "the nested files are not walked"
3456
    );
4dee277c Andy McCall ↶ 3457
    let a1 = app.commit("app with lib", &[]).unwrap();
3458
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3459
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3460
    assert!(!files.contains_key("libs/lib/lib.txt"));
3461
    assert!(!app.snapshot("status").unwrap().changed);
3462
    let subs = app.subrepos().unwrap();
3463
    assert_eq!(subs.len(), 1);
3464
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3465
3466
    // Advance the nested repository: the parent sees a modified pin.
75167672 Andy McCall 3467
    let nested = Repo::open(&app_dir.join("libs/lib"))
3468
        .unwrap()
3469
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3470
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3471
    let l2 = nested.commit("lib v2", &[]).unwrap();
3472
    assert!(nested.push("origin", false).unwrap()[0].ok);
3473
    let snap = app.snapshot("status").unwrap();
75167672 Andy McCall 3474
    assert_eq!(
3475
        snap.statuses
3476
            .iter()
3477
            .map(|s| (s.path.as_str(), s.status))
3478
            .collect::<Vec<_>>(),
3479
        vec![("libs/lib", ChangeStatus::Modified)]
3480
    );
4dee277c Andy McCall ↶ 3481
    let a2 = app.commit("bump lib", &[]).unwrap();
1a3b6203 Andy McCall ↶ 3482
    // Checking out the older app state brings the nested working copy back
3483
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4dee277c Andy McCall ↶ 3484
    let r = app.checkout(&[a1], false, "checkout").unwrap();
1a3b6203 Andy McCall ↶ 3485
    assert!(
3486
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3487
        "{:?}",
3488
        r.notes
3489
    );
4dee277c Andy McCall ↶ 3490
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
1a3b6203 Andy McCall ↶ 3491
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3492
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3493
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4dee277c Andy McCall ↶ 3494
    assert!(!app.snapshot("status").unwrap().changed);
3495
    // A dirty nested repository is left alone and reported.
3496
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3497
    let r = app.checkout(&[a2], false, "checkout").unwrap();
75167672 Andy McCall 3498
    assert!(
3499
        r.notes.iter().any(|n| n.contains("uncommitted")),
3500
        "{:?}",
3501
        r.notes
3502
    );
4dee277c Andy McCall ↶ 3503
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3504
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3505
    let r = app.submodule_update(false, &[]).unwrap();
3506
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3507
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3508
    let _ = l2;
3509
3510
    // A fresh clone of the app has the pin but no nested repository until update --init.
3511
    assert!(app.push("origin", false).unwrap()[0].ok);
3512
    let clone_dir = root.join("app-clone");
75167672 Andy McCall 3513
    let clone = Repo::clone(&app_url, &clone_dir)
3514
        .unwrap()
3515
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3516
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
75167672 Andy McCall 3517
    assert_eq!(
3518
        clone.submodule_update(false, &[]).unwrap(),
3519
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3520
    );
3521
    assert_eq!(
3522
        clone.submodule_update(true, &[]).unwrap(),
3523
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3524
    );
3525
    assert_eq!(
3526
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3527
        b"v2\n"
3528
    );
4dee277c Andy McCall ↶ 3529
    assert!(!clone.snapshot("status").unwrap().changed);
3530
    // Removing the subrepo leaves the directory and drops the node.
3531
    clone.submodule_remove("libs/lib").unwrap();
3532
    let snap = clone.snapshot("status").unwrap();
75167672 Andy McCall 3533
    assert!(
3534
        snap.statuses
3535
            .iter()
3536
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3537
        "{:?}",
3538
        snap.statuses
3539
    );
4dee277c Andy McCall ↶ 3540
    let c = clone.commit("drop lib", &[]).unwrap();
75167672 Andy McCall 3541
    assert!(!clone
3542
        .load_state(&[c])
3543
        .unwrap()
3544
        .materialize()
3545
        .files
3546
        .contains_key("libs/lib"));
4dee277c Andy McCall ↶ 3547
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
75167672 Andy McCall 3548
    assert!(
3549
        !clone.snapshot("status").unwrap().changed,
3550
        "an unregistered nested repository is ignored"
3551
    );
4dee277c Andy McCall ↶ 3552
}
3553
3554
#[test]
3555
fn git_submodules_import_and_export_as_gitlinks() {
3556
    hermetic();
75167672 Andy McCall 3557
    if std::process::Command::new("git")
3558
        .arg("--version")
3559
        .output()
3560
        .is_err()
3561
    {
4dee277c Andy McCall ↶ 3562
        eprintln!("git not installed; skipping");
3563
        return;
3564
    }
3565
    let dir = tempfile::tempdir().unwrap();
3566
    let root = dir.path();
3567
    let git_in = |d: &Path, args: &[&str]| -> String {
3568
        let out = std::process::Command::new("git")
3569
            .arg("-C")
3570
            .arg(d)
75167672 Andy McCall 3571
            .args([
3572
                "-c",
3573
                "user.name=Grace",
3574
                "-c",
3575
                "[email protected]",
3576
                "-c",
3577
                "commit.gpgsign=false",
3578
                "-c",
3579
                "protocol.file.allow=always",
3580
            ])
4dee277c Andy McCall ↶ 3581
            .args(args)
3582
            .output()
3583
            .unwrap();
75167672 Andy McCall 3584
        assert!(
3585
            out.status.success(),
3586
            "git {args:?}: {}",
3587
            String::from_utf8_lossy(&out.stderr)
3588
        );
4dee277c Andy McCall ↶ 3589
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3590
    };
3591
    let sub = root.join("sub");
3592
    fs::create_dir_all(&sub).unwrap();
3593
    git_in(&sub, &["init", "-q", "-b", "main"]);
3594
    write(&sub, "s.txt", b"sub\n");
3595
    git_in(&sub, &["add", "."]);
3596
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3597
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3598
    let g = root.join("main.git");
3599
    fs::create_dir_all(&g).unwrap();
3600
    git_in(&g, &["init", "-q", "-b", "main"]);
3601
    write(&g, "README.md", b"# app\n");
3602
    git_in(&g, &["add", "."]);
3603
    git_in(&g, &["commit", "-q", "-m", "initial"]);
75167672 Andy McCall 3604
    git_in(
3605
        &g,
3606
        &[
3607
            "submodule",
3608
            "add",
3609
            "-q",
3610
            sub.to_str().unwrap(),
3611
            "vendor/sub",
3612
        ],
3613
    );
4dee277c Andy McCall ↶ 3614
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3615
3616
    let dest = root.join("oxy");
3617
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3618
    let rep = repo.import_git(&g, "main").unwrap();
3619
    assert_eq!((rep.commits, rep.submodules), (2, 1));
75167672 Andy McCall 3620
    let files = repo
3621
        .load_state(&repo.bookmark_heads().unwrap())
3622
        .unwrap()
3623
        .materialize()
3624
        .files;
4dee277c Andy McCall ↶ 3625
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
75167672 Andy McCall 3626
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3627
        panic!()
3628
    };
3629
    assert_eq!(
3630
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3631
        crate::subrepo::Pin::Git {
3632
            sha: sub_sha.clone(),
3633
            branch: "HEAD".into()
3634
        }
3635
    );
3636
    let modules =
3637
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4dee277c Andy McCall ↶ 3638
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3639
    assert!(modules.entries["vendor/sub"].git);
75167672 Andy McCall 3640
    assert!(
3641
        files.contains_key(".gitmodules"),
3642
        "the Git file is kept for round trips"
3643
    );
3644
    assert!(
3645
        !dest.join("vendor/sub/.git").exists(),
3646
        "not cloned until update --init"
3647
    );
4dee277c Andy McCall ↶ 3648
    assert!(!repo.snapshot("status").unwrap().changed);
3649
    // update --init clones it at the pinned commit; status is unchanged.
75167672 Andy McCall 3650
    assert_eq!(
3651
        repo.submodule_update(true, &[]).unwrap(),
3652
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3653
    );
3654
    assert_eq!(
3655
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3656
        sub_sha
3657
    );
4dee277c Andy McCall ↶ 3658
    assert!(!repo.snapshot("status").unwrap().changed);
3659
    // Export writes the gitlink and .gitmodules back.
3660
    let mirror = root.join("mirror.git");
3661
    let rep = repo.git_export(&mirror).unwrap();
3662
    assert_eq!(rep.skipped_subrepos, 0);
3663
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
75167672 Andy McCall 3664
    assert!(
3665
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3666
        "{ls}"
3667
    );
3668
    assert_eq!(
3669
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3670
        ".gitmodules\nREADME.md\nvendor"
3671
    );
4dee277c Andy McCall ↶ 3672
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
75167672 Andy McCall 3673
    assert_eq!(
3674
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3675
        orig_tree,
3676
        "tree round trip"
3677
    );
4dee277c Andy McCall ↶ 3678
}
3679
957fee30 Andy McCall ↶ 3680
#[test]
3681
fn partial_commits_by_path_and_by_hunk() {
3682
    hermetic();
3683
    let dir = tempfile::tempdir().unwrap();
3684
    let root = dir.path();
3685
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3686
    write(root, "a.txt", b"1\n2\n3\n");
3687
    write(root, "b.txt", b"b\n");
3688
    let h0 = repo.commit("base", &[]).unwrap();
3689
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3690
    write(root, "b.txt", b"b\nbb\n");
3691
    write(root, "c.txt", b"c\n");
3692
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
75167672 Andy McCall 3693
    let h1 = repo
3694
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3695
        .unwrap();
957fee30 Andy McCall ↶ 3696
    let c1 = repo.store().get_change(&h1).unwrap();
75167672 Andy McCall 3697
    assert!(
3698
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3699
        "{:?}",
3700
        c1.tree_ops
3701
    );
957fee30 Andy McCall ↶ 3702
    assert_eq!(c1.deps, vec![h0]);
3703
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
75167672 Andy McCall 3704
    assert!(
3705
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3706
    );
957fee30 Andy McCall ↶ 3707
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3708
    assert!(!files.contains_key("c.txt"));
3709
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3710
    assert_eq!(
3711
        snap.statuses
3712
            .iter()
3713
            .map(|s| (s.path.as_str(), s.status))
3714
            .collect::<Vec<_>>(),
3715
        vec![
3716
            ("b.txt", ChangeStatus::Modified),
3717
            ("c.txt", ChangeStatus::Added)
3718
        ]
3719
    );
3720
    assert_eq!(
3721
        fs::read(root.join("b.txt")).unwrap(),
3722
        b"b\nbb\n",
3723
        "disk untouched"
3724
    );
957fee30 Andy McCall ↶ 3725
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3726
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 3727
    let b_hunk = hunks
3728
        .iter()
3729
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3730
        .unwrap()
3731
        .index;
3732
    let h2 = repo
3733
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3734
        .unwrap();
957fee30 Andy McCall ↶ 3735
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 3736
    assert!(
3737
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3738
    );
957fee30 Andy McCall ↶ 3739
    assert!(!files.contains_key("c.txt"));
3740
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3741
    assert_eq!(
3742
        snap.statuses
3743
            .iter()
3744
            .map(|s| s.path.as_str())
3745
            .collect::<Vec<_>>(),
3746
        vec!["c.txt"]
3747
    );
957fee30 Andy McCall ↶ 3748
    // Choosing only the content hunk of a file in a new directory pulls in
3749
    // the directory and file additions it needs.
3750
    write(root, "d/e.txt", b"e\n");
3751
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 3752
    let e_insert = hunks
3753
        .iter()
3754
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3755
        .unwrap()
3756
        .index;
3757
    let h3 = repo
3758
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3759
        .unwrap();
957fee30 Andy McCall ↶ 3760
    let c3 = repo.store().get_change(&h3).unwrap();
3761
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3762
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3763
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
d8c086ca Andy McCall ↶ 3764
    // Choosing a new file's addition hunk brings its content along.
3765
    write(root, "f/g.txt", b"g\n");
3766
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 3767
    let g_add = hunks
3768
        .iter()
3769
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3770
        .unwrap()
3771
        .index;
3772
    let h4 = repo
3773
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3774
        .unwrap();
d8c086ca Andy McCall ↶ 3775
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
75167672 Andy McCall 3776
    assert!(
3777
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3778
    );
3779
    assert!(!repo
3780
        .snapshot("status")
3781
        .unwrap()
3782
        .statuses
3783
        .iter()
3784
        .any(|s| s.path == "f/g.txt"));
957fee30 Andy McCall ↶ 3785
    // Everything left commits normally; the working copy is then clean.
3786
    repo.commit("the rest", &[]).unwrap();
3787
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 3788
    let files = repo
3789
        .load_state(&repo.bookmark_heads().unwrap())
3790
        .unwrap()
3791
        .materialize()
3792
        .files;
957fee30 Andy McCall ↶ 3793
    assert!(files.contains_key("c.txt"));
3794
}
3795
3796
#[test]
3797
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3798
    hermetic();
3799
    let dir = tempfile::tempdir().unwrap();
3800
    let root = dir.path();
3801
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3802
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3803
        .unwrap();
957fee30 Andy McCall ↶ 3804
    write(root, "a.txt", b"one\n");
3805
    let h1 = repo.commit("first", &[]).unwrap();
3806
    write(root, "a.txt", b"one\ntwo\n");
3807
    let h2 = repo.commit("second", &[]).unwrap();
3808
    let b = repo.blame("a.txt").unwrap();
75167672 Andy McCall 3809
    assert_eq!(
3810
        b.iter()
3811
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3812
            .collect::<Vec<_>>(),
3813
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3814
    );
957fee30 Andy McCall ↶ 3815
    assert!(b.iter().all(|l| l.author == "Ada"));
75167672 Andy McCall 3816
    assert_eq!(
3817
        b[0].change_id,
3818
        repo.store().get_change(&h1).unwrap().change_id
3819
    );
957fee30 Andy McCall ↶ 3820
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3821
    repo.commit("rename", &[]).unwrap();
3822
    let b = repo.blame("b.txt").unwrap();
75167672 Andy McCall 3823
    assert_eq!(
3824
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3825
        vec![h1, h2],
3826
        "the node survives the rename"
3827
    );
957fee30 Andy McCall ↶ 3828
    assert!(repo.blame("a.txt").is_err());
3829
}
3830
3831
#[test]
3832
fn bisect_finds_the_first_bad_change() {
3833
    hermetic();
3834
    let dir = tempfile::tempdir().unwrap();
3835
    let root = dir.path();
3836
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3837
    let mut content = String::new();
3838
    let mut hashes = Vec::new();
3839
    for i in 1..=8 {
3840
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3841
        write(root, "f.txt", content.as_bytes());
3842
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3843
    }
3844
    // Each step appends after the previous line, so the chain is linear.
3845
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3846
    repo.bisect_start().unwrap();
75167672 Andy McCall 3847
    assert!(matches!(
3848
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3849
        BisectStep::NeedMarks { good: 1, bad: 0 }
3850
    ));
957fee30 Andy McCall ↶ 3851
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
75167672 Andy McCall 3852
    assert!(
3853
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3854
        "{step:?}"
3855
    );
957fee30 Andy McCall ↶ 3856
    // Automated: bad when the bug line is present.
75167672 Andy McCall 3857
    let step = repo
3858
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3859
        .unwrap();
957fee30 Andy McCall ↶ 3860
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
75167672 Andy McCall 3861
    assert_eq!(
3862
        repo.bisect_status().unwrap(),
3863
        Some(BisectStep::Found { culprit: hashes[4] })
3864
    );
957fee30 Andy McCall ↶ 3865
    repo.bisect_reset().unwrap();
3866
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3867
    assert!(repo.bisect_status().unwrap().is_none());
3868
    assert!(!repo.snapshot("status").unwrap().changed);
3869
    // Manual marks and a skip.
3870
    repo.bisect_start().unwrap();
3871
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3872
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3873
    let mut skipped_once = false;
3874
    let mut guard = 0;
3875
    while let BisectStep::Testing { .. } = step {
3876
        guard += 1;
3877
        assert!(guard < 20);
3878
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3879
        if !skipped_once && text.contains("line 6") {
3880
            // An untestable state away from the boundary: the search routes around it.
3881
            skipped_once = true;
3882
            step = repo.bisect_mark(None, &[]).unwrap();
3883
            continue;
3884
        }
3885
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3886
    }
3887
    assert!(skipped_once);
3888
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3889
    repo.bisect_reset().unwrap();
3890
    // Skipping the culprit itself leaves it among the candidates reported.
3891
    repo.bisect_start().unwrap();
3892
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3893
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3894
    let mut guard = 0;
3895
    while let BisectStep::Testing { heads, .. } = &step {
3896
        guard += 1;
3897
        assert!(guard < 20);
3898
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 3899
        let is_culprit_state =
3900
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3901
        step = if is_culprit_state {
3902
            repo.bisect_mark(None, &[]).unwrap()
3903
        } else {
3904
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3905
        };
957fee30 Andy McCall ↶ 3906
    }
3907
    match step {
75167672 Andy McCall 3908
        BisectStep::Inconclusive { candidates } => assert!(
3909
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3910
            "{candidates:?}"
3911
        ),
957fee30 Andy McCall ↶ 3912
        other => panic!("{other:?}"),
3913
    }
3914
    repo.bisect_reset().unwrap();
3915
}
3916
728da0f9 Andy McCall ↶ 3917
#[test]
3918
fn squash_folds_a_change_into_its_dependency() {
3919
    hermetic();
3920
    let dir = tempfile::tempdir().unwrap();
3921
    let root = dir.path();
3922
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3923
    write(root, "a.txt", b"1\n");
3924
    let a = repo.commit("A", &[]).unwrap();
3925
    write(root, "a.txt", b"1\n2\n");
3926
    let c = repo.commit("C", &[]).unwrap();
3927
    write(root, "a.txt", b"1\n2\n3\n");
3928
    let e = repo.commit("E", &[]).unwrap();
3929
    write(root, "b.txt", b"b\n");
3930
    let b = repo.commit("B", &[]).unwrap();
3931
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3932
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3933
    // E depends on C which A lacks: refused, naming it.
3934
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3935
    assert!(err.contains(&c.short(12)), "{err}");
3936
    // C into A: A' has both, C is gone, E follows and still reads the same.
3937
    let a2 = repo.squash(&c, &a).unwrap();
3938
    let a2c = repo.store().get_change(&a2).unwrap();
3939
    assert_eq!(a2c.change_id, id_a);
3940
    assert!(a2c.deps.is_empty());
3941
    let heads = repo.bookmark_heads().unwrap();
3942
    let st = repo.load_state(&heads).unwrap();
3943
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
75167672 Andy McCall 3944
    let e2 = st
3945
        .changes()
3946
        .find(|(_, m)| m.change_id == id_e)
3947
        .map(|(h, _)| *h)
3948
        .unwrap();
3949
    assert_eq!(
3950
        repo.store().get_change(&e2).unwrap().deps,
3951
        vec![a2],
3952
        "E now depends on A' alone"
3953
    );
728da0f9 Andy McCall ↶ 3954
    let files = st.materialize().files;
75167672 Andy McCall 3955
    assert!(
3956
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3957
    );
728da0f9 Andy McCall ↶ 3958
    assert!(files.contains_key("b.txt"));
3959
    assert!(st.contains(&b));
3960
    assert!(!repo.snapshot("status").unwrap().changed);
3961
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3962
    // Undo restores the three original changes.
3963
    repo.undo().unwrap();
3964
    repo.undo().unwrap();
3965
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3966
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3967
}
3968
3969
#[test]
3970
fn rebase_re_expresses_a_change_against_another_base() {
3971
    hermetic();
3972
    let dir = tempfile::tempdir().unwrap();
3973
    let root = dir.path();
3974
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3975
    write(root, "a.txt", b"1\n2\n");
3976
    let a = repo.commit("A", &[]).unwrap();
3977
    write(root, "a.txt", b"1\n2\n3\n");
3978
    let c = repo.commit("C: append 3", &[]).unwrap();
3979
    write(root, "a.txt", b"1\n2\n3\n4\n");
3980
    let e = repo.commit("E: append 4", &[]).unwrap();
3981
    // A different base: A plus a change that prepends a line.
3982
    repo.checkout(&[a], true, "checkout").unwrap();
3983
    write(root, "a.txt", b"0\n1\n2\n");
3984
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3985
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3986
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3987
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3988
    let c2 = repo.rebase(&c, &[d]).unwrap();
3989
    let c2c = repo.store().get_change(&c2).unwrap();
3990
    assert_eq!(c2c.change_id, id_c);
3991
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3992
    let heads = repo.bookmark_heads().unwrap();
3993
    let st = repo.load_state(&heads).unwrap();
3994
    assert!(!st.contains(&c) && st.contains(&d));
75167672 Andy McCall 3995
    let e2 = st
3996
        .changes()
3997
        .find(|(_, m)| m.change_id == id_e)
3998
        .map(|(h, _)| *h)
3999
        .unwrap();
728da0f9 Andy McCall ↶ 4000
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
75167672 Andy McCall 4001
    assert!(
4002
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4003
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4004
    );
728da0f9 Andy McCall ↶ 4005
    let files = st.materialize().files;
75167672 Andy McCall 4006
    assert!(
4007
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4008
        "{:?}",
4009
        files["a.txt"].content
4010
    );
728da0f9 Andy McCall ↶ 4011
    assert!(!files["a.txt"].is_conflicted());
4012
    // Rebasing onto a state that already contains the change is refused.
4013
    assert!(repo.rebase(&c2, &[c2]).is_err());
4014
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
75167672 Andy McCall 4015
    assert!(
4016
        err.contains("lacks dependencies"),
4017
        "E needs C, which D's state does not have: {err}"
4018
    );
728da0f9 Andy McCall ↶ 4019
}
4020
c792033a Andy McCall ↶ 4021
#[test]
4022
fn unsigned_tags_keep_their_message() {
4023
    hermetic();
4024
    let dir = tempfile::tempdir().unwrap();
4025
    let root = dir.path();
4026
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4027
    write(root, "a.txt", b"a\n");
4028
    repo.commit("a", &[]).unwrap();
4029
    assert!(repo.secret_key().unwrap().is_none());
75167672 Andy McCall 4030
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4031
        .unwrap();
c792033a Andy McCall ↶ 4032
    let tags = repo.tags().unwrap();
75167672 Andy McCall 4033
    assert_eq!(
4034
        (
4035
            tags[0].name.as_str(),
4036
            tags[0].message.as_str(),
4037
            tags[0].signer.as_deref()
4038
        ),
4039
        ("v1", "first release", None)
4040
    );
4041
    assert!(
4042
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4043
        "an unsigned attestation is not advertised"
4044
    );
c792033a Andy McCall ↶ 4045
}
387335ff Andy McCall ↶ 4046
4047
#[test]
4048
fn fsck_passes_a_sound_repository_and_names_each_fault() {
64818938 Andy McCall ↶ 4049
    // Files on disk are what this tests: tampering with them, and the
4050
    // directory store's crash points.
4051
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4052
        return;
4053
    }
387335ff Andy McCall ↶ 4054
    hermetic();
4055
    let dir = tempfile::tempdir().unwrap();
4056
    let root = dir.path();
4057
    let origin_path = root.join("origin");
4058
    let origin = Repo::init(&origin_path).unwrap();
4059
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4060
        .unwrap()
4061
        .with_home(root.join("home-a"));
4062
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4063
        .unwrap();
4064
    write(&root.join("a"), "f.txt", b"one\n");
4065
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4066
    let h1 = a.commit("first", &[]).unwrap();
4067
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4068
    let h2 = a.commit("second", &[]).unwrap();
4069
    a.tag_create("v1", &[h2], "first release").unwrap();
4070
    a.checkpoint().unwrap();
4071
    assert!(a.push("origin", false).unwrap()[0].ok);
4072
4073
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4074
    for repo in [&a, &origin] {
4075
        let rep = repo.fsck().unwrap();
4076
        assert_eq!(rep.problems, vec![], "{rep:?}");
4077
        // The two commits, plus the working copy's change in `a`.
4078
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4079
        assert!(rep.ops > 1 && rep.objects > 5);
4080
    }
4081
    assert!(origin.fsck().unwrap().attestations >= 1);
4082
4083
    // A flipped byte in a stored object is corruption, named by hash.
4084
    let c1 = a.store().path_for(&h1);
4085
    let pristine = fs::read(&c1).unwrap();
4086
    let mut bytes = pristine.clone();
4087
    *bytes.last_mut().unwrap() ^= 1;
4088
    fs::write(&c1, &bytes).unwrap();
4089
    let rep = a.fsck().unwrap();
4090
    assert!(rep.errors() >= 1);
4091
    assert!(
4092
        rep.problems
4093
            .iter()
4094
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4095
        "{rep:?}"
4096
    );
4097
    fs::write(&c1, &pristine).unwrap();
4098
    assert_eq!(a.fsck().unwrap().errors(), 0);
4099
4100
    // A missing change is named with what needed it.
4101
    fs::remove_file(&c1).unwrap();
4102
    let rep = a.fsck().unwrap();
4103
    assert!(
4104
        rep.problems.iter().any(|p| p.severity == Severity::Error
4105
            && p.object == Some(h1)
4106
            && p.what.contains("change missing, needed by change")),
4107
        "{rep:?}"
4108
    );
4109
    fs::write(&c1, &pristine).unwrap();
4110
4111
    // A missing blob is an error in a full clone.
4112
    let c2 = a.store().get_change(&h1).unwrap();
4113
    let blob = c2
4114
        .edits
4115
        .iter()
4116
        .find_map(|e| match e {
4117
            Edit::Replace { new: Some(b), .. } => Some(*b),
4118
            _ => None,
4119
        })
4120
        .expect("the binary file is a blob");
4121
    let bp = a.store().path_for(&blob);
4122
    let blob_bytes = fs::read(&bp).unwrap();
4123
    fs::remove_file(&bp).unwrap();
4124
    let rep = a.fsck().unwrap();
4125
    assert!(
4126
        rep.problems
4127
            .iter()
4128
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4129
        "{rep:?}"
4130
    );
4131
    fs::write(&bp, &blob_bytes).unwrap();
4132
4133
    // A broken op log head is reported, not a crash.
4134
    let head = root.join("a/.oxy/ops/head");
4135
    let saved = fs::read(&head).unwrap();
4136
    fs::write(&head, b"not a hash").unwrap();
4137
    let rep = a.fsck().unwrap();
4138
    assert!(
4139
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4140
        "{rep:?}"
4141
    );
4142
    fs::write(&head, saved).unwrap();
4143
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4144
}
4dcb8c09 Andy McCall ↶ 4145
4146
/// Copy a directory tree (for restoring a pristine repository).
4147
fn copy_tree(from: &Path, to: &Path) {
4148
    fs::create_dir_all(to).unwrap();
4149
    for e in fs::read_dir(from).unwrap() {
4150
        let e = e.unwrap();
4151
        let target = to.join(e.file_name());
4152
        if e.file_type().unwrap().is_dir() {
4153
            copy_tree(&e.path(), &target);
4154
        } else {
4155
            fs::copy(e.path(), &target).unwrap();
4156
        }
4157
    }
4158
}
4159
4160
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4161
/// would, and check that both repositories still open, pass `fsck`, and
4162
/// accept the same operation again.
4163
#[test]
4164
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
64818938 Andy McCall ↶ 4165
    // Files on disk are what this tests: tampering with them, and the
4166
    // directory store's crash points.
4167
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4168
        return;
4169
    }
4dcb8c09 Andy McCall ↶ 4170
    use crate::durable::failpoint;
4171
    hermetic();
4172
    let dir = tempfile::tempdir().unwrap();
4173
    let pristine = dir.path().join("pristine");
4174
    let origin_path = pristine.join("origin");
4175
    Repo::init(&origin_path).unwrap();
4176
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4177
        .unwrap()
4178
        .with_home(dir.path().join("home"));
4179
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4180
        .unwrap();
4181
    write(&pristine.join("a"), "f.txt", b"one\n");
4182
    a.commit("first", &[]).unwrap();
4183
    assert!(a.push("origin", false).unwrap()[0].ok);
4184
    drop(a);
4185
4186
    type Op = fn(&Repo) -> Result<()>;
4187
    let edit_and_commit: Op = |r| {
4188
        write(r.root(), "f.txt", b"one\ntwo\n");
4189
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4190
        r.commit("second", &[]).map(|_| ())
4191
    };
4192
    let push: Op = |r| {
4193
        let res = r.push("origin", false)?;
4194
        if res.iter().all(|x| x.ok) {
4195
            Ok(())
4196
        } else {
4197
            Err(RepoError::Msg(format!("{res:?}")))
4198
        }
4199
    };
4200
4201
    for (name, prepare, op) in [
4202
        ("commit", None, edit_and_commit),
4203
        ("push", Some(edit_and_commit), push),
4204
    ] {
4205
        let mut steps = 0;
4206
        for n in 1.. {
4207
            let run = dir.path().join(format!("{name}-{n}"));
4208
            copy_tree(&pristine, &run);
4209
            // Clones record their remote by path; point it at this copy.
4210
            let open = |p: &Path| {
4211
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4212
                r.config
4213
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4214
                    .unwrap();
4215
                r.save_config().unwrap();
4216
                r
4217
            };
4218
            let a = open(&run.join("a"));
4219
            if let Some(prep) = prepare {
4220
                prep(&a).unwrap();
4221
            }
4222
            failpoint::crash_after(n);
4223
            let outcome = op(&a);
4224
            let crashed = failpoint::disarm();
4225
            drop(a);
4226
            if !crashed {
4227
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4228
                steps = n - 1;
4229
                break;
4230
            }
4231
            assert!(
4232
                outcome.is_err(),
4233
                "{name}: a crash at step {n} was swallowed"
4234
            );
4235
            for repo in ["a", "origin"] {
4236
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4237
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4238
                });
4239
                let rep = r.fsck().unwrap();
4240
                assert_eq!(
4241
                    rep.errors(),
4242
                    0,
4243
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4244
                    rep.problems
4245
                );
4246
            }
4247
            // The interrupted operation can simply be run again.
4248
            let a = open(&run.join("a"));
4249
            // A crash after the commit point leaves the commit done.
4250
            let landed = a
4251
                .bookmark_heads()
4252
                .unwrap()
4253
                .iter()
4254
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4255
            let again = match (name, landed) {
4256
                ("commit", true) => Ok(()),
4257
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4258
                _ => op(&a),
4259
            };
4260
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4261
            assert_eq!(a.fsck().unwrap().errors(), 0);
4262
            fs::remove_dir_all(&run).unwrap();
4263
        }
4264
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4265
    }
4266
}
19555025 Andy McCall ↶ 4267
4268
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4269
/// running at the same time lose nothing: every commit ends up on the
4270
/// bookmark, locally and on the remote, and the repository passes fsck.
4271
#[test]
4272
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4273
    hermetic();
4274
    let dir = tempfile::tempdir().unwrap();
4275
    let root = dir.path();
4276
    let origin = root.join("origin");
4277
    Repo::init_bare_unbound(&origin).unwrap();
4278
    let main = root.join("main");
4279
    let mut repo = Repo::init(&main).unwrap();
4280
    repo.config
4281
        .set("remote.origin.url", &origin.to_string_lossy())
4282
        .unwrap();
4283
    repo.save_config().unwrap();
4284
    write(&main, "seed.txt", b"seed\n");
4285
    repo.commit("seed", &[]).unwrap();
4286
    let second = root.join("second");
4287
    repo.workspace_add(&second, None).unwrap();
4288
    drop(repo);
4289
4290
    const EACH: usize = 15;
4291
    std::thread::scope(|s| {
4292
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4293
            s.spawn(move || {
4294
                let r = Repo::open(&dir).unwrap();
4295
                for i in 0..EACH {
4296
                    write(
4297
                        &dir,
4298
                        &format!("{tag}-{i}.txt"),
4299
                        format!("{tag} {i}\n").as_bytes(),
4300
                    );
4301
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4302
                    if push && i % 5 == 4 {
4303
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4304
                        let _ = r.push("origin", false);
4305
                    }
4306
                }
4307
            });
4308
        }
4309
    });
4310
4311
    let repo = Repo::open(&main).unwrap();
4312
    let heads = repo.bookmark_heads().unwrap();
4313
    let state = repo.load_state(&heads).unwrap();
4314
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4315
    for tag in ["a", "b"] {
4316
        for i in 0..EACH {
4317
            assert!(
4318
                messages.contains(&format!("{tag} {i}")),
4319
                "lost commit {tag} {i}; have {messages:?}"
4320
            );
4321
        }
4322
    }
4323
    let rep = repo.fsck().unwrap();
4324
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4325
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4326
    let hosted = Repo::open(&origin).unwrap();
4327
    let hosted_heads = hosted.bookmark_heads().unwrap();
4328
    assert_eq!(
4329
        hosted.load_state(&hosted_heads).unwrap().len(),
4330
        state.len(),
4331
        "the remote has every commit"
4332
    );
4333
}
4334
4335
/// Two operations recorded from the same parent (what two processes do
4336
/// when they race) are merged: both bookmarks' heads survive, and a
4337
/// change made on one side only is kept.
4338
#[test]
4339
fn operations_from_the_same_parent_are_merged() {
4340
    hermetic();
4341
    let dir = tempfile::tempdir().unwrap();
4342
    let root = dir.path();
4343
    let repo = Repo::init(root).unwrap();
4344
    write(root, "a.txt", b"a\n");
4345
    let a = repo.commit("a", &[]).unwrap();
4346
    write(root, "b.txt", b"b\n");
4347
    let b = repo.commit("b", &[]).unwrap();
4348
    let (x, op) = repo.head_op().unwrap();
4349
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4350
4351
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4352
    let mut one = op.view.clone();
4353
    one.bookmarks.insert("main".into(), state(vec![a]));
4354
    one.bookmarks.insert("topic".into(), state(vec![a]));
4355
    let mut two = op.view.clone();
4356
    two.bookmarks.insert("main".into(), state(vec![b]));
4357
    repo.record_op(&[x], "one", one).unwrap();
4358
    let merged = repo.record_op(&[x], "two", two).unwrap();
4359
4360
    let (head, op) = repo.head_op().unwrap();
4361
    assert_eq!(head, merged);
4362
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4363
    assert!(op.command.contains("merged with a concurrent operation"));
4364
    let mut main = repo
4365
        .store()
4366
        .get_state(&op.view.bookmarks["main"])
4367
        .unwrap()
4368
        .heads;
4369
    main.sort();
4370
    let mut want = vec![a, b];
4371
    want.sort();
4372
    assert_eq!(main, want, "both sides' heads are kept");
4373
    assert!(
4374
        op.view.bookmarks.contains_key("topic"),
4375
        "a one-sided change survives"
4376
    );
4377
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4378
}
3e5772cc Andy McCall ↶ 4379
4380
#[test]
4381
fn failed_requests_come_with_a_next_step() {
4382
    use crate::protocol::hint_for;
4383
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4384
        .unwrap()
4385
        .contains("token"));
4386
    assert!(hint_for("…: HTTP 403: forbidden")
4387
        .unwrap()
4388
        .contains("repo:write"));
4389
    assert!(hint_for("…: HTTP 404: no such repository")
4390
        .unwrap()
4391
        .contains("owner and repository name"));
4392
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4393
        .unwrap()
4394
        .contains("oxyhub-ca.pem"));
4395
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4396
        .unwrap()
4397
        .contains("running"));
4398
    assert!(hint_for("Dns Failed: failed to lookup address information")
4399
        .unwrap()
4400
        .contains("resolve"));
4401
    assert_eq!(hint_for("something else entirely"), None);
4402
}
4403
4404
#[test]
4405
fn doctor_names_problems_and_what_to_do() {
4406
    hermetic();
4407
    let dir = tempfile::tempdir().unwrap();
4408
    let root = dir.path();
4409
    let origin = root.join("origin");
4410
    Repo::init_bare_unbound(&origin).unwrap();
4411
    let mut repo = Repo::init(&root.join("r"))
4412
        .unwrap()
4413
        .with_home(root.join("home"));
4414
    let find = |r: &DoctorReport, area: &str, h: Health| {
4415
        r.checks
4416
            .iter()
4417
            .find(|c| c.area == area && c.health == h)
4418
            .cloned()
4419
    };
4420
4421
    let r = repo.doctor(true);
4422
    assert!(find(&r, "identity", Health::Warn)
4423
        .unwrap()
4424
        .hint
4425
        .unwrap()
4426
        .contains("oxy identity create"));
4427
    assert!(find(&r, "repository", Health::Ok).is_some());
4428
4429
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4430
        .unwrap();
4431
    repo.config.set("author.name", "Ada").unwrap();
4432
    repo.config.set("author.email", "[email protected]").unwrap();
4433
    repo.config
4434
        .set("remote.origin.url", &origin.to_string_lossy())
4435
        .unwrap();
4436
    repo.config
4437
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4438
        .unwrap();
4439
    repo.config.set("remote.down.token", "t").unwrap();
4440
    repo.config
4441
        .set("remote.badca.url", "https://example.invalid/a/b")
4442
        .unwrap();
4443
    repo.config
4444
        .set(
4445
            "remote.badca.ca",
4446
            &root.join("missing.pem").to_string_lossy(),
4447
        )
4448
        .unwrap();
4449
    repo.save_config().unwrap();
4450
4451
    let r = repo.doctor(true);
4452
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4453
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4454
    assert!(find(&r, "remote origin", Health::Ok)
4455
        .unwrap()
4456
        .message
4457
        .contains("first push binds it"));
4458
    let down = find(&r, "remote down", Health::Fail).unwrap();
4459
    assert!(
4460
        down.hint.as_deref().unwrap_or("").contains("running"),
4461
        "{down:?}"
4462
    );
4463
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4464
    assert!(
4465
        badca.hint.unwrap().contains("remote.badca.ca"),
4466
        "the remote's own name is in the hint"
4467
    );
4468
    assert_eq!(r.worst(), Health::Fail);
4469
4470
    // Offline, nothing is contacted.
4471
    let r = repo.doctor(false);
4472
    assert!(find(&r, "remote down", Health::Fail).is_none());
4473
    assert!(find(&r, "remote down", Health::Ok)
4474
        .unwrap()
4475
        .message
4476
        .contains("not contacted"));
4477
}
62794ecc Andy McCall ↶ 4478
4479
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4480
/// after it. Inserting after `b` and then deleting `b`, one commit after
4481
/// the other, must not leave a delete/insert conflict.
4482
#[test]
4483
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4484
    hermetic();
4485
    let dir = tempfile::tempdir().unwrap();
4486
    let root = dir.path();
4487
    let repo = Repo::init(root).unwrap();
4488
    write(root, "f", b"a\nb\nc\n");
4489
    repo.commit("base", &[]).unwrap();
4490
    write(root, "f", b"a\nb\nx\nc\n");
4491
    let insert = repo.commit("insert x after b", &[]).unwrap();
4492
    write(root, "f", b"a\nx\nc\n");
4493
    let delete = repo.commit("delete b", &[]).unwrap();
4494
    assert!(
4495
        repo.store()
4496
            .get_change(&delete)
4497
            .unwrap()
4498
            .deps
4499
            .contains(&insert),
4500
        "the deletion depends on the insertion below the deleted line"
4501
    );
4502
    let heads = repo.bookmark_heads().unwrap();
4503
    assert_eq!(heads, vec![delete]);
4504
    let snap = repo.load_state(&heads).unwrap().materialize();
4505
    assert!(!snap.is_conflicted());
4506
    assert!(
4507
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4508
    );
4509
}
4510
4511
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4512
/// replacement depends on the change that set the blob it replaces.
4513
#[test]
4514
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4515
    hermetic();
4516
    let dir = tempfile::tempdir().unwrap();
4517
    let root = dir.path();
4518
    let repo = Repo::init(root).unwrap();
4519
    write(root, "bin", b"\0A");
4520
    let v1 = repo.commit("v1", &[]).unwrap();
4521
    write(root, "bin", b"\0B");
4522
    let v2 = repo.commit("v2", &[]).unwrap();
4523
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4524
    write(root, "bin", b"\0A");
4525
    let v3 = repo.commit("back to A", &[]).unwrap();
4526
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4527
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4528
    let state = repo.load_state(&[v3]).unwrap();
4529
    let snap = state.materialize();
4530
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4531
        panic!("opaque")
4532
    };
4533
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4534
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4535
}
4536
4537
/// Spec §23: a binary file changed on two branches and merged in Git to
4538
/// one side's version comes back as that version at the merge, and the
4539
/// import verifies commit by commit.
4540
#[test]
4541
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4542
    hermetic();
4543
    if std::process::Command::new("git")
4544
        .arg("--version")
4545
        .output()
4546
        .is_err()
4547
    {
4548
        eprintln!("git not installed; skipping");
4549
        return;
4550
    }
4551
    let dir = tempfile::tempdir().unwrap();
4552
    let root = dir.path();
4553
    let g = root.join("src.git");
4554
    fs::create_dir_all(&g).unwrap();
4555
    let git = |args: &[&str]| -> String {
4556
        let out = std::process::Command::new("git")
4557
            .arg("-C")
4558
            .arg(&g)
4559
            .args([
4560
                "-c",
4561
                "user.name=Grace",
4562
                "-c",
4563
                "[email protected]",
4564
                "-c",
4565
                "commit.gpgsign=false",
4566
            ])
4567
            .args(args)
4568
            .output()
4569
            .unwrap();
4570
        assert!(
4571
            out.status.success(),
4572
            "git {args:?}: {}",
4573
            String::from_utf8_lossy(&out.stderr)
4574
        );
4575
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4576
    };
4577
    git(&["init", "-q", "-b", "main"]);
4578
    write(&g, "logo.bin", b"\0base");
4579
    write(&g, "notes.txt", b"a\nb\nc\n");
4580
    git(&["add", "."]);
4581
    git(&["commit", "-qm", "base"]);
4582
    git(&["checkout", "-qb", "side"]);
4583
    write(&g, "logo.bin", b"\0side");
4584
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4585
    git(&["commit", "-qam", "side"]);
4586
    git(&["checkout", "-q", "main"]);
4587
    write(&g, "logo.bin", b"\0main");
4588
    git(&["commit", "-qam", "main"]);
4589
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4590
    let _ = std::process::Command::new("git")
4591
        .arg("-C")
4592
        .arg(&g)
4593
        .args([
4594
            "-c",
4595
            "user.name=G",
4596
            "-c",
4597
            "user.email=g@e",
4598
            "merge",
4599
            "-q",
4600
            "side",
4601
        ])
4602
        .output();
4603
    write(&g, "logo.bin", b"\0main");
4604
    git(&["add", "."]);
4605
    git(&["commit", "-qm", "merge side"]);
4606
    // Then a revert of the binary to its first version.
4607
    write(&g, "logo.bin", b"\0base");
4608
    git(&["commit", "-qam", "back to base"]);
4609
4610
    let repo = Repo::init(&root.join("o")).unwrap();
4611
    let rep = repo.import_git(&g, "main").unwrap();
4612
    assert_eq!(rep.merges, 1);
4613
    let v = repo.verify_git_import(&g, "main").unwrap();
4614
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4615
    assert_eq!(v.commits, 5);
4616
    let snap = repo
4617
        .load_state(&repo.bookmark_heads().unwrap())
4618
        .unwrap()
4619
        .materialize();
4620
    assert!(!snap.is_conflicted());
4621
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4622
        panic!("opaque")
4623
    };
4624
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4625
}
c863c7a7 Andy McCall ↶ 4626
4627
/// Spec §7.7 on a file system without executable bits or symlinks: the
4628
/// recorded bit is kept, and a symlink checked out as a plain file holding
4629
/// its target is still that symlink.
4630
#[cfg(unix)]
4631
#[test]
4632
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4633
    use crate::portable::Platform;
4634
    use std::os::unix::fs::PermissionsExt;
4635
    hermetic();
4636
    let dir = tempfile::tempdir().unwrap();
4637
    let root = dir.path();
4638
    let repo = Repo::init(root).unwrap();
4639
    write(root, "run.sh", b"#!/bin/sh\n");
4640
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4641
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4642
    repo.commit("script and link", &[]).unwrap();
4643
    drop(repo);
4644
4645
    // What checking out on Windows leaves: no exec bit, the link as a file.
4646
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4647
    fs::remove_file(root.join("link")).unwrap();
4648
    write(root, "link", b"run.sh");
4649
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4650
    let s = win.snapshot("oxy status").unwrap();
4651
    assert!(
4652
        s.statuses.is_empty(),
4653
        "nothing changed on Windows: {:?}",
4654
        statuses(&s)
4655
    );
4656
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4657
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4658
    write(root, "link", b"other");
4659
    let h = win.commit("edit on Windows", &[]).unwrap();
4660
    let snap = win.load_state(&[h]).unwrap().materialize();
4661
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4662
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4663
    // The same working copy read as Linux sees the lost bit and the plain file.
4664
    let linux = Repo::open(root).unwrap();
4665
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4666
}
4667
4668
/// Paths that collide on case-insensitive or Windows file systems are
4669
/// named at checkout there, and by doctor everywhere.
4670
#[test]
4671
fn paths_other_platforms_cannot_hold_are_reported() {
4672
    use crate::portable::Platform;
4673
    hermetic();
4674
    let dir = tempfile::tempdir().unwrap();
4675
    let root = dir.path();
4676
    let repo = Repo::init(root).unwrap();
4677
    write(root, "README.md", b"a\n");
4678
    write(root, "readme.md", b"b\n");
4679
    write(root, "src/aux.c", b"int x;\n");
4680
    let h = repo.commit("unportable", &[]).unwrap();
4681
    let r = repo.doctor(false);
4682
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4683
    assert_eq!(port.health, Health::Warn);
4684
    assert!(
4685
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4686
        "{}",
4687
        port.message
4688
    );
4689
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4690
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4691
    assert!(
4692
        rep.notes
4693
            .iter()
4694
            .any(|n| n.contains("README.md and readme.md")),
4695
        "{:?}",
4696
        rep.notes
4697
    );
4698
    assert!(
4699
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4700
        "macOS allows aux.c"
4701
    );
4702
}
bc489b6c Andy McCall ↶ 4703
4704
#[test]
4705
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4706
    hermetic();
4707
    let dir = tempfile::tempdir().unwrap();
4708
    let repo = Repo::init(dir.path()).unwrap();
4709
    write(dir.path(), "a.txt", b"one\n");
4710
    write(dir.path(), "other.txt", b"x\n");
4711
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4712
    repo.snapshot("t").unwrap();
4713
    let c1 = repo.commit("first", &[]).unwrap();
4714
    write(dir.path(), "other.txt", b"y\n");
4715
    repo.snapshot("t").unwrap();
4716
    repo.commit("other only", &[]).unwrap();
4717
    write(dir.path(), "a.txt", b"one\ntwo\n");
4718
    repo.snapshot("t").unwrap();
4719
    let c3 = repo.commit("second line", &[]).unwrap();
4720
    write(dir.path(), "other.txt", b"z\n");
4721
    repo.snapshot("t").unwrap();
4722
    repo.commit("other again", &[]).unwrap();
4723
4724
    let heads = repo.bookmark_heads().unwrap();
4725
    let state = repo.load_state(&heads).unwrap();
4726
    let full: Vec<ChangeHash> = repo
4727
        .log_for_path_in("a.txt", &heads)
4728
        .unwrap()
4729
        .iter()
4730
        .map(|e| e.hash)
4731
        .collect();
4732
    assert_eq!(
4733
        full,
4734
        vec![c3, c1],
4735
        "newest first, only changes touching the path"
4736
    );
4737
    let newest: Vec<ChangeHash> = repo
4738
        .log_for_path_of(&state, "a.txt", Some(1))
4739
        .unwrap()
4740
        .iter()
4741
        .map(|e| e.hash)
4742
        .collect();
4743
    assert_eq!(newest, vec![c3], "stops at the first");
4744
    assert_eq!(
4745
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4746
        2
4747
    );
4748
    assert!(repo
4749
        .log_for_path_of(&state, "missing.txt", Some(1))
4750
        .is_err());
4751
    assert_eq!(
4752
        repo.log_state(&heads).unwrap().len(),
4753
        repo.log_of(&state).len()
4754
    );
4755
4756
    let tree = state.tree().view();
4757
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4758
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4759
    assert_eq!(
4760
        via_state
4761
            .iter()
4762
            .map(|l| (l.hash, l.text.clone()))
4763
            .collect::<Vec<_>>(),
4764
        via_heads
4765
            .iter()
4766
            .map(|l| (l.hash, l.text.clone()))
4767
            .collect::<Vec<_>>()
4768
    );
4769
    assert_eq!(
4770
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4771
        vec![c1, c3]
4772
    );
4773
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4774
}
696bbf29 Andy McCall ↶ 4775
4776
/// A text file whose stat matches the manifest and whose recorded hash is
4777
/// the base's content is taken from the base without reading it; anything
4778
/// else is read, so no edit is missed (spec §12.3).
4779
#[cfg(unix)]
4780
#[test]
4781
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4782
    use std::os::unix::fs::PermissionsExt;
4783
    hermetic();
4784
    let dir = tempfile::tempdir().unwrap();
4785
    let root = dir.path();
4786
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4787
    write(root, "a.txt", b"one\ntwo\n");
4788
    write(root, "b.txt", b"bee\n");
4789
    repo.commit("base", &[]).unwrap();
4790
    let age = |p: &str| {
4791
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4792
        fs::File::options()
4793
            .write(true)
4794
            .open(root.join(p))
4795
            .unwrap()
4796
            .set_modified(old)
4797
            .unwrap();
4798
    };
4799
    age("a.txt");
4800
    age("b.txt");
4801
    assert!(
4802
        !repo.snapshot("status").unwrap().changed,
4803
        "records the aged stat"
4804
    );
4805
4806
    // Clean and equal to the base: not read at all.
4807
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4808
    let snap = repo.snapshot("status").unwrap();
4809
    assert!(
4810
        !snap.changed && snap.statuses.is_empty(),
4811
        "{:?}",
4812
        snap.statuses
4813
    );
4814
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4815
4816
    // An uncommitted edit that is older than the manifest: stat-clean, but
4817
    // its hash is not the base's, so it is read and stays visible.
4818
    write(root, "b.txt", b"bee edited\n");
4819
    age("b.txt");
4820
    let first = repo.snapshot("status").unwrap();
4821
    assert_eq!(
4822
        statuses(&first),
4823
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4824
    );
4825
    let again = repo.snapshot("status").unwrap();
4826
    assert_eq!(
4827
        statuses(&again),
4828
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4829
        "still seen once stat-clean"
4830
    );
4831
    assert!(!again.changed, "and the working copy hashes the same");
4832
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4833
    assert!(
4834
        repo.snapshot("status").is_err(),
4835
        "an edited file must be read, never taken from the base"
4836
    );
4837
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4838
4839
    // A same-size edit made just now is racy and read.
4840
    write(root, "a.txt", b"one\nTWO\n");
4841
    assert_eq!(
4842
        statuses(&repo.snapshot("status").unwrap()),
4843
        vec![
4844
            ("a.txt".to_string(), ChangeStatus::Modified),
4845
            ("b.txt".to_string(), ChangeStatus::Modified)
4846
        ]
4847
    );
4848
    // Committing makes the edits the base: both are clean and served from it again.
4849
    repo.commit("edits", &[]).unwrap();
4850
    age("a.txt");
4851
    age("b.txt");
4852
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4853
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4854
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4855
    let snap = repo.snapshot("status").unwrap();
4856
    assert!(!snap.changed && snap.statuses.is_empty());
4857
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4858
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4859
}
afaba5f1 Andy McCall ↶ 4860
4861
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4862
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4863
/// file is unchanged, and loading through the checkpoint equals a full load.
4864
#[test]
4865
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4866
    hermetic();
4867
    let dir = tempfile::tempdir().unwrap();
4868
    let root = dir.path();
4869
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4870
    let long: String = (0..300)
4871
        .map(|i| format!("line {i} of a long file\n"))
4872
        .collect();
4873
    write(root, "long.txt", long.as_bytes());
4874
    write(root, "short.txt", b"short\n");
4875
    repo.commit("base", &[]).unwrap();
4876
    let (r1, _, _) = repo.checkpoint().unwrap();
4877
    let cp1 = crate::objects::Checkpoint::decode(
4878
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4879
    )
4880
    .unwrap();
4881
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4882
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4883
4884
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4885
    repo.gc(true).unwrap();
4886
    assert!(repo.store().has(&graphs1[0]));
4887
    let report = repo.fsck().unwrap();
4888
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4889
4890
    // Loading through the checkpoint equals a full load.
4891
    write(root, "short.txt", b"short, edited\n");
4892
    repo.commit("edit the short file", &[]).unwrap();
4893
    let heads = repo.bookmark_heads().unwrap();
4894
    let fast = repo.load_state(&heads).unwrap();
4895
    let full = repo.load_state_full(&heads).unwrap();
4896
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4897
4898
    // The next checkpoint shares the unchanged long file's graph.
4899
    let (r2, _, _) = repo.checkpoint().unwrap();
4900
    let cp2 = crate::objects::Checkpoint::decode(
4901
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
4902
    )
4903
    .unwrap();
4904
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
4905
4906
    // A shallow clone's bundle carries the graph blob with the checkpoint.
4907
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
4908
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
4909
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
4910
4911
    // A version 1 checkpoint written by an older oxy still loads.
4912
    let state = repo.load_state_full(&heads).unwrap();
4913
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
4914
    let cp_old = crate::objects::Checkpoint {
4915
        heads: cp2.heads.clone(),
4916
        count: cp2.count,
4917
        payload: old,
4918
    };
4919
    let r_old = repo
4920
        .store()
4921
        .put(ObjectType::Checkpoint, &cp_old.encode())
4922
        .unwrap();
4923
    repo.install_checkpoint("main", &r_old).unwrap();
4924
    assert_eq!(
4925
        repo.load_state(&heads).unwrap().checkpoint_payload(),
4926
        full.checkpoint_payload()
4927
    );
4928
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4929
4930
    // A lost graph blob fails the load loudly rather than dropping the
4931
    // file, and fsck reports it (a fresh repository, objects still loose).
4932
    let dir2 = tempfile::tempdir().unwrap();
4933
    let root2 = dir2.path();
4934
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
4935
    write(root2, "long.txt", long.as_bytes());
4936
    repo2.commit("base", &[]).unwrap();
4937
    let (r, _, _) = repo2.checkpoint().unwrap();
4938
    let cp = crate::objects::Checkpoint::decode(
4939
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
4940
    )
4941
    .unwrap();
4942
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
64818938 Andy McCall ↶ 4943
    repo2.store().remove_loose_for_test(&graph).unwrap();
afaba5f1 Andy McCall ↶ 4944
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
4945
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
4946
}
e3d071ce Andy McCall ↶ 4947
4948
/// A new repository has not stored the user's identity yet (that happens
4949
/// at the first signed change); looking it up falls back to the key
4950
/// directory, and a file there that does not hash to the key is refused.
4951
#[test]
4952
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
4953
    hermetic();
4954
    let dir = tempfile::tempdir().unwrap();
4955
    let home = dir.path().join("home");
4956
    let mut first = Repo::init(&dir.path().join("a"))
4957
        .unwrap()
4958
        .with_home(home.clone());
4959
    let (key, _) = first
4960
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4961
        .unwrap();
4962
    let fresh = Repo::init(&dir.path().join("b"))
4963
        .unwrap()
4964
        .with_home(home.clone());
4965
    assert!(!fresh.store().has(&key), "nothing stored yet");
4966
    let id = fresh.identity(&key).unwrap();
4967
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
4968
    // A key file that is not this identity is an error, not a wrong answer.
4969
    let keys = fresh.keys_dir.clone();
4970
    let (other, _) = first
4971
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4972
        .unwrap();
4973
    fs::copy(
4974
        keys.join(format!("{}.identity", other.to_hex())),
4975
        keys.join(format!("{}.identity", key.to_hex())),
4976
    )
4977
    .unwrap();
4978
    assert!(fresh
4979
        .identity(&key)
4980
        .unwrap_err()
4981
        .to_string()
4982
        .contains("does not hold identity"));
4983
}
cc7a0056 Andy McCall ↶ 4984
4985
/// Status snapshots (spec §12.3): a text file whose stat matches the
4986
/// manifest, and whose base graph key is the one the manifest recorded it
4987
/// equal to, is neither read nor rendered; any edit, and any change to the
4988
/// file's graph in the base, brings it back.
4989
#[cfg(unix)]
4990
#[test]
4991
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
4992
    use std::os::unix::fs::PermissionsExt;
4993
    hermetic();
4994
    let dir = tempfile::tempdir().unwrap();
4995
    let root = dir.path();
4996
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4997
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
4998
        write(root, p, c.as_bytes());
4999
    }
5000
    repo.commit("base", &[]).unwrap();
5001
    let age = |p: &str| {
5002
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5003
        fs::File::options()
5004
            .write(true)
5005
            .open(root.join(p))
5006
            .unwrap()
5007
            .set_modified(old)
5008
            .unwrap();
5009
    };
5010
    let lock = |p: &str, mode: u32| {
5011
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5012
    };
5013
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5014
        age(p);
5015
    }
5016
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5017
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5018
    assert!(
5019
        m.entries.values().all(|e| e.graph.is_some()),
5020
        "keys recorded"
5021
    );
5022
5023
    // Unreadable files prove they are not read; the status snapshot does
5024
    // not render them either, and its base lacks their graphs.
5025
    lock("a.txt", 0o000);
5026
    lock("b.txt", 0o000);
5027
    let snap = repo.snapshot_status("status").unwrap();
5028
    assert!(!snap.changed && snap.statuses.is_empty());
5029
    assert_eq!(
5030
        snap.base_snapshot
5031
            .unrendered
5032
            .iter()
5033
            .cloned()
5034
            .collect::<Vec<_>>(),
5035
        vec!["a.txt", "b.txt", "d/c.txt"]
5036
    );
5037
    assert!(!snap.base.is_full());
5038
    assert!(!snap.base_snapshot.is_conflicted());
5039
    // A full snapshot does not read them either, but renders everything.
5040
    let full = repo.snapshot("status").unwrap();
5041
    assert!(full.statuses.is_empty() && full.base.is_full());
5042
    assert!(full.base_snapshot.unrendered.is_empty());
5043
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5044
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5045
5046
    // An edit is seen; the file is rendered, the others still are not.
5047
    write(root, "d/c.txt", b"sea edited\n");
5048
    let snap = repo.snapshot_status("status").unwrap();
5049
    assert_eq!(
5050
        statuses(&snap),
5051
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5052
    );
5053
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5054
    // So is a mode change of an unread file.
5055
    lock("b.txt", 0o100);
5056
    assert_eq!(
5057
        statuses(&repo.snapshot_status("status").unwrap()),
5058
        vec![
5059
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5060
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5061
        ]
5062
    );
5063
    lock("b.txt", 0o000);
5064
5065
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5066
    // stays unread, c.txt is read once and then skipped too.
5067
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5068
        .unwrap();
5069
    age("d/c.txt");
5070
    let snap = repo.snapshot_status("status").unwrap();
5071
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5072
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5073
    lock("d/c.txt", 0o000);
5074
    let snap = repo.snapshot_status("status").unwrap();
5075
    assert!(snap.statuses.is_empty());
5076
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5077
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5078
        lock(p, 0o644);
5079
    }
5080
}
5081
5082
/// Attributes decide how a file compares with the base, so a changed
5083
/// `.oxyattributes` makes every text file be compared again.
5084
#[cfg(unix)]
5085
#[test]
5086
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5087
    hermetic();
5088
    let dir = tempfile::tempdir().unwrap();
5089
    let root = dir.path();
5090
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5091
    write(root, "a.txt", b"crlf\r\n");
5092
    repo.commit("base", &[]).unwrap();
5093
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5094
    fs::File::options()
5095
        .write(true)
5096
        .open(root.join("a.txt"))
5097
        .unwrap()
5098
        .set_modified(old)
5099
        .unwrap();
5100
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5101
    assert!(repo
5102
        .snapshot_status("status")
5103
        .unwrap()
5104
        .base_snapshot
5105
        .unrendered
5106
        .contains("a.txt"));
5107
    // With eol=lf, a.txt as stored no longer equals the base.
5108
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5109
    let snap = repo.snapshot_status("status").unwrap();
5110
    assert_eq!(
5111
        statuses(&snap),
5112
        vec![
5113
            (".oxyattributes".to_string(), ChangeStatus::Added),
5114
            ("a.txt".to_string(), ChangeStatus::Modified)
5115
        ]
5116
    );
5117
}
54cd08a1 Andy McCall ↶ 5118
5119
/// Bookmarks with `/` in their names: pushing records their
5120
/// attestations, and checkpoints are kept for them, beside `feature`
5121
/// itself.
5122
#[test]
5123
fn bookmarks_with_slashes_push_and_checkpoint() {
5124
    hermetic();
5125
    let dir = tempfile::tempdir().unwrap();
5126
    let root = dir.path();
5127
    let origin = Repo::init(&root.join("origin")).unwrap();
5128
    let url = root.join("origin").to_string_lossy().to_string();
5129
    let mut repo = Repo::clone(&url, &root.join("r"))
5130
        .unwrap()
5131
        .with_home(root.join("home"));
5132
    // With an identity, pushes carry reference attestations: the case
5133
    // that failed, since the attestation is a file named after the bookmark.
5134
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5135
        .unwrap();
5136
    let r = root.join("r");
5137
    write(&r, "a.txt", b"a\n");
5138
    let h_a = repo.commit("a", &[]).unwrap();
5139
    assert!(repo.push("origin", false).unwrap()[0].ok);
5140
    repo.bookmark_create("feature", None).unwrap();
5141
    repo.bookmark_create("feature/x", None).unwrap();
5142
    repo.bookmark_switch("feature/x", false).unwrap();
5143
    write(&r, "b.txt", b"b\n");
5144
    let h_b = repo.commit("b", &[]).unwrap();
5145
    for name in ["feature", "feature/x"] {
5146
        let res = repo.push_bookmark("origin", name, false).unwrap();
5147
        assert!(res[0].ok, "{name}: {res:?}");
5148
    }
5149
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5150
    assert_eq!(
5151
        origin.resolve_heads("feature/x").unwrap(),
5152
        repo.resolve_heads("feature/x").unwrap()
5153
    );
5154
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5155
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5156
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5157
5158
    // A checkpoint of feature/x is found again when loading its state.
5159
    let (cp, _, _) = repo.checkpoint().unwrap();
5160
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5161
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5162
    let heads = repo.resolve_heads("feature/x").unwrap();
5163
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
f8c69576 Andy McCall ↶ 5164
}
5165
5166
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5167
/// never the remote's own bookmark, and a bookmark created again later is
5168
/// accepted although the deletion's attestation stays the latest.
5169
#[test]
5170
fn bookmarks_are_deleted_on_a_remote() {
5171
    hermetic();
5172
    let dir = tempfile::tempdir().unwrap();
5173
    let root = dir.path();
5174
    let origin = Repo::init(&root.join("origin")).unwrap();
5175
    let url = root.join("origin").to_string_lossy().to_string();
5176
    let mut repo = Repo::clone(&url, &root.join("r"))
5177
        .unwrap()
5178
        .with_home(root.join("home"));
5179
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5180
        .unwrap();
5181
    let r = root.join("r");
5182
    write(&r, "a.txt", b"a\n");
5183
    repo.commit("a", &[]).unwrap();
5184
    assert!(repo.push("origin", false).unwrap()[0].ok);
5185
    repo.bookmark_create("feature/x", None).unwrap();
5186
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5187
    assert!(origin.resolve_heads("feature/x").is_ok());
5188
5189
    let res = repo.push_delete("origin", "feature/x").unwrap();
5190
    assert!(res[0].ok, "{res:?}");
5191
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5192
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5193
    assert!(
5194
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5195
        "the deletion is attested"
5196
    );
5197
    assert!(
5198
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5199
        "the local bookmark stays"
5200
    );
5201
    assert!(!repo
5202
        .view()
5203
        .unwrap()
5204
        .remotes
5205
        .get("origin")
5206
        .is_some_and(|m| m.contains_key("feature/x")));
5207
5208
    // Pushing it again creates it again, past the deletion's serial.
5209
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5210
    assert!(res[0].ok, "{res:?}");
5211
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5212
5213
    // Nothing to delete, and never the remote's own bookmark.
5214
    assert!(repo.push_delete("origin", "nope").is_err());
5215
    let res = repo.push_delete("origin", "main").unwrap();
5216
    assert!(
5217
        !res[0].ok && res[0].reason.contains("default bookmark"),
5218
        "{res:?}"
5219
    );
5220
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
54cd08a1 Andy McCall ↶ 5221
}
61e3bce7 Andy McCall ↶ 5222
5223
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5224
/// when the target has the same versions of the files it touches, and is
5225
/// refused, untouched, when it has others.
5226
#[test]
5227
fn switching_bookmarks_carries_uncommitted_work() {
5228
    hermetic();
5229
    let dir = tempfile::tempdir().unwrap();
5230
    let root = dir.path();
5231
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5232
    write(root, "a.txt", b"a\n");
5233
    write(root, "b.txt", b"b\n");
5234
    write(root, "gone.txt", b"gone\n");
5235
    repo.commit("base", &[]).unwrap();
5236
    repo.bookmark_create("feature", None).unwrap();
5237
    // Started on main, belongs on feature: edit, add, remove.
5238
    write(root, "a.txt", b"a\nmore\n");
5239
    write(root, "new.txt", b"new\n");
5240
    fs::remove_file(root.join("gone.txt")).unwrap();
5241
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5242
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5243
    assert_eq!(repo.config.bookmark, "feature");
5244
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5245
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5246
    assert!(!root.join("gone.txt").exists());
5247
    let snap = repo.snapshot("status").unwrap();
5248
    assert_eq!(
5249
        statuses(&snap),
5250
        vec![
5251
            ("a.txt".to_string(), ChangeStatus::Modified),
5252
            ("gone.txt".to_string(), ChangeStatus::Removed),
5253
            ("new.txt".to_string(), ChangeStatus::Added)
5254
        ]
5255
    );
5256
    repo.commit("the work", &[]).unwrap();
5257
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5258
5259
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5260
    repo.bookmark_switch("main", false).unwrap();
5261
    write(root, "b.txt", b"b on main\n");
5262
    repo.commit("b on main", &[]).unwrap();
5263
    repo.bookmark_switch("feature", false).unwrap();
5264
    write(root, "b.txt", b"b edited\n");
5265
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5266
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5267
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5268
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5269
}
1c2bd9ab Andy McCall ↶ 5270
5271
/// Merging and checking out (feedback 3): a working copy without changes
5272
/// follows a merge whichever state it sat on; a refused checkout names
5273
/// what is in the way; `checkout --carry` takes the work along.
5274
#[test]
5275
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5276
    hermetic();
5277
    let dir = tempfile::tempdir().unwrap();
5278
    let root = dir.path();
5279
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5280
    write(root, "a.txt", b"a\n");
5281
    let h1 = repo.commit("a", &[]).unwrap();
5282
    write(root, "b.txt", b"b\n");
5283
    repo.commit("b", &[]).unwrap();
5284
    repo.bookmark_create("feature", None).unwrap();
5285
    repo.bookmark_switch("feature", false).unwrap();
5286
    write(root, "c.txt", b"c\n");
5287
    repo.commit("c on feature", &[]).unwrap();
5288
    repo.bookmark_switch("main", false).unwrap();
5289
    // The working copy sits on an older state than main's heads.
5290
    repo.checkout(&[h1], false, "checkout").unwrap();
5291
    assert!(!root.join("b.txt").exists());
5292
    let m = repo.merge("feature").unwrap();
5293
    assert!(m.checked_out, "a clean working copy follows the merge");
5294
    for f in ["a.txt", "b.txt", "c.txt"] {
5295
        assert!(root.join(f).exists(), "{f}");
5296
    }
5297
5298
    // A refusal says which paths are in the way and what to do.
5299
    fs::remove_file(root.join("b.txt")).unwrap();
5300
    write(root, "a.txt", b"a edited\n");
5301
    let err = repo
5302
        .checkout(&[h1], false, "checkout")
5303
        .unwrap_err()
5304
        .to_string();
5305
    assert!(
5306
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5307
        "{err}"
5308
    );
fe9586d9 Andy McCall ↶ 5309
    // --carry takes them along: h1 has a.txt as the base has it, and the
5310
    // removed b.txt is already as h1 has it (none), so that is no conflict
5311
    // either (oxygen#100).
1c2bd9ab Andy McCall ↶ 5312
    let (_, carried) = repo
5313
        .checkout_carry(&[h1], "the first change", "checkout")
5314
        .unwrap();
5315
    assert_eq!(carried, vec!["a.txt"]);
5316
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5317
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5318
}
e7ac6c2e Andy McCall ↶ 5319
5320
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5321
/// user identity not stored in a new repository yet is fine while its
5322
/// secret key is there; an added subrepo is listed as not committed yet.
5323
#[test]
5324
fn a_new_repository_is_healthy_before_its_first_commit() {
5325
    hermetic();
5326
    let dir = tempfile::tempdir().unwrap();
5327
    let root = dir.path();
5328
    let home = root.join("home");
5329
    let mut first = Repo::init(&root.join("first"))
5330
        .unwrap()
5331
        .with_home(home.clone());
5332
    let (key, _) = first
5333
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5334
        .unwrap();
5335
    let repo = Repo::init(&root.join("second"))
5336
        .unwrap()
5337
        .with_home(home.clone());
5338
    // Only the secret key: no identity object anywhere this repository sees.
5339
    let keys = repo.keys_dir.clone();
5340
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5341
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5342
    let r = repo.doctor(true);
5343
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5344
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5345
    assert!(id.message.contains("first signed change"), "{}", id.message);
5346
5347
    // A subrepo added and not committed yet is listed, pinned where it is.
5348
    let lib = root.join("lib");
5349
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5350
    write(&lib, "x.txt", b"x\n");
5351
    l.commit("x", &[]).unwrap();
5352
    let second = root.join("second");
5353
    write(&second, "a.txt", b"a\n");
5354
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5355
        .unwrap();
5356
    let subs = repo.subrepos().unwrap();
5357
    assert_eq!(subs.len(), 1);
5358
    assert_eq!(
5359
        (subs[0].path.as_str(), subs[0].committed),
5360
        ("deps/lib", false)
5361
    );
5362
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5363
    repo.commit("add lib", &[]).unwrap();
5364
    let subs = repo.subrepos().unwrap();
5365
    assert!(subs[0].committed, "committed now");
5366
}
8ab265dc Andy McCall ↶ 5367
5368
/// Commit, diff, hunks and discard use the partial snapshot: a file
5369
/// unchanged since the manifest is neither read nor rendered, and showing
5370
/// a change renders only what it edits, the same as from a full base.
5371
#[cfg(unix)]
5372
#[test]
5373
fn commits_and_diffs_leave_unchanged_files_alone() {
5374
    use std::os::unix::fs::PermissionsExt;
5375
    hermetic();
5376
    let dir = tempfile::tempdir().unwrap();
5377
    let root = dir.path();
5378
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5379
    write(root, "big.txt", b"lots\nof\nlines\n");
5380
    write(root, "a.txt", b"one\ntwo\n");
5381
    repo.commit("base", &[]).unwrap();
5382
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5383
    for f in ["big.txt", "a.txt"] {
5384
        fs::File::options()
5385
            .write(true)
5386
            .open(root.join(f))
5387
            .unwrap()
5388
            .set_modified(old)
5389
            .unwrap();
5390
    }
5391
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5392
    // big.txt cannot be read at all from here on.
5393
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5394
5395
    write(root, "a.txt", b"one\nTWO\nthree\n");
5396
    let diff = repo.diff_files(None).unwrap();
5397
    assert_eq!(
5398
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5399
        ["a.txt"]
5400
    );
5401
    let (_, hunks) = repo.hunks().unwrap();
5402
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5403
    let h = repo.commit("edit a", &[]).unwrap();
5404
5405
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5406
    let c = repo.store().get_change(&h).unwrap();
5407
    let full = repo.load_state(&c.deps).unwrap();
5408
    let want = render_change(&c, &full, &full.materialize());
5409
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5410
    let (base, snap) = repo.change_base(&c).unwrap();
5411
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5412
5413
    // Discarding works the same way.
5414
    write(root, "a.txt", b"scratch\n");
5415
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5416
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5417
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5418
}
f7510b63 Andy McCall ↶ 5419
5420
/// A replace conflict (spec §9.3) is settled by a change that writes one
5421
/// candidate, or new bytes, at the path when the caller names it; a plain
5422
/// snapshot of a checkout never settles it on its own.
5423
#[test]
5424
fn replace_conflicts_are_settled_when_asked() {
5425
    hermetic();
5426
    let dir = tempfile::tempdir().unwrap();
5427
    let root = dir.path();
5428
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5429
    let blob = |n: u8| {
5430
        let mut v = vec![0u8; 64];
5431
        v[1] = n;
5432
        v
5433
    };
5434
    write(root, "img.bin", &blob(1));
5435
    repo.commit("add img", &[]).unwrap();
5436
    repo.bookmark_create("other", None).unwrap();
5437
    write(root, "img.bin", &blob(2));
5438
    repo.commit("img two", &[]).unwrap();
5439
    repo.bookmark_switch("other", false).unwrap();
5440
    write(root, "img.bin", &blob(3));
5441
    repo.commit("img three", &[]).unwrap();
5442
    repo.bookmark_switch("main", false).unwrap();
5443
    repo.merge("other").unwrap();
5444
    let heads = repo.bookmark_heads().unwrap();
5445
    let merged = repo.load_state(&heads).unwrap().materialize();
5446
    assert!(
5447
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5448
        "a replace conflict"
5449
    );
5450
    // A snapshot of the checkout records nothing.
5451
    assert!(repo
5452
        .snapshot("status")
5453
        .unwrap()
5454
        .statuses
5455
        .iter()
5456
        .all(|s| s.path != "img.bin"));
5457
5458
    // Keeping candidate 3 settles it.
5459
    let author = repo.author();
5460
    let edits = [FileEdit {
5461
        path: "img.bin".into(),
5462
        content: Some(blob(3)),
5463
    }];
5464
    let c = repo
5465
        .build_change(&heads, &edits, "keep three", author)
5466
        .unwrap();
5467
    assert_eq!(c.kind, ChangeKind::Resolution);
5468
    let mut st = repo.load_state(&heads).unwrap();
5469
    for d in &c.deps {
5470
        assert!(st.contains(d));
5471
    }
5472
    assert!(
5473
        heads.iter().all(|h| c.deps.contains(h)),
5474
        "depends on both contributors"
5475
    );
5476
    st.add(c).unwrap();
5477
    let after = st.materialize();
5478
    assert!(!after.is_conflicted());
5479
    assert_eq!(
5480
        after.files["img.bin"].content,
5481
        FileContent::Opaque {
5482
            blobs: vec![Repo::blob_ref(&blob(3))]
5483
        }
5484
    );
5485
5486
    // New bytes settle it too.
5487
    let edits = [FileEdit {
5488
        path: "img.bin".into(),
5489
        content: Some(blob(9)),
5490
    }];
5491
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5492
    let mut st = repo.load_state(&heads).unwrap();
5493
    st.add(c).unwrap();
5494
    assert_eq!(
5495
        st.materialize().files["img.bin"].content,
5496
        FileContent::Opaque {
5497
            blobs: vec![Repo::blob_ref(&blob(9))]
5498
        }
5499
    );
5500
}
83d61e80 Andy McCall ↶ 5501
5502
/// The history of a range of lines (spec §27): the changes that wrote
5503
/// or deleted its atoms, or deleted atoms from between them; edits outside
5504
/// the range and changes the range's lines survived are not in it.
5505
#[test]
5506
fn line_ranges_have_exact_histories() {
5507
    hermetic();
5508
    let dir = tempfile::tempdir().unwrap();
5509
    let root = dir.path();
5510
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5511
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5512
    let base = repo.commit("add f", &[]).unwrap();
5513
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5514
    let outside = repo.commit("change the import", &[]).unwrap();
5515
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5516
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5517
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5518
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5519
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5520
    let after = repo.commit("add b after a", &[]).unwrap();
5521
    let heads = repo.bookmark_heads().unwrap();
5522
5523
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5524
    let hist: Vec<ChangeHash> = repo
5525
        .line_history(&heads, "f.rs", 2, 4)
5526
        .unwrap()
5527
        .iter()
5528
        .map(|e| e.hash)
5529
        .collect();
5530
    for (h, what) in [
5531
        (base, "wrote it"),
5532
        (inside, "edited a line"),
5533
        (deleted, "deleted a line from inside"),
5534
    ] {
5535
        assert!(hist.contains(&h), "{what}");
5536
    }
5537
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5538
        assert!(!hist.contains(&h), "{what}");
5539
    }
5540
    assert_eq!(hist[0], deleted, "newest first");
5541
    // One line: only what touched it.
5542
    let one: Vec<ChangeHash> = repo
5543
        .line_history(&heads, "f.rs", 1, 1)
5544
        .unwrap()
5545
        .iter()
5546
        .map(|e| e.hash)
5547
        .collect();
5548
    assert!(one.contains(&outside) && !one.contains(&inside));
5549
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5550
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5551
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5552
}
fc1a466a Andy McCall ↶ 5553
5554
#[test]
5555
fn receipts_are_kept_with_their_state_and_verified() {
5556
    use crate::receipt::{Receipt, SignedReceipt};
5557
    hermetic();
5558
    let dir = tempfile::tempdir().unwrap();
5559
    let root = dir.path();
5560
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5561
    write(root, "a.txt", b"1\n");
5562
    repo.commit("A", &[]).unwrap();
5563
    let heads = repo.bookmark_heads().unwrap();
5564
    let state = repo
5565
        .store()
5566
        .put_state(&StateObject::new(heads.clone()))
5567
        .unwrap();
5568
    let out = repo.store_blob(b"built\n").unwrap();
5569
    let receipt = Receipt {
5570
        job_name: "build".into(),
5571
        pipeline_hash: ObjectRef([1; 32]),
5572
        scope_tree_hash: ObjectRef([2; 32]),
5573
        inputs: vec![],
5574
        environment: ObjectRef([3; 32]),
5575
        outputs: vec![out],
5576
        exit_code: 0,
5577
        duration_ms: 42,
5578
    };
5579
    let sk = SecretKey::generate();
5580
    let runner = sk.identity("earth-1", "runner@earth", 1);
5581
    let sr = SignedReceipt::sign(
5582
        receipt.clone(),
5583
        repo.id().unwrap(),
5584
        state,
5585
        "demo#1",
5586
        &runner,
5587
        &sk,
5588
    );
5589
5590
    let r = repo.add_receipt(&sr).unwrap();
5591
    let found = repo.receipts(&heads).unwrap();
5592
    assert_eq!(found.len(), 1);
5593
    assert_eq!(found[0].attest, r);
5594
    assert_eq!(found[0].signed, sr);
5595
    assert!(found[0].problem.is_none() && !found[0].revoked);
5596
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5597
5598
    // Another repository's receipt, or a forged one, is refused.
5599
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5600
    assert!(repo
5601
        .add_receipt(&elsewhere)
5602
        .unwrap_err()
5603
        .to_string()
5604
        .contains("another repository"));
5605
    let mut forged = sr.clone();
5606
    forged.receipt.exit_code = 1;
5607
    assert!(repo
5608
        .add_receipt(&forged)
5609
        .unwrap_err()
5610
        .to_string()
5611
        .contains("does not verify"));
5612
5613
    // gc keeps the receipt, its runner and its output while the state lives.
5614
    repo.gc(true).unwrap();
5615
    assert_eq!(repo.receipts(&heads).unwrap().len(), 1);
5616
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5617
    assert!(repo.fsck().unwrap().problems.is_empty());
dfb23a3a Andy McCall ↶ 5618
}
5619
5620
#[test]
3a4b3e01 Andy McCall ↶ 5621
fn approvals_are_kept_with_their_state_and_survive_gc() {
5622
    hermetic();
5623
    let dir = tempfile::tempdir().unwrap();
5624
    let root = dir.path();
5625
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5626
    write(root, "a.txt", b"1\n");
5627
    repo.commit("A", &[]).unwrap();
5628
    let heads = repo.bookmark_heads().unwrap();
5629
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
5630
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
5631
    let sk = SecretKey::generate();
5632
    let andy = sk.identity("Andy", "[email protected]", 1);
5633
    let statement = crate::approval::Statement {
5634
        repo: repo.id().unwrap(),
5635
        run: "https://hub.example/andy/infra/flow/8".into(),
5636
        job: "apply".into(),
5637
        job_hash: ObjectRef([1; 32]),
5638
        state,
5639
        inputs: vec![plan],
5640
        environment: "prod".into(),
5641
        approve: true,
5642
    };
5643
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
5644
    let r = repo.add_approval(&sa).unwrap();
5645
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
5646
    // Another repository's approval, or a changed one, is refused.
5647
    let elsewhere = crate::approval::SignedApproval::sign(
5648
        &crate::approval::Statement {
5649
            repo: [0; 16],
5650
            ..statement.clone()
5651
        },
5652
        &andy,
5653
        &sk,
5654
    );
5655
    assert!(repo
5656
        .add_approval(&elsewhere)
5657
        .unwrap_err()
5658
        .to_string()
5659
        .contains("another repository"));
5660
    let mut forged = sa.clone();
5661
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
5662
        *environment = "dev".into();
5663
    }
5664
    assert!(repo
5665
        .add_approval(&forged)
5666
        .unwrap_err()
5667
        .to_string()
5668
        .contains("does not verify"));
5669
    // gc keeps it, its signature and its signer while the state lives.
5670
    repo.gc(true).unwrap();
5671
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
5672
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
5673
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
5674
    assert!(repo.fsck().unwrap().problems.is_empty());
5675
}
5676
5677
#[test]
dfb23a3a Andy McCall ↶ 5678
fn status_leaves_an_unchanged_manifest_alone() {
5679
    hermetic();
5680
    let dir = tempfile::tempdir().unwrap();
5681
    let root = dir.path();
5682
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5683
    write(root, "a.txt", b"1\n");
5684
    write(root, "b.txt", b"2\n");
5685
    repo.commit("A", &[]).unwrap();
5686
    // Files last touched well outside the racy window.
5687
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5688
    for f in ["a.txt", "b.txt"] {
5689
        fs::File::options()
5690
            .write(true)
5691
            .open(root.join(f))
5692
            .unwrap()
5693
            .set_modified(old)
5694
            .unwrap();
5695
    }
5696
    repo.snapshot_status("status").unwrap();
5697
    let path = repo.manifest_path();
5698
    let first = fs::read(&path).unwrap();
5699
    repo.snapshot_status("status").unwrap();
5700
    assert_eq!(
5701
        fs::read(&path).unwrap(),
5702
        first,
5703
        "an unchanged tree does not rewrite the manifest"
5704
    );
5705
    // A change rewrites it.
5706
    write(root, "a.txt", b"1\n2\n");
5707
    repo.snapshot_status("status").unwrap();
5708
    assert_ne!(fs::read(&path).unwrap(), first);
fc1a466a Andy McCall ↶ 5709
}
6f8aeb99 Andy McCall ↶ 5710
5711
#[test]
5712
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5713
    hermetic();
5714
    let dir = tempfile::tempdir().unwrap();
5715
    let root = dir.path();
5716
    let origin_path = root.join("origin");
5717
    Repo::init(&origin_path).unwrap();
5718
    let origin_url = origin_path.to_string_lossy().to_string();
5719
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5720
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5721
    write(&root.join("a"), "big.txt", big.as_bytes());
5722
    write(&root.join("a"), "small.txt", b"small\n");
5723
    let h1 = a.commit("large", &[]).unwrap();
5724
    let (_, body) = a.store().get(&h1).unwrap();
5725
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5726
    assert!(a.push("origin", false).unwrap()[0].ok);
5727
5728
    // A clone reads the text from the blobs that came with the change.
5729
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5730
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5731
    // An edit in the middle of the stored insert is an ordinary change.
5732
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5733
    write(&root.join("b"), "big.txt", edited.as_bytes());
5734
    let h2 = b.commit("edit", &[]).unwrap();
5735
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5736
    assert!(b.push("origin", false).unwrap()[0].ok);
5737
    assert!(a.pull("origin").unwrap().checked_out);
5738
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5739
    assert_eq!(
5740
        a.fsck().unwrap().errors(),
5741
        0,
5742
        "{:?}",
5743
        a.fsck().unwrap().problems
5744
    );
5745
5746
    // With zero retention gc keeps the text blobs of every kept change.
5747
    let mut a = Repo::open(&root.join("a")).unwrap();
5748
    a.config.set("core.op-retention", "0").unwrap();
5749
    a.save_config().unwrap();
5750
    let a = Repo::open(&root.join("a")).unwrap();
5751
    a.gc(true).unwrap();
5752
    let a = Repo::open(&root.join("a")).unwrap();
5753
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5754
    assert_eq!(
5755
        a.fsck().unwrap().errors(),
5756
        0,
5757
        "{:?}",
5758
        a.fsck().unwrap().problems
5759
    );
5760
    // And a clone of the packed repository reads them from its packs.
5761
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5762
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5763
    drop(c);
6caacfff Andy McCall ↶ 5764
}
5765
5766
#[test]
5767
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5768
    hermetic();
5769
    let dir = tempfile::tempdir().unwrap();
5770
    let root = dir.path();
5771
    let repo = Repo::init(root).unwrap();
5772
    write(root, "a.txt", b"a\n");
5773
    let a = repo.commit("a", &[]).unwrap();
5774
    write(root, "b.txt", b"b\n");
5775
    repo.commit("b", &[]).unwrap();
5776
    let (x, op) = repo.head_op().unwrap();
5777
    let ws = *op.view.workspaces.keys().next().unwrap();
5778
    let mut one = op.view.clone();
5779
    one.workspaces.insert(ws, a);
5780
    let mut two = op.view.clone();
5781
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5782
    let first = repo.record_op(&[x], "one", one).unwrap();
5783
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5784
    assert!(
5785
        e.to_string()
5786
            .contains("changed this working copy at the same time"),
5787
        "{e}"
5788
    );
5789
    assert_eq!(
5790
        repo.head_op().unwrap().0,
5791
        first,
5792
        "the second is not recorded"
5793
    );
5794
}
5795
5796
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5797
/// rewrote the working copy recorded the half-written files as edits, and
5798
/// its view replaced the switch's.
5799
#[test]
5800
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5801
    hermetic();
5802
    let dir = tempfile::tempdir().unwrap();
5803
    let root = dir.path().to_path_buf();
5804
    let mut repo = Repo::init(&root).unwrap();
5805
    write(&root, "keep.txt", b"keep\n");
5806
    repo.commit("base", &[]).unwrap();
5807
    repo.bookmark_create("small", None).unwrap();
5808
    for i in 0..300 {
5809
        write(
5810
            &root,
5811
            &format!("many/f{i}.txt"),
5812
            format!("file {i}\n").as_bytes(),
5813
        );
5814
    }
5815
    repo.commit("many", &[]).unwrap();
5816
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5817
    let watcher = {
5818
        let (root, stop) = (root.clone(), stop.clone());
5819
        std::thread::spawn(move || {
5820
            let r = Repo::open(&root).unwrap();
5821
            let mut ran = 0;
5822
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
5823
                if r.snapshot_status("oxy status").is_ok() {
5824
                    ran += 1;
5825
                }
5826
            }
5827
            ran
5828
        })
5829
    };
5830
    for i in 0..20 {
5831
        let to = if i % 2 == 0 { "small" } else { "main" };
5832
        repo.bookmark_switch(to, false).unwrap();
5833
    }
5834
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
5835
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
5836
    // Back on main, clean, with every file where main has it.
5837
    let repo = Repo::open(&root).unwrap();
5838
    let s = repo.snapshot_status("oxy status").unwrap();
5839
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
5840
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
5841
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
5842
    assert!(root.join("many/f299.txt").exists());
1a3b6203 Andy McCall ↶ 5843
}
5844
5845
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
5846
/// put a subrepo that was ahead of its pin back at the pin and moved the
5847
/// subrepo's own bookmark backwards.
5848
#[test]
5849
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
5850
    hermetic();
5851
    let dir = tempfile::tempdir().unwrap();
5852
    let root = dir.path();
5853
    Repo::init(&root.join("lib-origin")).unwrap();
5854
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5855
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
5856
    write(&root.join("lib"), "lib.txt", b"v1\n");
5857
    lib.commit("lib v1", &[]).unwrap();
5858
    assert!(lib.push("origin", false).unwrap()[0].ok);
5859
5860
    let app_dir = root.join("app");
5861
    let mut app = Repo::init(&app_dir).unwrap();
5862
    write(&app_dir, "main.txt", b"app\n");
5863
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5864
    app.commit("app with lib", &[]).unwrap();
5865
    app.bookmark_create("feature", None).unwrap();
5866
5867
    // New work in the subrepo, not yet pinned by the parent.
5868
    let nested_dir = app_dir.join("libs/lib");
5869
    let nested = Repo::open(&nested_dir).unwrap();
5870
    write(&nested_dir, "new.txt", b"new\n");
5871
    let l2 = nested.commit("lib: new file", &[]).unwrap();
5872
    drop(nested);
5873
5874
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
5875
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
5876
    let nested = Repo::open(&nested_dir).unwrap();
5877
    assert!(
5878
        nested.bookmark_heads().unwrap().contains(&l2),
5879
        "its bookmark kept its work"
5880
    );
5881
    assert!(nested_dir.join("new.txt").exists(), "and its files");
5882
    let s = app.snapshot("status").unwrap();
5883
    assert_eq!(
5884
        statuses(&s),
5885
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
5886
    );
6f8aeb99 Andy McCall ↶ 5887
}
7d9dab13 Andy McCall ↶ 5888
5889
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
5890
/// moving `main` to a change this clone had pushed on another bookmark,
5891
/// the first `pull` said "Already up to date" while `main` was behind.
5892
#[test]
5893
fn pull_takes_a_remote_move_to_changes_already_here() {
5894
    hermetic();
5895
    let dir = tempfile::tempdir().unwrap();
5896
    let root = dir.path();
5897
    let origin_path = root.join("origin");
5898
    let origin = Repo::init(&origin_path).unwrap();
5899
    let url = origin_path.to_string_lossy().to_string();
5900
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
5901
    write(&root.join("b"), "base.txt", b"base\n");
5902
    b.commit("base", &[]).unwrap();
5903
    assert!(b.push("origin", false).unwrap()[0].ok);
5904
5905
    // A feature bookmark with one change, pushed.
5906
    b.bookmark_create("feat", None).unwrap();
5907
    b.bookmark_switch("feat", false).unwrap();
5908
    write(&root.join("b"), "x.txt", b"x\n");
5909
    let x = b.commit("x", &[]).unwrap();
5910
    assert!(b.push("origin", false).unwrap()[0].ok);
5911
    b.bookmark_switch("main", false).unwrap();
5912
5913
    // The remote lands it: its main moves to the feature's state.
5914
    let feat = origin
5915
        .store()
5916
        .get_state(&origin.view().unwrap().bookmarks["feat"])
5917
        .unwrap()
5918
        .heads;
5919
    origin.bookmark_set("main", &feat).unwrap();
5920
5921
    let r = b.pull("origin").unwrap();
5922
    assert!(r.changed, "{r:?}");
5923
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
5924
    let main = b
5925
        .bookmarks()
5926
        .unwrap()
5927
        .into_iter()
5928
        .find(|m| m.name == "main")
5929
        .unwrap();
5930
    assert_eq!(main.behind, Some(0), "{main:?}");
5931
}
86e1824f Andy McCall ↶ 5932
14edbaaf Andy McCall ↶ 5933
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
5934
/// to one only the remote has makes a local bookmark from it; a pull moves
5935
/// every local bookmark the remote has too; a clone checks out the remote's
5936
/// default bookmark.
5937
#[test]
5938
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
5939
    hermetic();
5940
    let dir = tempfile::tempdir().unwrap();
5941
    let root = dir.path();
5942
    let origin_path = root.join("origin");
5943
    let mut origin = Repo::init(&origin_path).unwrap();
5944
    let url = origin_path.to_string_lossy().to_string();
5945
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
5946
    write(&root.join("a"), "base.txt", b"base\n");
5947
    a.commit("base", &[]).unwrap();
5948
    assert!(a.push("origin", false).unwrap()[0].ok);
5949
    a.bookmark_create("develop", None).unwrap();
5950
    a.bookmark_switch("develop", false).unwrap();
5951
    write(&root.join("a"), "base.txt", b"base\nd1\n");
5952
    let d1 = a.commit("d1", &[]).unwrap();
5953
    assert!(a.push("origin", false).unwrap()[0].ok);
5954
5955
    // A clone has main only; origin/develop is a name all the same.
5956
    let c_root = root.join("c");
5957
    let mut c = Repo::clone(&url, &c_root).unwrap();
5958
    assert_eq!(c.config.bookmark, "main");
5959
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
5960
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
5961
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
5962
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
5963
5964
    // Switching makes the local bookmark from origin's.
5965
    c.bookmark_switch("develop", false).unwrap();
5966
    assert_eq!(c.config.bookmark, "develop");
5967
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
5968
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
5969
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
5970
    assert!(c.bookmark_switch("nowhere", false).is_err());
5971
5972
    // Both bookmarks move on the remote; one pull takes both.
5973
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
5974
    let d2 = a.commit("d2", &[]).unwrap();
5975
    assert!(a.push("origin", false).unwrap()[0].ok);
5976
    a.bookmark_switch("main", false).unwrap();
5977
    write(&root.join("a"), "m.txt", b"m\n");
5978
    let m = a.commit("m", &[]).unwrap();
5979
    assert!(a.push("origin", false).unwrap()[0].ok);
5980
    let r = c.pull("origin").unwrap();
5981
    assert!(r.changed && r.checked_out, "{r:?}");
5982
    assert_eq!(r.heads, vec![d2]);
5983
    assert_eq!(r.others, vec!["main".to_string()]);
5984
    assert!(c.resolve_heads("main").unwrap().contains(&m));
5985
    assert_eq!(
5986
        fs::read(c_root.join("base.txt")).unwrap(),
5987
        b"base\nd1\nd2\n"
5988
    );
5989
    let again = c.pull("origin").unwrap();
5990
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
5991
5992
    // A clone checks out the remote's default bookmark.
5993
    origin.config.set("workspace.bookmark", "develop").unwrap();
5994
    origin.save_config().unwrap();
5995
    let e = Repo::clone(&url, &root.join("e")).unwrap();
5996
    assert_eq!(e.config.bookmark, "develop");
5997
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
5998
    let reopened = Repo::open(&root.join("e")).unwrap();
5999
    assert_eq!(reopened.config.bookmark, "develop");
6000
    // REMOTE/NAME names the remote's bookmark to switch to.
6001
    let mut e = reopened;
6002
    e.bookmark_switch("origin/main", false).unwrap();
6003
    assert_eq!(e.config.bookmark, "main");
6004
    assert!(e.bookmark_heads().unwrap().contains(&m));
6005
}
6006
98a1620a Andy McCall ↶ 6007
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6008
/// op restore goes back to an operation, files included, and undo takes
6009
/// the restore back whole; op revert undoes one operation alone; each
6010
/// operation's changes are described from the views.
6011
#[test]
6012
fn operations_can_be_read_restored_and_reverted() {
6013
    hermetic();
6014
    let dir = tempfile::tempdir().unwrap();
6015
    let root = dir.path();
6016
    let repo = Repo::init(root).unwrap();
6017
    write(root, "a.txt", b"a\n");
6018
    let first = repo.commit("first", &[]).unwrap();
6019
    write(root, "a.txt", b"a\nb\n");
6020
    let second = repo.commit("second", &[]).unwrap();
6021
    let at_second = repo.head_op().unwrap().0.to_hex();
6022
    repo.bookmark_create("keep", None).unwrap();
6023
    let created = repo.head_op().unwrap().0.to_hex();
6024
    write(root, "n.txt", b"n\n");
6025
    let third = repo.commit("third", &[]).unwrap();
6026
6027
    // What each operation changed.
6028
    let ops = repo.op_log().unwrap();
6029
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6030
    assert!(
6031
        changes
6032
            .iter()
6033
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6034
        "{changes:?}"
6035
    );
6036
    assert!(changes
6037
        .iter()
6038
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6039
6040
    // Reading at an earlier operation.
6041
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6042
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6043
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6044
    write(root, "z.txt", b"z\n");
6045
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6046
    fs::remove_file(root.join("z.txt")).unwrap();
6047
    assert!(repo.resolve_op("zz").is_err());
6048
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
6049
6050
    // Restore goes back, files and all; undo takes it back whole.
6051
    repo.op_restore(&at_second, false).unwrap();
6052
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
6053
    assert!(!root.join("n.txt").exists());
6054
    repo.undo().unwrap();
6055
    let mut heads = repo.bookmark_heads().unwrap();
6056
    heads.sort();
6057
    let mut want = vec![second, third];
6058
    want.sort();
6059
    assert_eq!(heads, want);
6060
    assert!(
6061
        root.join("n.txt").exists(),
6062
        "the files came back with the undo"
6063
    );
6064
6065
    // Revert the bookmark's creation alone: the commit after it stays.
6066
    let r = repo.op_revert(&created).unwrap();
6067
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6068
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6069
    assert!(repo
6070
        .load_state(&repo.bookmark_heads().unwrap())
6071
        .unwrap()
6072
        .contains(&third));
6073
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6074
    let _ = first;
6075
}
6076
36041796 Andy McCall ↶ 6077
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6078
/// from the status cache while every file is as the snapshot left it, and
6079
/// from a snapshot again as soon as one is not.
6080
#[test]
6081
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6082
    hermetic();
6083
    let dir = tempfile::tempdir().unwrap();
6084
    let root = dir.path();
6085
    let repo = Repo::init(root).unwrap();
6086
    write(root, "a.txt", b"a\n");
6087
    write(root, "b.txt", b"b\n");
6088
    repo.commit("base", &[]).unwrap();
6089
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6090
6091
    write(root, "a.txt", b"a\nmore\n");
6092
    assert_eq!(
6093
        repo.status_by_manifest().unwrap(),
6094
        None,
6095
        "no snapshot of the edit yet"
6096
    );
6097
    let snap = repo.snapshot_status("oxy status").unwrap();
6098
    assert_eq!(snap.statuses.len(), 1);
6099
    let cached = repo
6100
        .status_by_manifest()
6101
        .unwrap()
6102
        .expect("answered from the cache");
6103
    assert_eq!(cached.len(), 1);
6104
    assert_eq!(
6105
        (cached[0].path.as_str(), cached[0].status),
6106
        ("a.txt", ChangeStatus::Modified)
6107
    );
6108
6109
    // Any further change sends status back to a snapshot.
6110
    write(root, "a.txt", b"a\nmore\nand more\n");
6111
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6112
    repo.snapshot_status("oxy status").unwrap();
6113
    assert!(repo.status_by_manifest().unwrap().is_some());
6114
    write(root, "new.txt", b"n\n");
6115
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6116
    fs::remove_file(root.join("new.txt")).unwrap();
6117
    assert!(
6118
        repo.status_by_manifest().unwrap().is_some(),
6119
        "back as it was"
6120
    );
6121
    fs::remove_file(root.join("b.txt")).unwrap();
6122
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6123
    write(root, "b.txt", b"b\n");
6124
6125
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6126
    repo.snapshot_status("oxy status").unwrap();
6127
    repo.commit("more", &[]).unwrap();
6128
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6129
}
6130
77445673 Andy McCall ↶ 6131
/// oxygen#41: while the status cache holds, the working copy's diff is
6132
/// rendered from the stored working-copy change, and says exactly what a
6133
/// snapshot's diff says.
6134
#[test]
6135
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6136
    hermetic();
6137
    let dir = tempfile::tempdir().unwrap();
6138
    let root = dir.path();
6139
    let repo = Repo::init(root).unwrap();
6140
    write(root, "a.txt", b"one\ntwo\nthree\n");
6141
    write(root, "gone.txt", b"bye\n");
6142
    repo.commit("base", &[]).unwrap();
6143
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6144
    write(root, "new.txt", b"hello\n");
6145
    fs::remove_file(root.join("gone.txt")).unwrap();
6146
    let snap = repo.snapshot_status("oxy status").unwrap();
6147
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6148
    assert!(
6149
        repo.status_by_manifest().unwrap().is_some(),
6150
        "the cache holds"
6151
    );
6152
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6153
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6154
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
74b4a3c6 Andy McCall ↶ 6155
6156
    // Committed, nothing changes: the diff is empty without loading the
6157
    // base (oxygen#94), and the same as rendering it.
6158
    repo.commit("all", &[]).unwrap();
6159
    repo.snapshot_status("oxy status").unwrap();
6160
    assert!(repo.status_by_manifest().unwrap().is_some());
6161
    assert!(repo
6162
        .working_copy_with_base_unless_unchanged()
6163
        .unwrap()
6164
        .is_none());
6165
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6166
    assert_eq!(render_change(&wc, &base, &snapshot), "");
6167
    assert!(repo.diff_files(None).unwrap().is_empty());
77445673 Andy McCall ↶ 6168
}
6169
1ec3f008 Andy McCall ↶ 6170
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6171
/// while none has moved, the check stats the tracked files without listing
6172
/// the tree, and a file added or removed anywhere moves its directory's
6173
/// time, so the tree is listed again.
6174
#[test]
6175
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6176
    hermetic();
6177
    let dir = tempfile::tempdir().unwrap();
6178
    let root = dir.path();
6179
    let repo = Repo::init(root).unwrap();
6180
    write(root, "a.txt", b"a\n");
6181
    write(root, "sub/deep/b.txt", b"b\n");
6182
    repo.commit("base", &[]).unwrap();
6183
    // Out of the racy window: every file and directory a minute old.
6184
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6185
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6186
        fs::File::open(root.join(p))
6187
            .unwrap()
6188
            .set_modified(old)
6189
            .unwrap();
6190
    }
6191
    repo.snapshot_status("oxy status").unwrap();
6192
    repo.write_manifest(false, false).unwrap();
6193
    let m = repo.read_manifest().unwrap().unwrap().2;
6194
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6195
    assert_eq!(
6196
        repo.disk_differs_by_dirs(&m),
6197
        Some(false),
6198
        "no listing needed"
6199
    );
6200
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6201
6202
    // A same-size edit with a new time: found by its stat.
6203
    write(root, "sub/deep/b.txt", b"c\n");
6204
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6205
    write(root, "sub/deep/b.txt", b"b\n");
6206
    fs::File::open(root.join("sub/deep/b.txt"))
6207
        .unwrap()
6208
        .set_modified(old)
6209
        .unwrap();
6210
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6211
6212
    // A new file moves its directory's time: the tree must be listed.
6213
    write(root, "sub/deep/new.txt", b"n\n");
6214
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6215
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6216
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6217
    // A removed one too.
6218
    fs::remove_file(root.join("a.txt")).unwrap();
6219
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6220
}
6221
e226a6cc Andy McCall ↶ 6222
/// oxygen#41: a commit right after a status takes the snapshot the status
6223
/// left (the status cache holds) rather than walking again, and commits
6224
/// exactly what a snapshot would have.
6225
#[test]
6226
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6227
    hermetic();
6228
    let dir = tempfile::tempdir().unwrap();
6229
    let root = dir.path();
6230
    let repo = Repo::init(root).unwrap();
6231
    write(root, "a.txt", b"a\nb\n");
6232
    write(root, ".oxyattributes", b"*.bin binary\n");
6233
    repo.commit("base", &[]).unwrap();
6234
    write(root, "a.txt", b"a\nB\n");
6235
    write(root, "new.txt", b"new\n");
6236
    let snap = repo.snapshot_status("oxy status").unwrap();
6237
    let cached = repo
6238
        .snapshot_from_cache()
6239
        .unwrap()
6240
        .expect("the cache holds");
6241
    assert_eq!(cached.wc_hash, snap.wc_hash);
6242
    assert_eq!(cached.statuses, snap.statuses);
6243
    assert!(
6244
        !cached.attributes.is_empty(),
6245
        "the .oxyattributes file was read"
6246
    );
6247
    let h = repo.commit("edit", &[]).unwrap();
6248
    let c = repo.store().get_change(&h).unwrap();
6249
    assert_eq!(
6250
        c.tree_ops.len() + c.edits.len(),
6251
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6252
    );
6253
    assert_eq!(
6254
        repo.status_by_manifest().unwrap(),
6255
        Some(vec![]),
6256
        "clean after the commit"
6257
    );
6258
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6259
}
6260
0389c3e8 Andy McCall ↶ 6261
/// oxygen#41: a clean check that verified racy entries restamps the
6262
/// manifest, so later checks can trust them, and a same-size rewrite
6263
/// straight afterwards is still found: entries within two seconds of the
6264
/// new time stay racy.
6265
#[test]
6266
fn a_verified_clean_check_restamps_the_manifest_safely() {
6267
    hermetic();
6268
    let dir = tempfile::tempdir().unwrap();
6269
    let root = dir.path();
6270
    let repo = Repo::init(root).unwrap();
6271
    write(root, "a.txt", b"one\n");
6272
    repo.commit("one", &[]).unwrap();
6273
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6274
    assert!(repo.clean_by_manifest().unwrap());
6275
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6276
    assert!(after > before, "restamped");
6277
    write(root, "a.txt", b"two\n");
6278
    assert!(
6279
        !repo.clean_by_manifest().unwrap(),
6280
        "a same-size rewrite is still seen"
6281
    );
6282
}
6283
86e1824f Andy McCall ↶ 6284
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6285
/// stored insert's text blob only when it builds that file's graph, and
6286
/// builds the same graph a full load does.
6287
#[test]
6288
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6289
    hermetic();
6290
    let dir = tempfile::tempdir().unwrap();
6291
    let root = dir.path();
6292
    let repo = Repo::init(root).unwrap();
6293
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6294
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6295
    write(root, "big.txt", big.as_bytes());
6296
    write(root, "other.txt", other.as_bytes());
6297
    let h = repo.commit("two large files", &[]).unwrap();
6298
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6299
    let h2 = repo.commit("append", &[]).unwrap();
6300
6301
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6302
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6303
        FileContent::Text { bytes, .. } => bytes.clone(),
6304
        other => panic!("{other:?}"),
6305
    };
6306
    // Built on demand, every graph renders as the full load's.
6307
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6308
    let big_node = full.files["big.txt"].node;
6309
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6310
    repo.load_all_graphs(&mut hist).unwrap();
6311
    let rendered = hist.materialize();
6312
    for p in ["big.txt", "other.txt"] {
6313
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6314
    }
6315
6316
    // Without other.txt's text blob, history still loads and big.txt still
6317
    // builds: nothing read the other text.
6318
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6319
    assert_eq!(texts.len(), 2);
6320
    let content = |r: &ObjectRef| -> Vec<u8> {
6321
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6322
        blob.chunks
6323
            .iter()
6324
            .flat_map(|c| repo.store().get(c).unwrap().1)
6325
            .collect()
6326
    };
6327
    let other_text = texts
6328
        .iter()
a4fad5b0 Andy McCall ↶ 6329
        .filter_map(|t| match t {
0f93f49c Andy McCall ↶ 6330
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
a4fad5b0 Andy McCall ↶ 6331
            _ => None,
6332
        })
86e1824f Andy McCall ↶ 6333
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6334
        .unwrap();
64818938 Andy McCall ↶ 6335
    repo.store().remove_loose_for_test(&other_text).unwrap();
86e1824f Andy McCall ↶ 6336
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6337
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6338
    assert!(repo
6339
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6340
        .is_err());
6341
}
6342
6343
/// oxygen#35: the first status after a commit read and rendered every
6344
/// file (79 s and more than 14 GB on the Linux tree), because the
6345
/// manifest had no graph keys for files the commit added.
6346
#[test]
6347
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6348
    use std::os::unix::fs::PermissionsExt;
6349
    hermetic();
6350
    let dir = tempfile::tempdir().unwrap();
6351
    let root = dir.path();
6352
    let repo = Repo::init(root).unwrap();
6353
    let files = ["a.txt", "b.txt", "d/c.txt"];
6354
    for p in files {
6355
        write(root, p, format!("{p}\n").as_bytes());
6356
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6357
        fs::File::options()
6358
            .write(true)
6359
            .open(root.join(p))
6360
            .unwrap()
6361
            .set_modified(old)
6362
            .unwrap();
6363
    }
6364
    repo.commit("added", &[]).unwrap();
6365
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6366
    assert!(
6367
        m.entries.values().all(|e| e.graph.is_some()),
6368
        "keys recorded at commit"
6369
    );
6370
    // Unreadable files prove the next status reads none of them.
6371
    for p in files {
6372
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6373
    }
6374
    let snap = repo.snapshot_status("status").unwrap();
6375
    for p in files {
6376
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6377
    }
6378
    assert!(!snap.changed && snap.statuses.is_empty());
6379
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6380
}
c5ce0367 Andy McCall ↶ 6381
6382
/// oxygen#35: a checkout reads, renders and writes only the files whose
6383
/// graphs differ, and renders the rest a batch at a time.
6384
#[test]
6385
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6386
    use std::os::unix::fs::PermissionsExt;
6387
    hermetic();
6388
    let dir = tempfile::tempdir().unwrap();
6389
    let root = dir.path();
6390
    let origin = root.join("origin");
6391
    let mut repo = Repo::init(&origin).unwrap();
6392
    // More files than one batch holds.
6393
    let n = 2100;
6394
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6395
    for i in 0..n {
6396
        let p = format!("f/{i:04}.txt");
6397
        write(&origin, &p, format!("file {i}\n").as_bytes());
6398
        fs::File::options()
6399
            .write(true)
6400
            .open(origin.join(&p))
6401
            .unwrap()
6402
            .set_modified(old)
6403
            .unwrap();
6404
    }
6405
    repo.commit("many", &[]).unwrap();
6406
    repo.bookmark_create("feature", None).unwrap();
6407
    repo.bookmark_switch("feature", false).unwrap();
6408
    write(&origin, "f/0007.txt", b"changed\n");
6409
    repo.commit("one change", &[]).unwrap();
6410
6411
    // Switching back to main must not read the unchanged files.
6412
    for i in 0..n {
6413
        if i != 7 {
6414
            let p = origin.join(format!("f/{i:04}.txt"));
6415
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6416
        }
6417
    }
6418
    let r = repo.bookmark_switch("main", false).unwrap();
6419
    for i in 0..n {
6420
        let p = origin.join(format!("f/{i:04}.txt"));
6421
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6422
    }
6423
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6424
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6425
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6426
6427
    // A clone renders every file, across batches.
6428
    let c = root.join("clone");
6429
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6430
    for i in [0, 2047, 2048, n - 1] {
6431
        assert_eq!(
6432
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6433
            format!("file {i}\n").as_bytes()
6434
        );
6435
    }
6436
    let cloned = Repo::open(&c).unwrap();
6437
    assert!(cloned
6438
        .snapshot_status("status")
6439
        .unwrap()
6440
        .statuses
6441
        .is_empty());
d3cd7ef9 Andy McCall ↶ 6442
}
6443
6444
/// A file written just before the manifest (inside the racy window) is
6445
/// checked by its hash: trusted when equal, caught when edited in place
6446
/// with the same size and time.
6447
#[test]
6448
fn a_racy_manifest_entry_is_checked_by_hash() {
6449
    hermetic();
6450
    let dir = tempfile::tempdir().unwrap();
6451
    let root = dir.path();
6452
    let repo = Repo::init(root).unwrap();
6453
    write(root, "a.txt", b"one\n");
6454
    repo.commit("fresh", &[]).unwrap();
6455
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6456
    let t = fs::metadata(root.join("a.txt"))
6457
        .unwrap()
6458
        .modified()
6459
        .unwrap();
6460
    write(root, "a.txt", b"two\n");
6461
    fs::File::options()
6462
        .write(true)
6463
        .open(root.join("a.txt"))
6464
        .unwrap()
6465
        .set_modified(t)
6466
        .unwrap();
6467
    assert!(
6468
        !repo.clean_by_manifest().unwrap(),
6469
        "same size and time, other bytes"
6470
    );
6471
    assert_eq!(
6472
        statuses(&repo.snapshot_status("status").unwrap()),
6473
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6474
    );
c5ce0367 Andy McCall ↶ 6475
}
2c75672f Andy McCall ↶ 6476
6477
/// A fetch on one machine moves changes as stored, text blobs among the
6478
/// objects; a change whose text blob did not come is refused, not stored.
6479
#[test]
6480
fn a_raw_bundle_without_a_changes_text_is_refused() {
6481
    hermetic();
6482
    let dir = tempfile::tempdir().unwrap();
6483
    let root = dir.path();
6484
    let a = Repo::init(&root.join("a")).unwrap();
6485
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6486
    write(&root.join("a"), "big.txt", big.as_bytes());
6487
    let h = a.commit("big", &[]).unwrap();
6488
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6489
    assert_eq!(bundle.raw_changes.len(), 1);
6490
    assert!(bundle.changes.is_empty());
6491
    let b = Repo::init(&root.join("b")).unwrap();
6492
    let mut without = bundle.clone();
6493
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6494
    let e = b.import_bundle(&without, false).unwrap_err();
6495
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6496
    assert!(!b.store().has(&h));
6497
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6498
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6499
}
a87c7b9d Andy McCall ↶ 6500
6501
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6502
/// again was a second node for one Git path, so a file moved into it on
6503
/// another line, where the first node still stood, ended up in two places.
6504
/// An import now brings the directory back rather than make a new one.
6505
#[test]
6506
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6507
    hermetic();
6508
    if std::process::Command::new("git")
6509
        .arg("--version")
6510
        .output()
6511
        .is_err()
6512
    {
6513
        eprintln!("git not installed; skipping");
6514
        return;
6515
    }
6516
    let dir = tempfile::tempdir().unwrap();
6517
    let root = dir.path();
6518
    let g = root.join("src.git");
6519
    fs::create_dir_all(&g).unwrap();
6520
    let git = |args: &[&str]| -> String {
6521
        let out = std::process::Command::new("git")
6522
            .arg("-C")
6523
            .arg(&g)
6524
            .args([
6525
                "-c",
6526
                "user.name=Grace",
6527
                "-c",
6528
                "[email protected]",
6529
                "-c",
6530
                "commit.gpgsign=false",
6531
            ])
6532
            .args(args)
6533
            .output()
6534
            .unwrap();
6535
        assert!(
6536
            out.status.success(),
6537
            "git {args:?}: {}",
6538
            String::from_utf8_lossy(&out.stderr)
6539
        );
6540
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6541
    };
6542
    git(&["init", "-q", "-b", "main"]);
6543
    write(&g, "d/a.txt", b"a\n");
6544
    write(&g, "c/x.txt", b"x\n");
6545
    git(&["add", "."]);
6546
    git(&["commit", "-qm", "base"]);
6547
    // One line: move x into d while d still stands.
6548
    git(&["checkout", "-qb", "side"]);
6549
    git(&["mv", "c/x.txt", "d/x.txt"]);
6550
    git(&["commit", "-qm", "x into d"]);
6551
    // The other: d goes, comes back, and x moves into it too.
6552
    git(&["checkout", "-q", "main"]);
6553
    git(&["rm", "-q", "d/a.txt"]);
6554
    git(&["commit", "-qm", "d goes"]);
6555
    write(&g, "d/b.txt", b"b\n");
6556
    git(&["add", "."]);
6557
    git(&["commit", "-qm", "d comes back"]);
6558
    git(&["mv", "c/x.txt", "d/x.txt"]);
6559
    git(&["commit", "-qm", "x into d again"]);
6560
    git(&["merge", "-q", "--no-edit", "side"]);
6561
6562
    let repo = Repo::init(&root.join("o")).unwrap();
6563
    repo.import_git(&g, "main").unwrap();
6564
    let v = repo.verify_git_import(&g, "main").unwrap();
6565
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6566
    let st = repo
6567
        .load_state_history(&repo.bookmark_heads().unwrap())
6568
        .unwrap();
6569
    let view = st.tree().view();
6570
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6571
    // The directory is the one the first commit made.
6572
    // Commits made in one second tie on time: find the first by its message.
6573
    let first = repo
6574
        .log()
6575
        .unwrap()
6576
        .into_iter()
6577
        .find(|e| e.change.message.starts_with("base"))
6578
        .unwrap();
6579
    let base = repo
6580
        .load_state_history(&[first.hash])
6581
        .unwrap()
6582
        .tree()
6583
        .view();
6584
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6585
}
6586
6587
/// oxygen#30, the rest: a placement left under a directory another line
6588
/// removed is out of sight, so no diff reaches it; the merge that settles
6589
/// where the file is retires it.
6590
#[test]
6591
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6592
    hermetic();
6593
    if std::process::Command::new("git")
6594
        .arg("--version")
6595
        .output()
6596
        .is_err()
6597
    {
6598
        eprintln!("git not installed; skipping");
6599
        return;
6600
    }
6601
    let dir = tempfile::tempdir().unwrap();
6602
    let root = dir.path();
6603
    let g = root.join("src.git");
6604
    fs::create_dir_all(&g).unwrap();
6605
    let run = |args: &[&str]| {
6606
        std::process::Command::new("git")
6607
            .arg("-C")
6608
            .arg(&g)
6609
            .args([
6610
                "-c",
6611
                "user.name=Grace",
6612
                "-c",
6613
                "[email protected]",
6614
                "-c",
6615
                "commit.gpgsign=false",
6616
            ])
6617
            .args(args)
6618
            .output()
6619
            .unwrap()
6620
    };
6621
    let git = |args: &[&str]| {
6622
        let out = run(args);
6623
        assert!(
6624
            out.status.success(),
6625
            "git {args:?}: {}",
6626
            String::from_utf8_lossy(&out.stderr)
6627
        );
6628
    };
6629
    git(&["init", "-q", "-b", "main"]);
6630
    write(&g, "c/x.txt", b"x\n");
6631
    write(&g, "keep.txt", b"k\n");
6632
    git(&["add", "."]);
6633
    git(&["commit", "-qm", "base"]);
6634
    // One line renames the file within c; the other moves it out of c,
6635
    // which goes.
6636
    git(&["checkout", "-qb", "side"]);
6637
    git(&["mv", "c/x.txt", "c/y.txt"]);
6638
    git(&["commit", "-qm", "rename within c"]);
6639
    git(&["checkout", "-q", "main"]);
6640
    fs::create_dir_all(g.join("n")).unwrap();
6641
    git(&["mv", "c/x.txt", "n/x.txt"]);
6642
    git(&["commit", "-qm", "move out of c"]);
6643
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6644
    let _ = run(&["merge", "-q", "side"]);
6645
    let _ = run(&[
6646
        "rm",
6647
        "-q",
6648
        "--cached",
6649
        "--ignore-unmatch",
6650
        "c/y.txt",
6651
        "c/x.txt",
6652
    ]);
6653
    let _ = std::fs::remove_dir_all(g.join("c"));
6654
    write(&g, "n/x.txt", b"x\n");
6655
    git(&["add", "-A"]);
6656
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6657
6658
    let repo = Repo::init(&root.join("o")).unwrap();
6659
    repo.import_git(&g, "main").unwrap();
6660
    let v = repo.verify_git_import(&g, "main").unwrap();
6661
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6662
    let st = repo
6663
        .load_state_history(&repo.bookmark_heads().unwrap())
6664
        .unwrap();
6665
    let view = st.tree().view();
6666
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6667
    assert!(view.entries.contains_key("n/x.txt"));
6668
}
6669
6670
/// oxygen#30, orphans: a file added on one line into a directory the other
6671
/// line removed is placed where the tree cannot show it; Git's merge keeps
6672
/// the file, and the import's merge leaves exactly one of it.
6673
#[test]
6674
fn git_import_merge_leaves_no_orphan_behind() {
6675
    hermetic();
6676
    if std::process::Command::new("git")
6677
        .arg("--version")
6678
        .output()
6679
        .is_err()
6680
    {
6681
        eprintln!("git not installed; skipping");
6682
        return;
6683
    }
6684
    let dir = tempfile::tempdir().unwrap();
6685
    let root = dir.path();
6686
    let g = root.join("src.git");
6687
    fs::create_dir_all(&g).unwrap();
6688
    let git = |args: &[&str]| {
6689
        let out = std::process::Command::new("git")
6690
            .arg("-C")
6691
            .arg(&g)
6692
            .args([
6693
                "-c",
6694
                "user.name=Grace",
6695
                "-c",
6696
                "[email protected]",
6697
                "-c",
6698
                "commit.gpgsign=false",
6699
            ])
6700
            .args(args)
6701
            .output()
6702
            .unwrap();
6703
        assert!(
6704
            out.status.success(),
6705
            "git {args:?}: {}",
6706
            String::from_utf8_lossy(&out.stderr)
6707
        );
6708
    };
6709
    git(&["init", "-q", "-b", "main"]);
6710
    write(&g, "d/f.txt", b"f\n");
6711
    write(&g, "keep.txt", b"k\n");
6712
    git(&["add", "."]);
6713
    git(&["commit", "-qm", "base"]);
6714
    git(&["checkout", "-qb", "side"]);
6715
    write(&g, "d/new.txt", b"new\n");
6716
    git(&["add", "."]);
6717
    git(&["commit", "-qm", "add into d"]);
6718
    git(&["checkout", "-q", "main"]);
6719
    git(&["rm", "-q", "d/f.txt"]);
6720
    git(&["commit", "-qm", "d goes"]);
6721
    git(&["merge", "-q", "--no-edit", "side"]);
6722
6723
    let repo = Repo::init(&root.join("o")).unwrap();
6724
    repo.import_git(&g, "main").unwrap();
6725
    let v = repo.verify_git_import(&g, "main").unwrap();
6726
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6727
    let st = repo
6728
        .load_state_history(&repo.bookmark_heads().unwrap())
6729
        .unwrap();
6730
    let view = st.tree().view();
6731
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6732
    assert!(view.entries.contains_key("d/new.txt"));
6733
}
d77e1702 Andy McCall ↶ 6734
6735
/// fsck checks a change's text as the blobs it is stored in, without
6736
/// decoding it: a missing text blob is an error named for the change.
6737
#[test]
6738
fn fsck_names_a_missing_text_blob() {
6739
    hermetic();
6740
    let dir = tempfile::tempdir().unwrap();
6741
    let root = dir.path();
6742
    let repo = Repo::init(root).unwrap();
6743
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6744
    write(root, "big.txt", big.as_bytes());
6745
    let h = repo.commit("big", &[]).unwrap();
6746
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6747
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6748
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6749
        panic!("a stored text")
6750
    };
64818938 Andy McCall ↶ 6751
    repo.store().remove_loose_for_test(&b).unwrap();
d77e1702 Andy McCall ↶ 6752
    let rep = repo.fsck().unwrap();
6753
    assert!(rep.errors() > 0);
6754
    assert!(
6755
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6756
        "{:?}",
6757
        rep.problems
6758
    );
6759
}
a07f60a3 Andy McCall ↶ 6760
6761
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6762
/// reached with that remote's token and CA (a private subrepo then clones
6763
/// for anyone who can read the parent); another hub gets none of them.
6764
#[test]
6765
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6766
    hermetic();
6767
    let dir = tempfile::tempdir().unwrap();
6768
    let mut repo = Repo::init(dir.path()).unwrap();
6769
    repo.config
6770
        .set(
6771
            "remote.origin.url",
6772
            "https://Hub.example:7343/doomsdayone/metalgear",
6773
        )
6774
        .unwrap();
6775
    repo.config.set("remote.origin.token", "secret").unwrap();
6776
    repo.config
6777
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6778
        .unwrap();
6779
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6780
    assert_eq!(same.token.as_deref(), Some("secret"));
6781
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6782
    for other in [
6783
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6784
        "https://hub.example/doomsdayone/rstar-api",
6785
        "http://hub.example:7343/doomsdayone/rstar-api",
6786
    ] {
6787
        let o = repo.credentials_for(other);
6788
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6789
    }
6790
}
ce14f0d6 Andy McCall ↶ 6791
ff1f62fe Andy McCall ↶ 6792
/// oxygen#47: a remote with no token of its own uses the user's credential
6793
/// store for its hub, and a nested checkout finds its parent's remote
6794
/// token there instead of keeping a copy.
ce14f0d6 Andy McCall ↶ 6795
#[test]
ff1f62fe Andy McCall ↶ 6796
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
6797
    hermetic();
6798
    let home = tempfile::tempdir().unwrap();
6799
    let dir = tempfile::tempdir().unwrap();
6800
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
6801
    parent
6802
        .config
6803
        .set("remote.origin.url", "https://hub.example/o/parent")
6804
        .unwrap();
6805
    parent.save_config().unwrap();
6806
    assert_eq!(parent.remote_options("origin").token, None);
6807
    crate::credentials::Credentials::at(home.path())
6808
        .save("https://hub.example", "stored", Some("andy"), None)
6809
        .unwrap();
6810
    assert_eq!(
6811
        parent.remote_options("origin").token.as_deref(),
6812
        Some("stored")
6813
    );
6814
6815
    let empty_home = tempfile::tempdir().unwrap();
6816
    let nested = dir.path().join("deps").join("child");
6817
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
6818
    child
6819
        .config
6820
        .set("remote.origin.url", "https://hub.example/o/child")
6821
        .unwrap();
6822
    child.save_config().unwrap();
6823
    assert_eq!(child.remote_options("origin").token, None);
6824
    parent
6825
        .config
6826
        .set("remote.origin.token", "checkout")
6827
        .unwrap();
6828
    parent.save_config().unwrap();
6829
    assert_eq!(
6830
        child.remote_options("origin").token.as_deref(),
6831
        Some("checkout")
6832
    );
6833
    // Another hub's checkout token is not borrowed.
6834
    child
6835
        .config
6836
        .set("remote.origin.url", "https://other.example/o/child")
6837
        .unwrap();
6838
    assert_eq!(child.remote_options("origin").token, None);
6839
}
6840
6841
#[test]
ce14f0d6 Andy McCall ↶ 6842
fn the_metadata_cache_survives_a_torn_tail() {
6843
    hermetic();
6844
    let dir = tempfile::tempdir().unwrap();
6845
    let root = dir.path();
6846
    let repo = Repo::init(root).unwrap();
6847
    write(root, "a.txt", b"1\n");
6848
    let h = repo.commit("first", &[]).unwrap();
6849
    let meta = repo.store().get_change_meta(&h).unwrap();
6850
    let cache = repo.store().dir().join("metas");
6851
    let len = fs::metadata(&cache).unwrap().len();
6852
    assert!(len > 0, "a change read is cached");
6853
    // A torn record at the end: the cache reads up to it and cuts it off.
6854
    fs::OpenOptions::new()
6855
        .append(true)
6856
        .open(&cache)
6857
        .unwrap()
6858
        .write_all(&[7; 20])
6859
        .unwrap();
6860
    let again = Repo::open(root).unwrap();
6861
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
6862
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
6863
}
f9466021 Andy McCall ↶ 6864
6865
#[test]
6866
fn a_manifest_that_does_not_check_reads_as_none() {
6867
    hermetic();
6868
    let dir = tempfile::tempdir().unwrap();
6869
    let root = dir.path();
6870
    let repo = Repo::init(root).unwrap();
6871
    write(root, "a.txt", b"1\n");
6872
    repo.commit("first", &[]).unwrap();
6873
    let path = repo.manifest_path();
6874
    let mut bytes = fs::read(&path).unwrap();
6875
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
6876
    let last = bytes.len() - 1;
6877
    bytes[last] ^= 1;
6878
    fs::write(&path, &bytes).unwrap();
6879
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
6880
    // The next status reads the files and writes it again.
6881
    let again = Repo::open(root).unwrap();
6882
    assert!(!again.snapshot("status").unwrap().changed);
6883
    assert!(again.read_manifest().unwrap().is_some());
6884
}
6885
6886
#[test]
6887
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
6888
    hermetic();
6889
    let dir = tempfile::tempdir().unwrap();
6890
    let root = dir.path();
6891
    let repo = Repo::init(root).unwrap();
6892
    write(root, "a.txt", b"1\n");
6893
    write(root, "b.txt", b"2\n");
6894
    // b.txt outside the racy window, so snapshots take it as unchanged.
6895
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6896
    fs::File::options()
6897
        .write(true)
6898
        .open(root.join("b.txt"))
6899
        .unwrap()
6900
        .set_modified(old)
6901
        .unwrap();
6902
    repo.commit("first", &[]).unwrap();
6903
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
6904
    repo.snapshot_status("status").unwrap();
6905
    write(root, "a.txt", b"1\n2\n");
6906
    repo.commit("second", &[]).unwrap();
6907
    assert!(
6908
        repo.clean_by_manifest().unwrap(),
6909
        "after a commit of one file"
6910
    );
6911
    // Edited, seen by a status, edited again, then committed: the status
6912
    // left the first edit's stat, which the commit must not keep.
6913
    write(root, "a.txt", b"1\n2\n3\n");
6914
    repo.snapshot_status("status").unwrap();
6915
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
6916
    repo.commit("third", &[]).unwrap();
6917
    assert!(
6918
        repo.clean_by_manifest().unwrap(),
6919
        "after an edit a status saw"
6920
    );
6921
}
e266b7d4 Andy McCall ↶ 6922
6923
#[test]
6924
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
6925
    hermetic();
6926
    let dir = tempfile::tempdir().unwrap();
6927
    let root = dir.path();
6928
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6929
    write(root, "a.txt", b"1\n2\n");
6930
    let a = repo.commit("A", &[]).unwrap();
6931
    repo.bookmark_create("develop", Some(&[a])).unwrap();
6932
    write(root, "a.txt", b"1\nX\n");
6933
    let c = repo.commit("C: 2 to X", &[]).unwrap();
6934
    repo.bookmark_switch("develop", false).unwrap();
6935
    write(root, "a.txt", b"1\nY\n");
6936
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
6937
    repo.bookmark_switch("main", false).unwrap();
6938
6939
    let err = repo.rebase(&c, &[d]).unwrap_err();
6940
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
6941
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
6942
    assert!(r.changed && r.checked_out);
6943
    let snap = repo.snapshot_status("status").unwrap();
6944
    assert!(
6945
        snap.base_snapshot.is_conflicted(),
6946
        "the conflict is in the working copy"
6947
    );
6948
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
6949
    assert!(text.contains('X') && text.contains('Y'), "{text}");
6950
6951
    write(root, "a.txt", b"1\nXY\n");
6952
    repo.commit("Resolve", &[]).unwrap();
6953
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
6954
    assert!(st.contains(&c) && st.contains(&d));
6955
    let files = st.materialize().files;
6956
    assert!(!files["a.txt"].is_conflicted());
6957
    assert!(
6958
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
6959
    );
6960
6961
    // A change the current bookmark does not hold is refused.
6962
    repo.bookmark_switch("develop", false).unwrap();
6963
    write(root, "b.txt", b"b\n");
6964
    let e = repo.commit("E", &[]).unwrap();
6965
    repo.bookmark_switch("main", false).unwrap();
6966
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
6967
    assert!(
6968
        err.to_string().contains("not on the current bookmark"),
6969
        "{err}"
6970
    );
6971
}
d4dbab97 Andy McCall ↶ 6972
6973
#[test]
6974
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
6975
    hermetic();
6976
    let dir = tempfile::tempdir().unwrap();
6977
    let root = dir.path();
6978
    let repo = Repo::init(root).unwrap();
6979
    write(root, "a.txt", b"a\n");
6980
    write(root, "kept.log", b"tracked\n");
6981
    repo.commit("first", &[]).unwrap();
6982
    write(root, "build.log", b"made\n");
6983
    let snap = repo.snapshot_status("status").unwrap();
6984
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
6985
    // A rule written afterwards leaves the added file out again, while the
6986
    // committed one stays tracked.
6987
    write(root, ".gitignore", b"*.log\n");
6988
    let snap = repo.snapshot_status("status").unwrap();
6989
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
6990
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
6991
    write(root, "kept.log", b"tracked, edited\n");
6992
    let snap = repo.snapshot_status("status").unwrap();
6993
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
6994
}
fd280228 Andy McCall ↶ 6995
6996
#[test]
6997
fn shed_graphs_come_back_the_same() {
6998
    hermetic();
6999
    let dir = tempfile::tempdir().unwrap();
7000
    let root = dir.path();
7001
    let repo = Repo::init(root).unwrap();
7002
    write(root, "a.txt", b"1\n2\n3\n");
7003
    write(root, "b.txt", b"x\n");
7004
    repo.commit("first", &[]).unwrap();
7005
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7006
    repo.commit("second", &[]).unwrap();
7007
    let heads = repo.bookmark_heads().unwrap();
7008
    let mut st = repo.load_state_history(&heads).unwrap();
7009
    let view = st.tree().view();
7010
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7011
        .iter()
7012
        .map(|p| view.entries[*p].node)
7013
        .collect();
7014
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7015
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7016
    assert_eq!(st.built_count(), 2);
7017
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7018
    assert_eq!((shed, st.built_count()), (2, 0));
7019
    // A later change applies on top of the shed history.
7020
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7021
    let h3 = repo.commit("third", &[]).unwrap();
7022
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7023
    st.add_known(h3, skeleton, texts);
7024
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7025
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7026
    assert_eq!(after[1], before[1]);
7027
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7028
}
360aa74a Andy McCall ↶ 7029
7030
#[test]
7031
fn many_edited_files_diff_in_parallel() {
7032
    // Enough edited files that the builder diffs them in parallel; the
7033
    // commit must hold exactly what is on disk, and a second snapshot
7034
    // must find nothing left to commit.
7035
    hermetic();
7036
    let dir = tempfile::tempdir().unwrap();
7037
    let root = dir.path();
7038
    let repo = Repo::init(root).unwrap();
7039
    let text = |i: usize, round: usize| {
7040
        let mut s = String::new();
7041
        for line in 0..50 {
7042
            if round > 0 && line % 7 == i % 7 {
7043
                s.push_str(&format!("edited {round} {i} {line}\n"));
7044
            } else {
7045
                s.push_str(&format!("file {i} line {line}\n"));
7046
            }
7047
        }
7048
        if round > 0 && i.is_multiple_of(3) {
7049
            s.push_str("appended\n");
7050
        }
7051
        s
7052
    };
7053
    for i in 0..40 {
7054
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7055
    }
7056
    repo.commit("first", &[]).unwrap();
7057
    for i in 0..40 {
7058
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7059
    }
7060
    let h = repo.commit("edit every file", &[]).unwrap();
7061
    let snap = repo.load_state(&[h]).unwrap().materialize();
7062
    for i in 0..40 {
7063
        let want = text(i, 1);
7064
        assert!(
7065
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
7066
            "d/f{i}.txt as committed"
7067
        );
7068
    }
7069
    assert!(
7070
        repo.commit("nothing", &[]).is_err(),
7071
        "nothing left to commit"
7072
    );
7073
}
b35df36b Andy McCall ↶ 7074
7075
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7076
/// is known (fetch printed "up to date" while main was behind), a change
7077
/// only fetched resolves and says where it is, and a checkout whose only
7078
/// remote is not `origin` uses that one.
7079
#[test]
7080
fn a_fetched_change_shows_as_behind_and_resolves() {
7081
    hermetic();
7082
    let dir = tempfile::tempdir().unwrap();
7083
    let root = dir.path();
7084
    let origin = Repo::init(&root.join("origin")).unwrap();
7085
    drop(origin);
7086
    let url = root.join("origin").to_string_lossy().to_string();
7087
    let a = Repo::clone(&url, &root.join("a"))
7088
        .unwrap()
7089
        .with_home(root.join("home-a"));
7090
    write(&root.join("a"), "f.txt", b"one\n");
7091
    a.commit("one", &[]).unwrap();
7092
    a.push("origin", false).unwrap();
7093
    let b = Repo::clone(&url, &root.join("b"))
7094
        .unwrap()
7095
        .with_home(root.join("home-b"));
7096
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7097
7098
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7099
    let h2 = a.commit("two", &[]).unwrap();
7100
    a.push("origin", false).unwrap();
7101
    b.fetch("origin").unwrap();
7102
    // Fetched, not pulled: one behind, the change found and placed.
7103
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7104
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7105
    assert_eq!(
7106
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7107
            .unwrap(),
7108
        h2
7109
    );
7110
    assert_eq!(
7111
        b.remote_only_location(&h2).unwrap().as_deref(),
7112
        Some("origin/main")
7113
    );
7114
    // Fetching again changes nothing: still behind, which is what the
7115
    // CLI now says rather than "up to date".
7116
    b.fetch("origin").unwrap();
7117
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7118
    b.pull("origin").unwrap();
7119
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7120
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7121
7122
    // One remote, not called origin: it is the default.
7123
    let mut c = Repo::init(&root.join("c")).unwrap();
7124
    assert_eq!(c.default_remote(), "origin");
7125
    c.config.set("remote.earth.url", &url).unwrap();
7126
    assert_eq!(c.default_remote(), "earth");
7127
    c.config.set("remote.origin.url", &url).unwrap();
7128
    assert_eq!(c.default_remote(), "origin");
7129
}
827281ee Andy McCall ↶ 7130
7131
/// oxygen#57: a clone from a relative local path records the remote as an
7132
/// absolute path, so fetch still finds it from inside the clone.
7133
#[test]
7134
fn a_clone_from_a_relative_path_records_it_absolute() {
7135
    hermetic();
7136
    let dir = tempfile::tempdir().unwrap();
7137
    let root = dir.path();
7138
    Repo::init(&root.join("origin")).unwrap();
7139
    let rel = crate::protocol::stored_url("relative/repo");
7140
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7141
    assert_eq!(
7142
        crate::protocol::stored_url("https://hub.example/o/n"),
7143
        "https://hub.example/o/n"
7144
    );
7145
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8d803563 Andy McCall ↶ 7146
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7147
    // A bucket is kept as written: it is not a path.
7148
    assert_eq!(
7149
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7150
        "s3://bucket/prefix?profile=p"
7151
    );
827281ee Andy McCall ↶ 7152
    let url = root.join("origin").to_string_lossy().to_string();
7153
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7154
    assert_eq!(b.config.remotes["origin"], url);
7155
    b.fetch("origin").unwrap();
7156
}
a46f3e4f Andy McCall ↶ 7157
7158
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7159
/// and gets its subrepos at their pins from this workspace's copies, with
7160
/// their remotes pointing where the subrepos come from.
7161
#[test]
7162
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7163
    hermetic();
7164
    let dir = tempfile::tempdir().unwrap();
7165
    let root = dir.path();
7166
    Repo::init(&root.join("lib-origin")).unwrap();
7167
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7168
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7169
        .unwrap()
7170
        .with_home(root.join("home"));
7171
    write(&root.join("lib"), "lib.txt", b"v1\n");
7172
    let l1 = lib.commit("lib v1", &[]).unwrap();
7173
    assert!(lib.push("origin", false).unwrap()[0].ok);
7174
7175
    let app_dir = root.join("app");
7176
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7177
    write(&app_dir, "main.txt", b"app\n");
7178
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7179
    app.commit("app with lib", &[]).unwrap();
7180
    // A second bookmark, and the main workspace on another.
7181
    app.bookmark_create("develop", None).unwrap();
7182
    app.bookmark_create("feature", None).unwrap();
7183
    let mut app = app;
7184
    app.bookmark_switch("feature", false).unwrap();
7185
    assert_eq!(app.config.bookmark, "feature");
7186
7187
    // The library's origin goes away: the subrepo must come from here.
7188
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7189
    let heads = app.resolve_heads("develop").unwrap();
7190
    let ws = app
7191
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7192
        .unwrap();
7193
    assert_eq!(
7194
        ws.config.bookmark, "develop",
7195
        "the new workspace is on develop"
7196
    );
7197
    assert_eq!(
7198
        app.config.bookmark, "feature",
7199
        "and this one stays on its own"
7200
    );
7201
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7202
    assert_eq!(
7203
        sub.config.remotes["origin"], lib_url,
7204
        "its origin is the subrepo's URL"
7205
    );
7206
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7207
    assert_eq!(
7208
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7209
        b"v1\n"
7210
    );
7211
}
47ce8b8e Andy McCall ↶ 7212
7213
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7214
/// operators and the predicates, over a small graph with two heads and
7215
/// a rename.
7216
#[test]
7217
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7218
    hermetic();
7219
    let dir = tempfile::tempdir().unwrap();
7220
    let root = dir.path();
7221
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7222
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7223
        .unwrap();
7224
    write(root, "src/a.rs", b"one\n");
7225
    let a = repo.commit("first: add a", &[]).unwrap();
7226
    write(root, "src/a.rs", b"one\ntwo\n");
7227
    let b = repo.commit("second: grow a", &[]).unwrap();
7228
    // A second head, independent of b: a new file on top of a.
7229
    repo.checkout(&[a], false, "checkout a").unwrap();
7230
    write(root, "docs/notes.md", b"notes\n");
7231
    let c = repo.commit("third: notes", &[]).unwrap();
7232
    // Back to both heads, then rename a.rs: the node keeps its identity.
7233
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7234
        .unwrap();
7235
    fs::remove_file(root.join("src/a.rs")).unwrap();
7236
    write(root, "src/z.rs", b"one\ntwo\n");
7237
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7238
    let wc = repo.working_copy().unwrap().0;
7239
    // A saved revset is checked when set.
7240
    repo.set_user_config("revset.mine", "author(me) & ::main")
7241
        .unwrap();
7242
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7243
    let set = |src: &str| -> Vec<ChangeHash> {
7244
        let mut v = repo.revset(src).unwrap().hashes;
7245
        v.sort();
7246
        v
7247
    };
7248
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7249
        let mut v = hs.to_vec();
7250
        v.sort();
7251
        v
7252
    };
7253
7254
    // Changes commute: a new file depends on nothing and the rename on the
7255
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7256
    // copy on the three heads b, c, d.
7257
    let heads = sorted(&repo.bookmark_heads().unwrap());
7258
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7259
    assert!(heads.contains(&d) && heads.contains(&c));
7260
    // Symbols and closures.
7261
    assert_eq!(set("main"), heads);
7262
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7263
    assert_eq!(set("@"), vec![wc]);
7264
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7265
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7266
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7267
    assert_eq!(
7268
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7269
        sorted(&[a, b])
7270
    );
7271
    // Ranges: what main has beyond b, and `..` forms.
7272
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7273
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7274
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7275
    // Operators and precedence: ~ binds tighter than &, & than |.
7276
    assert_eq!(
7277
        set(&format!("::main ~ #{}", d.short(12))),
7278
        sorted(&[a, b, c])
7279
    );
7280
    assert_eq!(
7281
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7282
        sorted(&[b, c])
7283
    );
7284
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7285
    // Relations.
7286
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7287
    head_deps.sort();
7288
    head_deps.dedup();
7289
    assert_eq!(set("deps(main)"), head_deps);
7290
    let on_a: Vec<ChangeHash> = [b, c, d]
7291
        .into_iter()
7292
        .filter(|h| meta(h).deps.contains(&a))
7293
        .collect();
7294
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7295
    assert_eq!(set("heads(::main)"), heads);
7296
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7297
    assert_eq!(
7298
        set(&format!(
7299
            "heads(#{} | #{} | #{})",
7300
            a.short(12),
7301
            b.short(12),
7302
            c.short(12)
7303
        )),
7304
        sorted(&[b, c])
7305
    );
7306
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7307
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7308
    assert_eq!(set("none()"), vec![]);
7309
    // Predicates: author by name, email, key prefix and `me`.
7310
    let key = repo.config.author_key.unwrap();
7311
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7312
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7313
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7314
    assert_eq!(set("author(me) & ::main").len(), 4);
7315
    assert_eq!(set("author(nobody)"), vec![]);
7316
    assert_eq!(set("description(notes)"), vec![c]);
7317
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7318
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7319
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7320
    // touches follows the node through the rename, in the current state.
7321
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7322
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7323
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7324
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7325
    // Newest first in the result order.
7326
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7327
    // The saved revset, and errors that say what is wrong.
7328
    assert_eq!(set("mine()").len(), 4);
7329
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7330
    assert!(e.contains("unknown function nosuch()"), "{e}");
7331
    let e = repo.revset("main &").unwrap_err().to_string();
7332
    assert!(e.contains("at character"), "{e}");
7333
    let e = repo.revset("zzzz").unwrap_err().to_string();
7334
    assert!(e.contains("no change matches"), "{e}");
7335
    let e = repo
7336
        .revset_with_budget("::main", std::time::Duration::ZERO)
7337
        .unwrap_err()
7338
        .to_string();
7339
    assert!(e.contains("budget"), "{e}");
7340
    // The log entries carry the bookmark's heads and the working copy.
7341
    let entries = repo.log_revset("::@").unwrap();
7342
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
2c9ddac3 Andy McCall ↶ 7343
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7344
    // push); then a signed change, a tag, and a revocation.
7345
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7346
    assert_eq!(set("signed_by(me)"), vec![]);
7347
    repo.sign_change(&d).unwrap();
7348
    assert_eq!(set("signed_by(me)"), vec![d]);
7349
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7350
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7351
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7352
    assert_eq!(set("delegated()"), vec![]);
7353
    assert_eq!(set("revoked()"), vec![]);
7354
    assert_eq!(set("attested(tag)"), vec![]);
7355
    repo.tag_create("v1", &[b], "first").unwrap();
7356
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7357
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7358
    assert_eq!(set("attested(receipt)"), vec![]);
7359
    assert_eq!(set("built(test)"), vec![]);
7360
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7361
    assert!(e.contains("tag, receipt or ref"), "{e}");
7362
    repo.revoke_identity(&key, "test").unwrap();
7363
    assert_eq!(set("revoked()"), vec![d]);
7364
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
543bbf64 Andy McCall ↶ 7365
    // independent(X, IN): what could ship without X. c and d neither
7366
    // depend on b nor are depended on by it; a is below, the working copy
7367
    // above.
7368
    assert_eq!(
7369
        set(&format!("independent(#{}, ::@)", b.short(12))),
7370
        sorted(&[c, d])
7371
    );
7372
    assert_eq!(
7373
        set(&format!("independent(#{}, ::main)", a.short(12))),
7374
        vec![c]
7375
    );
7376
    // conflicts(S): nothing conflicts yet; then two edits of one line.
7377
    assert_eq!(set("conflicts()"), vec![]);
7378
    assert_eq!(set("conflicts(main)"), vec![]);
7379
    // (The saved revset above edited the user config under the root:
7380
    // discard it.)
7381
    repo.checkout(&[a], true, "checkout a").unwrap();
7382
    write(root, "src/a.rs", b"one\nTWO\n");
7383
    let e = repo
7384
        .commit("fifth: the other edit of line two", &[])
7385
        .unwrap();
7386
    repo.checkout(&repo.bookmark_heads().unwrap(), true, "checkout main")
7387
        .unwrap();
7388
    let conflicted = repo.revset("conflicts()").unwrap().hashes;
7389
    assert!(
7390
        conflicted.contains(&e) && conflicted.contains(&b),
7391
        "{conflicted:?} should hold b and e"
7392
    );
7393
    assert!(!conflicted.contains(&c));
7394
    assert_eq!(set("conflicts() & author(nobody)"), vec![]);
47ce8b8e Andy McCall ↶ 7395
}
614f55e1 Andy McCall ↶ 7396
7397
#[test]
7398
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7399
    let dir = tempfile::tempdir().unwrap();
7400
    let root = dir.path();
7401
    let home = root.join("home");
7402
    // Ada's identity lives in the user file; repository `a` pins the same
7403
    // key in its own file, repository `b` names none.
7404
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7405
    let (key, _) = a
7406
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7407
        .unwrap();
7408
    a.config.set("author.key", &key.to_hex()).unwrap();
7409
    a.save_config().unwrap();
7410
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7411
    let r = a
7412
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7413
        .unwrap();
7414
    assert_eq!(
7415
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7416
        r.new.to_hex(),
7417
        "the user file follows"
7418
    );
7419
    assert_eq!(
7420
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7421
        r.new.to_hex(),
7422
        "the pinning repository follows"
7423
    );
7424
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7425
    assert_eq!(
7426
        b.config.author_key,
7427
        Some(r.new),
7428
        "a checkout without a pin follows the user file"
7429
    );
7430
    // A repository-scoped identity leaves the user file alone.
7431
    let other_home = root.join("home2");
7432
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7433
    let (ck, _) = c
7434
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7435
        .unwrap();
7436
    assert!(!other_home.join("config.toml").exists());
7437
    let r2 = c.rotate_identity().unwrap();
7438
    assert_ne!(r2.new, ck);
7439
    assert_eq!(
7440
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7441
        r2.new.to_hex()
7442
    );
7443
    assert!(
7444
        !other_home.join("config.toml").exists(),
7445
        "a repository-scoped identity stays repository-scoped"
7446
    );
7447
    // Several delegates in one rotation; a repeat is refused.
7448
    let (d1, d2) = (
7449
        SecretKey::generate().identity("D1", "d1@x", 1),
7450
        SecretKey::generate().identity("D2", "d2@x", 1),
7451
    );
7452
    let r3 = c
7453
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7454
        .unwrap();
7455
    assert_eq!(r3.identity.delegates.len(), 2);
7456
    assert!(c
7457
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7458
        .is_err());
7459
}
33be2409 Andy McCall ↶ 7460
7461
/// Two unrelated histories that both add the same file, joined by two
7462
/// independent merges on two branches, then those branches merged: Git
7463
/// merges identical additions cleanly, and the import must too (#71,
7464
/// found in VS Code's history).
7465
#[test]
7466
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7467
    // Batches of one: every merge renders apart from the state, where a
7468
    // file whose graph the state had built came out empty (#71).
7469
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7470
    hermetic();
7471
    if std::process::Command::new("git")
7472
        .arg("--version")
7473
        .output()
7474
        .is_err()
7475
    {
7476
        eprintln!("git not installed; skipping");
7477
        return;
7478
    }
7479
    let dir = tempfile::tempdir().unwrap();
7480
    let root = dir.path();
7481
    let g = root.join("src.git");
7482
    fs::create_dir_all(&g).unwrap();
7483
    let git = |args: &[&str]| -> String {
7484
        let out = std::process::Command::new("git")
7485
            .arg("-C")
7486
            .arg(&g)
7487
            .args([
7488
                "-c",
7489
                "user.name=Grace",
7490
                "-c",
7491
                "[email protected]",
7492
                "-c",
7493
                "commit.gpgsign=false",
7494
            ])
7495
            .args(args)
7496
            .output()
7497
            .unwrap();
7498
        assert!(
7499
            out.status.success(),
7500
            "git {args:?}: {}",
7501
            String::from_utf8_lossy(&out.stderr)
7502
        );
7503
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7504
    };
7505
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7506
    // History A: main.
7507
    git(&["init", "-q", "-b", "main"]);
7508
    write(&g, "gulpfile.js", text);
7509
    write(&g, "a.txt", b"a\n");
7510
    git(&["add", "."]);
7511
    git(&["commit", "-q", "-m", "A root"]);
7512
    // History B: an unrelated root adding the same file, identical.
7513
    git(&["checkout", "-q", "--orphan", "fork"]);
7514
    git(&["rm", "-q", "-r", "--cached", "."]);
7515
    for f in ["gulpfile.js", "a.txt"] {
7516
        let _ = fs::remove_file(g.join(f));
7517
    }
7518
    write(&g, "gulpfile.js", text);
7519
    write(&g, "b.txt", b"b\n");
7520
    git(&["add", "."]);
7521
    git(&["commit", "-q", "-m", "B root"]);
7522
    // Two branches from main, each joining B on its own.
7523
    git(&["checkout", "-q", "-b", "one", "main"]);
7524
    git(&[
7525
        "merge",
7526
        "-q",
7527
        "--no-ff",
7528
        "--allow-unrelated-histories",
7529
        "-m",
7530
        "join on one",
7531
        "fork",
7532
    ]);
7533
    git(&["checkout", "-q", "-b", "two", "main"]);
7534
    write(&g, "a.txt", b"a\ntwo\n");
7535
    git(&["commit", "-q", "-am", "work on two"]);
7536
    git(&[
7537
        "merge",
7538
        "-q",
7539
        "--no-ff",
7540
        "--allow-unrelated-histories",
7541
        "-m",
7542
        "join on two",
7543
        "fork",
7544
    ]);
7545
    // Then the two joins meet, and the file is reformatted after.
7546
    git(&["checkout", "-q", "main"]);
7547
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7548
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7549
    write(
7550
        &g,
7551
        "gulpfile.js",
7552
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7553
    );
7554
    git(&["commit", "-q", "-am", "after"]);
7555
7556
    let dest = root.join("dest");
7557
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7558
    repo.import_git(&g, "main").unwrap();
7559
    let v = repo.verify_git_import(&g, "main").unwrap();
7560
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7561
    assert_eq!(
7562
        fs::read(dest.join("gulpfile.js")).unwrap(),
7563
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7564
    );
7565
}
7566
7567
/// As above, but the two joins keep different copies (each branch had a
7568
/// different version when it joined), and later work edits each copy:
7569
/// the shape of VS Code's c67ef57cda90 (#71).
7570
#[test]
7571
fn git_import_joins_where_each_join_kept_a_different_copy() {
7572
    // Batches of one: every merge renders apart from the state, where a
7573
    // file whose graph the state had built came out empty (#71).
7574
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7575
    hermetic();
7576
    if std::process::Command::new("git")
7577
        .arg("--version")
7578
        .output()
7579
        .is_err()
7580
    {
7581
        eprintln!("git not installed; skipping");
7582
        return;
7583
    }
7584
    let dir = tempfile::tempdir().unwrap();
7585
    let root = dir.path();
7586
    let g = root.join("src.git");
7587
    fs::create_dir_all(&g).unwrap();
7588
    let run = |args: &[&str]| {
7589
        std::process::Command::new("git")
7590
            .arg("-C")
7591
            .arg(&g)
7592
            .args([
7593
                "-c",
7594
                "user.name=Grace",
7595
                "-c",
7596
                "[email protected]",
7597
                "-c",
7598
                "commit.gpgsign=false",
7599
            ])
7600
            .args(args)
7601
            .output()
7602
            .unwrap()
7603
    };
7604
    let git = |args: &[&str]| -> String {
7605
        let out = run(args);
7606
        assert!(
7607
            out.status.success(),
7608
            "git {args:?}: {}",
7609
            String::from_utf8_lossy(&out.stderr)
7610
        );
7611
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7612
    };
7613
    git(&["init", "-q", "-b", "main"]);
7614
    write(
7615
        &g,
7616
        "gulpfile.js",
7617
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7618
    );
7619
    git(&["add", "."]);
7620
    git(&["commit", "-q", "-m", "A root"]);
7621
    write(
7622
        &g,
7623
        "gulpfile.js",
7624
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7625
    );
7626
    git(&["commit", "-q", "-am", "whitespace"]);
7627
    git(&["checkout", "-q", "--orphan", "fork"]);
7628
    git(&["rm", "-q", "-r", "--cached", "."]);
7629
    let _ = fs::remove_file(g.join("gulpfile.js"));
7630
    write(
7631
        &g,
7632
        "gulpfile.js",
7633
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7634
    );
7635
    git(&["add", "."]);
7636
    git(&["commit", "-q", "-m", "B root"]);
7637
    // Branch one joins B keeping main's copy; branch two keeps B's.
7638
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7639
        git(&["checkout", "-q", "-b", branch, "main"]);
7640
        let _ = run(&[
7641
            "merge",
7642
            "-q",
7643
            "--no-ff",
7644
            "--allow-unrelated-histories",
7645
            "-m",
7646
            "join",
7647
            "fork",
7648
        ]);
7649
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7650
        git(&["add", "gulpfile.js"]);
7651
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7652
    }
7653
    // Each branch then edits its copy.
7654
    git(&["checkout", "-q", "one"]);
7655
    write(
7656
        &g,
7657
        "gulpfile.js",
7658
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7659
    );
7660
    git(&["commit", "-q", "-am", "tslint on one"]);
7661
    git(&["checkout", "-q", "two"]);
7662
    write(
7663
        &g,
7664
        "gulpfile.js",
7665
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7666
    );
7667
    write(&g, "extra.txt", b"x\n");
7668
    write(&g, "more.txt", b"m\n");
7669
    git(&["add", "."]);
7670
    git(&["commit", "-q", "-am", "fmt on two"]);
7671
    // They meet: resolved by hand.
7672
    git(&["checkout", "-q", "one"]);
7673
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7674
    write(
7675
        &g,
7676
        "gulpfile.js",
7677
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7678
    );
7679
    git(&["add", "gulpfile.js"]);
7680
    git(&["commit", "-q", "-m", "merge two into one"]);
7681
7682
    let dest = root.join("dest");
7683
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7684
    repo.import_git(&g, "one").unwrap();
7685
    let v = repo.verify_git_import(&g, "one").unwrap();
7686
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7687
}
dd21fd82 Andy McCall ↶ 7688
7689
/// oxygen#68: on a store that is not this disk's directory, the operation
7690
/// head is the store's reference record, moved by compare-and-swap. Two
7691
/// handles recording from the same head both get through, merged; a swap
7692
/// from a stale version is refused; a second repository cannot start on a
7693
/// store that already holds one.
7694
#[test]
7695
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
7696
    use crate::strata::{MemoryStore, Store as _};
7697
    let backend = std::sync::Arc::new(MemoryStore::new());
7698
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
7699
    let dir = tempfile::tempdir().unwrap();
7700
    let a = Repo::init(dir.path()).unwrap();
7701
    assert!(
7702
        !dir.path().join(".oxy/ops/head").exists(),
7703
        "the head is not a file"
7704
    );
7705
    let (h0, op0) = a.head_op().unwrap();
7706
    let record = backend
7707
        .read_ref(HEAD_RECORD)
7708
        .unwrap()
7709
        .expect("the head is the store's record");
7710
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
7711
7712
    let b = Repo::open(dir.path()).unwrap();
7713
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
7714
    let mut va = op0.view.clone();
7715
    va.bookmarks.insert("from-a".into(), state);
7716
    let mut vb = op0.view.clone();
7717
    vb.bookmarks.insert("from-b".into(), state);
7718
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
7719
    assert_eq!(b.head_ref().unwrap(), rb);
7720
    // a recorded from h0 too: the head moved, so the two are merged.
7721
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
7722
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
7723
    assert_eq!(head, ra);
7724
    assert!(
7725
        op.command.ends_with("(merged with a concurrent operation)"),
7726
        "{}",
7727
        op.command
7728
    );
7729
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
7730
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
7731
7732
    // A swap from a version that is no longer current moves nothing.
7733
    let (h, v) = a.read_head().unwrap();
7734
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
7735
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
7736
    assert_eq!(a.head_ref().unwrap(), rb);
7737
7738
    let other = tempfile::tempdir().unwrap();
7739
    let err = Repo::init(other.path())
7740
        .err()
7741
        .expect("the store already holds a log")
7742
        .to_string();
7743
    assert!(
7744
        err.contains("already holds a repository's operation log"),
7745
        "{err}"
7746
    );
7747
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
7748
}
d069701a Andy McCall ↶ 7749
7750
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
7751
/// objects and operation head there, with `.oxy/cache` in front: it works
7752
/// as one on disk does, reopens, and survives losing its cache.
7753
#[test]
7754
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
7755
    hermetic();
7756
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
7757
        return;
7758
    }
7759
    let dir = tempfile::tempdir().unwrap();
7760
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
7761
    let url = format!("dir://{}", bucket.display());
7762
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
7763
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
7764
    write(&root, "a.txt", b"one\n");
7765
    let h1 = repo.commit("First", &[]).unwrap();
7766
    write(&root, "a.txt", b"one\ntwo\n");
7767
    let h2 = repo.commit("Second", &[]).unwrap();
7768
    assert!(
7769
        !root.join(".oxy/ops/head").exists(),
7770
        "the head is in the store"
7771
    );
7772
    assert!(bucket.join("ops/head").is_file());
7773
    assert!(root.join(".oxy/cache").is_dir());
7774
    drop(repo);
7775
7776
    // Reopened, and again with no cache at all: everything comes from the store.
7777
    for drop_cache in [false, true] {
7778
        if drop_cache {
7779
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
7780
        }
7781
        let repo = Repo::open(&root).unwrap();
7782
        let log: Vec<String> = repo
7783
            .op_log()
7784
            .unwrap()
7785
            .into_iter()
7786
            .map(|(_, op)| op.command)
7787
            .collect();
7788
        assert!(log.len() >= 3, "{log:?}");
7789
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
7790
        let heads = repo
7791
            .store()
7792
            .get_state(&repo.view().unwrap().bookmarks["main"])
7793
            .unwrap()
7794
            .heads;
7795
        assert_eq!(heads, vec![h2]);
7796
        assert_eq!(
7797
            repo.load_state(&heads).unwrap().materialize().files.len(),
7798
            1
7799
        );
7800
    }
7801
7802
    // A second repository cannot start on the same store.
7803
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
7804
        .err()
7805
        .unwrap()
7806
        .to_string();
7807
    assert!(
7808
        err.contains("already holds a repository's operation log"),
7809
        "{err}"
7810
    );
7811
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
7812
        .err()
7813
        .unwrap()
7814
        .to_string();
7815
    assert!(err.contains("cannot open that kind of store"), "{err}");
7816
}
80677b7a Andy McCall ↶ 7817
7818
/// oxygen#75: the prompt's quick check agrees with status in a repository
7819
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
7820
/// another state, clean again once that pin is committed. (It compared the
7821
/// subrepo's directory as if it were a file, so it was always dirty.)
7822
#[test]
7823
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
7824
    hermetic();
7825
    let dir = tempfile::tempdir().unwrap();
7826
    let root = dir.path();
7827
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7828
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7829
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7830
        .unwrap()
7831
        .with_home(root.join("home"));
7832
    write(&root.join("lib"), "lib.txt", b"v1\n");
7833
    lib.commit("lib v1", &[]).unwrap();
7834
    assert!(lib.push("origin", false).unwrap()[0].ok);
7835
    let app_dir = root.join("app");
7836
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7837
    write(&app_dir, "main.txt", b"app\n");
7838
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7839
    app.commit("app with lib", &[]).unwrap();
7840
    // Out of the racy window, so the stat-only path decides.
7841
    std::thread::sleep(std::time::Duration::from_millis(2100));
7842
    let reopen = || Repo::open(&app_dir).unwrap();
7843
    assert_eq!(
7844
        reopen().quick_dirty().unwrap(),
7845
        Some(false),
7846
        "clean, as status says"
7847
    );
7848
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
7849
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
7850
    nested.commit("lib v2", &[]).unwrap();
7851
    assert_eq!(
7852
        reopen().quick_dirty().unwrap(),
7853
        Some(true),
7854
        "the subrepo moved"
7855
    );
7856
    reopen().commit("pin lib v2", &[]).unwrap();
7857
    std::thread::sleep(std::time::Duration::from_millis(2100));
7858
    assert_eq!(
7859
        reopen().quick_dirty().unwrap(),
7860
        Some(false),
7861
        "the new pin is committed"
7862
    );
7863
}
7993d465 Andy McCall ↶ 7864
7865
#[test]
7866
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
7867
    // oxygen#72: a .oxymodules section with no subrepo behind it.
7868
    hermetic();
7869
    let dir = tempfile::tempdir().unwrap();
7870
    let root = dir.path();
7871
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7872
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7873
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7874
        .unwrap()
7875
        .with_home(root.join("home"));
7876
    write(&root.join("lib"), "lib.txt", b"v1\n");
7877
    lib.commit("lib v1", &[]).unwrap();
7878
    assert!(lib.push("origin", false).unwrap()[0].ok);
7879
    let app_dir = root.join("app");
7880
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7881
    write(
7882
        &app_dir,
7883
        ".oxymodules",
7884
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
7885
    );
7886
    let unpinned = app.unpinned_modules().unwrap();
7887
    assert_eq!(unpinned.len(), 1);
7888
    assert_eq!(unpinned[0].0, "libs/lib");
7889
    assert_eq!(unpinned[0].1.url, lib_url);
7890
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
7891
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7892
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
7893
}
bf3a6781 Andy McCall ↶ 7894
7895
#[test]
7896
fn the_bookmark_revset_function_names_only_bookmarks() {
7897
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
7898
    hermetic();
7899
    let dir = tempfile::tempdir().unwrap();
7900
    let repo = Repo::init(dir.path()).unwrap();
7901
    write(dir.path(), "a.txt", b"a\n");
7902
    let a = repo.commit("A", &[]).unwrap();
7903
    write(dir.path(), "b.txt", b"b\n");
7904
    let b = repo.commit("B", &[]).unwrap();
7905
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
7906
    heads.sort();
7907
    let mut want = repo.bookmark_heads().unwrap();
7908
    want.sort();
7909
    assert_eq!(heads, want);
7910
    assert!(heads.contains(&b));
7911
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
7912
    // A change prefix is a symbol, not a bookmark.
7913
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
7914
    assert!(repo.revset(&prefix).is_ok());
7915
    let e = repo
7916
        .revset(&format!("bookmark({prefix})"))
7917
        .unwrap_err()
7918
        .to_string();
7919
    assert!(e.contains("no such bookmark"), "{e}");
7920
}
72484195 Andy McCall ↶ 7921
7922
#[test]
7923
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
7924
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
7925
    // pinning the subrepo, and the nested repository on disk at that pin.
7926
    hermetic();
7927
    let dir = tempfile::tempdir().unwrap();
7928
    let root = dir.path();
7929
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7930
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7931
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7932
        .unwrap()
7933
        .with_home(root.join("home"));
7934
    write(&root.join("lib"), "lib.txt", b"v1\n");
7935
    lib.commit("lib v1", &[]).unwrap();
7936
    assert!(lib.push("origin", false).unwrap()[0].ok);
7937
    let app_dir = root.join("app");
7938
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7939
    write(&app_dir, "main.txt", b"app\n");
7940
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7941
    // The stale state: registered in .oxymodules, never pinned.
7942
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
7943
    app.commit("initial", &[]).unwrap();
7944
    let stale = app.bookmark_heads().unwrap();
7945
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
7946
    app.commit("pin lib", &[]).unwrap();
7947
    let newer = app.bookmark_heads().unwrap();
7948
    app.checkout(&stale, false, "test").unwrap();
7949
    write(&app_dir, "notes.txt", b"mine\n");
7950
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
7951
    assert_eq!(carried, vec!["notes.txt".to_string()]);
7952
    assert!(app_dir.join("notes.txt").exists());
7953
}
7954
7955
#[test]
7956
fn a_bookmark_only_behind_its_remote_catches_up() {
7957
    // oxygen#74: switch takes the remote's state rather than a stale one.
7958
    hermetic();
7959
    let dir = tempfile::tempdir().unwrap();
7960
    let root = dir.path();
7961
    let _origin = Repo::init(&root.join("origin")).unwrap();
7962
    let url = root.join("origin").to_string_lossy().to_string();
7963
    let one = Repo::clone(&url, &root.join("one"))
7964
        .unwrap()
7965
        .with_home(root.join("home"));
7966
    write(&root.join("one"), "a.txt", b"a\n");
7967
    one.commit("A", &[]).unwrap();
7968
    assert!(one.push("origin", false).unwrap()[0].ok);
7969
    let two = Repo::clone(&url, &root.join("two"))
7970
        .unwrap()
7971
        .with_home(root.join("home"));
7972
    write(&root.join("two"), "b.txt", b"b\n");
7973
    two.commit("B", &[]).unwrap();
7974
    assert!(two.push("origin", false).unwrap()[0].ok);
7975
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
7976
    one.fetch("origin").unwrap();
7977
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
7978
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
7979
    // Local work the remote lacks: left alone.
7980
    write(&root.join("one"), "c.txt", b"c\n");
7981
    one.commit("C", &[]).unwrap();
7982
    write(&root.join("two"), "d.txt", b"d\n");
7983
    two.commit("D", &[]).unwrap();
7984
    assert!(two.push("origin", false).unwrap()[0].ok);
7985
    one.fetch("origin").unwrap();
7986
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
7987
}
42ccf504 Andy McCall ↶ 7988
7989
#[test]
7990
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
7991
    // oxygen#83: remotes earth and gcs, origin removed.
7992
    hermetic();
7993
    let dir = tempfile::tempdir().unwrap();
7994
    let root = dir.path();
7995
    let _up = Repo::init(&root.join("up")).unwrap();
7996
    let url = root.join("up").to_string_lossy().to_string();
7997
    let other = Repo::clone(&url, &root.join("other"))
7998
        .unwrap()
7999
        .with_home(root.join("home"));
8000
    write(&root.join("other"), "a.txt", b"a\n");
8001
    other.commit("a", &[]).unwrap();
8002
    assert!(other.push("origin", false).unwrap()[0].ok);
8003
    let mut one = Repo::clone(&url, &root.join("one"))
8004
        .unwrap()
8005
        .with_home(root.join("home"));
8006
    one.config.set("remote.earth.url", &url).unwrap();
8007
    one.config.set("remote.gcs.url", &url).unwrap();
8008
    one.config.set("remote.origin.url", "").unwrap();
8009
    one.save_config().unwrap();
8010
    write(&root.join("other"), "b.txt", b"b\n");
8011
    other.commit("b", &[]).unwrap();
8012
    assert!(other.push("origin", false).unwrap()[0].ok);
8013
    one.fetch("earth").unwrap();
8014
    let b = one
8015
        .bookmarks()
8016
        .unwrap()
8017
        .into_iter()
8018
        .find(|b| b.name == "main")
8019
        .unwrap();
8020
    assert_eq!(
8021
        (b.remote.as_deref(), b.behind),
8022
        (Some("earth"), Some(1)),
8023
        "a stale origin copy is not used"
8024
    );
8025
    assert_eq!(
8026
        one.default_remote(),
8027
        "origin",
8028
        "no default chosen among several"
8029
    );
8030
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8031
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8032
    one.config.set("core.remote", "earth").unwrap();
8033
    assert_eq!(one.default_remote(), "earth");
8034
}
cbe8499a Andy McCall ↶ 8035
8036
#[test]
8037
fn a_missing_author_identity_says_how_to_fix_it() {
8038
    // oxygen#82: an agent home's author.key naming an identity the
8039
    // repository does not hold.
8040
    hermetic();
8041
    let dir = tempfile::tempdir().unwrap();
8042
    let mut repo = Repo::init(dir.path()).unwrap();
8043
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8044
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8045
    let e = repo.identity(&missing).unwrap_err().to_string();
8046
    assert!(
8047
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8048
        "{e}"
8049
    );
8050
    assert!(e.contains("this repository's config"), "{e}");
8051
}
f6dccc45 Andy McCall ↶ 8052
8053
#[test]
8054
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8055
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8056
    // the working copy, a pull with nothing new left it there, and status
8057
    // said "clean".
8058
    hermetic();
8059
    let dir = tempfile::tempdir().unwrap();
8060
    let root = dir.path();
8061
    let _up = Repo::init(&root.join("up")).unwrap();
8062
    let url = root.join("up").to_string_lossy().to_string();
8063
    let other = Repo::clone(&url, &root.join("other"))
8064
        .unwrap()
8065
        .with_home(root.join("home"));
8066
    write(&root.join("other"), "a.txt", b"a\n");
8067
    other.commit("a", &[]).unwrap();
8068
    assert!(other.push("origin", false).unwrap()[0].ok);
8069
    let one = Repo::clone(&url, &root.join("one"))
8070
        .unwrap()
8071
        .with_home(root.join("home"));
8072
    write(&root.join("other"), "b.txt", b"b\n");
8073
    other.commit("b", &[]).unwrap();
8074
    assert!(other.push("origin", false).unwrap()[0].ok);
8075
    one.fetch("origin").unwrap();
8076
    // The bookmark moves; the working copy does not.
8077
    let theirs = one.resolve_heads("origin/main").unwrap();
8078
    one.bookmark_set("main", &theirs).unwrap();
8079
    assert!(!root.join("one/b.txt").exists());
8080
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8081
    let r = one.pull("origin").unwrap();
8082
    assert!(
8083
        !r.changed && r.checked_out,
8084
        "nothing new, but the working copy caught up"
8085
    );
8086
    assert!(root.join("one/b.txt").exists());
8087
    assert_eq!(one.working_copy_behind().unwrap(), None);
8088
}
170bb436 Andy McCall ↶ 8089
8090
#[test]
8091
fn touched_nodes_cache_answers_as_the_changes_do() {
8092
    hermetic();
8093
    let dir = tempfile::tempdir().unwrap();
8094
    let repo = Repo::init(dir.path()).unwrap();
8095
    write(dir.path(), "a.txt", b"one\n");
8096
    write(dir.path(), "b.txt", b"x\n");
8097
    repo.snapshot("t").unwrap();
8098
    let c1 = repo.commit("first", &[]).unwrap();
8099
    write(dir.path(), "b.txt", b"y\n");
8100
    repo.snapshot("t").unwrap();
8101
    repo.commit("b only", &[]).unwrap();
8102
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8103
    write(dir.path(), "c.txt", b"one\ntwo\n");
8104
    repo.snapshot("t").unwrap();
8105
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8106
    // Uncommitted work, so the working copy touches a file too.
8107
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8108
    repo.snapshot("t").unwrap();
8109
8110
    let path = dir.path().join(".oxy/index/touched");
8111
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8112
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8113
    assert!(path.exists(), "the first query writes the cache");
8114
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8115
    assert_eq!(cold, warm, "the cache answers as the changes do");
8116
    let (wc, _) = repo.working_copy().unwrap();
8117
    assert_eq!(
8118
        cold,
8119
        vec![wc, c3, c1],
8120
        "renames followed, the working copy included"
8121
    );
8122
8123
    // Working-copy changes are not kept: they are replaced by every snapshot.
8124
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8125
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8126
    assert!(cached.contains(&c1) && cached.contains(&c3));
8127
8128
    // A damaged cache is ignored, not trusted.
8129
    let mut bytes = fs::read(&path).unwrap();
8130
    let last = bytes.len() - 40;
8131
    bytes[last] ^= 1;
8132
    fs::write(&path, &bytes).unwrap();
8133
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8134
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8135
    assert_eq!(hashes(touches), vec![c3, c1]);
8136
}
e8e6e0ca Andy McCall ↶ 8137
8138
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8139
/// file back where it was leave two placements at one place, which the
8140
/// tree shows as one file. Removing it, and then its directory, retires
8141
/// both, so no copy is left under a directory that is gone.
8142
#[test]
8143
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8144
    hermetic();
8145
    if std::process::Command::new("git")
8146
        .arg("--version")
8147
        .output()
8148
        .is_err()
8149
    {
8150
        eprintln!("git not installed; skipping");
8151
        return;
8152
    }
8153
    let dir = tempfile::tempdir().unwrap();
8154
    let root = dir.path();
8155
    let g = root.join("src.git");
8156
    fs::create_dir_all(&g).unwrap();
8157
    let git = |args: &[&str]| {
8158
        let out = std::process::Command::new("git")
8159
            .arg("-C")
8160
            .arg(&g)
8161
            .args([
8162
                "-c",
8163
                "user.name=Grace",
8164
                "-c",
8165
                "[email protected]",
8166
                "-c",
8167
                "commit.gpgsign=false",
8168
            ])
8169
            .args(args)
8170
            .output()
8171
            .unwrap();
8172
        assert!(
8173
            out.status.success(),
8174
            "git {args:?}: {}",
8175
            String::from_utf8_lossy(&out.stderr)
8176
        );
8177
    };
8178
    git(&["init", "-q", "-b", "main"]);
8179
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8180
    write(&g, "keep.txt", b"k\n");
8181
    git(&["add", "."]);
8182
    git(&["commit", "-qm", "base"]);
8183
    fs::create_dir_all(g.join("d/sub")).unwrap();
8184
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8185
    git(&["commit", "-qm", "into sub"]);
8186
    git(&["checkout", "-qb", "side"]);
8187
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8188
    git(&["commit", "-qm", "back, on side"]);
8189
    git(&["checkout", "-q", "main"]);
8190
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8191
    git(&["commit", "-qm", "back, on main"]);
8192
    git(&["merge", "-q", "--no-edit", "side"]);
8193
    git(&["rm", "-rq", "d"]);
8194
    git(&["commit", "-qm", "d goes"]);
8195
8196
    let repo = Repo::init(&root.join("o")).unwrap();
8197
    repo.import_git(&g, "main").unwrap();
8198
    let v = repo.verify_git_import(&g, "main").unwrap();
8199
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8200
    let st = repo
8201
        .load_state_history(&repo.bookmark_heads().unwrap())
8202
        .unwrap();
8203
    let view = st.tree().view();
8204
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8205
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8206
}
5552e69c Andy McCall ↶ 8207
8208
/// oxygen#94: a state index's file histories are read, and checked by
8209
/// their own hashes, only when a file is built. One found damaged is an
8210
/// error that says so, the index is removed, and the next read rebuilds it.
8211
#[test]
8212
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8213
    hermetic();
8214
    let dir = tempfile::tempdir().unwrap();
8215
    let repo = Repo::init(dir.path()).unwrap();
8216
    for i in 0..6 {
8217
        write(
8218
            dir.path(),
8219
            &format!("f{i}.txt"),
8220
            format!("one {i}\n").as_bytes(),
8221
        );
8222
    }
8223
    repo.snapshot("t").unwrap();
8224
    repo.commit("first", &[]).unwrap();
8225
    for i in 0..6 {
8226
        write(
8227
            dir.path(),
8228
            &format!("f{i}.txt"),
8229
            format!("one {i}\ntwo\n").as_bytes(),
8230
        );
8231
    }
8232
    repo.snapshot("t").unwrap();
8233
    repo.commit("second", &[]).unwrap();
8234
    let want: Vec<Vec<u8>> = (0..6)
8235
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8236
        .collect();
8237
    // The index of the working copy's base, holding every file's history
8238
    // (a few changes behind, an index is replayed onto, not rewritten).
8239
    let (_, wc) = repo.working_copy().unwrap();
8240
    let base = repo.load_state_history(&wc.deps).unwrap();
8241
    repo.write_state_index(&wc.deps, &base);
8242
    for (i, w) in want.iter().enumerate() {
8243
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8244
    }
8245
    let index = repo.state_indexes();
8246
    assert!(!index.is_empty(), "a state index was written");
8247
    // The histories are last in the file: damage the last of them.
8248
    let mut bytes = fs::read(&index[0]).unwrap();
8249
    let last = bytes.len() - 1;
8250
    bytes[last] ^= 0x40;
8251
    fs::write(&index[0], &bytes).unwrap();
8252
8253
    let reads: Vec<_> = (0..6)
8254
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8255
        .collect();
8256
    let damaged: Vec<String> = reads
8257
        .iter()
8258
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8259
        .collect();
8260
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8261
    assert!(
8262
        damaged[0].contains("state index was damaged")
8263
            && damaged[0].contains("run the command again"),
8264
        "{}",
8265
        damaged[0]
8266
    );
8267
    // Every file reads right again, from an index rebuilt from history.
8268
    for (i, w) in want.iter().enumerate() {
8269
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8270
    }
8271
}
cb8b8082 Andy McCall ↶ 8272
8273
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8274
/// objects alone and in dependency order, and the last moves the bookmark.
8275
/// The remote ends with every change and the same state, and says how each
8276
/// part went.
8277
#[test]
8278
fn a_long_push_goes_in_parts() {
8279
    hermetic();
8280
    let dir = tempfile::tempdir().unwrap();
8281
    let root = dir.path();
8282
    let origin = root.join("origin");
8283
    Repo::init_bare_unbound(&origin).unwrap();
8284
    let main = root.join("main");
8285
    let mut repo = Repo::init(&main).unwrap();
8286
    repo.config
8287
        .set("remote.origin.url", &origin.to_string_lossy())
8288
        .unwrap();
8289
    // One byte: every change is a part of its own.
8290
    repo.config.set("push.batch-bytes", "1").unwrap();
8291
    repo.save_config().unwrap();
8292
    for i in 0..6 {
8293
        write(
8294
            &main,
8295
            &format!("f{i}.txt"),
8296
            format!("file {i}\n").as_bytes(),
8297
        );
8298
        repo.commit(&format!("c{i}"), &[]).unwrap();
8299
    }
8300
    let mut parts = Vec::new();
8301
    let results = repo
8302
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8303
        .unwrap();
8304
    assert!(
8305
        results.iter().any(|r| r.ok && r.name == "main"),
8306
        "{results:?}"
8307
    );
8308
    assert_eq!(parts.len(), 6, "{parts:?}");
8309
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8310
8311
    let remote = Repo::open(&origin).unwrap();
8312
    let heads = repo.bookmark_heads().unwrap();
8313
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8314
    assert_eq!(
8315
        remote.log_state(&heads).unwrap().len(),
8316
        repo.log_state(&heads).unwrap().len()
8317
    );
8318
    // A push of objects alone reports how it went, as `objects`.
8319
    let got = remote
8320
        .receive_push(Bundle::default(), vec![], None, vec![])
8321
        .unwrap();
8322
    assert_eq!(got.len(), 1);
8323
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8324
}
d6e0d5b8 Andy McCall ↶ 8325
8326
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8327
/// own commits (Git author email = its email, any case) with its key, and
8328
/// leaves anyone else's with the zero key; the history verifies as before.
8329
#[test]
8330
fn git_import_claims_your_own_commits() {
8331
    hermetic();
8332
    if std::process::Command::new("git")
8333
        .arg("--version")
8334
        .output()
8335
        .is_err()
8336
    {
8337
        eprintln!("git not installed; skipping");
8338
        return;
8339
    }
8340
    let dir = tempfile::tempdir().unwrap();
8341
    let root = dir.path();
8342
    let g = root.join("src.git");
8343
    fs::create_dir_all(&g).unwrap();
8344
    let git = |who: &str, args: &[&str]| {
8345
        let (name, email) = who.split_once(' ').unwrap();
8346
        let out = std::process::Command::new("git")
8347
            .arg("-C")
8348
            .arg(&g)
8349
            .args([
8350
                "-c",
8351
                &format!("user.name={name}"),
8352
                "-c",
8353
                &format!("user.email={email}"),
8354
                "-c",
8355
                "commit.gpgsign=false",
8356
            ])
8357
            .args(args)
8358
            .output()
8359
            .unwrap();
8360
        assert!(
8361
            out.status.success(),
8362
            "git {args:?}: {}",
8363
            String::from_utf8_lossy(&out.stderr)
8364
        );
8365
    };
8366
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8367
    write(&g, "a.txt", b"a\n");
8368
    git("Grace [email protected]", &["add", "."]);
8369
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8370
    write(&g, "b.txt", b"b\n");
8371
    git("Ada [email protected]", &["add", "."]);
8372
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8373
8374
    let mut repo = Repo::init(&root.join("o")).unwrap();
8375
    let (key, _) = repo
8376
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8377
        .unwrap();
8378
    repo.config.set("git.claim", "true").unwrap();
8379
    repo.save_config().unwrap();
8380
    let repo = Repo::open(&root.join("o")).unwrap();
8381
    repo.import_git(&g, "main").unwrap();
8382
    let v = repo.verify_git_import(&g, "main").unwrap();
8383
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8384
    let heads = repo.bookmark_heads().unwrap();
8385
    let by_message: std::collections::HashMap<String, KeyId> = repo
8386
        .log_state(&heads)
8387
        .unwrap()
8388
        .into_iter()
8389
        .map(|e| {
8390
            (
8391
                e.change.message.lines().next().unwrap_or("").to_string(),
8392
                e.change.author,
8393
            )
8394
        })
8395
        .collect();
8396
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8397
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8398
}
34fad4a9 Andy McCall ↶ 8399
8400
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8401
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8402
#[test]
8403
fn removing_a_remote_leaves_nothing_of_it() {
8404
    hermetic();
8405
    let dir = tempfile::tempdir().unwrap();
8406
    let origin = dir.path().join("origin");
8407
    Repo::init_bare_unbound(&origin).unwrap();
8408
    let main = dir.path().join("main");
8409
    let mut repo = Repo::init(&main).unwrap();
8410
    repo.config
8411
        .set("remote.origin.url", &origin.to_string_lossy())
8412
        .unwrap();
8413
    repo.config
8414
        .set("remote.origin.token", "secret-ish")
8415
        .unwrap();
8416
    repo.config
8417
        .set("remote.keep.url", &origin.to_string_lossy())
8418
        .unwrap();
8419
    repo.save_config().unwrap();
8420
    write(&main, "a.txt", b"a\n");
8421
    repo.commit("a", &[]).unwrap();
8422
    assert!(repo.push("origin", false).unwrap()[0].ok);
8423
    assert!(
8424
        repo.view().unwrap().remotes.contains_key("origin"),
8425
        "a tracking bookmark"
8426
    );
8427
8428
    repo.remove_remote("origin").unwrap();
8429
    let again = Repo::open(&main).unwrap();
8430
    assert!(
8431
        !again
8432
            .config
8433
            .repo_layer()
8434
            .keys()
8435
            .any(|k| k.starts_with("remote.origin.")),
8436
        "{:?}",
8437
        again.config.repo_layer()
8438
    );
8439
    assert!(!again.config.remotes.contains_key("origin"));
8440
    assert!(
8441
        !again.view().unwrap().remotes.contains_key("origin"),
8442
        "its tracking bookmarks go"
8443
    );
8444
    assert!(
8445
        again.config.remotes.contains_key("keep"),
8446
        "another remote stays"
8447
    );
8448
    let mut again = again;
8449
    assert!(
8450
        again.remove_remote("origin").is_err(),
8451
        "a second removal is refused"
8452
    );
8453
}
9d580f21 Andy McCall ↶ 8454
8455
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
8456
/// unreachable from history, so gc prunes it, unless the host names it:
8457
/// then it and its chunks stay, and it reads back whole.
8458
#[test]
8459
fn gc_keeps_the_blobs_a_host_names() {
8460
    hermetic();
8461
    let dir = tempfile::tempdir().unwrap();
8462
    let repo = Repo::init(dir.path()).unwrap();
8463
    write(dir.path(), "a.txt", b"a\n");
8464
    repo.commit("a", &[]).unwrap();
8465
    // Large enough to be several chunks.
8466
    let body: Vec<u8> = (0..400_000u32)
8467
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
8468
        .collect();
8469
    let kept = repo.store_blob(&body).unwrap();
8470
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
8471
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
8472
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
8473
    assert!(!repo.store().has(&lost), "not named: pruned");
8474
    repo.gc(true).unwrap();
8475
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
8476
}
530a0fc6 Andy McCall ↶ 8477
8478
/// oxygen#99: undo in one workspace undoes that workspace's last command,
8479
/// never another workspace's, says what it undid, and goes further back
8480
/// when run again.
8481
#[test]
8482
fn undo_is_scoped_to_its_workspace() {
8483
    hermetic();
8484
    let dir = tempfile::tempdir().unwrap();
8485
    let root = dir.path().join("main");
8486
    let a = Repo::init(&root).unwrap();
8487
    write(&root, "base.txt", b"base\n");
8488
    let base = a.commit("base", &[]).unwrap();
8489
    a.bookmark_create("feature", None).unwrap();
8490
    let ws_dir = dir.path().join("ws");
8491
    let heads = a.resolve_heads("feature").unwrap();
8492
    let b = a
8493
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
8494
        .unwrap();
8495
8496
    // A commits on main, then B commits on feature: B's is the newest.
8497
    write(&root, "a.txt", b"a\n");
8498
    let ca = a.commit("from a", &[]).unwrap();
8499
    write(&ws_dir, "b.txt", b"b\n");
8500
    let cb = b.commit("from b", &[]).unwrap();
8501
8502
    // A's undo undoes A's commit and leaves B's.
8503
    let u = a.undo().unwrap();
8504
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8505
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
8506
    assert!(!u.changes.is_empty());
8507
    let view = a.view().unwrap();
8508
    // (Independent changes commute, so a bookmark's heads may hold base too.)
8509
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
8510
    assert!(
8511
        a.heads_of(&view, "feature").unwrap().contains(&cb),
8512
        "B's commit stands"
8513
    );
8514
    assert!(
8515
        a.store().get_change(&ca).is_ok(),
8516
        "the change itself is still in the store"
8517
    );
8518
    // A's working copy was clean, so its files followed; B's are untouched.
8519
    assert!(!root.join("a.txt").exists());
8520
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
8521
    assert!(ws_dir.join("b.txt").exists());
8522
8523
    // B's undo still finds B's own commit, under A's undo.
8524
    let u = b.undo().unwrap();
8525
    assert_eq!(u.command, "oxy commit -m \"from b\"");
8526
    assert!(!b
8527
        .heads_of(&b.view().unwrap(), "feature")
8528
        .unwrap()
8529
        .contains(&cb));
8530
    assert_eq!(
8531
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
8532
        vec![base],
8533
        "A's undo stands"
8534
    );
8535
8536
    // A's next undo goes past the commit it already undid, to adding B's
8537
    // workspace: refused, since B has worked there since.
8538
    let e = a.undo().unwrap_err().to_string();
8539
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
8540
}
8541
8542
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
8543
/// own commit's head, and the other workspace's head stays.
8544
#[test]
8545
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
8546
    hermetic();
8547
    let dir = tempfile::tempdir().unwrap();
8548
    let root = dir.path().join("main");
8549
    let a = Repo::init(&root).unwrap();
8550
    write(&root, "base.txt", b"base\n");
8551
    a.commit("base", &[]).unwrap();
8552
    let ws_dir = dir.path().join("ws");
8553
    let b = a.workspace_add(&ws_dir, None).unwrap();
8554
    write(&root, "a.txt", b"a\n");
8555
    let ca = a.commit("from a", &[]).unwrap();
8556
    write(&ws_dir, "b.txt", b"b\n");
8557
    let cb = b.commit("from b", &[]).unwrap();
8558
    let u = a.undo().unwrap();
8559
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8560
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
8561
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
8562
}
8563
8564
/// oxygen#99: an undo that would also take back what another workspace
8565
/// did since to the same bookmark is refused, naming it.
8566
#[test]
8567
fn undo_refuses_to_take_back_another_workspaces_work() {
8568
    hermetic();
8569
    let dir = tempfile::tempdir().unwrap();
8570
    let root = dir.path().join("main");
8571
    let a = Repo::init(&root).unwrap();
8572
    write(&root, "base.txt", b"base\n");
8573
    a.commit("base", &[]).unwrap();
8574
    let ws_dir = dir.path().join("ws");
8575
    let b = a.workspace_add(&ws_dir, None).unwrap();
8576
    // Both on main: A commits, then B builds on it, editing A's file.
8577
    write(&root, "a.txt", b"a\n");
8578
    a.commit("from a", &[]).unwrap();
8579
    let heads = b.resolve_heads("main").unwrap();
8580
    b.checkout(&heads, false, "oxy checkout").unwrap();
8581
    write(&ws_dir, "a.txt", b"a, then b\n");
8582
    b.commit("from b", &[]).unwrap();
8583
    let e = a.undo().unwrap_err().to_string();
8584
    assert!(
8585
        e.contains("bookmark main") && e.contains("builds on"),
8586
        "{e}"
8587
    );
8588
    assert!(e.contains("oxy op restore"), "{e}");
8589
}
8590
8591
/// oxygen#99: undoing a commit that was already pushed says so: the remote
8592
/// still has it.
8593
#[test]
8594
fn undo_says_when_the_commit_was_pushed() {
8595
    hermetic();
8596
    let dir = tempfile::tempdir().unwrap();
8597
    let root = dir.path();
8598
    Repo::init(&root.join("origin")).unwrap();
8599
    let url = root.join("origin").to_string_lossy().to_string();
8600
    let repo = Repo::clone(&url, &root.join("work"))
8601
        .unwrap()
8602
        .with_home(root.join("home"));
8603
    write(&root.join("work"), "a.txt", b"a\n");
8604
    repo.commit("a", &[]).unwrap();
8605
    assert!(repo.push("origin", false).unwrap()[0].ok);
8606
    // The push itself is passed over: the remote keeps what it was sent.
8607
    let u = repo.undo().unwrap();
8608
    assert_eq!(u.command, "oxy commit -m \"a\"");
8609
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
8610
}
b689779e Andy McCall ↶ 8611
8612
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
8613
/// out of the snapshot and named; tracked files and files already in the
8614
/// working copy are not.
8615
#[test]
8616
fn large_new_files_are_left_out_of_snapshots() {
8617
    hermetic();
8618
    let dir = tempfile::tempdir().unwrap();
8619
    let root = dir.path();
8620
    let mut repo = Repo::init(root).unwrap();
8621
    repo.config.max_new_file = 1024;
8622
    write(root, "small.txt", b"small\n");
8623
    write(root, "big.bin", &vec![0u8; 4096]);
8624
    let s = repo.snapshot("oxy status").unwrap();
8625
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8626
    assert_eq!(paths, ["small.txt"]);
8627
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
8628
    repo.commit("small", &[]).unwrap();
8629
8630
    // A tracked file may grow past the limit.
8631
    write(root, "small.txt", &vec![b'x'; 4096]);
8632
    let s = repo.snapshot("oxy status").unwrap();
8633
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
8634
    // With no limit the big file is taken in, and stays once it is.
8635
    repo.config.max_new_file = 0;
8636
    let s = repo.snapshot("oxy status").unwrap();
8637
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
8638
    repo.config.max_new_file = 1024;
8639
    let s = repo.snapshot("oxy status").unwrap();
8640
    assert!(
8641
        s.statuses.iter().any(|p| p.path == "big.bin"),
8642
        "already in the working copy"
8643
    );
8644
    assert!(repo.skipped_large().is_empty());
8645
}
8646
8647
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
8648
/// snapshots expire, and kept while they have not.
8649
#[test]
8650
fn gc_prunes_what_only_expired_snapshots_held() {
8651
    hermetic();
8652
    let dir = tempfile::tempdir().unwrap();
8653
    let root = dir.path();
8654
    let mut repo = Repo::init(root).unwrap();
8655
    repo.config.gc_grace_days = 0;
8656
    write(root, "a.txt", b"a\n");
8657
    repo.commit("a", &[]).unwrap();
8658
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
8659
    write(root, "image.tar", &image);
8660
    repo.snapshot("oxy status").unwrap();
8661
    std::fs::remove_file(root.join("image.tar")).unwrap();
8662
    repo.snapshot("oxy status").unwrap();
8663
    let blob = Repo::blob_ref(&image);
8664
    assert!(repo.store().has(&blob));
8665
    repo.gc(true).unwrap();
8666
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
8667
    repo.config.snapshot_retention_days = 0;
8668
    repo.gc(true).unwrap();
8669
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
8670
    assert_eq!(
8671
        repo.file_at("a.txt", None).unwrap(),
8672
        b"a\n",
8673
        "committed files stay"
8674
    );
fe9586d9 Andy McCall ↶ 8675
}
8676
8677
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
8678
/// already has is no conflict: the switch goes through, nothing is lost,
8679
/// and other carried work still comes along.
8680
#[test]
8681
fn carrying_work_the_target_already_has_is_no_conflict() {
8682
    hermetic();
8683
    let dir = tempfile::tempdir().unwrap();
8684
    let root = dir.path();
8685
    let mut repo = Repo::init(root).unwrap();
8686
    write(root, "a.txt", b"one\n");
8687
    write(root, "b.txt", b"b\n");
8688
    repo.commit("one", &[]).unwrap();
8689
    repo.bookmark_create("landed", None).unwrap();
8690
    // On landed, a.txt becomes "two" (as a proposal landing would).
8691
    repo.bookmark_switch("landed", false).unwrap();
8692
    write(root, "a.txt", b"two\n");
8693
    repo.commit("two", &[]).unwrap();
8694
    repo.bookmark_switch("main", false).unwrap();
8695
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
8696
    // The same edit, uncommitted, on main; and another edit besides.
8697
    write(root, "a.txt", b"two\n");
8698
    write(root, "b.txt", b"b, edited\n");
8699
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
8700
    assert_eq!(
8701
        carried,
8702
        vec!["b.txt".to_string()],
8703
        "only the work landed lacks is carried"
8704
    );
8705
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
8706
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
8707
    let s = repo.snapshot("oxy status").unwrap();
8708
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8709
    assert_eq!(paths, ["b.txt"]);
8710
8711
    // A real difference is still refused.
8712
    repo.bookmark_switch("main", true).unwrap();
8713
    write(root, "a.txt", b"three\n");
8714
    let e = repo
8715
        .bookmark_switch_carry("landed")
8716
        .unwrap_err()
8717
        .to_string();
8718
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
b689779e Andy McCall ↶ 8719
}
aa4939e0 Andy McCall ↶ 8720
8721
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
8722
/// resolves, so JSON output feeds back into commands.
8723
#[test]
8724
fn a_full_hash_resolves_without_its_hash_sign() {
8725
    hermetic();
8726
    let dir = tempfile::tempdir().unwrap();
8727
    let root = dir.path();
8728
    let repo = Repo::init(root).unwrap();
8729
    write(root, "a.txt", b"a\n");
8730
    let h = repo.commit("a", &[]).unwrap();
8731
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
8732
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
8733
    assert!(repo
8734
        .resolve_change(&"0".repeat(64))
8735
        .unwrap_err()
8736
        .to_string()
8737
        .contains("no change matches"));
8738
}
f2f91ceb Andy McCall ↶ 8739
8740
#[test]
8741
fn a_pin_change_moves_only_the_pin() {
8742
    hermetic();
8743
    let dir = tempfile::tempdir().unwrap();
8744
    let root = dir.path();
8745
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8746
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8747
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8748
        .unwrap()
8749
        .with_home(root.join("home"));
8750
    write(&root.join("lib"), "lib.txt", b"v1\n");
8751
    lib.commit("lib v1", &[]).unwrap();
8752
    assert!(lib.push("origin", false).unwrap()[0].ok);
8753
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
8754
    let app_dir = root.join("app");
8755
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
8756
        .unwrap()
8757
        .with_home(root.join("home"));
8758
    write(&app_dir, "main.txt", b"app\n");
8759
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8760
    let a1 = app.commit("app with lib", &[]).unwrap();
8761
    // The library moves on.
8762
    write(&root.join("lib"), "more.txt", b"v2\n");
8763
    let l2 = lib.commit("lib v2", &[]).unwrap();
8764
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
8765
        panic!("an Oxygen pin")
8766
    };
8767
    let pin2 = crate::subrepo::Pin::Oxy {
8768
        repo,
8769
        heads: vec![l2],
8770
        bookmark,
8771
    };
8772
    let author = app.store().get_change(&a1).unwrap().author;
8773
    let change = app
8774
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
8775
        .unwrap();
8776
    let mut state = app.load_state(&[a1]).unwrap();
8777
    state.add(change).unwrap();
8778
    let files = state.materialize().files;
8779
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
8780
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
8781
        panic!("a pin is opaque")
8782
    };
8783
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
8784
    assert_eq!(read, pin2, "the new pin");
8785
    assert!(
8786
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
8787
        "nothing else changes"
8788
    );
8789
    // Only a subrepo's pin can be moved this way.
8790
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
8791
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
8792
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
8793
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
8794
}