OXYGENHUB
# d8524a9f0117 oxygen / crates / oxy-core / src / repo / tests.rs
341.3 KiB · Rust · last changed WIP #129: a tag's signer travels with the push (part 1 of 3) 17 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}");
137
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
138
    assert!(d.contains("-fn main() {}"), "{d}");
139
140
    // Resolution by prefix.
141
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
75167672 Andy McCall 142
    assert_eq!(
143
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
144
        h1
145
    );
98286406 Andy McCall ↶ 146
    assert!(repo.resolve_change("zzzz").is_err());
147
148
    // Undo the commit: bookmark and working copy go back.
149
    repo.undo().unwrap();
150
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
151
    let s = repo.snapshot("oxy status").unwrap();
75167672 Andy McCall 152
    assert!(
153
        !s.changed,
154
        "files on disk still match the pre-commit working copy"
155
    );
98286406 Andy McCall ↶ 156
    assert_eq!(s.statuses.len(), 3);
157
}
158
159
/// Make `main` conflicted: two commits on the same base that edit the same line.
160
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
161
    let dir = tempfile::tempdir().unwrap();
162
    let root = dir.path();
163
    let repo = Repo::init(root).unwrap();
164
    write(root, "f.txt", b"a\nb\nc\n");
165
    let h1 = repo.commit("base", &[]).unwrap();
166
    write(root, "f.txt", b"a\nB\nc\n");
167
    let h2 = repo.commit("upper", &[]).unwrap();
168
    repo.checkout(&[h1], false, "checkout").unwrap();
169
    write(root, "f.txt", b"a\nX\nc\n");
170
    let h3 = repo.commit("ex", &[]).unwrap();
171
    (dir, repo, h1, h2, h3)
172
}
173
174
#[test]
175
fn concurrent_edits_conflict_and_can_be_resolved() {
176
    hermetic();
177
    let (dir, repo, h1, h2, h3) = conflicted_repo();
178
    let root = dir.path();
179
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
180
    assert_eq!(heads, [h2, h3].into_iter().collect());
181
    let st = repo.load_state(&[h2, h3]).unwrap();
182
    assert!(st.materialize().is_conflicted());
183
184
    // Checking out main writes markers.
75167672 Andy McCall 185
    let r = repo
186
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
187
        .unwrap();
98286406 Andy McCall ↶ 188
    assert!(r.conflicted);
189
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 190
    assert!(
191
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
192
        "{marked}"
193
    );
194
    assert!(
195
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
196
        "{marked}"
197
    );
98286406 Andy McCall ↶ 198
    assert!(has_conflict_markers(marked.as_bytes()));
199
    // Untouched markers: clean working copy; commit has nothing to do.
200
    let s = repo.snapshot("status").unwrap();
201
    assert!(s.statuses.is_empty());
202
    assert!(!s.resolves);
203
204
    // Partially edited file that still has markers cannot be committed.
205
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
206
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 207
    assert_eq!(
208
        statuses(&s),
209
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
210
    );
98286406 Andy McCall ↶ 211
    assert!(repo.commit("no", &[]).is_err());
212
213
    // Resolve by keeping one side and adding a line elsewhere.
214
    write(root, "f.txt", b"a\nX\nc\nd\n");
215
    let s = repo.snapshot("status").unwrap();
216
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
217
    assert!(s.resolves);
218
    let h4 = repo.commit("resolve", &[]).unwrap();
219
    let c4 = repo.store().get_change(&h4).unwrap();
220
    assert_eq!(c4.kind, ChangeKind::Resolution);
221
    let mut want = vec![h1, h2, h3];
222
    want.sort();
75167672 Andy McCall 223
    assert_eq!(
224
        c4.deps, want,
225
        "a resolution depends on exactly the contributors and what it references"
226
    );
98286406 Andy McCall ↶ 227
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
228
    let snap = repo.load_state(&[h4]).unwrap().materialize();
229
    assert!(!snap.is_conflicted());
75167672 Andy McCall 230
    assert!(
231
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
232
    );
98286406 Andy McCall ↶ 233
    assert!(!repo.snapshot("status").unwrap().changed);
234
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
235
    // whatever order the changes arrive in.
236
    let mut st = State::new();
237
    for h in [h4, h3, h1, h2] {
238
        st.add_unchecked(repo.store().get_change(&h).unwrap());
239
    }
240
    st.validate().unwrap();
75167672 Andy McCall 241
    assert!(
242
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
243
    );
98286406 Andy McCall ↶ 244
}
245
246
#[test]
247
fn resolution_may_keep_both_sides_or_neither() {
248
    hermetic();
249
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
250
    let root = dir.path();
75167672 Andy McCall 251
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
252
        .unwrap();
98286406 Andy McCall ↶ 253
    // Keep both sides in a chosen order.
254
    write(root, "f.txt", b"a\nX\nB\nc\n");
255
    let h = repo.commit("both", &[]).unwrap();
256
    let snap = repo.load_state(&[h]).unwrap().materialize();
257
    assert!(!snap.is_conflicted());
75167672 Andy McCall 258
    assert!(
259
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
260
    );
98286406 Andy McCall ↶ 261
    // Undo and instead drop the whole region.
262
    repo.undo().unwrap();
263
    write(root, "f.txt", b"a\nc\n");
264
    let h = repo.commit("neither", &[]).unwrap();
265
    let snap = repo.load_state(&[h]).unwrap().materialize();
266
    assert!(!snap.is_conflicted());
75167672 Andy McCall 267
    assert!(
268
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
269
    );
98286406 Andy McCall ↶ 270
}
271
272
#[test]
273
fn name_conflict_resolved_by_removing_a_candidate() {
274
    hermetic();
275
    let dir = tempfile::tempdir().unwrap();
276
    let root = dir.path();
277
    let repo = Repo::init(root).unwrap();
278
    write(root, "keep.txt", b"k\n");
279
    let h1 = repo.commit("base", &[]).unwrap();
280
    write(root, "new.txt", b"one\n");
281
    repo.commit("one", &[]).unwrap();
282
    repo.checkout(&[h1], false, "checkout").unwrap();
283
    write(root, "new.txt", b"two\n");
284
    repo.commit("two", &[]).unwrap();
75167672 Andy McCall 285
    let r = repo
286
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
287
        .unwrap();
98286406 Andy McCall ↶ 288
    assert!(r.conflicted);
75167672 Andy McCall 289
    assert!(
290
        root.join("new.txt.oxy-conflict-1").exists()
291
            && root.join("new.txt.oxy-conflict-2").exists()
292
    );
98286406 Andy McCall ↶ 293
    assert!(!root.join("new.txt").exists());
294
    // Candidate numbering follows change-hash order, so pick by content:
295
    // keep the "two" candidate under the real name and drop the other.
75167672 Andy McCall 296
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
297
        (1, 2)
298
    } else {
299
        (2, 1)
300
    };
98286406 Andy McCall ↶ 301
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
75167672 Andy McCall 302
    fs::rename(
303
        root.join(format!("new.txt.oxy-conflict-{keep}")),
304
        root.join("new.txt"),
305
    )
306
    .unwrap();
98286406 Andy McCall ↶ 307
    let h = repo.commit("pick two", &[]).unwrap();
75167672 Andy McCall 308
    assert_eq!(
309
        repo.store().get_change(&h).unwrap().kind,
310
        ChangeKind::Resolution
311
    );
98286406 Andy McCall ↶ 312
    // The resolution does not touch keep.txt, so it does not depend on h1;
313
    // the bookmark keeps both as heads and their union is the state.
314
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
315
    assert_eq!(heads, [h1, h].into_iter().collect());
75167672 Andy McCall 316
    let snap = repo
317
        .load_state(&repo.bookmark_heads().unwrap())
318
        .unwrap()
319
        .materialize();
98286406 Andy McCall ↶ 320
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
75167672 Andy McCall 321
    assert_eq!(
322
        snap.files.keys().cloned().collect::<Vec<_>>(),
323
        ["keep.txt", "new.txt"]
324
    );
325
    assert!(
326
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
327
    );
98286406 Andy McCall ↶ 328
}
329
330
#[test]
331
fn identities_and_signed_commits() {
332
    hermetic();
333
    let dir = tempfile::tempdir().unwrap();
334
    let root = dir.path();
335
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
336
    write(root, "a.txt", b"a\n");
337
    let h0 = repo.commit("unsigned", &[]).unwrap();
338
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
75167672 Andy McCall 339
    assert_eq!(
340
        repo.store().get_change(&h0).unwrap().author,
341
        ObjectRef::ZERO
342
    );
98286406 Andy McCall ↶ 343
75167672 Andy McCall 344
    let (key, id) = repo
345
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
346
        .unwrap();
98286406 Andy McCall ↶ 347
    assert_eq!(id.hash(), key);
348
    assert_eq!(repo.config.author_key, Some(key));
349
    // Config survives reopen; the secret key is found again.
350
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
351
    assert_eq!(reopened.config.author_key, Some(key));
352
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
353
354
    // Default core.sign = seal: commits carry the author but no signature.
355
    write(root, "a.txt", b"a\nb\n");
356
    let h1 = repo.commit("authored", &[]).unwrap();
357
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
358
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
359
    // Signing later works too.
360
    repo.sign_change(&h1).unwrap();
75167672 Andy McCall 361
    assert!(
362
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
363
    );
98286406 Andy McCall ↶ 364
365
    repo.config.set("core.sign", "change").unwrap();
366
    repo.save_config().unwrap();
367
    write(root, "a.txt", b"a\nb\nc\n");
368
    let h2 = repo.commit("signed", &[]).unwrap();
75167672 Andy McCall 369
    assert_eq!(
370
        repo.verify_change(&h2).unwrap(),
371
        SignatureStatus::Valid {
372
            key,
373
            name: "Ada".into(),
374
            email: "[email protected]".into(),
375
            sealed: false,
376
            revoked: false
377
        }
378
    );
98286406 Andy McCall ↶ 379
05e71ed6 Andy McCall ↶ 380
    // A signature by a key that is not the author or a delegate is rejected
381
    // when the change names an author; an anonymous change (made before any
382
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
98286406 Andy McCall ↶ 383
    let other = SecretKey::generate();
384
    let other_id = other.identity("Mallory", "[email protected]", 0);
385
    let other_key = repo.store().put_identity(&other_id).unwrap();
05e71ed6 Andy McCall ↶ 386
    write(root, "a.txt", b"a\nb\nc\nd\n");
387
    repo.config.set("core.sign", "seal").unwrap();
388
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
389
    let forged = other.sign(Domain::Change, &other_key, &h3);
390
    repo.store().put_signature(&h3, &forged).unwrap();
75167672 Andy McCall 391
    assert!(
05e71ed6 Andy McCall ↶ 392
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
75167672 Andy McCall 393
    );
05e71ed6 Andy McCall ↶ 394
    let adopted = other.sign(Domain::Change, &other_key, &h0);
395
    repo.store().put_signature(&h0, &adopted).unwrap();
396
    assert!(
397
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
398
    );
98286406 Andy McCall ↶ 399
400
    // Tampering with the stored signature invalidates it.
401
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
402
    sig.ed[0] ^= 1;
403
    repo.store().put_signature(&h2, &sig).unwrap();
75167672 Andy McCall 404
    assert!(matches!(
405
        repo.verify_change(&h2).unwrap(),
406
        SignatureStatus::Invalid(_)
407
    ));
98286406 Andy McCall ↶ 408
409
    // Without the secret key, signing at commit fails cleanly.
410
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
411
    write(root, "a.txt", b"z\n");
412
    assert!(no_keys.commit("cannot sign", &[]).is_err());
413
}
414
415
#[test]
416
fn checkout_moves_the_working_copy() {
417
    hermetic();
418
    let dir = tempfile::tempdir().unwrap();
419
    let root = dir.path();
420
    let repo = Repo::init(root).unwrap();
421
    write(root, "a.txt", b"one\n");
422
    write(root, "sub/deep/b.txt", b"b\n");
423
    let h1 = repo.commit("first", &[]).unwrap();
424
    write(root, "a.txt", b"two\n");
425
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
426
    write(root, "bin.dat", &[0, 1, 2, 3]);
427
    let h2 = repo.commit("second", &[]).unwrap();
428
429
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
75167672 Andy McCall 430
    assert_eq!(
431
        r,
432
        CheckoutReport {
433
            written: 2,
434
            removed: 1,
435
            conflicted: false,
d3cd7ef9 Andy McCall ↶ 436
            notes: vec![],
437
            lacks: 1,
75167672 Andy McCall 438
        }
439
    );
98286406 Andy McCall ↶ 440
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
441
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
442
    assert!(!root.join("bin.dat").exists());
443
    let (_, wc) = repo.working_copy().unwrap();
444
    assert_eq!(wc.deps, vec![h1]);
75167672 Andy McCall 445
    assert!(
446
        !repo.snapshot("status").unwrap().changed,
447
        "checkout leaves a clean working copy"
448
    );
98286406 Andy McCall ↶ 449
    // The bookmark still points at h2.
450
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
451
452
    // Dirty working copy refuses without --discard.
453
    write(root, "a.txt", b"dirty\n");
454
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
75167672 Andy McCall 455
    let r = repo
456
        .checkout(&[h2], true, "oxy checkout --discard")
457
        .unwrap();
98286406 Andy McCall ↶ 458
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
459
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
460
    assert!(!root.join("sub").exists(), "empty directories are pruned");
461
    assert_eq!(r.removed, 1);
462
    assert!(!repo.snapshot("status").unwrap().changed);
463
464
    // Refuses to write through a symlinked directory.
465
    #[cfg(unix)]
466
    {
467
        fs::remove_dir_all(root.join("sub")).ok();
468
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
469
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
470
    }
471
}
472
473
#[test]
474
fn large_files_are_chunked_and_read_back() {
475
    hermetic();
476
    let dir = tempfile::tempdir().unwrap();
477
    let repo = Repo::init(dir.path()).unwrap();
478
    let mut big = vec![0u8; 700 * 1024];
479
    for (i, b) in big.iter_mut().enumerate() {
480
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
481
    }
482
    let r = repo.store_blob(&big).unwrap();
483
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
484
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
485
    assert_eq!(repo.read_blob(&r).unwrap(), big);
486
    assert_eq!(Repo::blob_ref(&big), r);
487
}
488
489
#[test]
490
fn clone_push_pull_with_seals_and_attestations() {
491
    hermetic();
492
    let dir = tempfile::tempdir().unwrap();
493
    let root = dir.path();
494
    let origin_path = root.join("origin");
495
    let origin = Repo::init(&origin_path).unwrap();
496
    let origin_url = origin_path.to_string_lossy().to_string();
497
498
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
75167672 Andy McCall 499
    let mut a = Repo::clone(&origin_url, &root.join("a"))
500
        .unwrap()
501
        .with_home(root.join("home-a"));
98286406 Andy McCall ↶ 502
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
75167672 Andy McCall 503
    let (key_a, _) = a
504
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
505
        .unwrap();
98286406 Andy McCall ↶ 506
    write(&root.join("a"), "f.txt", b"a\n");
507
    let h1 = a.commit("first", &[]).unwrap();
508
    let results = a.push("origin", false).unwrap();
509
    assert!(results[0].ok, "{}", results[0].reason);
510
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
511
    // The change was sealed at push and the reference attested.
75167672 Andy McCall 512
    assert!(
513
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
514
    );
515
    assert_eq!(
516
        origin.verify_change(&h1).unwrap(),
517
        SignatureStatus::Unsigned
518
    );
f8c69576 Andy McCall ↶ 519
    let serial_of = |att: &SignedAttest| match att.attest.body {
520
        AttestBody::Ref { serial, .. } => serial,
521
        _ => unreachable!(),
522
    };
98286406 Andy McCall ↶ 523
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 524
    // A bookmark new to the remote starts at the clock (past any deleted
525
    // namesake's serial); later updates count up from there.
526
    let first = serial_of(&att);
527
    assert!(first > 1_000_000_000_000, "{first}");
98286406 Andy McCall ↶ 528
    let again = a.push("origin", false).unwrap();
529
    assert!(again[0].ok && again[0].reason.contains("up to date"));
530
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 531
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
98286406 Andy McCall ↶ 532
533
    // B clones and sees the file and the seal.
534
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
535
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
536
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
75167672 Andy McCall 537
    assert!(matches!(
538
        b.authenticate_change(&h1).unwrap(),
539
        SignatureStatus::Valid { sealed: true, .. }
540
    ));
98286406 Andy McCall ↶ 541
542
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
543
    write(&root.join("b"), "f.txt", b"a\nb\n");
544
    let h2 = b.commit("second", &[]).unwrap();
545
    assert!(b.push("origin", false).unwrap()[0].ok);
546
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
547
548
    // A commits an independent change; push is refused until A pulls.
549
    write(&root.join("a"), "g.txt", b"g\n");
550
    let h3 = a.commit("third", &[]).unwrap();
551
    assert!(a.push("origin", false).is_err());
552
    let pr = a.pull("origin").unwrap();
553
    assert!(pr.changed && pr.checked_out);
554
    let mut want = vec![h2, h3];
555
    want.sort();
556
    assert_eq!(pr.heads, want);
557
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
558
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
559
    let results = a.push("origin", false).unwrap();
560
    assert!(results[0].ok, "{}", results[0].reason);
561
    let mut origin_heads = origin.bookmark_heads().unwrap();
562
    origin_heads.sort();
563
    assert_eq!(origin_heads, want);
564
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 565
    assert_eq!(serial_of(&att), first + 1);
98286406 Andy McCall ↶ 566
567
    // B pulls and ends up identical.
568
    let pr = b.pull("origin").unwrap();
569
    assert_eq!(pr.heads, want);
570
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
571
    assert!(!b.snapshot("status").unwrap().changed);
572
573
    // Concurrent edits of the same line: the union is a reified conflict.
574
    write(&root.join("a"), "f.txt", b"a\nA\n");
575
    a.commit("a-edit", &[]).unwrap();
576
    a.push("origin", false).unwrap();
577
    write(&root.join("b"), "f.txt", b"a\nB\n");
578
    b.commit("b-edit", &[]).unwrap();
579
    let pr = b.pull("origin").unwrap();
580
    assert!(pr.changed && pr.checked_out);
581
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
582
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
583
    write(&root.join("b"), "f.txt", b"a\nAB\n");
584
    let hr = b.commit("resolve", &[]).unwrap();
75167672 Andy McCall 585
    assert_eq!(
586
        b.store().get_change(&hr).unwrap().kind,
587
        ChangeKind::Resolution
588
    );
98286406 Andy McCall ↶ 589
    assert!(b.push("origin", false).unwrap()[0].ok);
590
    a.pull("origin").unwrap();
591
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
592
    // The resolution depends on the conflicting edits, but nothing depends
593
    // on "third" (it only added g.txt), so it stays a head beside it.
594
    let mut want = vec![hr, h3];
595
    want.sort();
596
    assert_eq!(a.bookmark_heads().unwrap(), want);
597
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
598
}
599
600
#[test]
601
fn receive_push_rejects_bad_updates() {
602
    hermetic();
603
    let dir = tempfile::tempdir().unwrap();
604
    let root = dir.path();
605
    let origin = Repo::init(&root.join("origin")).unwrap();
606
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 607
    let mut a = Repo::clone(&url, &root.join("a"))
608
        .unwrap()
609
        .with_home(root.join("home"));
610
    let (key, _) = a
611
        .create_identity("Ada", "a@b", IdentityScope::Repo)
612
        .unwrap();
98286406 Andy McCall ↶ 613
    write(&root.join("a"), "f.txt", b"x\n");
614
    let h1 = a.commit("one", &[]).unwrap();
615
    assert!(a.push("origin", false).unwrap()[0].ok);
616
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
75167672 Andy McCall 617
    let s1 = origin
618
        .store()
619
        .put_state(&StateObject::new(vec![h1]))
620
        .unwrap();
98286406 Andy McCall ↶ 621
622
    // Missing head.
75167672 Andy McCall 623
    let ghost = origin
624
        .store()
625
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
626
        .unwrap();
627
    let r = origin
628
        .receive_push(
629
            Bundle::default(),
630
            vec![RefUpdate {
631
                name: "main".into(),
632
                old_state: s1,
633
                new_state: ghost,
634
                force: false,
635
                attestation: None,
636
            }],
637
            None,
638
            vec![],
639
        )
640
        .unwrap();
641
    assert!(
642
        !r[0].ok && r[0].reason.contains("missing"),
643
        "{}",
644
        r[0].reason
645
    );
98286406 Andy McCall ↶ 646
647
    // Stale old_state.
75167672 Andy McCall 648
    let r = origin
649
        .receive_push(
650
            Bundle::default(),
651
            vec![RefUpdate {
652
                name: "main".into(),
653
                old_state: empty,
654
                new_state: s1,
655
                force: false,
656
                attestation: None,
657
            }],
658
            None,
659
            vec![],
660
        )
661
        .unwrap();
98286406 Andy McCall ↶ 662
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
663
664
    // Non-fast-forward without force is refused; with force it passes.
75167672 Andy McCall 665
    let r = origin
666
        .receive_push(
667
            Bundle::default(),
668
            vec![RefUpdate {
669
                name: "main".into(),
670
                old_state: s1,
671
                new_state: empty,
672
                force: false,
673
                attestation: None,
674
            }],
675
            None,
676
            vec![],
677
        )
678
        .unwrap();
679
    assert!(
680
        !r[0].ok && r[0].reason.contains("fast-forward"),
681
        "{}",
682
        r[0].reason
683
    );
684
    let r = origin
685
        .receive_push(
686
            Bundle::default(),
687
            vec![RefUpdate {
688
                name: "main".into(),
689
                old_state: s1,
690
                new_state: empty,
691
                force: true,
692
                attestation: None,
693
            }],
694
            None,
695
            vec![],
696
        )
697
        .unwrap();
98286406 Andy McCall ↶ 698
    assert!(r[0].ok);
699
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
700
701
    // Attestation with a stale serial is a rollback and is refused.
75167672 Andy McCall 702
    let sa = a
703
        .sign_attest(&Attest {
704
            repo: a.id().unwrap(),
705
            hlc: Hlc::now(),
706
            body: AttestBody::Ref {
707
                name: "main".into(),
708
                old_state: empty,
709
                new_state: s1,
710
                serial: 1,
711
            },
712
        })
713
        .unwrap();
714
    let r = origin
715
        .receive_push(
716
            Bundle::default(),
717
            vec![RefUpdate {
718
                name: "main".into(),
719
                old_state: empty,
720
                new_state: s1,
721
                force: false,
722
                attestation: Some(sa.clone()),
723
            }],
724
            None,
725
            vec![],
726
        )
727
        .unwrap();
728
    assert!(
729
        !r[0].ok && r[0].reason.contains("serial"),
730
        "{}",
731
        r[0].reason
732
    );
98286406 Andy McCall ↶ 733
    // An attestation for a different update is refused too.
75167672 Andy McCall 734
    let sa2 = a
735
        .sign_attest(&Attest {
736
            repo: a.id().unwrap(),
737
            hlc: Hlc::now(),
738
            body: AttestBody::Ref {
739
                name: "main".into(),
740
                old_state: s1,
741
                new_state: empty,
742
                serial: 5,
743
            },
744
        })
745
        .unwrap();
746
    let r = origin
747
        .receive_push(
748
            Bundle::default(),
749
            vec![RefUpdate {
750
                name: "main".into(),
751
                old_state: empty,
752
                new_state: s1,
753
                force: false,
754
                attestation: Some(sa2),
755
            }],
756
            None,
757
            vec![],
758
        )
759
        .unwrap();
760
    assert!(
761
        !r[0].ok && r[0].reason.contains("describe"),
762
        "{}",
763
        r[0].reason
764
    );
98286406 Andy McCall ↶ 765
    let _ = key;
766
}
767
768
#[test]
769
fn user_config_supplies_defaults_and_clones_sign() {
770
    hermetic();
771
    let dir = tempfile::tempdir().unwrap();
772
    let root = dir.path();
773
    let home = root.join("home");
774
    let origin = Repo::init(&root.join("origin")).unwrap();
775
    let url = root.join("origin").to_string_lossy().to_string();
776
777
    // Identity at user scope: the repository file stays free of author keys.
778
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
75167672 Andy McCall 779
    let (key, _) = a
780
        .create_identity("Ada", "[email protected]", IdentityScope::User)
781
        .unwrap();
98286406 Andy McCall ↶ 782
    assert!(!a.config.repo_layer().contains_key("author.key"));
783
    assert_eq!(a.config.author_key, Some(key));
784
    assert!(home.join("config.toml").exists());
785
    a.set_user_config("core.sign", "change").unwrap();
786
    assert!(a.config.sign_changes);
787
788
    // Repository settings override user settings and are the only ones saved.
789
    a.config.set("core.sign", "seal").unwrap();
790
    a.save_config().unwrap();
791
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
792
    assert!(!again.config.sign_changes);
793
    assert_eq!(again.config.author_key, Some(key));
75167672 Andy McCall 794
    assert_eq!(
795
        read_config_file(&root.join("a/.oxy/config"))
796
            .unwrap()
797
            .get("core.sign")
798
            .map(String::as_str),
799
        Some("seal")
800
    );
98286406 Andy McCall ↶ 801
802
    // A fresh clone made by this user signs with the user-level identity,
803
    // even though the clone's store has never seen the identity object.
804
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
805
    assert!(b.config.sign_changes);
806
    write(&root.join("b"), "f.txt", b"f\n");
807
    let h = b.commit("signed from a clone", &[]).unwrap();
75167672 Andy McCall 808
    assert!(
809
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
810
    );
98286406 Andy McCall ↶ 811
    assert!(b.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 812
    assert!(matches!(
813
        origin.verify_change(&h).unwrap(),
814
        SignatureStatus::Valid { .. }
815
    ));
98286406 Andy McCall ↶ 816
}
817
818
#[test]
819
fn format1_repositories_are_migrated_on_open() {
820
    hermetic();
821
    use crate::oplog::{Format1Op, Format1View};
822
    let dir = tempfile::tempdir().unwrap();
823
    let root = dir.path();
824
    let repo = Repo::init(root).unwrap();
825
    write(root, "a.txt", b"a\n");
826
    let h1 = repo.commit("one", &[]).unwrap();
827
    let (wc_hash, _) = repo.working_copy().unwrap();
828
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
829
    let mut v1 = Format1View::default();
830
    v1.bookmarks.insert("main".into(), vec![]);
831
    v1.workspaces.insert(repo.workspace(), wc_hash);
75167672 Andy McCall 832
    let init = Format1Op {
833
        parents: vec![],
834
        hlc: Hlc::default(),
835
        command: "oxy init".into(),
836
        view: v1.clone(),
837
    };
98286406 Andy McCall ↶ 838
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
839
    v1.bookmarks.insert("main".into(), vec![h1]);
75167672 Andy McCall 840
    let commit = Format1Op {
841
        parents: vec![init_ref],
842
        hlc: Hlc::default(),
843
        command: "oxy commit".into(),
844
        view: v1,
845
    };
98286406 Andy McCall ↶ 846
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
847
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
848
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
849
    drop(repo);
850
851
    let repo = Repo::open(root).unwrap();
75167672 Andy McCall 852
    assert_eq!(
853
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
854
        FORMAT_LINE
855
    );
98286406 Andy McCall ↶ 856
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
857
    let ops = repo.op_log().unwrap();
75167672 Andy McCall 858
    assert_eq!(
859
        ops.iter()
860
            .map(|(_, o)| o.command.as_str())
861
            .collect::<Vec<_>>(),
862
        ["oxy commit", "oxy init"]
863
    );
98286406 Andy McCall ↶ 864
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
865
    assert!(!repo.snapshot("status").unwrap().changed);
866
    // Reopening again is a no-op.
867
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
868
}
869
870
#[test]
871
fn undo_skips_snapshot_operations() {
872
    hermetic();
873
    let dir = tempfile::tempdir().unwrap();
874
    let root = dir.path();
875
    let repo = Repo::init(root).unwrap();
876
    write(root, "a.txt", b"a\n");
877
    let h1 = repo.commit("a", &[]).unwrap();
878
    // A later command snapshots new edits on top of the commit.
879
    write(root, "b.txt", b"b\n");
880
    let s = repo.snapshot("oxy status").unwrap();
881
    assert!(s.changed);
882
    assert!(repo.head_op().unwrap().1.is_snapshot());
883
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
884
    // Undo must undo the commit, not the snapshot.
885
    repo.undo().unwrap();
886
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
887
    let s = repo.snapshot("oxy status").unwrap();
888
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
75167672 Andy McCall 889
    assert_eq!(
890
        paths,
891
        ["a.txt", "b.txt"],
892
        "both files are back in the working copy"
893
    );
98286406 Andy McCall ↶ 894
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
895
    // Only snapshots remain above `init`, so there is nothing left to undo.
896
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
897
    assert!(repo.undo().is_err());
898
}
899
900
#[test]
901
fn independent_changes_commute_and_make_multiple_heads() {
902
    hermetic();
903
    let dir = tempfile::tempdir().unwrap();
904
    let root = dir.path();
905
    let repo = Repo::init(root).unwrap();
906
    write(root, "a.txt", b"a\n");
907
    let h1 = repo.commit("a", &[]).unwrap();
908
    write(root, "b.txt", b"b\n");
909
    let h2 = repo.commit("b", &[]).unwrap();
910
    let c2 = repo.store().get_change(&h2).unwrap();
911
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
912
    let mut heads = repo.bookmark_heads().unwrap();
913
    heads.sort();
914
    let mut want = vec![h1, h2];
915
    want.sort();
916
    assert_eq!(heads, want);
917
    // Editing a.txt depends on h1 only.
918
    write(root, "a.txt", b"a\na2\n");
919
    let h3 = repo.commit("a2", &[]).unwrap();
920
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
921
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
922
    assert_eq!(heads, [h2, h3].into_iter().collect());
923
    // Explicit dependency.
924
    write(root, "c.txt", b"c\n");
925
    let h4 = repo.commit("c", &[h2]).unwrap();
926
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
927
}
928
929
#[test]
930
fn mode_change_and_text_binary_switch() {
931
    hermetic();
932
    let dir = tempfile::tempdir().unwrap();
933
    let root = dir.path();
934
    let repo = Repo::init(root).unwrap();
935
    write(root, "run.sh", b"#!/bin/sh\n");
936
    repo.commit("add script", &[]).unwrap();
937
    #[cfg(unix)]
938
    {
939
        use std::os::unix::fs::PermissionsExt;
940
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
941
        let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 942
        assert_eq!(
943
            statuses(&s),
944
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
945
        );
98286406 Andy McCall ↶ 946
        let h = repo.commit("exec", &[]).unwrap();
947
        let snap = repo.load_state(&[h]).unwrap().materialize();
948
        assert!(snap.files["run.sh"].mode.exec);
949
    }
950
    // Text → binary → text.
951
    write(root, "run.sh", b"\0binary");
952
    let h = repo.commit("binary", &[]).unwrap();
953
    let snap = repo.load_state(&[h]).unwrap().materialize();
954
    assert!(snap.files["run.sh"].mode.opaque);
955
    write(root, "run.sh", b"text again\n");
956
    let h = repo.commit("text", &[]).unwrap();
957
    let snap = repo.load_state(&[h]).unwrap().materialize();
958
    assert!(!snap.files["run.sh"].mode.opaque);
75167672 Andy McCall 959
    assert!(
960
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
961
    );
98286406 Andy McCall ↶ 962
    assert!(!snap.is_conflicted());
963
}
83e0677b Andy McCall ↶ 964
6eae06b6 Andy McCall ↶ 965
/// oxygen#87: a binary file given new contents and the executable bit in
966
/// one commit kept the contents and lost the bit.
967
#[cfg(unix)]
968
#[test]
969
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
970
    use std::os::unix::fs::PermissionsExt;
971
    hermetic();
972
    let dir = tempfile::tempdir().unwrap();
973
    let root = dir.path();
974
    let repo = Repo::init(root).unwrap();
975
    write(root, "tool.exe", b"MZ\0one");
976
    repo.commit("add", &[]).unwrap();
977
    write(root, "tool.exe", b"MZ\0two");
978
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
979
    let h = repo.commit("update and +x", &[]).unwrap();
980
    let snap = repo.load_state(&[h]).unwrap().materialize();
981
    let f = &snap.files["tool.exe"];
982
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
983
    assert!(
984
        repo.snapshot("status").unwrap().statuses.is_empty(),
985
        "nothing left to commit"
986
    );
987
}
988
f0a517d2 Andy McCall ↶ 989
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
990
/// key whose certificate an issuer gave pushes when the policy grants its
991
/// subject, and a fetch accepts what it attested; an expired certificate,
992
/// or a subject the policy does not grant, may not move the bookmark.
83e0677b Andy McCall ↶ 993
#[test]
f0a517d2 Andy McCall ↶ 994
fn a_certified_key_pushes_under_a_subject_grant() {
995
    use crate::cert::{Certificate, SignedCertificate};
996
    use crate::identity::Scope;
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
    let mut a = Repo::clone(&url, &root.join("a"))
1003
        .unwrap()
1004
        .with_home(root.join("home-a"));
1005
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1006
        .unwrap();
1007
    write(&root.join("a"), "a.txt", b"a\n");
1008
    a.commit("a", &[]).unwrap();
1009
    a.policy_init().unwrap();
1010
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1011
    let hub_sk = SecretKey::generate();
1012
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1013
    a.policy_grant_subject(
1014
        "agent:claude@ada",
1015
        hub.clone(),
1016
        Scope::CHANGES | Scope::REFS,
1017
        None,
1018
    )
1019
    .unwrap();
1020
    assert!(a
1021
        .push("origin", false)
1022
        .unwrap()
1023
        .iter()
1024
        .any(|r| r.name == "policy" && r.ok));
1025
1026
    let now = Hlc::now().wall_ms;
1027
    // An agent repository whose key the hub certified for `subject`, from
1028
    // `from` to `to`.
1029
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1030
        let mut r = Repo::clone(&url, &root.join(name))
1031
            .unwrap()
1032
            .with_home(root.join(format!("home-{name}")));
1033
        let (_, id) = r
1034
            .create_identity(name, "[email protected]", IdentityScope::User)
1035
            .unwrap();
1036
        let cert = SignedCertificate::sign(
1037
            Certificate {
1038
                key: id,
1039
                issuer: hub.hash(),
1040
                subject: subject.into(),
1041
                claims: vec![],
1042
                scope: Scope::CHANGES | Scope::REFS,
1043
                not_before: from,
1044
                expires: to,
a2387d54 Andy McCall ↶ 1045
                grant: None,
f0a517d2 Andy McCall ↶ 1046
            },
1047
            &hub,
1048
            &hub_sk,
1049
        );
1050
        r.store().put_identity(&hub).unwrap();
1051
        r.store().put_certificate(&cert).unwrap();
1052
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1053
        r.commit("work", &[]).unwrap();
1054
        r
1055
    };
1056
1057
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1058
    let r = claude.push("origin", false).unwrap();
1059
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1060
    // Ada's fetch accepts the bookmark the certified key attested.
1061
    a.pull("origin").unwrap();
1062
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1063
        .store()
1064
        .get_change(h)
1065
        .map(|c| c.message == "work")
1066
        .unwrap_or(false)));
1067
f53cbe7a Andy McCall ↶ 1068
    // Step 4c: a host with an acceptor key records when it accepted the
1069
    // certified update and serves it; a fetch checks the certificate at
1070
    // that time only when the certificate's issuer signed it for exactly
1071
    // this attestation, else at the attestation's own time.
1072
    let host = Repo::open(&root.join("origin"))
1073
        .unwrap()
1074
        .with_acceptor(hub.clone(), hub_sk.clone());
1075
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1076
    host.record_acceptance(&attest_ref).unwrap();
1077
    let served = host.remote_refs().unwrap();
1078
    let acc = served
1079
        .refs
1080
        .iter()
1081
        .find(|r| r.name == "main")
1082
        .unwrap()
1083
        .accepted
1084
        .clone()
1085
        .expect("served with the refs");
1086
    let signer = sa.sigs[0].key;
1087
    assert_eq!(
1088
        a.certified_time(&signer, &sa, Some(&acc)),
1089
        acc.attest.hlc.wall_ms
1090
    );
1091
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1092
    let stranger_sk = SecretKey::generate();
1093
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1094
    let mut forged = acc.clone();
1095
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1096
    assert_eq!(
1097
        a.certified_time(&signer, &sa, Some(&forged)),
1098
        sa.attest.hlc.wall_ms,
1099
        "not the issuer's"
1100
    );
1101
    let mut elsewhere = acc.clone();
1102
    elsewhere.attest.body = AttestBody::Accepted {
1103
        attest: ObjectRef([7; 32]),
1104
    };
1105
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1106
    assert_eq!(
1107
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1108
        sa.attest.hlc.wall_ms,
1109
        "another attestation's"
1110
    );
1111
    a.pull("origin").unwrap();
1112
    // gc keeps the acceptance with the attestation.
1113
    host.gc(true).unwrap();
1114
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1115
f0a517d2 Andy McCall ↶ 1116
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1117
    let r = late.push("origin", false).unwrap();
1118
    assert!(
1119
        !r[0].ok && r[0].reason.contains("may not update"),
1120
        "an expired certificate: {r:?}"
1121
    );
1122
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1123
    let r = other.push("origin", false).unwrap();
1124
    assert!(
1125
        !r[0].ok && r[0].reason.contains("may not update"),
1126
        "a subject not granted: {r:?}"
1127
    );
1128
}
1129
d8524a9f Andy McCall ↶ 1130
/// A tag made under one short-lived key and pushed under another: its
1131
/// signer travels with the push (identity and certificate), so a receiver
1132
/// that has never seen that key accepts it. A tag-only push by a keyless
1133
/// agent was refused "unknown key" (found releasing OxygenFlow 0.2.0).
1134
#[test]
1135
fn a_tag_signed_by_an_earlier_short_lived_key_is_pushed() {
1136
    use crate::cert::{Certificate, SignedCertificate};
1137
    use crate::identity::Scope;
1138
    hermetic();
1139
    let dir = tempfile::tempdir().unwrap();
1140
    let root = dir.path();
1141
    let _origin = Repo::init(&root.join("origin")).unwrap();
1142
    let url = root.join("origin").to_string_lossy().to_string();
1143
    let mut a = Repo::clone(&url, &root.join("a"))
1144
        .unwrap()
1145
        .with_home(root.join("home-a"));
1146
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1147
        .unwrap();
1148
    write(&root.join("a"), "a.txt", b"a\n");
1149
    a.commit("a", &[]).unwrap();
1150
    a.policy_init().unwrap();
1151
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1152
    let hub_sk = SecretKey::generate();
1153
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1154
    a.policy_grant_subject(
1155
        "agent:claude@ada",
1156
        hub.clone(),
1157
        Scope::CHANGES | Scope::REFS,
1158
        Some("*"),
1159
    )
1160
    .unwrap();
1161
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1162
1163
    let now = Hlc::now().wall_ms;
1164
    let mut agent = Repo::clone(&url, &root.join("agent"))
1165
        .unwrap()
1166
        .with_home(root.join("home-agent"));
1167
    agent.store().put_identity(&hub).unwrap();
1168
    let certify = |agent: &Repo, id| {
1169
        let cert = SignedCertificate::sign(
1170
            Certificate {
1171
                key: id,
1172
                issuer: hub.hash(),
1173
                subject: "agent:claude@ada".into(),
1174
                claims: vec![],
1175
                scope: Scope::CHANGES | Scope::REFS,
1176
                not_before: now - 60_000,
1177
                expires: now + 600_000,
1178
                grant: None,
1179
            },
1180
            &hub,
1181
            &hub_sk,
1182
        );
1183
        agent.store().put_certificate(&cert).unwrap();
1184
    };
1185
    // The tag, under the first short-lived key.
1186
    let (first, first_id) = agent
1187
        .create_identity("claude", "[email protected]", IdentityScope::User)
1188
        .unwrap();
1189
    certify(&agent, first_id);
1190
    let heads = agent.bookmark_heads().unwrap();
1191
    agent.tag_create("v1", &heads, "first").unwrap();
1192
    // The push, under a second one (a later process's ten-minute key).
1193
    let (second, second_id) = agent
1194
        .create_identity("claude", "[email protected]", IdentityScope::User)
1195
        .unwrap();
1196
    assert_ne!(first, second);
1197
    certify(&agent, second_id);
1198
    agent
1199
        .set_user_config("author.signer", &second.to_hex())
1200
        .unwrap();
1201
    let host = Repo::open(&root.join("origin")).unwrap();
1202
    assert!(host.store().get_identity(&first).is_err(), "the host has never seen the tag's key");
1203
    let r = agent.push("origin", false).unwrap();
1204
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1205
    let host = Repo::open(&root.join("origin")).unwrap();
1206
    assert!(host.tag_refs().unwrap().iter().any(|t| t.name == "v1"), "the tag arrived");
1207
}
1208
d36ba2f7 Andy McCall ↶ 1209
/// oxygenhub#266: a short-lived key its issuer certified moves a bookmark
1210
/// and signs no change (a keyless agent naming a bookmark). A third
1211
/// party's clone gets the key's identity, its certificate and the
1212
/// issuer's identity with the fetch, so the policy's subject grant
1213
/// authorizes the move and the signature verifies.
1214
#[test]
1215
fn a_bookmark_moved_by_a_certified_key_alone_is_fetched() {
1216
    use crate::cert::{Certificate, SignedCertificate};
1217
    use crate::identity::Scope;
1218
    hermetic();
1219
    let dir = tempfile::tempdir().unwrap();
1220
    let root = dir.path();
1221
    let _origin = Repo::init(&root.join("origin")).unwrap();
1222
    let url = root.join("origin").to_string_lossy().to_string();
1223
    let mut a = Repo::clone(&url, &root.join("a"))
1224
        .unwrap()
1225
        .with_home(root.join("home-a"));
1226
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1227
        .unwrap();
1228
    write(&root.join("a"), "a.txt", b"a\n");
1229
    a.commit("a", &[]).unwrap();
1230
    a.policy_init().unwrap();
1231
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1232
    let hub_sk = SecretKey::generate();
1233
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1234
    a.policy_grant_subject(
1235
        "agent:claude@ada",
1236
        hub.clone(),
1237
        Scope::CHANGES | Scope::REFS,
1238
        None,
1239
    )
1240
    .unwrap();
1241
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1242
1243
    let now = Hlc::now().wall_ms;
1244
    let mut agent = Repo::clone(&url, &root.join("agent"))
1245
        .unwrap()
1246
        .with_home(root.join("home-agent"));
1247
    let (key, id) = agent
1248
        .create_identity("claude", "[email protected]", IdentityScope::User)
1249
        .unwrap();
1250
    let cert = SignedCertificate::sign(
1251
        Certificate {
1252
            key: id,
1253
            issuer: hub.hash(),
1254
            subject: "agent:claude@ada".into(),
1255
            claims: vec![],
1256
            scope: Scope::CHANGES | Scope::REFS,
1257
            not_before: now - 60_000,
1258
            expires: now + 600_000,
1259
            grant: None,
1260
        },
1261
        &hub,
1262
        &hub_sk,
1263
    );
1264
    agent.store().put_identity(&hub).unwrap();
1265
    agent.store().put_certificate(&cert).unwrap();
1266
    let heads = agent.bookmark_heads().unwrap();
1267
    agent.bookmark_create("agent-work", Some(&heads)).unwrap();
1268
    let r = agent.push_bookmark("origin", "agent-work", false).unwrap();
1269
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1270
    let host = Repo::open(&root.join("origin")).unwrap();
1271
    let (_, sa) = host.latest_ref_attest("agent-work").unwrap().unwrap();
1272
    assert_eq!(sa.sigs[0].key, key, "the certified key alone moved it");
1273
1274
    // A fetch naming no change brings the certificate and both identities.
1275
    let bundle = host.bundle_raw_for(&[], None).unwrap();
1276
    assert!(bundle.changes.is_empty() && bundle.raw_changes.is_empty());
1277
    assert_eq!(bundle.certificates.len(), 1);
1278
    for k in [key, hub.hash()] {
1279
        assert!(bundle
1280
            .objects
1281
            .iter()
1282
            .any(|(t, b)| *t == ObjectType::Identity && hash_object(*t, b) == k));
1283
    }
1284
1285
    let c = Repo::clone(&url, &root.join("c")).unwrap();
1286
    let tracked = c.view().unwrap().remotes["origin"].clone();
1287
    assert_eq!(
1288
        tracked.get("agent-work"),
1289
        host.view().unwrap().bookmarks.get("agent-work")
1290
    );
1291
    assert!(c.store().certificate_of(&key).unwrap().is_some());
1292
}
1293
028545df Andy McCall ↶ 1294
/// Trusted time (oxygenhub#240, spec §14.8): a fetched attestation by a
1295
/// short-lived key is judged at its integrated time, the earliest time a
1296
/// pinned witness cosigned a checkpoint holding it. A certificate valid
1297
/// then but expired now passes; a witness this user does not trust gives
1298
/// no time (the earlier rule, said so); a backdated attestation is noted;
1299
/// an answer without the new fields is judged as before.
1300
#[test]
1301
fn a_fetched_attestation_is_judged_at_its_integrated_time() {
1302
    use super::transparency::LogCheck;
1303
    use crate::cert::{Certificate, SignedCertificate};
1304
    use crate::identity::Scope;
1305
    use crate::protocol::{Integration, Logged, RefsResponse, RemoteRef};
1306
    use crate::tlog::{self, Checkpoint, Entry, Hash, Integrated, Note};
1307
    hermetic();
1308
    let dir = tempfile::tempdir().unwrap();
1309
    let root = dir.path();
1310
    let mut a = Repo::init(&root.join("a"))
1311
        .unwrap()
1312
        .with_home(root.join("home-a"));
1313
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1314
        .unwrap();
1315
    write(&root.join("a"), "a.txt", b"a\n");
1316
    a.commit("a", &[]).unwrap();
1317
    a.policy_init().unwrap();
1318
    let issuer_sk = SecretKey::generate();
1319
    let issuer = issuer_sk.identity("hub", "[email protected]", 1);
1320
    a.policy_grant_subject(
1321
        "agent:claude@ada",
1322
        issuer.clone(),
1323
        Scope::CHANGES | Scope::REFS,
1324
        None,
1325
    )
1326
    .unwrap();
1327
    let p = a.current_policy().unwrap().unwrap().1.policy;
1328
1329
    // An agent key the issuer certified for ten minutes two hours ago.
1330
    let now = Hlc::now().wall_ms;
1331
    let t0 = now - 2 * 3_600_000;
1332
    let agent_sk = SecretKey::generate();
1333
    let agent = agent_sk.identity("claude", "[email protected]", t0);
1334
    let cert = SignedCertificate::sign(
1335
        Certificate {
1336
            key: agent.clone(),
1337
            issuer: issuer.hash(),
1338
            subject: "agent:claude@ada".into(),
1339
            claims: vec![],
1340
            scope: Scope::CHANGES | Scope::REFS,
1341
            not_before: t0,
1342
            expires: t0 + 600_000,
1343
            grant: None,
1344
        },
1345
        &issuer,
1346
        &issuer_sk,
1347
    );
1348
    a.store().put_identity(&agent).unwrap();
1349
    a.store().put_certificate(&cert).unwrap();
1350
    let signer = agent.hash();
1351
    let attested = |claimed: u64| {
1352
        let attest = Attest {
1353
            repo: a.id().unwrap(),
1354
            hlc: Hlc {
1355
                wall_ms: claimed,
1356
                logical: 0,
1357
            },
1358
            body: AttestBody::Ref {
1359
                name: "main".into(),
1360
                old_state: ObjectRef([1; 32]),
1361
                new_state: ObjectRef([2; 32]),
1362
                serial: 1,
1363
            },
1364
        };
1365
        let sig = agent_sk.sign(Domain::Attest, &signer, &attest.hash());
1366
        SignedAttest {
1367
            attest,
1368
            sigs: vec![sig],
1369
        }
1370
    };
1371
1372
    // The hub's log: eight entries, the attestation's at 3, the latest
1373
    // checkpoint of 8, and one of 4 that witnesses cosigned.
1374
    let log_sk = SecretKey::generate();
1375
    let log_key = log_sk.identity("hub.example", "[email protected]", 1);
1376
    let origin = "hub.example/log";
1377
    let hub = "https://hub.example";
1378
    let url = "https://hub.example/ada/a";
1379
    let w_sk = SecretKey::generate();
1380
    let w = w_sk.identity("w", "[email protected]", 1);
1381
    let stranger_sk = SecretKey::generate();
1382
    let stranger = stranger_sk.identity("s", "[email protected]", 1);
1383
    let sa = attested(t0 + 300_000);
1384
    let entry_of = |i: u64| {
1385
        let (kind, object) = if i == 3 {
1386
            ("ref", sa.attest.hash())
1387
        } else {
1388
            ("seal", ObjectRef([i as u8; 32]))
1389
        };
1390
        Entry {
1391
            kind: kind.into(),
1392
            repo: sa.attest.repo,
1393
            object,
1394
            signers: vec![signer],
1395
            received: t0 + 300_000,
1396
        }
1397
        .encode()
1398
    };
1399
    let mut stored: Vec<Hash> = Vec::new();
1400
    for i in 0..8 {
1401
        let add = tlog::stored_hashes_for_leaf(i, tlog::leaf_hash(&entry_of(i)), &stored).unwrap();
1402
        stored.extend(add);
1403
    }
1404
    let note_of = |n: u64, cosigners: &[(&str, &Identity, &SecretKey, u64)]| {
1405
        let mut note = Checkpoint {
1406
            origin: origin.into(),
1407
            size: n,
1408
            root: tlog::tree_hash(n, &stored).unwrap(),
1409
            extensions: vec![],
1410
        }
1411
        .sign(&log_key, &log_sk)
1412
        .unwrap();
1413
        for (name, id, sk, t) in cosigners {
1414
            note.sigs
1415
                .extend(tlog::cosign(&note.text, name, id, sk, *t).unwrap());
1416
        }
1417
        note.encode()
1418
    };
1419
    let latest = note_of(8, &[]);
1420
    let witnessed_at = (t0 + 360_000) / 1000;
1421
    let cosigned = note_of(
1422
        4,
1423
        &[
1424
            ("w.example", &w, &w_sk, witnessed_at),
1425
            ("s.example", &stranger, &stranger_sk, 1),
1426
        ],
1427
    );
1428
    let answer = |integration: Vec<Integration>, witnesses: Vec<(String, Vec<u8>)>| RefsResponse {
1429
        refs: vec![RemoteRef {
1430
            name: "main".into(),
1431
            state: ObjectRef([2; 32]),
1432
            heads: vec![],
1433
            attestation: Some(sa.clone()),
1434
            last_serial: None,
1435
            accepted: None,
1436
            logged: Some(Logged {
1437
                index: 3,
1438
                entry: entry_of(3),
1439
                proof: tlog::prove_inclusion(8, 3, &stored).unwrap(),
1440
            }),
1441
            integration,
1442
        }],
1443
        log: Some(latest.clone()),
1444
        witnesses,
1445
        ..RefsResponse::default()
1446
    };
1447
    let proof4 = tlog::prove_inclusion(4, 3, &stored).unwrap();
1448
    let served = vec![Integration {
1449
        note: cosigned.clone(),
1450
        proof: proof4.clone(),
1451
    }];
1452
    let listed = vec![("w.example".to_string(), w.encode())];
1453
    // This user saw the hub's log before (pinned, so nothing is fetched).
1454
    a.remember_log(hub, &log_key, &Note::parse(&latest).unwrap())
1455
        .unwrap();
1456
1457
    // The witness is pinned on first sight, silently; the stranger's
1458
    // earlier cosignature counts for nothing.
1459
    let resp = answer(served.clone(), listed.clone());
1460
    let lc = a.check_log(url, None, &resp).unwrap();
1461
    assert!(lc.notes.is_empty(), "{:?}", lc.notes);
1462
    let t = lc.time_of("main").unwrap();
1463
    assert_eq!((t.time, t.witness.as_str()), (witnessed_at, "w.example"));
1464
    // The certificate expired an hour and fifty minutes ago, but covered
1465
    // the integrated time: accepted, and nothing to say.
1466
    assert!(cert.cert.expires < now);
1467
    let mut notes = Vec::new();
1468
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1469
        .unwrap();
1470
    assert!(notes.is_empty(), "{notes:?}");
1471
1472
    // Only the stranger cosigned: no witnessed time, so the earlier rule
1473
    // (the attestation's own time, inside the window), said so.
1474
    let lonely = vec![Integration {
1475
        note: note_of(4, &[("s.example", &stranger, &stranger_sk, 1)]),
1476
        proof: proof4.clone(),
1477
    }];
1478
    let resp = answer(lonely, vec![]);
1479
    let lc = a.check_log(url, None, &resp).unwrap();
1480
    assert!(lc
1481
        .time_of("main")
1482
        .unwrap_err()
1483
        .contains("no witness this user trusts"));
1484
    let mut notes = Vec::new();
1485
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1486
        .unwrap();
1487
    assert!(
1488
        notes.len() == 1 && notes[0].contains("not at a witnessed time"),
1489
        "{notes:?}"
1490
    );
1491
1492
    // A witness listed later under the pinned name with another key is
1493
    // pinned with a note, as a new log key is.
1494
    let resp = answer(
1495
        served.clone(),
1496
        vec![("w.example".into(), stranger.encode())],
1497
    );
1498
    let lc = a.check_log(url, None, &resp).unwrap();
1499
    assert!(
1500
        lc.notes.iter().any(|n| n.contains("another key")),
1501
        "{:?}",
1502
        lc.notes
1503
    );
1504
    assert!(
1505
        lc.time_of("main").is_err(),
1506
        "w's cosignature is by its old key"
1507
    );
1508
    a.check_log(url, None, &answer(served.clone(), listed.clone()))
1509
        .unwrap();
1510
1511
    // An old peer's answer: no log, no witnesses, no integration. Judged
1512
    // as before, silently.
1513
    let mut old = answer(vec![], vec![]);
1514
    old.log = None;
1515
    old.refs[0].logged = None;
1516
    let lc = a.check_log(url, None, &old).unwrap();
1517
    assert!(!lc.kept && lc.notes.is_empty());
1518
    let mut notes = Vec::new();
1519
    a.authorize_in_time(&p, "origin", &old.refs[0], &sa, &signer, &lc, &mut notes)
1520
        .unwrap();
1521
    assert!(notes.is_empty(), "{notes:?}");
1522
1523
    // Judged at given integrated times.
1524
    let at = |secs_after_t0: u64| {
1525
        let mut times = std::collections::HashMap::new();
1526
        times.insert(
1527
            "main".to_string(),
1528
            Ok(Integrated {
1529
                time: (t0 + secs_after_t0 * 1000) / 1000,
1530
                witness: "w.example".into(),
1531
                size: 4,
1532
            }),
1533
        );
1534
        LogCheck {
1535
            kept: true,
1536
            times,
1537
            ..LogCheck::default()
1538
        }
1539
    };
1540
    let judged = |sa: &SignedAttest, lc: &LogCheck| {
1541
        let mut notes = Vec::new();
1542
        a.authorize_in_time(&p, "origin", &old.refs[0], sa, &signer, lc, &mut notes)
1543
            .map(|_| notes)
1544
    };
1545
    // Claimed inside the window, first witnessed an hour later, after
1546
    // the certificate expired: backdated, or held back. Accepted by the
1547
    // earlier rule while logs are new, with both said.
1548
    let notes = judged(&sa, &at(3600)).unwrap();
1549
    assert!(
1550
        notes
1551
            .iter()
1552
            .any(|n| n.contains("had lapsed when witness w.example"))
1553
            && notes
1554
                .iter()
1555
                .any(|n| n.contains("55 minutes before witness")),
1556
        "{notes:?}"
1557
    );
1558
    // Claimed after the certificate expired, but witnessed inside its
1559
    // window: the clock the signer did not choose decides. The gap is
1560
    // still noted.
1561
    let fast = attested(now);
1562
    let notes = judged(&fast, &at(400)).unwrap();
1563
    assert!(
1564
        notes.len() == 1 && notes[0].contains("after witness w.example saw it"),
1565
        "{notes:?}"
1566
    );
1567
    // Claimed and witnessed after it expired: refused, as before.
1568
    assert!(judged(&fast, &at(3600)).is_err());
1569
    // A gap within ten minutes is nothing to note.
1570
    assert!(judged(&sa, &at(500)).unwrap().is_empty());
1571
}
1572
a2387d54 Andy McCall ↶ 1573
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1574
/// subject the author granted, seals changes in the author's name; with
1575
/// no grant, a stranger's, or one that had ended, it is neither the
1576
/// author nor a delegate.
f0a517d2 Andy McCall ↶ 1577
#[test]
a2387d54 Andy McCall ↶ 1578
fn a_certified_key_acts_for_its_author_under_a_grant() {
1579
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1580
    use crate::identity::{Identity, Scope};
1581
    hermetic();
1582
    let dir = tempfile::tempdir().unwrap();
1583
    let root = dir.path();
1584
    let _origin = Repo::init(&root.join("origin")).unwrap();
1585
    let url = root.join("origin").to_string_lossy().to_string();
1586
    let mut a = Repo::clone(&url, &root.join("a"))
1587
        .unwrap()
1588
        .with_home(root.join("home-a"));
1589
    let (ada, _) = a
1590
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1591
        .unwrap();
1592
    write(&root.join("a"), "a.txt", b"a\n");
1593
    a.commit("a", &[]).unwrap();
1594
    a.policy_init().unwrap();
1595
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1596
    let hub_sk = SecretKey::generate();
1597
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1598
    a.policy_grant_subject(
1599
        "agent:claude@ada",
1600
        hub.clone(),
1601
        Scope::CHANGES | Scope::REFS,
1602
        None,
1603
    )
1604
    .unwrap();
1605
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1606
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1607
    let ada_id = a.identity(&ada).unwrap();
1608
1609
    let now = Hlc::now().wall_ms;
1610
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1611
        SignedGrant::sign(
1612
            Grant {
1613
                grantor: by.hash(),
1614
                subject: "agent:claude@ada".into(),
1615
                issuer: hub.hash(),
1616
                scope: Scope::CHANGES | Scope::SEAL,
1617
                not_before: from,
1618
                expires: to,
1619
            },
1620
            by,
1621
            sk,
1622
        )
1623
    };
1624
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1625
    // certified (with `g` inside) the signer.
1626
    let agent = |name: &str, g: Option<SignedGrant>| {
1627
        let mut r = Repo::clone(&url, &root.join(name))
1628
            .unwrap()
1629
            .with_home(root.join(format!("home-{name}")));
1630
        let (key, id) = r
1631
            .create_identity(name, "[email protected]", IdentityScope::User)
1632
            .unwrap();
1633
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1634
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1635
        let cert = SignedCertificate::sign(
1636
            Certificate {
1637
                key: id,
1638
                issuer: hub.hash(),
1639
                subject: "agent:claude@ada".into(),
1640
                claims: vec![],
1641
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1642
                not_before: now - 60_000,
1643
                expires: now + 600_000,
1644
                grant: g,
1645
            },
1646
            &hub,
1647
            &hub_sk,
1648
        );
1649
        r.store().put_identity(&hub).unwrap();
1650
        r.store().put_certificate(&cert).unwrap();
1651
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1652
        let h = r.commit("work", &[]).unwrap();
1653
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1654
        (r, key, h)
1655
    };
1656
1657
    let (claude, key, h) = agent(
1658
        "claude",
1659
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1660
    );
1661
    let r = claude.push("origin", false).unwrap();
1662
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1663
    let host = Repo::open(&root.join("origin")).unwrap();
1664
    assert!(matches!(
1665
        host.authenticate_change(&h).unwrap(),
1666
        SignatureStatus::Valid { key: k, sealed: true, .. } if k == key
1667
    ));
1668
    a.pull("origin").unwrap();
1669
    assert!(matches!(
1670
        a.authenticate_change(&h).unwrap(),
1671
        SignatureStatus::Valid { key: k, .. } if k == key
1672
    ));
1673
1674
    let (none, _, _) = agent("none", None);
1675
    let r = none.push("origin", false).unwrap();
1676
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1677
    let mallory_sk = SecretKey::generate();
1678
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1679
    let (stranger, _, _) = agent(
1680
        "stranger",
1681
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1682
    );
1683
    let r = stranger.push("origin", false).unwrap();
1684
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1685
    let (ended, _, eh) = agent(
1686
        "ended",
1687
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1688
    );
1689
    let r = ended.push("origin", false).unwrap();
1690
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1691
    assert!(matches!(
1692
        ended.authenticate_change(&eh).unwrap(),
1693
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1694
    ));
1695
}
1696
1697
#[test]
83e0677b Andy McCall ↶ 1698
fn trust_policy_governs_pushes_and_fetches() {
1699
    hermetic();
1700
    let dir = tempfile::tempdir().unwrap();
1701
    let root = dir.path();
1702
    let origin = Repo::init(&root.join("origin")).unwrap();
1703
    let url = root.join("origin").to_string_lossy().to_string();
1704
1705
    // A is the root. Before the policy, an unsigned push from B is fine.
75167672 Andy McCall 1706
    let mut a = Repo::clone(&url, &root.join("a"))
1707
        .unwrap()
1708
        .with_home(root.join("home-a"));
1709
    let (key_a, _) = a
1710
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1711
        .unwrap();
1712
    let mut b = Repo::clone(&url, &root.join("b"))
1713
        .unwrap()
1714
        .with_home(root.join("home-b"));
83e0677b Andy McCall ↶ 1715
    write(&root.join("b"), "b.txt", b"b\n");
1716
    b.commit("unsigned before policy", &[]).unwrap();
1717
    assert!(b.push("origin", false).unwrap()[0].ok);
1718
1719
    // A creates the policy and pushes it; origin now enforces it.
1720
    write(&root.join("a"), "a.txt", b"a\n");
1721
    a.commit("a", &[]).unwrap();
1722
    let sp = a.policy_init().unwrap();
1723
    assert_eq!(sp.policy.serial, 1);
1724
    a.pull("origin").unwrap();
1725
    let results = a.push("origin", false).unwrap();
1726
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1727
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1728
1729
    // B pulls the policy. Without an identity B cannot push at all.
1730
    b.pull("origin").unwrap();
75167672 Andy McCall 1731
    assert!(
1732
        b.current_policy().unwrap().is_some(),
1733
        "the policy arrived with the fetch"
1734
    );
83e0677b Andy McCall ↶ 1735
    assert!(b.push("origin", false).is_err());
1736
    // With an identity the policy does not list, the push is rejected by origin.
75167672 Andy McCall 1737
    let (key_b, id_b) = b
1738
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1739
        .unwrap();
83e0677b Andy McCall ↶ 1740
    write(&root.join("b"), "b.txt", b"b2\n");
1741
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1742
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1743
    let r = b.push("origin", false).unwrap();
75167672 Andy McCall 1744
    assert!(
1745
        !r[0].ok && r[0].reason.contains("may not update"),
1746
        "{:?}",
1747
        r
1748
    );
83e0677b Andy McCall ↶ 1749
1750
    // A grants B (identity handed over as a file) and publishes the policy.
1751
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1752
    assert_eq!(sp.policy.serial, 2);
1753
    let r = a.push("origin", false).unwrap();
1754
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1755
    // B must fetch the new policy before pushing.
75167672 Andy McCall 1756
    assert!(b
1757
        .push("origin", false)
1758
        .unwrap_or_else(|e| vec![RefResult {
1759
            name: "main".into(),
1760
            ok: false,
1761
            reason: e.to_string()
1762
        }])
1763
        .iter()
1764
        .all(|x| !x.ok));
83e0677b Andy McCall ↶ 1765
    b.pull("origin").unwrap();
1766
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1767
    let r = b.push("origin", false).unwrap();
1768
    assert!(r[0].ok, "{:?}", r);
1769
    // Origin verified B's change under the policy.
1770
    let heads = origin.bookmark_heads().unwrap();
1771
    for h in &heads {
1772
        let c = origin.store().get_change(h).unwrap();
1773
        if c.author == key_b {
75167672 Andy McCall 1774
            origin
1775
                .change_allowed(
1776
                    h,
1777
                    &origin.current_policy().unwrap().unwrap().1.policy,
1778
                    "main",
1779
                )
1780
                .unwrap();
83e0677b Andy McCall ↶ 1781
        }
1782
    }
1783
1784
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1785
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1786
    forged.serial = 3;
1787
    forged.roots = vec![key_b];
1788
    let fh = forged.hash();
1789
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 1790
    let forged = SignedPolicy {
1791
        policy: forged,
1792
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1793
    };
1794
    let r = origin
1795
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1796
        .unwrap();
83e0677b Andy McCall ↶ 1797
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1798
    let stale = a.current_policy().unwrap().unwrap().1;
1799
    let mut old = stale.clone();
1800
    old.policy.serial = 1;
75167672 Andy McCall 1801
    let r = origin
1802
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1803
        .unwrap();
83e0677b Andy McCall ↶ 1804
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1805
1806
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1807
    a.pull("origin").unwrap();
1808
    a.policy_revoke(&key_b).unwrap();
1809
    let r = a.push("origin", false).unwrap();
1810
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1811
    b.pull("origin").unwrap();
1812
    write(&root.join("b"), "b.txt", b"b3\n");
1813
    b.commit("b3", &[]).unwrap();
1814
    let r = b.push("origin", false).unwrap();
1815
    assert!(!r[0].ok, "{:?}", r);
1816
1817
    // A clone by a third party receives and verifies everything.
75167672 Andy McCall 1818
    let c = Repo::clone(&url, &root.join("c"))
1819
        .unwrap()
1820
        .with_home(root.join("home-c"));
83e0677b Andy McCall ↶ 1821
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
75167672 Andy McCall 1822
    assert!(c
1823
        .current_policy()
1824
        .unwrap()
1825
        .unwrap()
1826
        .1
1827
        .policy
1828
        .roots
1829
        .contains(&key_a));
83e0677b Andy McCall ↶ 1830
    assert!(!c.snapshot("status").unwrap().changed);
1831
}
d02e545d Andy McCall ↶ 1832
9ae4d15a Andy McCall ↶ 1833
/// oxygen#66: a gc says what it is doing, phase by phase.
d02e545d Andy McCall ↶ 1834
#[test]
9ae4d15a Andy McCall ↶ 1835
fn gc_reports_its_phases() {
1836
    hermetic();
1837
    let dir = tempfile::tempdir().unwrap();
1838
    let repo = Repo::init(dir.path()).unwrap();
1839
    for i in 0..3 {
1840
        write(
1841
            dir.path(),
1842
            &format!("f{i}.txt"),
1843
            format!("{i}\n").as_bytes(),
1844
        );
1845
        repo.commit(&format!("c{i}"), &[]).unwrap();
1846
    }
1847
    let mut phases = Vec::new();
1848
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1849
        .unwrap();
1850
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1851
    assert!(
1852
        phases.iter().any(|p| p.starts_with("pruning")),
1853
        "{phases:?}"
1854
    );
1855
    assert!(
1856
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1857
        "{phases:?}"
1858
    );
1859
    assert!(
1860
        phases
1861
            .iter()
1862
            .any(|p| p.starts_with("writing the index of ")),
1863
        "{phases:?}"
1864
    );
1865
}
1866
1867
#[test]
d02e545d Andy McCall ↶ 1868
fn gc_packs_objects_and_history_still_works() {
1869
    hermetic();
1870
    let dir = tempfile::tempdir().unwrap();
1871
    let root = dir.path();
1872
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1873
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1874
        .unwrap();
d02e545d Andy McCall ↶ 1875
    repo.set_user_config("core.sign", "change").unwrap();
1876
    write(root, "a.txt", b"one\n");
1877
    let h1 = repo.commit("one", &[]).unwrap();
1878
    write(root, "a.txt", b"two\n");
1879
    write(root, "big.bin", &vec![0u8; 100_000]);
1880
    let h2 = repo.commit("two", &[]).unwrap();
ba160f60 Andy McCall ↶ 1881
    // Several snapshots leave superseded working-copy versions behind.
1882
    for i in 0..5 {
1883
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1884
        repo.snapshot("status").unwrap();
1885
    }
1886
    write(root, "a.txt", b"two\n");
1887
    repo.snapshot("status").unwrap();
d02e545d Andy McCall ↶ 1888
    let before = repo.store().list().unwrap();
1889
    assert!(repo.store().loose_count().unwrap() > 0);
ba160f60 Andy McCall ↶ 1890
1891
    // With the default retention every operation's view is a root: nothing prunes.
1892
    let r = repo.gc(true).unwrap();
1893
    assert_eq!(r.packed.objects, before.len());
1894
    assert_eq!(r.pruned.objects, 0);
d02e545d Andy McCall ↶ 1895
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1896
    assert_eq!(repo.store().list().unwrap(), before);
ba160f60 Andy McCall ↶ 1897
1898
    // With zero retention only the current view is a root: superseded
1899
    // working copies go, everything reachable stays.
1900
    repo.config.set("core.op-retention", "0").unwrap();
1901
    repo.save_config().unwrap();
21b2aec2 Andy McCall ↶ 1902
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
ba160f60 Andy McCall ↶ 1903
    let r = repo.gc(true).unwrap();
1904
    assert!(r.pruned.objects >= 5, "{r:?}");
1905
    let after = repo.store().list().unwrap();
1906
    assert!(after.len() < before.len());
1907
    assert!(after.contains(&h1) && after.contains(&h2));
1908
    for (_, op) in repo.op_log().unwrap() {
1909
        assert!(!op.command.is_empty(), "operation objects are all kept");
1910
    }
1911
    // Everything still works from the pruned, packed store.
d02e545d Andy McCall ↶ 1912
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
75167672 Andy McCall 1913
    assert!(matches!(
1914
        repo.verify_change(&h2).unwrap(),
1915
        SignatureStatus::Valid { .. }
1916
    ));
d02e545d Andy McCall ↶ 1917
    assert_eq!(repo.log().unwrap().len(), 3);
1918
    repo.checkout(&[h1], false, "checkout").unwrap();
1919
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1920
    repo.checkout(&[h2], false, "checkout").unwrap();
1921
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1922
    assert!(!repo.snapshot("status").unwrap().changed);
ba160f60 Andy McCall ↶ 1923
    // Grace period defers pruning of young garbage.
d02e545d Andy McCall ↶ 1924
    write(root, "a.txt", b"three\n");
1925
    repo.commit("three", &[]).unwrap();
ba160f60 Andy McCall ↶ 1926
    let r = repo.gc(false).unwrap();
1927
    assert_eq!(r.pruned.objects, 0);
1928
    assert!(r.pruned.deferred > 0);
1929
    let r = repo.gc(true).unwrap();
1930
    assert!(r.pruned.objects > 0);
1931
    assert_eq!(repo.log().unwrap().len(), 4);
21b2aec2 Andy McCall ↶ 1932
    // Restoring the default retention makes the old views roots again; the
1933
    // working copies they name were pruned, which gc tolerates.
1934
    repo.config.set("core.op-retention", "90").unwrap();
1935
    repo.save_config().unwrap();
1936
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1937
    let r = repo.gc(false).unwrap();
1938
    assert_eq!(r.pruned.objects, 0);
1939
    assert_eq!(repo.log().unwrap().len(), 4);
d02e545d Andy McCall ↶ 1940
}
614541c3 Andy McCall ↶ 1941
1942
#[test]
1943
fn describe_amend_abandon_heads() {
1944
    hermetic();
1945
    let dir = tempfile::tempdir().unwrap();
1946
    let root = dir.path();
1947
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1948
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1949
        .unwrap();
614541c3 Andy McCall ↶ 1950
    repo.set_user_config("core.sign", "change").unwrap();
1951
    write(root, "a.txt", b"one\n");
1952
    let h1 = repo.commit("first", &[]).unwrap();
1953
    write(root, "a.txt", b"one\ntwo\n");
1954
    let h2 = repo.commit("secnod", &[]).unwrap();
1955
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1956
1957
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1958
    let h2b = repo.describe(&h2, "second").unwrap();
1959
    assert_ne!(h2b, h2);
1960
    let c = repo.store().get_change(&h2b).unwrap();
75167672 Andy McCall 1961
    assert_eq!(
1962
        (c.change_id, c.message.as_str(), c.deps.clone()),
1963
        (id2, "second", vec![h1])
1964
    );
614541c3 Andy McCall ↶ 1965
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
75167672 Andy McCall 1966
    assert!(matches!(
1967
        repo.verify_change(&h2b).unwrap(),
1968
        SignatureStatus::Valid { .. }
1969
    ));
614541c3 Andy McCall ↶ 1970
    let s = repo.snapshot("status").unwrap();
1971
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
75167672 Andy McCall 1972
    assert_eq!(
1973
        repo.resolve_change(&id2.short(8)).unwrap(),
1974
        h2b,
1975
        "the old object is no longer reachable from the log"
1976
    );
c07e0e7d Andy McCall ↶ 1977
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1978
    let h1b = repo.describe(&h1, "first, described").unwrap();
1979
    assert_ne!(h1b, h1);
1980
    let heads = repo.bookmark_heads().unwrap();
1981
    assert_eq!(heads.len(), 1);
1982
    let top = repo.store().get_change(&heads[0]).unwrap();
1983
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
75167672 Andy McCall 1984
    assert!(
1985
        matches!(
1986
            repo.verify_change(&heads[0]).unwrap(),
1987
            SignatureStatus::Valid { .. }
1988
        ),
1989
        "rewritten own change is re-signed"
1990
    );
c07e0e7d Andy McCall ↶ 1991
    let (_, wc) = repo.working_copy().unwrap();
75167672 Andy McCall 1992
    assert_eq!(
1993
        wc.deps,
1994
        vec![heads[0]],
1995
        "the working copy follows the rewrite"
1996
    );
c07e0e7d Andy McCall ↶ 1997
    assert!(!repo.snapshot("status").unwrap().changed);
1998
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 1999
    assert!(
2000
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
2001
    );
614541c3 Andy McCall ↶ 2002
2003
    // amend: fold an edit into the head; the result is one change from h1.
2004
    write(root, "a.txt", b"one\ntwo\nthree\n");
2005
    write(root, "b.txt", b"b\n");
2006
    let h2c = repo.amend(None).unwrap();
2007
    let c = repo.store().get_change(&h2c).unwrap();
2008
    assert_eq!(c.change_id, id2);
2009
    assert_eq!(c.message, "second");
2010
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
75167672 Andy McCall 2011
    assert_eq!(
2012
        repo.log().unwrap().len(),
2013
        3,
2014
        "working copy, amended head, first"
2015
    );
614541c3 Andy McCall ↶ 2016
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
75167672 Andy McCall 2017
    assert!(
2018
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
2019
    );
614541c3 Andy McCall ↶ 2020
    assert!(snap.files.contains_key("b.txt"));
2021
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 2022
    assert!(
2023
        repo.amend(None).is_err(),
2024
        "clean working copy and no message"
2025
    );
614541c3 Andy McCall ↶ 2026
    let h2d = repo.amend(Some("second, amended")).unwrap();
75167672 Andy McCall 2027
    assert_eq!(
2028
        repo.store().get_change(&h2d).unwrap().message,
2029
        "second, amended"
2030
    );
614541c3 Andy McCall ↶ 2031
2032
    // abandon: the head goes, its content stays as uncommitted work.
2033
    repo.abandon(&h2d).unwrap();
75167672 Andy McCall 2034
    assert_eq!(
2035
        repo.bookmark_heads().unwrap(),
2036
        vec![h1b],
2037
        "the described first change is the head again"
2038
    );
614541c3 Andy McCall ↶ 2039
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 2040
    let paths: Vec<_> = s
2041
        .statuses
2042
        .iter()
2043
        .map(|p| (p.path.as_str(), p.status))
2044
        .collect();
2045
    assert_eq!(
2046
        paths,
2047
        vec![
2048
            ("a.txt", ChangeStatus::Modified),
2049
            ("b.txt", ChangeStatus::Added)
2050
        ]
2051
    );
614541c3 Andy McCall ↶ 2052
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
2053
    let h3 = repo.commit("recommitted", &[]).unwrap();
2054
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
2055
    // undo brings the abandoned head back.
2056
    repo.undo().unwrap();
2057
    repo.undo().unwrap();
2058
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
c07e0e7d Andy McCall ↶ 2059
6706bdcf Andy McCall ↶ 2060
    // Abandoning a non-head whose dependent references its atoms reifies
2061
    // the references (here: a.txt vanishes with it, so the dependent's edit
2062
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
c07e0e7d Andy McCall ↶ 2063
    let base = repo.bookmark_heads().unwrap()[0];
2064
    let base_change = repo.store().get_change(&base).unwrap();
2065
    let h1_now = base_change.deps[0];
6706bdcf Andy McCall ↶ 2066
    let notes = repo.abandon(&h1_now).unwrap();
75167672 Andy McCall 2067
    assert!(
2068
        !notes.is_empty(),
2069
        "the dependent's edit of a.txt was reified"
2070
    );
6706bdcf Andy McCall ↶ 2071
    let heads = repo.bookmark_heads().unwrap();
2072
    let after = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 2073
    assert!(
2074
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
2075
        "{:?}",
2076
        after.files.keys()
2077
    );
6706bdcf Andy McCall ↶ 2078
    repo.undo().unwrap();
2079
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
c07e0e7d Andy McCall ↶ 2080
    write(root, "c.txt", b"c\n");
2081
    let hc = repo.commit("c", &[]).unwrap();
2082
    write(root, "d.txt", b"d\n");
2083
    let hd = repo.commit("d", &[hc]).unwrap();
2084
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
2085
    repo.abandon(&hc).unwrap();
2086
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2087
    assert!(!heads.contains(&hc));
75167672 Andy McCall 2088
    let d_now = heads
2089
        .iter()
2090
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
2091
        .copied()
2092
        .unwrap();
2093
    assert!(
2094
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
2095
        "d inherited c's (empty) dependencies"
2096
    );
c07e0e7d Andy McCall ↶ 2097
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 2098
    assert_eq!(
2099
        s.statuses
2100
            .iter()
2101
            .map(|p| p.path.as_str())
2102
            .collect::<Vec<_>>(),
2103
        vec!["c.txt"],
2104
        "c's content is now uncommitted work"
2105
    );
614541c3 Andy McCall ↶ 2106
}
79ab8528 Andy McCall ↶ 2107
2108
#[test]
2109
fn git_export_mirrors_history() {
2110
    hermetic();
75167672 Andy McCall 2111
    if std::process::Command::new("git")
2112
        .arg("--version")
2113
        .output()
2114
        .is_err()
2115
    {
79ab8528 Andy McCall ↶ 2116
        eprintln!("git not installed; skipping");
2117
        return;
2118
    }
2119
    let dir = tempfile::tempdir().unwrap();
2120
    let root = dir.path();
75167672 Andy McCall 2121
    let mut repo = Repo::init(&root.join("r"))
2122
        .unwrap()
2123
        .with_home(root.join("home"));
2124
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
2125
        .unwrap();
79ab8528 Andy McCall ↶ 2126
    let r = root.join("r");
2127
    write(&r, "README.md", b"hello\n");
2128
    write(&r, "src/main.rs", b"fn main() {}\n");
2129
    let h1 = repo.commit("first", &[]).unwrap();
2130
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
2131
    write(&r, "logo.png", b"\x89PNG\0\0");
2132
    let h2 = repo.commit("second", &[]).unwrap();
2133
2134
    let git_dir = root.join("mirror.git");
2135
    let rep = repo.git_export(&git_dir).unwrap();
2136
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
2137
    let git = |args: &[&str]| -> String {
75167672 Andy McCall 2138
        let out = std::process::Command::new("git")
2139
            .arg("-C")
2140
            .arg(&git_dir)
2141
            .args(args)
2142
            .output()
2143
            .unwrap();
2144
        assert!(
2145
            out.status.success(),
2146
            "{}",
2147
            String::from_utf8_lossy(&out.stderr)
2148
        );
79ab8528 Andy McCall ↶ 2149
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2150
    };
2151
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
2152
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2153
    assert_eq!(git(&["show", "main:README.md"]), "hello");
2154
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 2155
    assert!(
2156
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
2157
        "{body}"
2158
    );
79ab8528 Andy McCall ↶ 2159
    assert!(body.contains("Change-Id: "), "{body}");
75167672 Andy McCall 2160
    assert_eq!(
2161
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
2162
        "Ada Lovelace <[email protected]>"
2163
    );
2164
    assert_eq!(
2165
        git(&["ls-tree", "--name-only", "main"]),
2166
        "README.md\nlogo.png\nsrc"
2167
    );
79ab8528 Andy McCall ↶ 2168
2169
    // Re-export is incremental.
2170
    let rep = repo.git_export(&git_dir).unwrap();
2171
    assert_eq!((rep.exported, rep.skipped), (0, 2));
2172
2173
    // An independent change makes two heads; the next state is one more
2174
    // commit on the linear branch whose tree is the union.
2175
    repo.checkout(&[h1], false, "checkout").unwrap();
2176
    write(&r, "other.txt", b"o\n");
2177
    let h3 = repo.commit("third", &[]).unwrap();
2178
    let rep = repo.git_export(&git_dir).unwrap();
2179
    assert_eq!((rep.exported, rep.heads), (1, 2));
2180
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
2181
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
2182
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
2183
    assert_eq!(git(&["show", "main:other.txt"]), "o");
2184
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
75167672 Andy McCall 2185
    assert_eq!(
2186
        git(&["ls-tree", "--name-only", "main"]),
2187
        "README.md\nlogo.png\nother.txt\nsrc"
2188
    );
79ab8528 Andy McCall ↶ 2189
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 2190
    assert!(
2191
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
2192
        "{body}"
2193
    );
79ab8528 Andy McCall ↶ 2194
    // A rewrite is a new state whose one new change is the rewritten one.
2195
    repo.describe(&h3, "third, described").unwrap();
2196
    let rep = repo.git_export(&git_dir).unwrap();
2197
    assert_eq!(rep.exported, 1);
75167672 Andy McCall 2198
    assert_eq!(
2199
        git(&["log", "-1", "--format=%s", "main"]),
2200
        "third, described"
2201
    );
79ab8528 Andy McCall ↶ 2202
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
2203
    let _ = h2;
2204
}
c3069537 Andy McCall ↶ 2205
2206
#[test]
2207
fn git_import_reproduces_trees() {
c3d2ef61 Andy McCall ↶ 2208
    git_import_reproduces_trees_with(None);
2209
}
2210
2211
/// The same import with every merge rendered in batches of one file
2212
/// (oxygen#25): what a merge onto a base of thousands of files takes.
2213
#[test]
2214
fn git_import_reproduces_trees_in_batches() {
2215
    git_import_reproduces_trees_with(Some(1));
2216
}
2217
2218
fn git_import_reproduces_trees_with(batch: Option<usize>) {
2219
    crate::repo::git::set_merge_batch_for_tests(batch);
c3069537 Andy McCall ↶ 2220
    hermetic();
75167672 Andy McCall 2221
    if std::process::Command::new("git")
2222
        .arg("--version")
2223
        .output()
2224
        .is_err()
2225
    {
c3069537 Andy McCall ↶ 2226
        eprintln!("git not installed; skipping");
2227
        return;
2228
    }
2229
    let dir = tempfile::tempdir().unwrap();
2230
    let root = dir.path();
2231
    let g = root.join("src.git");
2232
    fs::create_dir_all(&g).unwrap();
2233
    let git = |args: &[&str]| -> String {
2234
        let out = std::process::Command::new("git")
2235
            .arg("-C")
2236
            .arg(&g)
75167672 Andy McCall 2237
            .args([
2238
                "-c",
2239
                "user.name=Grace",
2240
                "-c",
2241
                "[email protected]",
2242
                "-c",
2243
                "commit.gpgsign=false",
2244
            ])
c3069537 Andy McCall ↶ 2245
            .args(args)
2246
            .output()
2247
            .unwrap();
75167672 Andy McCall 2248
        assert!(
2249
            out.status.success(),
2250
            "git {args:?}: {}",
2251
            String::from_utf8_lossy(&out.stderr)
2252
        );
c3069537 Andy McCall ↶ 2253
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2254
    };
2255
    git(&["init", "-q", "-b", "main"]);
2256
    write(&g, "README.md", b"# Hi\n");
2257
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
2258
    git(&["add", "."]);
2259
    git(&["commit", "-q", "-m", "initial"]);
2260
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2261
    write(&g, "run.sh", b"#!/bin/sh\n");
2262
    #[cfg(unix)]
2263
    {
2264
        use std::os::unix::fs::PermissionsExt;
2265
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
2266
    }
2267
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
2268
    git(&["add", "."]);
75167672 Andy McCall 2269
    git(&[
2270
        "commit",
2271
        "-q",
2272
        "-m",
2273
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
2274
    ]);
c3069537 Andy McCall ↶ 2275
    // A branch that edits README, merged back with a conflict-free merge.
2276
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
2277
    write(&g, "README.md", b"# Hi\n\nMore.\n");
2278
    git(&["commit", "-q", "-am", "readme"]);
2279
    git(&["checkout", "-q", "main"]);
2280
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
2281
    // A branch from the initial commit inserting at the same place as
2282
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
2283
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
2284
    git(&["checkout", "-q", "-b", "clash", &initial]);
2285
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
2286
    git(&["commit", "-q", "-am", "clash"]);
2287
    git(&["checkout", "-q", "main"]);
75167672 Andy McCall 2288
    let _ = std::process::Command::new("git")
2289
        .arg("-C")
2290
        .arg(&g)
2291
        .args(["merge", "-q", "clash"])
2292
        .output();
2293
    write(
2294
        &g,
2295
        "src/lib.rs",
2296
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2297
    );
c3069537 Andy McCall ↶ 2298
    git(&["add", "."]);
2299
    git(&["commit", "-q", "-m", "resolve clash"]);
2300
    git(&["rm", "-q", "logo.png"]);
2301
    git(&["commit", "-q", "-m", "drop logo"]);
6e723b81 Andy McCall ↶ 2302
    // A rename with a small edit is imported as a move of the same node.
2303
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
75167672 Andy McCall 2304
    write(
2305
        &g,
2306
        "src/lib2.rs",
2307
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
2308
    );
6e723b81 Andy McCall ↶ 2309
    git(&["add", "."]);
2310
    git(&["commit", "-q", "-m", "rename lib"]);
958fb27d Andy McCall ↶ 2311
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
2312
    // run.sh is the same as in the first parent's tree, but the merged
2313
    // change touched it, so the importer must compare it, not skip it.
2314
    git(&["checkout", "-q", "-b", "discarded"]);
2315
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
2316
    git(&["commit", "-q", "-am", "discarded edit"]);
2317
    git(&["checkout", "-q", "main"]);
314db9b4 Andy McCall ↶ 2318
    git(&[
2319
        "merge",
2320
        "-q",
2321
        "-s",
2322
        "ours",
2323
        "-m",
2324
        "merge discarded, keeping ours",
2325
        "discarded",
2326
    ]);
c3069537 Andy McCall ↶ 2327
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
2328
2329
    let dest = root.join("oxy");
2330
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
2331
    let rep = repo.import_git(&g, "main").unwrap();
2332
    assert_eq!(rep.commits, expected_count);
958fb27d Andy McCall ↶ 2333
    assert_eq!(rep.merges, 3);
314db9b4 Andy McCall ↶ 2334
    assert_eq!(
2335
        fs::read(dest.join("run.sh")).unwrap(),
2336
        b"#!/bin/sh\n",
2337
        "the ours merge kept main's run.sh"
2338
    );
958fb27d Andy McCall ↶ 2339
    let v = repo.verify_git_import(&g, "main").unwrap();
2340
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
2341
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
c3069537 Andy McCall ↶ 2342
    // The working copy equals the Git tree at main.
75167672 Andy McCall 2343
    assert_eq!(
2344
        fs::read(dest.join("src/lib2.rs")).unwrap(),
2345
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2346
    );
6e723b81 Andy McCall ↶ 2347
    assert!(!dest.join("src/lib.rs").exists());
75167672 Andy McCall 2348
    assert_eq!(
2349
        fs::read(dest.join("README.md")).unwrap(),
2350
        b"# Hi\n\nMore.\n"
2351
    );
c3069537 Andy McCall ↶ 2352
    assert!(!dest.join("logo.png").exists());
2353
    #[cfg(unix)]
2354
    {
2355
        use std::os::unix::fs::PermissionsExt;
75167672 Andy McCall 2356
        assert!(
2357
            fs::metadata(dest.join("run.sh"))
2358
                .unwrap()
2359
                .permissions()
2360
                .mode()
2361
                & 0o111
2362
                != 0
2363
        );
c3069537 Andy McCall ↶ 2364
    }
75167672 Andy McCall 2365
    assert!(
2366
        !repo.snapshot("status").unwrap().changed,
2367
        "clean after import"
2368
    );
c3069537 Andy McCall ↶ 2369
    let heads = repo.bookmark_heads().unwrap();
2370
    let st = repo.load_state(&heads).unwrap();
2371
    assert!(!st.materialize().is_conflicted());
2372
    assert_eq!(st.len(), expected_count);
75167672 Andy McCall 2373
    let tip = repo
2374
        .log()
2375
        .unwrap()
2376
        .into_iter()
2377
        .find(|e| e.change.message.starts_with("rename lib"))
2378
        .unwrap();
6e723b81 Andy McCall ↶ 2379
    let c = repo.store().get_change(&tip.hash).unwrap();
75167672 Andy McCall 2380
    assert!(
2381
        c.tree_ops
2382
            .iter()
2383
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
2384
        "{:?}",
2385
        c.tree_ops
2386
    );
2387
    assert!(!c
2388
        .tree_ops
2389
        .iter()
2390
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
c3069537 Andy McCall ↶ 2391
    // Messages carry Git trailers; the Change-Id trailer was honoured.
2392
    let log = repo.log().unwrap();
75167672 Andy McCall 2393
    let second = log
2394
        .iter()
2395
        .find(|e| e.change.message.starts_with("second"))
2396
        .unwrap();
2397
    assert_eq!(
2398
        second.change.change_id,
2399
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
2400
    );
2401
    assert!(second
2402
        .change
2403
        .message
2404
        .contains("Git-Author: Grace <[email protected]>"));
2405
    let resolve = log
2406
        .iter()
2407
        .find(|e| e.change.message.starts_with("resolve clash"))
2408
        .unwrap();
2409
    assert_eq!(
2410
        resolve.change.kind,
2411
        ChangeKind::Resolution,
2412
        "a conflicting Git merge becomes a resolution"
2413
    );
c3069537 Andy McCall ↶ 2414
    // Re-importing into another fresh repository gives the same ChangeIds.
75167672 Andy McCall 2415
    let repo2 = Repo::init(&root.join("oxy2"))
2416
        .unwrap()
2417
        .with_home(root.join("home"));
c3069537 Andy McCall ↶ 2418
    repo2.import_git(&g, "main").unwrap();
dfb23a3a Andy McCall ↶ 2419
    // New nodes' identifiers derive from the commit (spec §23), so the
2420
    // re-import is not just the same ChangeIds but the same changes.
2421
    assert_eq!(
2422
        repo2.bookmark_heads().unwrap(),
2423
        repo.bookmark_heads().unwrap()
2424
    );
75167672 Andy McCall 2425
    let ids: BTreeSet<ChangeId> = repo
2426
        .log()
2427
        .unwrap()
2428
        .iter()
2429
        .filter(|e| !e.is_working_copy)
2430
        .map(|e| e.change.change_id)
2431
        .collect();
2432
    let ids2: BTreeSet<ChangeId> = repo2
2433
        .log()
2434
        .unwrap()
2435
        .iter()
2436
        .filter(|e| !e.is_working_copy)
2437
        .map(|e| e.change.change_id)
2438
        .collect();
c3069537 Andy McCall ↶ 2439
    assert_eq!(ids, ids2);
2440
    // Round trip back out to Git reproduces the tip tree.
2441
    let mirror = root.join("mirror.git");
2442
    repo.git_export(&mirror).unwrap();
75167672 Andy McCall 2443
    let out = std::process::Command::new("git")
2444
        .arg("-C")
2445
        .arg(&mirror)
2446
        .args(["show", "main:src/lib2.rs"])
2447
        .output()
2448
        .unwrap();
2449
    assert_eq!(
2450
        String::from_utf8_lossy(&out.stdout),
2451
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2452
    );
2453
    let out = std::process::Command::new("git")
2454
        .arg("-C")
2455
        .arg(&mirror)
2456
        .args(["show", "main:src/lib.rs"])
2457
        .output()
2458
        .unwrap();
2459
    assert!(
2460
        !out.status.success(),
2461
        "the old path is gone from the export"
2462
    );
c3069537 Andy McCall ↶ 2463
}
252e8cb2 Andy McCall ↶ 2464
2465
#[test]
2466
fn checkpoints_accelerate_loading_and_stay_correct() {
2467
    hermetic();
2468
    let dir = tempfile::tempdir().unwrap();
2469
    let root = dir.path();
2470
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2471
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2472
    repo.save_config().unwrap();
2473
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2474
    let mut hashes = Vec::new();
2475
    for i in 0..12 {
75167672 Andy McCall 2476
        write(
2477
            root,
2478
            "a.txt",
2479
            format!(
2480
                "{}\n",
2481
                (0..=i)
2482
                    .map(|k| k.to_string())
2483
                    .collect::<Vec<_>>()
2484
                    .join("\n")
2485
            )
2486
            .as_bytes(),
2487
        );
252e8cb2 Andy McCall ↶ 2488
        write(root, &format!("f{i}.txt"), b"x\n");
2489
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2490
    }
75167672 Andy McCall 2491
    let (_, cp) = repo
2492
        .latest_checkpoint("main")
2493
        .unwrap()
2494
        .expect("automatic checkpoint");
252e8cb2 Andy McCall ↶ 2495
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2496
    // Loading through the checkpoint equals loading everything.
2497
    let heads = repo.bookmark_heads().unwrap();
2498
    let fast = repo.load_state(&heads).unwrap();
2499
    let full = repo.load_state_full(&heads).unwrap();
2500
    assert_eq!(fast.len(), full.len());
2501
    assert_eq!(fast.heads(), full.heads());
2502
    let (a, b) = (fast.materialize(), full.materialize());
75167672 Andy McCall 2503
    assert_eq!(
2504
        a.files.keys().collect::<Vec<_>>(),
2505
        b.files.keys().collect::<Vec<_>>()
2506
    );
252e8cb2 Andy McCall ↶ 2507
    for (p, f) in &a.files {
2508
        assert_eq!(f.content, b.files[p].content, "{p}");
2509
    }
2510
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2511
    // A head set that does not contain the checkpoint's heads falls back.
75167672 Andy McCall 2512
    assert!(repo
2513
        .load_state_checkpointed(&[hashes[0]])
2514
        .unwrap()
2515
        .is_none());
252e8cb2 Andy McCall ↶ 2516
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2517
    // Everything else keeps working on top of the checkpoint.
2518
    assert!(!repo.snapshot("status").unwrap().changed);
2519
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2520
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2521
    let (r, n, bytes) = repo.checkpoint().unwrap();
2522
    assert!(n >= 12 && bytes > 0);
2523
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2524
    write(root, "a.txt", b"after\n");
2525
    let h_after = repo.commit("after", &[]).unwrap();
2526
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2527
    assert!(st.contains(&h_after));
75167672 Andy McCall 2528
    assert!(
2529
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2530
    );
252e8cb2 Andy McCall ↶ 2531
    assert_eq!(repo.log().unwrap().len(), 14);
2532
    // Checkpoints survive gc.
2533
    repo.gc(true).unwrap();
2534
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
75167672 Andy McCall 2535
    assert!(repo
2536
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2537
        .unwrap()
2538
        .is_some());
252e8cb2 Andy McCall ↶ 2539
}
135212de Andy McCall ↶ 2540
2541
#[test]
2542
fn quick_status_for_prompts() {
2543
    hermetic();
2544
    let dir = tempfile::tempdir().unwrap();
2545
    let root = dir.path();
2546
    let origin = Repo::init(&root.join("origin")).unwrap();
2547
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2548
    let a = Repo::clone(&url, &root.join("a"))
2549
        .unwrap()
2550
        .with_home(root.join("home"));
135212de Andy McCall ↶ 2551
    let ops_before = a.op_log().unwrap().len();
2552
    let info = a.quick_status().unwrap();
75167672 Andy McCall 2553
    assert_eq!(
2554
        (
2555
            info.bookmark.as_str(),
2556
            info.heads,
2557
            info.dirty,
2558
            info.conflicted,
2559
            info.ahead,
2560
            info.behind
2561
        ),
2562
        ("main", 0, false, false, Some(0), Some(0))
2563
    );
135212de Andy McCall ↶ 2564
    write(&root.join("a"), "f.txt", b"f\n");
2565
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
75167672 Andy McCall 2566
    assert_eq!(
2567
        a.op_log().unwrap().len(),
2568
        ops_before,
2569
        "quick_status records nothing"
2570
    );
135212de Andy McCall ↶ 2571
    // A snapshotted but uncommitted change is still dirty.
2572
    a.snapshot("status").unwrap();
2573
    assert!(a.quick_status().unwrap().dirty);
2574
    a.commit("f", &[]).unwrap();
2575
    let info = a.quick_status().unwrap();
2576
    assert!(!info.dirty, "clean right after a commit");
2577
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
75167672 Andy McCall 2578
    assert_eq!(
2579
        info.format("%b %c%d%x%A%D"),
2580
        format!("main {}+1", info.change_id)
2581
    );
135212de Andy McCall ↶ 2582
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2583
    // Touching a file without changing it is not dirty; changing content of
2584
    // the same size is.
2585
    let p = root.join("a/f.txt");
2586
    let content = fs::read(&p).unwrap();
2587
    fs::write(&p, &content).unwrap();
2588
    assert!(!a.quick_status().unwrap().dirty);
2589
    fs::write(&p, b"g\n").unwrap();
2590
    assert!(a.quick_status().unwrap().dirty);
2591
    fs::write(&p, b"f\n").unwrap();
2592
    // Push, then a second clone commits and pushes: we are behind.
2593
    assert!(a.push("origin", false).unwrap()[0].ok);
2594
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
75167672 Andy McCall 2595
    let b = Repo::clone(&url, &root.join("b"))
2596
        .unwrap()
2597
        .with_home(root.join("home-b"));
135212de Andy McCall ↶ 2598
    write(&root.join("b"), "g.txt", b"g\n");
2599
    b.commit("g", &[]).unwrap();
2600
    b.push("origin", false).unwrap();
2601
    a.fetch("origin").unwrap();
2602
    let info = a.quick_status().unwrap();
2603
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2604
    assert_eq!(info.format("%A%D"), "-1");
2605
    let _ = origin;
2606
}
b3c5a59a Andy McCall ↶ 2607
2608
#[test]
2609
fn lazy_blobs_are_fetched_on_first_read() {
2610
    hermetic();
2611
    let dir = tempfile::tempdir().unwrap();
2612
    let root = dir.path();
2613
    let origin_dir = root.join("origin");
75167672 Andy McCall 2614
    let origin = Repo::init(&origin_dir)
2615
        .unwrap()
2616
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 2617
    let url = origin_dir.to_string_lossy().to_string();
2618
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2619
    write(&origin_dir, "big.bin", &big);
2620
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2621
    write(&origin_dir, "t.txt", b"t\n");
2622
    let h = origin.commit("blobs", &[]).unwrap();
2623
    let big_ref = Repo::blob_ref(&big);
2624
2625
    // Fetch only (no checkout) with a filter: the big blob stays absent.
75167672 Andy McCall 2626
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2627
        .unwrap()
2628
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 2629
    let a = {
2630
        let mut a = a;
2631
        a.config.set("remote.origin.url", &url).unwrap();
2632
        a.config.set("filter.max-blob", "100K").unwrap();
2633
        a.save_config().unwrap();
2634
        a
2635
    };
2636
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2637
    a.fetch("origin").unwrap();
2638
    assert!(a.store().has(&h));
2639
    assert!(!a.store().has(&big_ref), "withheld");
75167672 Andy McCall 2640
    assert!(
2641
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2642
        "small blob came along"
2643
    );
b3c5a59a Andy McCall ↶ 2644
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2645
2646
    // status and commit do not need it: adopt the state, edit a text file, commit.
2647
    let (op_ref, op) = a.head_op().unwrap();
2648
    let mut view = op.view.clone();
75167672 Andy McCall 2649
    view.bookmarks.insert(
2650
        "main".into(),
2651
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2652
    );
b3c5a59a Andy McCall ↶ 2653
    a.record_op(&[op_ref], "adopt", view).unwrap();
2654
    // Checkout reads the blob lazily, which fetches it.
2655
    a.checkout(&[h], true, "checkout").unwrap();
2656
    assert!(a.store().has(&big_ref), "fetched on first read");
2657
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2658
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2659
    write(&root.join("a"), "t.txt", b"t2\n");
2660
    a.commit("text edit", &[]).unwrap();
2661
2662
    // clone --max-blob records the filter; the checkout fetches lazily.
7421309f Andy McCall ↶ 2663
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
b3c5a59a Andy McCall ↶ 2664
    assert_eq!(b.config.max_blob, Some(1024));
2665
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2666
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2667
    assert!(parse_size("lots").is_err());
2668
}
7421309f Andy McCall ↶ 2669
2670
#[test]
2671
fn sparse_checkout_materializes_only_chosen_paths() {
2672
    hermetic();
2673
    let dir = tempfile::tempdir().unwrap();
2674
    let root = dir.path();
2675
    let origin_dir = root.join("origin");
75167672 Andy McCall 2676
    let origin = Repo::init(&origin_dir)
2677
        .unwrap()
2678
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 2679
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2680
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2681
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2682
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2683
    write(&origin_dir, "docs/logo.png", &logo);
2684
    write(&origin_dir, "README.md", b"# top\n");
2685
    let h1 = origin.commit("tree", &[]).unwrap();
2686
    let url = origin_dir.to_string_lossy().to_string();
2687
75167672 Andy McCall 2688
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2689
        .unwrap()
2690
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 2691
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2692
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2693
    assert!(root.join("a/src/main.rs").exists());
2694
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
75167672 Andy McCall 2695
    assert!(
2696
        !a.store().has(&Repo::blob_ref(&logo)),
2697
        "out-of-scope blob never fetched"
2698
    );
2699
    assert!(
2700
        !a.snapshot("status").unwrap().changed,
2701
        "out-of-scope files are not removals"
2702
    );
05e71ed6 Andy McCall ↶ 2703
    assert!(!a.quick_status().unwrap().dirty);
7421309f Andy McCall ↶ 2704
2705
    // Edits in scope commit normally and keep the rest of the tree intact.
75167672 Andy McCall 2706
    write(
2707
        &root.join("a"),
2708
        "src/lib.rs",
2709
        b"pub fn a() {}\npub fn b() {}\n",
2710
    );
7421309f Andy McCall ↶ 2711
    let h2 = a.commit("edit lib", &[]).unwrap();
2712
    let st = a.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 2713
    assert!(
2714
        st.files.contains_key("docs/guide.md"),
2715
        "the state still has everything"
2716
    );
7421309f Andy McCall ↶ 2717
    assert!(a.push("origin", false).unwrap()[0].ok);
2718
    // Files created outside the scope are ignored by status.
2719
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2720
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2721
2722
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2723
    let mut a = a;
2724
    a.config.set("filter.paths", "src,docs").unwrap();
2725
    a.save_config().unwrap();
75167672 Andy McCall 2726
    let r = a
2727
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2728
        .unwrap();
7421309f Andy McCall ↶ 2729
    assert!(r.written >= 2);
75167672 Andy McCall 2730
    assert_eq!(
2731
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2732
        logo,
2733
        "now fetched lazily"
2734
    );
7421309f Andy McCall ↶ 2735
    assert!(!root.join("a/README.md").exists());
2736
    // Origin sees the change made under a sparse checkout with the full tree intact.
2737
    origin.pull("origin").err();
75167672 Andy McCall 2738
    let full = origin
2739
        .load_state(&origin.bookmark_heads().unwrap())
2740
        .unwrap()
2741
        .materialize();
2742
    assert!(
2743
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2744
    );
7421309f Andy McCall ↶ 2745
    assert!(full.files.contains_key("README.md"));
2746
    let _ = h1;
2747
}
2863456a Andy McCall ↶ 2748
2749
#[test]
2750
fn shallow_clone_and_deepen() {
2751
    hermetic();
2752
    let dir = tempfile::tempdir().unwrap();
2753
    let root = dir.path();
2754
    let origin_dir = root.join("origin");
75167672 Andy McCall 2755
    let origin = Repo::init(&origin_dir)
2756
        .unwrap()
2757
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2758
    let mut hashes = Vec::new();
2759
    for i in 0..8 {
75167672 Andy McCall 2760
        write(
2761
            &origin_dir,
2762
            "a.txt",
2763
            format!(
2764
                "{}\n",
2765
                (0..=i)
2766
                    .map(|k| k.to_string())
2767
                    .collect::<Vec<_>>()
2768
                    .join("\n")
2769
            )
2770
            .as_bytes(),
2771
        );
2863456a Andy McCall ↶ 2772
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2773
    }
2774
    let url = origin_dir.to_string_lossy().to_string();
75167672 Andy McCall 2775
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2776
        .unwrap()
2777
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2778
    assert!(a.is_shallow());
75167672 Andy McCall 2779
    assert_eq!(
2780
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2781
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2782
    );
2783
    assert!(
2784
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2785
        "three levels present"
2786
    );
2863456a Andy McCall ↶ 2787
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2788
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
75167672 Andy McCall 2789
    assert_eq!(
2790
        a.log().unwrap().len(),
2791
        9,
2792
        "the log shows every change from the checkpoint's metadata"
2793
    );
2863456a Andy McCall ↶ 2794
    assert!(!a.snapshot("status").unwrap().changed);
2795
    assert_eq!(a.quick_status().unwrap().heads, 1);
2796
2797
    // Work continues on top of the shallow history and pushes back.
2798
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2799
    let h_new = a.commit("c8", &[]).unwrap();
2800
    assert!(a.push("origin", false).unwrap()[0].ok);
2801
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2802
    // Fetching new work from origin into the shallow clone works too.
2803
    write(&origin_dir, "b.txt", b"b\n");
2804
    origin.pull("origin").err();
2805
    let (_, wc) = origin.working_copy().unwrap();
2806
    let _ = wc;
75167672 Andy McCall 2807
    origin
2808
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2809
        .unwrap();
2863456a Andy McCall ↶ 2810
    write(&origin_dir, "b.txt", b"b\n");
2811
    let h_b = origin.commit("b", &[]).unwrap();
2812
    let pr = a.pull("origin").unwrap();
2813
    assert!(pr.changed);
2814
    assert!(a.store().has(&h_b));
2815
    assert!(root.join("a/b.txt").exists());
2816
2817
    // Deepening fetches older history until the boundary is gone.
2818
    // Every commit also depends on the change that created the file, so two
2819
    // levels below the boundary hold h4, h3, and the root.
2820
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2821
    assert!(a.store().has(&hashes[3]));
2822
    assert!(a.is_shallow());
2823
    a.deepen("origin", 100).unwrap();
2824
    assert!(!a.is_shallow(), "boundary reached the root");
2825
    assert!(a.store().has(&hashes[0]));
75167672 Andy McCall 2826
    assert_eq!(
2827
        a.load_state_full(&a.bookmark_heads().unwrap())
2828
            .unwrap()
2829
            .len(),
2830
        10
2831
    );
2863456a Andy McCall ↶ 2832
}
132b884b Andy McCall ↶ 2833
2834
#[test]
2835
fn tags_are_immutable_named_states_and_travel() {
2836
    hermetic();
2837
    let dir = tempfile::tempdir().unwrap();
2838
    let root = dir.path();
2839
    let origin = Repo::init(&root.join("origin")).unwrap();
2840
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2841
    let mut a = Repo::clone(&url, &root.join("a"))
2842
        .unwrap()
2843
        .with_home(root.join("home-a"));
2844
    let (key_a, _) = a
2845
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2846
        .unwrap();
132b884b Andy McCall ↶ 2847
    write(&root.join("a"), "f.txt", b"1\n");
2848
    let h1 = a.commit("one", &[]).unwrap();
2849
    write(&root.join("a"), "f.txt", b"1\n2\n");
2850
    let h2 = a.commit("two", &[]).unwrap();
2851
2852
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
75167672 Andy McCall 2853
    assert_eq!(
2854
        (t.heads.clone(), t.signer.as_deref()),
2855
        (vec![h1], Some("Ada"))
2856
    );
132b884b Andy McCall ↶ 2857
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2858
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2859
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2860
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2861
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2862
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2863
    assert_eq!(sa.sigs[0].key, key_a);
2864
    // Checkout by tag.
75167672 Andy McCall 2865
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2866
        .unwrap();
132b884b Andy McCall ↶ 2867
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
75167672 Andy McCall 2868
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2869
        .unwrap();
132b884b Andy McCall ↶ 2870
2871
    // Push carries the tag; a second attestation for the name is refused.
2872
    let r = a.push("origin", false).unwrap();
2873
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2874
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
75167672 Andy McCall 2875
    let mut forged = a
2876
        .tag_refs()
2877
        .unwrap()
2878
        .into_iter()
2879
        .find(|t| t.name == "v1")
2880
        .unwrap();
2881
    forged.state = origin
2882
        .store()
2883
        .put_state(&StateObject::new(vec![h2]))
2884
        .unwrap();
132b884b Andy McCall ↶ 2885
    forged.heads = vec![h2];
2886
    forged.attestation = None;
75167672 Andy McCall 2887
    let r = origin
2888
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2889
        .unwrap();
132b884b Andy McCall ↶ 2890
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2891
2892
    // A clone gets the tag; a later tag arrives on fetch.
75167672 Andy McCall 2893
    let b = Repo::clone(&url, &root.join("b"))
2894
        .unwrap()
2895
        .with_home(root.join("home-b"));
132b884b Andy McCall ↶ 2896
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2897
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2898
    a.tag_create("v2", &[h2], "second").unwrap();
2899
    a.push("origin", false).unwrap();
2900
    let rep = b.fetch("origin").unwrap();
2901
    assert_eq!(rep.new_tags, 1);
2902
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2903
2904
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2905
    a.policy_init().unwrap();
2906
    a.push("origin", false).unwrap();
75167672 Andy McCall 2907
    let unattested = crate::protocol::TagRef {
2908
        name: "v3".into(),
2909
        state: origin
2910
            .store()
2911
            .put_state(&StateObject::new(vec![h2]))
2912
            .unwrap(),
2913
        heads: vec![h2],
2914
        attestation: None,
2915
    };
2916
    let r = origin
2917
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2918
        .unwrap();
132b884b Andy McCall ↶ 2919
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2920
    a.tag_create("v3", &[h2], "").unwrap();
2921
    let r = a.push("origin", false).unwrap();
2922
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2923
    assert!(a.gc(true).is_ok());
2924
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2925
}
4e88e774 Andy McCall ↶ 2926
2927
#[test]
2928
fn multiple_workspaces_share_a_repository() {
2929
    hermetic();
2930
    let dir = tempfile::tempdir().unwrap();
2931
    let root = dir.path();
2932
    let main_dir = root.join("main");
2933
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2934
    write(&main_dir, "a.txt", b"a\n");
2935
    let h1 = repo.commit("a", &[]).unwrap();
2936
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2937
2938
    // A second workspace elsewhere, checked out on the bookmark.
2939
    let ws_dir = root.join("ws2");
2940
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2941
    assert!(ws_dir.join(".oxy").is_file());
2942
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2943
    assert_ne!(ws.workspace(), repo.workspace());
2944
    let list = repo.workspaces().unwrap();
2945
    assert_eq!(list.len(), 2);
75167672 Andy McCall 2946
    assert!(list
2947
        .iter()
2948
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
4e88e774 Andy McCall ↶ 2949
    assert!(!ws.snapshot("status").unwrap().changed);
2950
2951
    // Work in the second workspace: its own working copy, shared bookmark.
2952
    write(&ws_dir, "b.txt", b"b\n");
2953
    let s = ws.snapshot("status").unwrap();
2954
    assert_eq!(s.statuses.len(), 1);
75167672 Andy McCall 2955
    assert!(
2956
        !repo.snapshot("status").unwrap().changed,
2957
        "the first workspace is untouched"
2958
    );
4e88e774 Andy McCall ↶ 2959
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2960
    let mut heads = repo.bookmark_heads().unwrap();
2961
    heads.sort();
2962
    let mut want = vec![h1, h2];
2963
    want.sort();
2964
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2965
    assert!(!main_dir.join("b.txt").exists());
75167672 Andy McCall 2966
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2967
        .unwrap();
4e88e774 Andy McCall ↶ 2968
    assert!(main_dir.join("b.txt").exists());
2969
2970
    // Reopening from inside the second workspace finds the shared repository.
2971
    let reopened = Repo::open(&ws_dir).unwrap();
2972
    assert_eq!(reopened.workspace(), ws.workspace());
2973
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2974
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2975
2976
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2977
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2978
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2979
    repo.workspace_forget(&ws.workspace()).unwrap();
2980
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2981
    assert!(ws_dir.join("b.txt").exists());
75167672 Andy McCall 2982
    assert!(
2983
        ws.snapshot("status").is_err(),
2984
        "a forgotten workspace is no longer in the view"
2985
    );
4e88e774 Andy McCall ↶ 2986
6caacfff Andy McCall ↶ 2987
    // The working-copy lock: re-entrant in a thread; a lock whose process
2988
    // is gone is taken over, and a live process's is not, however old.
4e88e774 Andy McCall ↶ 2989
    let lock = repo.lock_snapshot().unwrap();
6caacfff Andy McCall ↶ 2990
    let again = repo.lock_working_copy().unwrap();
2991
    drop(again);
4e88e774 Andy McCall ↶ 2992
    drop(lock);
75167672 Andy McCall 2993
    let lock_path = main_dir
2994
        .join(".oxy/workspaces")
2995
        .join(repo.workspace().to_hex())
2996
        .join("lock");
4e88e774 Andy McCall ↶ 2997
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
6caacfff Andy McCall ↶ 2998
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2999
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
3000
    age(&lock_path);
3001
    assert!(
3002
        !super::workspace::lock_is_stale(&lock_path),
3003
        "a live process keeps its lock"
3004
    );
3005
    fs::write(&lock_path, "4294967295").unwrap();
3006
    age(&lock_path);
4e88e774 Andy McCall ↶ 3007
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
3008
}
cdb5beba Andy McCall ↶ 3009
3010
#[test]
3011
fn attributes_binary_eol_nocompress_lockable() {
3012
    hermetic();
3013
    let dir = tempfile::tempdir().unwrap();
3014
    let root = dir.path();
3015
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3016
    write(
3017
        root,
3018
        ".oxyattributes",
3019
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
3020
    );
cdb5beba Andy McCall ↶ 3021
    write(root, "plain.dat", b"no nul bytes here\n");
3022
    write(root, "notes.txt", b"one\r\ntwo\r\n");
3023
    write(root, "assets/model.bin", b"\0model");
3024
    let h = repo.commit("attrs", &[]).unwrap();
3025
    let snap = repo.load_state(&[h]).unwrap().materialize();
75167672 Andy McCall 3026
    assert!(
3027
        snap.files["plain.dat"].mode.opaque,
3028
        "binary attribute forces opaque without NUL bytes"
3029
    );
3030
    assert!(
3031
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3032
        "stored with LF"
3033
    );
3034
    assert!(
3035
        !repo.snapshot("status").unwrap().changed,
3036
        "CRLF on disk equals LF in the state"
3037
    );
cdb5beba Andy McCall ↶ 3038
    // nocompress chunks pack raw.
3039
    let r = repo.gc(true).unwrap();
3040
    assert!(r.packed.objects > 0);
3041
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
3042
    fs::remove_file(root.join("notes.txt")).unwrap();
3043
    repo.checkout(&[h], true, "co").unwrap();
3044
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
75167672 Andy McCall 3045
    assert!(fs::metadata(root.join("assets/model.bin"))
3046
        .unwrap()
3047
        .permissions()
3048
        .readonly());
cdb5beba Andy McCall ↶ 3049
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
3050
    repo.lock_path("assets/model.bin").unwrap();
75167672 Andy McCall 3051
    assert!(!fs::metadata(root.join("assets/model.bin"))
3052
        .unwrap()
3053
        .permissions()
3054
        .readonly());
cdb5beba Andy McCall ↶ 3055
    assert!(repo.is_locked("assets/model.bin"));
3056
    write(root, "assets/model.bin", b"\0model2");
3057
    repo.commit("edit model", &[]).unwrap();
3058
    repo.unlock_path("assets/model.bin").unwrap();
75167672 Andy McCall 3059
    assert!(fs::metadata(root.join("assets/model.bin"))
3060
        .unwrap()
3061
        .permissions()
3062
        .readonly());
cdb5beba Andy McCall ↶ 3063
    // A later checkout can still overwrite a read-only lockable file.
3064
    repo.checkout(&[h], true, "co").unwrap();
3065
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
3066
}
6d3eefbc Andy McCall ↶ 3067
3068
#[cfg(unix)]
3069
#[test]
3070
fn hooks_can_veto_observe_and_add_dependencies() {
3071
    use std::os::unix::fs::PermissionsExt;
3072
    hermetic();
3073
    let dir = tempfile::tempdir().unwrap();
3074
    let root = dir.path();
3075
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3076
    let hooks = root.join(".oxy/hooks");
3077
    fs::create_dir_all(&hooks).unwrap();
3078
    let hook = |name: &str, body: &str| {
3079
        let p = hooks.join(name);
3080
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
3081
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
3082
    };
3083
    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");
3084
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
3085
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
3086
    hook("pre-push", "echo pushing blocked >&2; exit 3");
3087
    write(root, ".oxyignore", b".last-*\n");
3088
    write(root, "a.txt", b"a\n");
3089
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
3090
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
3091
    let h1 = repo.commit("first", &[]).unwrap();
3092
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
75167672 Andy McCall 3093
    assert!(
3094
        pre.contains("\"event\":\"pre-commit\"")
3095
            && pre.contains("\"path\":\"a.txt\"")
3096
            && pre.contains("\"message\":\"first\""),
3097
        "{pre}"
3098
    );
6d3eefbc Andy McCall ↶ 3099
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
3100
    assert!(post.contains(&h1.to_hex()), "{post}");
3101
    repo.checkout(&[h1], false, "co").unwrap();
75167672 Andy McCall 3102
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
3103
        .unwrap()
3104
        .contains("post-checkout"));
6d3eefbc Andy McCall ↶ 3105
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
3106
    repo.save_config().unwrap();
3107
    let err = repo.push("origin", false).unwrap_err().to_string();
3108
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
3109
3110
    // semantic-deps: only when enabled; adds an explicit dependency.
3111
    write(root, "b.txt", b"b\n");
75167672 Andy McCall 3112
    hook(
3113
        "semantic-deps",
3114
        &format!(
3115
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
3116
            h1.to_hex()
3117
        ),
3118
    );
6d3eefbc Andy McCall ↶ 3119
    let h2 = repo.commit("b without hook", &[]).unwrap();
75167672 Andy McCall 3120
    assert!(
3121
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
3122
        "hook disabled by default"
3123
    );
6d3eefbc Andy McCall ↶ 3124
    repo.config.set("hooks.semantic-deps", "true").unwrap();
3125
    repo.save_config().unwrap();
3126
    write(root, "c.txt", b"c\n");
3127
    let h3 = repo.commit("c with hook", &[]).unwrap();
3128
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
3129
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
75167672 Andy McCall 3130
    assert!(
3131
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
3132
        "{sem}"
3133
    );
6d3eefbc Andy McCall ↶ 3134
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
3135
}
23b217d7 Andy McCall ↶ 3136
3137
#[test]
3138
fn amend_into_older_change_and_split() {
3139
    hermetic();
3140
    let dir = tempfile::tempdir().unwrap();
3141
    let root = dir.path();
3142
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3143
    repo.create_identity("Ada", "a@b", IdentityScope::User)
3144
        .unwrap();
23b217d7 Andy McCall ↶ 3145
    repo.set_user_config("core.sign", "change").unwrap();
3146
    write(root, "a.txt", b"one\ntwo\n");
3147
    let h0 = repo.commit("base", &[]).unwrap();
3148
    write(root, "a.txt", b"one\nTWO\n");
3149
    let h1 = repo.commit("edit two", &[]).unwrap();
3150
    write(root, "a.txt", b"one\nTWO\nthree\n");
3151
    let h2 = repo.commit("add three", &[]).unwrap();
3152
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3153
3154
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
3155
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3156
    let h1b = repo.amend_into(&h1, None).unwrap();
3157
    assert_ne!(h1b, h1);
3158
    let c1b = repo.store().get_change(&h1b).unwrap();
3159
    assert_eq!(c1b.change_id, id1);
3160
    assert_eq!(c1b.deps, vec![h0]);
75167672 Andy McCall 3161
    assert!(matches!(
3162
        repo.verify_change(&h1b).unwrap(),
3163
        SignatureStatus::Valid { .. }
3164
    ));
23b217d7 Andy McCall ↶ 3165
    let heads = repo.bookmark_heads().unwrap();
3166
    assert_eq!(heads.len(), 1);
3167
    let top = repo.store().get_change(&heads[0]).unwrap();
3168
    assert_eq!(top.message, "add three");
75167672 Andy McCall 3169
    assert_eq!(
3170
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
3171
        [h0, h1b].into_iter().collect(),
3172
        "depends on the file's creator and the rewritten line"
3173
    );
23b217d7 Andy McCall ↶ 3174
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 3175
    assert!(
3176
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
3177
    );
3178
    assert!(
3179
        !repo.snapshot("status").unwrap().changed,
3180
        "the working copy is clean after folding"
3181
    );
23b217d7 Andy McCall ↶ 3182
    // Only h1b's own state shows the fix without "three".
3183
    let only = repo.load_state(&[h1b]).unwrap().materialize();
75167672 Andy McCall 3184
    assert!(
3185
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
3186
    );
23b217d7 Andy McCall ↶ 3187
    assert_eq!(repo.log().unwrap().len(), 4);
3188
3189
    // An edit to a line introduced by h2 cannot fold into h1.
3190
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
3191
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
3192
    assert!(err.contains("introduced after"), "{err}");
75167672 Andy McCall 3193
    assert!(
3194
        repo.snapshot("status").unwrap().statuses.len() == 1,
3195
        "nothing was changed by the refusal"
3196
    );
23b217d7 Andy McCall ↶ 3197
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3198
3199
    // Split the head that touches two files.
3200
    write(root, "b.txt", b"b\n");
3201
    write(root, "c.txt", b"c\n");
3202
    let h3 = repo.commit("b and c", &[]).unwrap();
3203
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
3204
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
3205
    let c_1 = repo.store().get_change(&p1).unwrap();
3206
    let c_2 = repo.store().get_change(&p2).unwrap();
3207
    assert!(c_1.message.contains("part 1: b.txt"));
3208
    assert_eq!(c_2.change_id, id3);
3209
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
75167672 Andy McCall 3210
    assert!(
3211
        heads.contains(&p1) && heads.contains(&p2),
3212
        "independent parts are both heads"
3213
    );
3214
    let snap = repo
3215
        .load_state(&repo.bookmark_heads().unwrap())
3216
        .unwrap()
3217
        .materialize();
23b217d7 Andy McCall ↶ 3218
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
3219
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
3220
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
3221
    assert!(!repo.snapshot("status").unwrap().changed);
3222
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
3223
    let _ = h2;
3224
}
28fc23d7 Andy McCall ↶ 3225
3226
#[test]
3227
fn identity_lifecycle() {
3228
    hermetic();
3229
    let dir = tempfile::tempdir().unwrap();
3230
    let root = dir.path();
3231
    let origin = Repo::init(&root.join("origin")).unwrap();
3232
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3233
    let mut a = Repo::clone(&url, &root.join("a"))
3234
        .unwrap()
3235
        .with_home(root.join("home-a"));
28fc23d7 Andy McCall ↶ 3236
    a.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 3237
    let (key_a, _) = a
3238
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3239
        .unwrap();
28fc23d7 Andy McCall ↶ 3240
    write(&root.join("a"), "a.txt", b"a\n");
3241
    let h1 = a.commit("one", &[]).unwrap();
3242
    assert!(a.policy_init().unwrap().applied);
3243
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3244
3245
    // Expiry: an identity that had expired when the change was made does not authenticate it.
75167672 Andy McCall 3246
    let mut e = Repo::init(&root.join("e"))
3247
        .unwrap()
3248
        .with_home(root.join("home-e"));
28fc23d7 Andy McCall ↶ 3249
    e.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 3250
    e.create_identity_with(
3251
        "Eve",
3252
        "[email protected]",
3253
        IdentityScope::User,
3254
        Some(Hlc::now().wall_ms - 1),
3255
    )
3256
    .unwrap();
28fc23d7 Andy McCall ↶ 3257
    write(&root.join("e"), "e.txt", b"e\n");
3258
    let he = e.commit("late", &[]).unwrap();
75167672 Andy McCall 3259
    assert!(
3260
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
3261
    );
28fc23d7 Andy McCall ↶ 3262
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
75167672 Andy McCall 3263
    let r = e
3264
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
3265
        .unwrap();
28fc23d7 Andy McCall ↶ 3266
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
3267
    write(&root.join("e"), "e.txt", b"e2\n");
3268
    let he2 = e.commit("in time", &[]).unwrap();
75167672 Andy McCall 3269
    assert!(
3270
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
3271
    );
28fc23d7 Andy McCall ↶ 3272
3273
    // Rotation: a fresh key; the old change still verifies; the policy follows.
3274
    let r = a.rotate_identity().unwrap();
3275
    assert_eq!(r.old, key_a);
3276
    assert_eq!(a.config.author_key, Some(r.new));
3277
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
3278
    assert!(r.policy.as_ref().unwrap().applied);
3279
    let (_, sp) = a.current_policy().unwrap().unwrap();
75167672 Andy McCall 3280
    assert_eq!(
3281
        (sp.policy.serial, sp.policy.roots.clone()),
3282
        (2, vec![r.new])
3283
    );
3284
    assert!(
3285
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
3286
        "superseded, not revoked"
3287
    );
28fc23d7 Andy McCall ↶ 3288
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
75167672 Andy McCall 3289
    assert!(
3290
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
3291
    );
28fc23d7 Andy McCall ↶ 3292
    write(&root.join("a"), "a.txt", b"a2\n");
3293
    let h2 = a.commit("two", &[]).unwrap();
75167672 Andy McCall 3294
    assert!(
3295
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
3296
    );
28fc23d7 Andy McCall ↶ 3297
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
3298
    let res = a.push("origin", false).unwrap();
3299
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3300
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
3301
    let key_a = r.new;
3302
3303
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
3304
    // identity object, so Ada's KeyId changes while her keys stay the same.
75167672 Andy McCall 3305
    let mut b = Repo::clone(&url, &root.join("b"))
3306
        .unwrap()
3307
        .with_home(root.join("home-b"));
3308
    let (key_b, id_b) = b
3309
        .create_identity("Bob", "[email protected]", IdentityScope::User)
3310
        .unwrap();
7ba155f2 Andy McCall ↶ 3311
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
28fc23d7 Andy McCall ↶ 3312
    assert_eq!(r.old, key_a);
3313
    let key_a2 = r.new;
75167672 Andy McCall 3314
    assert_eq!(
7ba155f2 Andy McCall ↶ 3315
        a.identity(&key_a2).unwrap().delegates,
3316
        vec![Delegate::full(key_b)]
3317
    );
3318
    assert_eq!(
75167672 Andy McCall 3319
        a.identity(&key_a2).unwrap().ed25519_pk,
3320
        a.identity(&key_a).unwrap().ed25519_pk
7ba155f2 Andy McCall ↶ 3321
    );
3322
    assert!(
3323
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
3324
        "already a delegate"
75167672 Andy McCall 3325
    );
28fc23d7 Andy McCall ↶ 3326
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3327
    write(&root.join("a"), "a.txt", b"a3\n");
3328
    let h3 = a.commit("three", &[]).unwrap();
75167672 Andy McCall 3329
    assert!(
3330
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
3331
        "the same secret signs under the new KeyId"
3332
    );
28fc23d7 Andy McCall ↶ 3333
    // A change authored by Ada but signed only by Bob verifies through the delegation.
3334
    a.set_user_config("core.sign", "seal").unwrap();
3335
    write(&root.join("a"), "a.txt", b"a4\n");
3336
    let h4 = a.commit("four", &[]).unwrap();
3337
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
3338
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 3339
    a.store()
3340
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
3341
        .unwrap();
3342
    assert!(
3343
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
3344
    );
28fc23d7 Andy McCall ↶ 3345
    a.set_user_config("core.sign", "change").unwrap();
3346
    // Withdrawing the delegation re-issues the identity again.
3347
    let r = a.delegate_remove(&key_b).unwrap();
3348
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
3349
    assert!(a.delegate_remove(&key_b).is_err());
3350
    let key_a3 = r.new;
3351
    let res = a.push("origin", false).unwrap();
3352
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3353
3354
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
3355
    // both applied under the old threshold of 1. A grant then needs Bob too.
3356
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
3357
    assert!(a.policy_root_add(id_b.clone()).is_err());
3358
    assert!(a.policy_set_threshold(3).is_err());
3359
    assert!(a.policy_set_threshold(2).unwrap().applied);
3360
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3361
    b.pull("origin").unwrap();
75167672 Andy McCall 3362
    assert_eq!(
3363
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
3364
        2
3365
    );
3366
    let mut c = Repo::init(&root.join("c"))
3367
        .unwrap()
3368
        .with_home(root.join("home-c"));
3369
    let (key_c, id_c) = c
3370
        .create_identity("Cy", "[email protected]", IdentityScope::User)
3371
        .unwrap();
28fc23d7 Andy McCall ↶ 3372
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
3373
    let proposal = a.policy_grant(id_c, None).unwrap();
3374
    assert!(!proposal.applied && proposal.sigs.len() == 1);
3375
    assert_eq!(proposal.policy.serial, serial_before + 1);
75167672 Andy McCall 3376
    assert_eq!(
3377
        a.current_policy().unwrap().unwrap().1.policy.serial,
3378
        serial_before,
3379
        "a proposal changes nothing yet"
3380
    );
28fc23d7 Andy McCall ↶ 3381
    // Bob signs the proposal, handed over as a file, and it applies for him.
3382
    let bytes = proposal.signed().encode();
75167672 Andy McCall 3383
    let signed = b
3384
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
3385
        .unwrap();
28fc23d7 Andy McCall ↶ 3386
    assert!(signed.applied && signed.sigs.len() == 2);
75167672 Andy McCall 3387
    assert!(b
3388
        .current_policy()
3389
        .unwrap()
3390
        .unwrap()
3391
        .1
3392
        .policy
3393
        .authorizes(&key_c, "main"));
3394
    assert!(
3395
        b.policy_sign(signed.signed()).is_err(),
3396
        "a stale proposal is refused"
3397
    );
28fc23d7 Andy McCall ↶ 3398
    // Bob publishes it and Ada picks it up.
75167672 Andy McCall 3399
    assert!(b
3400
        .push("origin", false)
3401
        .unwrap()
3402
        .iter()
3403
        .any(|x| x.name == "policy" && x.ok));
28fc23d7 Andy McCall ↶ 3404
    a.pull("origin").unwrap();
75167672 Andy McCall 3405
    assert_eq!(
3406
        a.current_policy().unwrap().unwrap().1.policy.serial,
3407
        serial_before + 1
3408
    );
28fc23d7 Andy McCall ↶ 3409
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3410
    assert!(a.policy_revoke(&key_a3).is_err());
75167672 Andy McCall 3411
    let u = a
3412
        .revoke_identity(&key_c, "left the project")
3413
        .unwrap()
3414
        .unwrap();
28fc23d7 Andy McCall ↶ 3415
    assert!(!u.applied);
3416
    assert!(a.is_revoked(&key_c).unwrap());
3417
    assert!(!b.is_revoked(&key_c).unwrap());
3418
    let u = b.policy_sign(u.signed()).unwrap();
3419
    assert!(u.applied && u.policy.is_revoked(&key_c));
3420
    assert!(b.is_revoked(&key_c).unwrap());
3421
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
75167672 Andy McCall 3422
    assert!(
3423
        b.policy_revoke(&key_a3).is_err(),
3424
        "would leave one root for a threshold of 2"
3425
    );
28fc23d7 Andy McCall ↶ 3426
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3427
    let key_c_own = c.config.author_key.unwrap();
75167672 Andy McCall 3428
    assert!(c
3429
        .revoke_identity(&key_c_own, "lost laptop")
3430
        .unwrap()
3431
        .is_none());
28fc23d7 Andy McCall ↶ 3432
    assert!(c.is_revoked(&key_c_own).unwrap());
3433
    assert_eq!(key_c_own, key_c);
3434
}
3435
6e723b81 Andy McCall ↶ 3436
#[test]
3437
fn renames_are_detected_and_tracked_as_moves() {
3438
    hermetic();
3439
    let dir = tempfile::tempdir().unwrap();
3440
    let root = dir.path();
3441
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3442
    write(
3443
        root,
3444
        "src/old.rs",
3445
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3446
    );
6e723b81 Andy McCall ↶ 3447
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3448
    write(root, "tiny.txt", b"x\n");
3449
    let h1 = repo.commit("base", &[]).unwrap();
3450
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3451
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3452
3453
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3454
    // that shares nothing with the removed file.
3455
    fs::remove_file(root.join("src/old.rs")).unwrap();
75167672 Andy McCall 3456
    write(
3457
        root,
3458
        "lib/new.rs",
3459
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3460
    );
6e723b81 Andy McCall ↶ 3461
    fs::remove_file(root.join("img.bin")).unwrap();
3462
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3463
    fs::remove_file(root.join("tiny.txt")).unwrap();
3464
    write(root, "other.txt", b"completely different\n");
3465
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3466
    let statuses: Vec<(&str, ChangeStatus)> = snap
3467
        .statuses
3468
        .iter()
3469
        .map(|s| (s.path.as_str(), s.status))
3470
        .collect();
6e723b81 Andy McCall ↶ 3471
    assert_eq!(
3472
        statuses,
75167672 Andy McCall 3473
        vec![
3474
            ("assets/img.bin", ChangeStatus::Renamed),
3475
            ("lib/new.rs", ChangeStatus::Renamed),
3476
            ("other.txt", ChangeStatus::Added),
3477
            ("src", ChangeStatus::Removed),
3478
            ("tiny.txt", ChangeStatus::Removed)
3479
        ]
6e723b81 Andy McCall ↶ 3480
    );
3481
    let h2 = repo.commit("move things", &[]).unwrap();
3482
    let c = repo.store().get_change(&h2).unwrap();
75167672 Andy McCall 3483
    let moves: Vec<_> = c
3484
        .tree_ops
3485
        .iter()
3486
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3487
        .collect();
6e723b81 Andy McCall ↶ 3488
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
75167672 Andy McCall 3489
    assert!(c.tree_ops.iter().any(
3490
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3491
    ));
3492
    assert!(c.tree_ops.iter().any(
3493
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3494
    ));
6e723b81 Andy McCall ↶ 3495
    let snap = repo.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 3496
    assert_eq!(
3497
        snap.files["lib/new.rs"].node, node_old,
3498
        "the node survives the rename"
3499
    );
3500
    assert!(
3501
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3502
    );
6e723b81 Andy McCall ↶ 3503
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
75167672 Andy McCall 3504
    assert!(render_change(
3505
        &c,
3506
        &repo.load_state(&[h1]).unwrap(),
3507
        &repo.load_state(&[h1]).unwrap().materialize()
3508
    )
3509
    .contains("R "));
6e723b81 Andy McCall ↶ 3510
    // A fresh checkout reproduces the tree.
3511
    let other = tempfile::tempdir().unwrap();
3512
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
75167672 Andy McCall 3513
    assert_eq!(
3514
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3515
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3516
    );
6e723b81 Andy McCall ↶ 3517
    assert!(!other.path().join("src").exists());
3518
    assert!(!clone.snapshot("status").unwrap().changed);
3519
    // Similarity is line based, byte weighted.
3520
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3521
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3522
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3523
    assert_eq!(similarity(b"", b"x\n"), 0);
3524
}
3525
30ea9c1e Andy McCall ↶ 3526
#[test]
3527
fn git_fetch_and_push_round_trip() {
3528
    hermetic();
75167672 Andy McCall 3529
    if std::process::Command::new("git")
3530
        .arg("--version")
3531
        .output()
3532
        .is_err()
3533
    {
30ea9c1e Andy McCall ↶ 3534
        eprintln!("git not installed; skipping");
3535
        return;
3536
    }
3537
    let dir = tempfile::tempdir().unwrap();
3538
    let root = dir.path();
3539
    let git_in = |d: &Path, args: &[&str]| -> String {
3540
        let out = std::process::Command::new("git")
3541
            .arg("-C")
3542
            .arg(d)
75167672 Andy McCall 3543
            .args([
3544
                "-c",
3545
                "user.name=Grace",
3546
                "-c",
3547
                "[email protected]",
3548
                "-c",
3549
                "commit.gpgsign=false",
3550
            ])
30ea9c1e Andy McCall ↶ 3551
            .args(args)
3552
            .output()
3553
            .unwrap();
75167672 Andy McCall 3554
        assert!(
3555
            out.status.success(),
3556
            "git {args:?}: {}",
3557
            String::from_utf8_lossy(&out.stderr)
3558
        );
30ea9c1e Andy McCall ↶ 3559
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3560
    };
3561
    // A bare "remote" and a work tree that pushes to it.
3562
    let remote = root.join("remote.git");
3563
    fs::create_dir_all(&remote).unwrap();
3564
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3565
    let work = root.join("work");
75167672 Andy McCall 3566
    git_in(
3567
        root,
3568
        &[
3569
            "clone",
3570
            "-q",
3571
            remote.to_str().unwrap(),
3572
            work.to_str().unwrap(),
3573
        ],
3574
    );
30ea9c1e Andy McCall ↶ 3575
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3576
    write(&work, "README.md", b"# Project\n");
3577
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3578
    git_in(&work, &["add", "."]);
3579
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3580
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3581
    git_in(&work, &["commit", "-q", "-am", "second"]);
3582
    git_in(&work, &["push", "-q", "origin", "main"]);
3583
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3584
3585
    // Fetch into a fresh oxy repository.
3586
    let o = root.join("oxy");
3587
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3588
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3589
        .unwrap();
30ea9c1e Andy McCall ↶ 3590
    let url = remote.to_string_lossy().to_string();
3591
    let r = repo.git_fetch(&url, "main").unwrap();
3592
    assert_eq!((r.commits, r.heads), (2, 1));
75167672 Andy McCall 3593
    assert_eq!(
3594
        fs::read(o.join("src/lib.rs")).unwrap(),
3595
        b"pub fn a() {}\npub fn b() {}\n"
3596
    );
30ea9c1e Andy McCall ↶ 3597
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 3598
    assert_eq!(
3599
        repo.git_fetch(&url, "main").unwrap().commits,
3600
        0,
3601
        "nothing new"
3602
    );
30ea9c1e Andy McCall ↶ 3603
3604
    // An oxy change, pushed back: one commit on top of the Git tip.
75167672 Andy McCall 3605
    write(
3606
        &o,
3607
        "src/lib.rs",
3608
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3609
    );
30ea9c1e Andy McCall ↶ 3610
    write(&o, "NOTES.md", b"from oxy\n");
3611
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3612
    let r = repo.git_push(&url, "main").unwrap();
3613
    assert_eq!(r.exported, 1, "{r:?}");
3614
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
75167672 Andy McCall 3615
    assert_eq!(
3616
        git_in(&work, &["log", "--format=%s", "main"]),
3617
        "add c and notes\nsecond\ninitial"
3618
    );
30ea9c1e Andy McCall ↶ 3619
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3620
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3621
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
75167672 Andy McCall 3622
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3623
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3624
    assert_eq!(
3625
        repo.git_push(&url, "main").unwrap().exported,
3626
        0,
3627
        "already pushed"
3628
    );
30ea9c1e Andy McCall ↶ 3629
3630
    // Git moves on; pushing without fetching is refused, fetching brings
3631
    // the commit in and the working copy follows.
3632
    write(&work, "README.md", b"# Project\n\nMore.\n");
3633
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3634
    git_in(&work, &["push", "-q", "origin", "main"]);
3635
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
75167672 Andy McCall 3636
    assert!(repo
3637
        .git_push(&url, "main")
3638
        .unwrap_err()
3639
        .to_string()
3640
        .contains("fetch"));
30ea9c1e Andy McCall ↶ 3641
    let r = repo.git_fetch(&url, "main").unwrap();
75167672 Andy McCall 3642
    assert_eq!(
3643
        (r.commits, r.heads),
3644
        (1, 2),
3645
        "the Git change and the oxy change commute"
3646
    );
3647
    assert_eq!(
3648
        fs::read(o.join("README.md")).unwrap(),
3649
        b"# Project\n\nMore.\n"
3650
    );
30ea9c1e Andy McCall ↶ 3651
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3652
    assert!(!repo.snapshot("status").unwrap().changed);
3653
    // Another oxy change pushes on top of Git's newest commit.
3654
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3655
    repo.commit("notes again", &[]).unwrap();
3656
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3657
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3658
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
75167672 Andy McCall 3659
    assert_eq!(
3660
        fs::read(work.join("NOTES.md")).unwrap(),
3661
        b"from oxy\nagain\n"
3662
    );
3663
    assert_eq!(
3664
        git_in(&work, &["log", "--format=%s", "main"])
3665
            .lines()
3666
            .count(),
3667
        5
3668
    );
30ea9c1e Andy McCall ↶ 3669
}
3670
2b872d07 Andy McCall ↶ 3671
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3672
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3673
#[test]
3674
#[ignore]
3675
fn bench_one_gibibyte_file() {
3676
    hermetic();
3677
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3678
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3679
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3680
        None => tempfile::tempdir().unwrap(),
3681
    };
3682
    let root = dir.path();
75167672 Andy McCall 3683
    let repo = Repo::init(&root.join("r"))
3684
        .unwrap()
3685
        .with_home(root.join("home"));
2b872d07 Andy McCall ↶ 3686
    let size = 1usize << 30;
3687
    let mut data = vec![0u8; size];
3688
    let mut x = 0x9e3779b97f4a7c15u64;
3689
    for chunk in data.chunks_mut(8) {
3690
        x ^= x << 13;
3691
        x ^= x >> 7;
3692
        x ^= x << 17;
3693
        let b = x.to_le_bytes();
3694
        chunk.copy_from_slice(&b[..chunk.len()]);
3695
    }
3696
    let t = std::time::Instant::now();
3697
    write(&root.join("r"), "big.bin", &data);
3698
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3699
    let t = std::time::Instant::now();
3700
    let h = repo.commit("big", &[]).unwrap();
3701
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3702
    let t = std::time::Instant::now();
3703
    assert!(!repo.snapshot("status").unwrap().changed);
3704
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3705
    let t = std::time::Instant::now();
3706
    let objects = repo.store().list().unwrap().len();
3707
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3708
    let t = std::time::Instant::now();
3709
    let g = repo.gc(true).unwrap();
3710
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3711
    let t = std::time::Instant::now();
3712
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3713
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3714
    let t = std::time::Instant::now();
3715
    let back = fs::read(root.join("c/big.bin")).unwrap();
3716
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3717
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3718
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3719
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
75167672 Andy McCall 3720
    eprintln!(
3721
        "store size: {:.1} MiB for 1 GiB of data",
3722
        store_bytes as f64 / (1024.0 * 1024.0)
3723
    );
2b872d07 Andy McCall ↶ 3724
}
3725
3726
fn walkdir_size(p: &Path) -> u64 {
3727
    let mut total = 0;
3728
    if let Ok(rd) = fs::read_dir(p) {
3729
        for e in rd.flatten() {
3730
            let path = e.path();
3731
            if path.is_dir() {
3732
                total += walkdir_size(&path);
3733
            } else if let Ok(m) = fs::metadata(&path) {
3734
                total += m.len();
3735
            }
3736
        }
3737
    }
3738
    total
3739
}
3740
b7f102fc Andy McCall ↶ 3741
/// An opaque file whose size and mtime match the manifest is not read on
3742
/// the next snapshot: its blob comes from the manifest's stat cache.
3743
#[cfg(unix)]
3744
#[test]
3745
fn stat_cache_skips_reading_unchanged_opaque_files() {
3746
    use std::os::unix::fs::PermissionsExt;
3747
    hermetic();
3748
    let dir = tempfile::tempdir().unwrap();
3749
    let root = dir.path();
3750
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3751
    let mut big = vec![0u8; 300 * 1024];
3752
    for (i, b) in big.iter_mut().enumerate() {
3753
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3754
    }
3755
    big[0] = 0;
3756
    write(root, "big.bin", &big);
3757
    write(root, "a.txt", b"text\n");
3758
    let h1 = repo.commit("base", &[]).unwrap();
3759
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
75167672 Andy McCall 3760
    assert!(
3761
        m.entries["big.bin"].blob.is_some(),
3762
        "opaque files record their blob"
3763
    );
b7f102fc Andy McCall ↶ 3764
    assert!(m.entries["a.txt"].blob.is_none());
3765
    let blob = m.entries["big.bin"].blob.unwrap();
3766
    assert!(repo.store().has(&blob));
3767
3768
    // Files modified within two seconds of the manifest are racy and still
3769
    // read; age the file so the cache applies, then snapshot to record it.
3770
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
75167672 Andy McCall 3771
    fs::File::options()
3772
        .write(true)
3773
        .open(root.join("big.bin"))
3774
        .unwrap()
3775
        .set_modified(old)
3776
        .unwrap();
b7f102fc Andy McCall ↶ 3777
    assert!(!repo.snapshot("status").unwrap().changed);
3778
    // Now the file cannot be read at all; the snapshot succeeds without it.
3779
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3780
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3781
    assert!(
3782
        !snap.changed && snap.statuses.is_empty(),
3783
        "{:?}",
3784
        snap.statuses
3785
    );
b7f102fc Andy McCall ↶ 3786
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3787
    // A real change (new mtime, new content) is seen and committed correctly.
3788
    let mut big2 = big.clone();
3789
    big2[10] ^= 0xff;
3790
    write(root, "big.bin", &big2);
3791
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3792
    assert_eq!(
3793
        snap.statuses
3794
            .iter()
3795
            .map(|s| (s.path.as_str(), s.status))
3796
            .collect::<Vec<_>>(),
3797
        vec![("big.bin", ChangeStatus::Modified)]
3798
    );
b7f102fc Andy McCall ↶ 3799
    let h2 = repo.commit("edit", &[]).unwrap();
3800
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 3801
    assert_eq!(
3802
        files["big.bin"].content,
3803
        FileContent::Opaque {
3804
            blobs: vec![Repo::blob_ref(&big2)]
3805
        }
3806
    );
b7f102fc Andy McCall ↶ 3807
    // Checkout writes a manifest with blobs too, so the next status is cached.
3808
    repo.checkout(&[h1], false, "checkout").unwrap();
3809
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3810
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3811
    assert!(!repo.snapshot("status").unwrap().changed);
3812
}
3813
50a046e4 Andy McCall ↶ 3814
#[test]
3815
fn status_json_lists_conflicts_with_contributors() {
3816
    hermetic();
3817
    let dir = tempfile::tempdir().unwrap();
3818
    let root = dir.path();
3819
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3820
    write(root, "a.txt", b"one\n");
3821
    let h1 = repo.commit("base", &[]).unwrap();
3822
    write(root, "a.txt", b"one\nleft\n");
3823
    let ha = repo.commit("left", &[]).unwrap();
3824
    repo.checkout(&[h1], true, "checkout").unwrap();
3825
    write(root, "a.txt", b"one\nright\n");
3826
    let hb = repo.commit("right", &[]).unwrap();
3827
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3828
    let snap = repo.snapshot("status").unwrap();
3829
    assert!(snap.base_snapshot.is_conflicted());
3830
    let json = repo.status_json(&snap).unwrap();
3831
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3832
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3833
    assert!(json.contains("\"conflicted\":true"), "{json}");
75167672 Andy McCall 3834
    assert!(
3835
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3836
        "{json}"
3837
    );
50a046e4 Andy McCall ↶ 3838
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3839
    assert!(json.contains("\"resolved\":false"), "{json}");
3840
    assert!(json.starts_with('{') && json.ends_with('}'));
3841
    // Resolve and the report says so; a clean copy has no conflicts.
3842
    write(root, "a.txt", b"one\nleft\nright\n");
3843
    let snap = repo.snapshot("status").unwrap();
3844
    let json = repo.status_json(&snap).unwrap();
3845
    assert!(json.contains("\"resolved\":true"), "{json}");
3846
    repo.commit("resolve", &[]).unwrap();
3847
    let snap = repo.snapshot("status").unwrap();
3848
    let json = repo.status_json(&snap).unwrap();
75167672 Andy McCall 3849
    assert!(
3850
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3851
        "{json}"
3852
    );
50a046e4 Andy McCall ↶ 3853
}
3854
9ac1fbe2 Andy McCall ↶ 3855
#[test]
3856
fn ignore_rules_do_not_untrack_files() {
3857
    hermetic();
3858
    let dir = tempfile::tempdir().unwrap();
3859
    let root = dir.path();
3860
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3861
    write(root, "src.c", b"int x;\n");
3862
    write(root, "build/out.o", b"\0obj");
3863
    write(root, "sub/keep.log", b"keep\n");
3864
    write(root, "sub/junk.log", b"junk\n");
3865
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3866
    let snap = repo.snapshot("status").unwrap();
3867
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 3868
    assert_eq!(
3869
        added,
3870
        vec![".oxyignore", "src.c", "sub/keep.log"],
3871
        "anchored, glob, and negated rules"
3872
    );
9ac1fbe2 Andy McCall ↶ 3873
    let h1 = repo.commit("base", &[]).unwrap();
3874
    // Ignoring a tracked file changes nothing about it.
3875
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3876
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3877
    assert_eq!(
3878
        snap.statuses
3879
            .iter()
3880
            .map(|s| s.path.as_str())
3881
            .collect::<Vec<_>>(),
3882
        vec![".oxyignore"]
3883
    );
9ac1fbe2 Andy McCall ↶ 3884
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
75167672 Andy McCall 3885
    assert!(repo
3886
        .load_state(&[h2])
3887
        .unwrap()
3888
        .materialize()
3889
        .files
3890
        .contains_key("src.c"));
9ac1fbe2 Andy McCall ↶ 3891
    // Its edits are still seen, by status and by the prompt.
3892
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3893
    write(root, "src.c", b"int x, y;\n");
3894
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3895
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3896
    assert_eq!(
3897
        snap.statuses
3898
            .iter()
3899
            .map(|s| (s.path.as_str(), s.status))
3900
            .collect::<Vec<_>>(),
3901
        vec![("src.c", ChangeStatus::Modified)]
3902
    );
9ac1fbe2 Andy McCall ↶ 3903
    let h3 = repo.commit("edit src.c", &[]).unwrap();
75167672 Andy McCall 3904
    assert!(
3905
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3906
    );
9ac1fbe2 Andy McCall ↶ 3907
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3908
    fs::remove_file(root.join("src.c")).unwrap();
3909
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3910
    assert_eq!(
3911
        snap.statuses
3912
            .iter()
3913
            .map(|s| (s.path.as_str(), s.status))
3914
            .collect::<Vec<_>>(),
3915
        vec![("src.c", ChangeStatus::Removed)]
3916
    );
9ac1fbe2 Andy McCall ↶ 3917
    repo.checkout(&[h3], true, "checkout").unwrap();
3918
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3919
    assert!(!repo.snapshot("status").unwrap().changed);
3920
    let _ = h1;
3921
}
3922
b837d2b5 Andy McCall ↶ 3923
#[test]
3924
fn split_works_on_non_heads_by_node() {
3925
    hermetic();
3926
    let dir = tempfile::tempdir().unwrap();
3927
    let root = dir.path();
3928
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3929
    write(root, "a.txt", b"one\n");
3930
    write(root, "junk/x.lock", b"lock\n");
3931
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3932
    write(root, "a.txt", b"one\ntwo\n");
3933
    let h2 = repo.commit("more work", &[]).unwrap();
3934
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3935
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3936
    // h1 is not a head: split it by node.
3937
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3938
    assert_ne!(h1b, h1);
75167672 Andy McCall 3939
    assert_eq!(
3940
        repo.store().get_change(&h1b).unwrap().change_id,
3941
        id1,
3942
        "the rest keeps the ChangeId"
3943
    );
b837d2b5 Andy McCall ↶ 3944
    let junk = repo.store().get_change(&hj).unwrap();
75167672 Andy McCall 3945
    assert!(junk.tree_ops.iter().all(
3946
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3947
    ));
b837d2b5 Andy McCall ↶ 3948
    let heads = repo.bookmark_heads().unwrap();
75167672 Andy McCall 3949
    assert!(
3950
        heads.contains(&hj),
3951
        "the split-off part is a head of its own"
3952
    );
b837d2b5 Andy McCall ↶ 3953
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 3954
    assert!(
3955
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3956
        "the dependent was rewritten onto the new hash"
3957
    );
b837d2b5 Andy McCall ↶ 3958
    assert!(snap.files.contains_key("junk/x.lock"));
75167672 Andy McCall 3959
    let h2b = heads
3960
        .iter()
3961
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3962
        .copied()
3963
        .unwrap();
b837d2b5 Andy McCall ↶ 3964
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3965
    assert!(!repo.snapshot("status").unwrap().changed);
3966
    // Abandoning the split-off head removes the junk from history.
3967
    repo.abandon(&hj).unwrap();
3968
    let heads = repo.bookmark_heads().unwrap();
3969
    let snap = repo.load_state(&heads).unwrap().materialize();
3970
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3971
    assert!(snap.files.contains_key("a.txt"));
3972
    // A dependent that touches the split-off paths blocks the split.
3973
    write(root, "junk/y.lock", b"y\n");
3974
    let hb = repo.commit("junk base", &[]).unwrap();
3975
    write(root, "junk/y.lock", b"yy\n");
3976
    write(root, "b.txt", b"b\n");
3977
    repo.commit("touches junk", &[]).unwrap();
3978
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3979
    assert!(err.contains("depends on the split-off paths"), "{err}");
3980
}
3981
7b9809e6 Andy McCall ↶ 3982
#[test]
3983
fn bookmarks_switch_merge_and_push() {
3984
    hermetic();
3985
    let dir = tempfile::tempdir().unwrap();
3986
    let root = dir.path();
3987
    let origin = Repo::init(&root.join("origin")).unwrap();
3988
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3989
    let mut repo = Repo::clone(&url, &root.join("r"))
3990
        .unwrap()
3991
        .with_home(root.join("home"));
7b9809e6 Andy McCall ↶ 3992
    let r = root.join("r");
3993
    write(&r, "a.txt", b"a\n");
3994
    let h_a = repo.commit("a", &[]).unwrap();
3995
    assert!(repo.push("origin", false).unwrap()[0].ok);
3996
3997
    // A bookmark at the working copy's base, then work on it.
3998
    assert!(repo.bookmark_create("bad name..", None).is_err());
3999
    assert!(repo.bookmark_create("-x", None).is_err());
4000
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
4001
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
4002
    repo.bookmark_switch("feature", false).unwrap();
4003
    assert_eq!(repo.config.bookmark, "feature");
4004
    write(&r, "a.txt", b"a\nb\n");
4005
    write(&r, "b.txt", b"b\n");
4006
    let h_b = repo.commit("b on feature", &[]).unwrap();
75167672 Andy McCall 4007
    assert_eq!(
4008
        repo.bookmark_heads().unwrap(),
4009
        vec![h_b],
4010
        "b edits a.txt, so it depends on a"
4011
    );
4012
    assert_eq!(
4013
        repo.resolve_heads("main").unwrap(),
4014
        vec![h_a],
4015
        "main is untouched"
4016
    );
4017
    assert_eq!(
4018
        repo.resolve_change("feature").unwrap(),
4019
        h_b,
4020
        "a one-head bookmark names its change"
4021
    );
7b9809e6 Andy McCall ↶ 4022
    // Reopening keeps the workspace's bookmark.
4023
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
4024
    assert_eq!(reopened.config.bookmark, "feature");
4025
    // Back to main: b.txt goes away; work there.
4026
    repo.bookmark_switch("main", false).unwrap();
4027
    assert!(!r.join("b.txt").exists());
4028
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
4029
    write(&r, "c.txt", b"c\n");
4030
    let h_c = repo.commit("c on main", &[]).unwrap();
4031
    let list = repo.bookmarks().unwrap();
75167672 Andy McCall 4032
    assert_eq!(
4033
        list.iter()
4034
            .map(|b| (b.name.as_str(), b.current))
4035
            .collect::<Vec<_>>(),
4036
        vec![("feature", false), ("main", true)]
4037
    );
4038
    assert_eq!(
4039
        list.iter().find(|b| b.name == "main").unwrap().ahead,
4040
        Some(1),
4041
        "c is not on origin yet"
4042
    );
7b9809e6 Andy McCall ↶ 4043
    // Merge feature into main: the union, both heads, no merge change.
4044
    let m = repo.merge("feature").unwrap();
4045
    assert!(m.changed && m.checked_out);
4046
    let mut want = vec![h_b, h_c];
4047
    want.sort();
4048
    assert_eq!(m.heads, want);
4049
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
4050
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
4051
    assert!(repo.merge("main").is_err());
4052
    // The other bookmark can be pushed by name and appears at origin.
4053
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
4054
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
4055
    assert!(repo.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 4056
    assert_eq!(
4057
        repo.bookmarks()
4058
            .unwrap()
4059
            .iter()
4060
            .find(|b| b.name == "main")
4061
            .unwrap()
4062
            .ahead,
4063
        Some(0)
4064
    );
7b9809e6 Andy McCall ↶ 4065
    // A second workspace inherits the current bookmark and can switch independently.
4066
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
4067
    assert_eq!(ws.config.bookmark, "main");
4068
    let mut ws = ws;
4069
    ws.bookmark_switch("feature", false).unwrap();
75167672 Andy McCall 4070
    assert_eq!(
4071
        Repo::open(&r).unwrap().config.bookmark,
4072
        "main",
4073
        "the first workspace is unaffected"
4074
    );
4075
    assert!(
4076
        repo.bookmark_delete("feature").is_err(),
4077
        "current bookmark of another workspace"
4078
    );
7b9809e6 Andy McCall ↶ 4079
    ws.bookmark_switch("main", false).unwrap();
4080
    // Set and delete.
4081
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
4082
    assert!(repo.bookmark_delete("main").is_err(), "current here");
4083
    repo.bookmark_delete("feature").unwrap();
4084
    assert!(repo.resolve_heads("feature").is_err());
4085
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
75167672 Andy McCall 4086
    assert!(
4087
        repo.checkout(&[h_a], false, "checkout").is_ok(),
4088
        "changes of a deleted bookmark remain"
4089
    );
7b9809e6 Andy McCall ↶ 4090
}
4091
4dee277c Andy McCall ↶ 4092
#[test]
4093
fn oxygen_subrepos_pin_follow_and_update() {
4094
    hermetic();
4095
    let dir = tempfile::tempdir().unwrap();
4096
    let root = dir.path();
4097
    // A library repository with two commits, and a bare-ish origin for it.
4098
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
4099
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
75167672 Andy McCall 4100
    let lib = Repo::clone(&lib_url, &root.join("lib"))
4101
        .unwrap()
4102
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 4103
    write(&root.join("lib"), "lib.txt", b"v1\n");
4104
    let l1 = lib.commit("lib v1", &[]).unwrap();
4105
    assert!(lib.push("origin", false).unwrap()[0].ok);
4106
    let _ = lib_origin;
4107
4108
    // The application (a clone of its own origin) adds it as a subrepo.
4109
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
4110
    let app_url = root.join("app-origin").to_string_lossy().to_string();
4111
    let _ = app_origin;
4112
    let app_dir = root.join("app");
75167672 Andy McCall 4113
    let app = Repo::clone(&app_url, &app_dir)
4114
        .unwrap()
4115
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 4116
    write(&app_dir, "main.txt", b"app\n");
4117
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
4118
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
4119
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
4120
    let snap = app.snapshot("status").unwrap();
4121
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 4122
    assert_eq!(
4123
        paths,
4124
        vec![".oxymodules", "libs/lib", "main.txt"],
4125
        "the nested files are not walked"
4126
    );
4dee277c Andy McCall ↶ 4127
    let a1 = app.commit("app with lib", &[]).unwrap();
4128
    let files = app.load_state(&[a1]).unwrap().materialize().files;
4129
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
4130
    assert!(!files.contains_key("libs/lib/lib.txt"));
4131
    assert!(!app.snapshot("status").unwrap().changed);
4132
    let subs = app.subrepos().unwrap();
4133
    assert_eq!(subs.len(), 1);
4134
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
4135
4136
    // Advance the nested repository: the parent sees a modified pin.
75167672 Andy McCall 4137
    let nested = Repo::open(&app_dir.join("libs/lib"))
4138
        .unwrap()
4139
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 4140
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
4141
    let l2 = nested.commit("lib v2", &[]).unwrap();
4142
    assert!(nested.push("origin", false).unwrap()[0].ok);
4143
    let snap = app.snapshot("status").unwrap();
75167672 Andy McCall 4144
    assert_eq!(
4145
        snap.statuses
4146
            .iter()
4147
            .map(|s| (s.path.as_str(), s.status))
4148
            .collect::<Vec<_>>(),
4149
        vec![("libs/lib", ChangeStatus::Modified)]
4150
    );
4dee277c Andy McCall ↶ 4151
    let a2 = app.commit("bump lib", &[]).unwrap();
1a3b6203 Andy McCall ↶ 4152
    // Checking out the older app state brings the nested working copy back
4153
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4dee277c Andy McCall ↶ 4154
    let r = app.checkout(&[a1], false, "checkout").unwrap();
1a3b6203 Andy McCall ↶ 4155
    assert!(
4156
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
4157
        "{:?}",
4158
        r.notes
4159
    );
4dee277c Andy McCall ↶ 4160
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
1a3b6203 Andy McCall ↶ 4161
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
4162
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
4163
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4dee277c Andy McCall ↶ 4164
    assert!(!app.snapshot("status").unwrap().changed);
4165
    // A dirty nested repository is left alone and reported.
4166
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
4167
    let r = app.checkout(&[a2], false, "checkout").unwrap();
75167672 Andy McCall 4168
    assert!(
4169
        r.notes.iter().any(|n| n.contains("uncommitted")),
4170
        "{:?}",
4171
        r.notes
4172
    );
4dee277c Andy McCall ↶ 4173
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4174
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
4175
    let r = app.submodule_update(false, &[]).unwrap();
4176
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
4177
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
4178
    let _ = l2;
4179
4180
    // A fresh clone of the app has the pin but no nested repository until update --init.
4181
    assert!(app.push("origin", false).unwrap()[0].ok);
4182
    let clone_dir = root.join("app-clone");
75167672 Andy McCall 4183
    let clone = Repo::clone(&app_url, &clone_dir)
4184
        .unwrap()
4185
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 4186
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
75167672 Andy McCall 4187
    assert_eq!(
4188
        clone.submodule_update(false, &[]).unwrap(),
4189
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
4190
    );
4191
    assert_eq!(
4192
        clone.submodule_update(true, &[]).unwrap(),
4193
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
4194
    );
4195
    assert_eq!(
4196
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
4197
        b"v2\n"
4198
    );
4dee277c Andy McCall ↶ 4199
    assert!(!clone.snapshot("status").unwrap().changed);
4200
    // Removing the subrepo leaves the directory and drops the node.
4201
    clone.submodule_remove("libs/lib").unwrap();
4202
    let snap = clone.snapshot("status").unwrap();
75167672 Andy McCall 4203
    assert!(
4204
        snap.statuses
4205
            .iter()
4206
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
4207
        "{:?}",
4208
        snap.statuses
4209
    );
4dee277c Andy McCall ↶ 4210
    let c = clone.commit("drop lib", &[]).unwrap();
75167672 Andy McCall 4211
    assert!(!clone
4212
        .load_state(&[c])
4213
        .unwrap()
4214
        .materialize()
4215
        .files
4216
        .contains_key("libs/lib"));
4dee277c Andy McCall ↶ 4217
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
75167672 Andy McCall 4218
    assert!(
4219
        !clone.snapshot("status").unwrap().changed,
4220
        "an unregistered nested repository is ignored"
4221
    );
4dee277c Andy McCall ↶ 4222
}
4223
4224
#[test]
4225
fn git_submodules_import_and_export_as_gitlinks() {
4226
    hermetic();
75167672 Andy McCall 4227
    if std::process::Command::new("git")
4228
        .arg("--version")
4229
        .output()
4230
        .is_err()
4231
    {
4dee277c Andy McCall ↶ 4232
        eprintln!("git not installed; skipping");
4233
        return;
4234
    }
4235
    let dir = tempfile::tempdir().unwrap();
4236
    let root = dir.path();
4237
    let git_in = |d: &Path, args: &[&str]| -> String {
4238
        let out = std::process::Command::new("git")
4239
            .arg("-C")
4240
            .arg(d)
75167672 Andy McCall 4241
            .args([
4242
                "-c",
4243
                "user.name=Grace",
4244
                "-c",
4245
                "[email protected]",
4246
                "-c",
4247
                "commit.gpgsign=false",
4248
                "-c",
4249
                "protocol.file.allow=always",
4250
            ])
4dee277c Andy McCall ↶ 4251
            .args(args)
4252
            .output()
4253
            .unwrap();
75167672 Andy McCall 4254
        assert!(
4255
            out.status.success(),
4256
            "git {args:?}: {}",
4257
            String::from_utf8_lossy(&out.stderr)
4258
        );
4dee277c Andy McCall ↶ 4259
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4260
    };
4261
    let sub = root.join("sub");
4262
    fs::create_dir_all(&sub).unwrap();
4263
    git_in(&sub, &["init", "-q", "-b", "main"]);
4264
    write(&sub, "s.txt", b"sub\n");
4265
    git_in(&sub, &["add", "."]);
4266
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
4267
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
4268
    let g = root.join("main.git");
4269
    fs::create_dir_all(&g).unwrap();
4270
    git_in(&g, &["init", "-q", "-b", "main"]);
4271
    write(&g, "README.md", b"# app\n");
4272
    git_in(&g, &["add", "."]);
4273
    git_in(&g, &["commit", "-q", "-m", "initial"]);
75167672 Andy McCall 4274
    git_in(
4275
        &g,
4276
        &[
4277
            "submodule",
4278
            "add",
4279
            "-q",
4280
            sub.to_str().unwrap(),
4281
            "vendor/sub",
4282
        ],
4283
    );
4dee277c Andy McCall ↶ 4284
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
4285
4286
    let dest = root.join("oxy");
4287
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
4288
    let rep = repo.import_git(&g, "main").unwrap();
4289
    assert_eq!((rep.commits, rep.submodules), (2, 1));
75167672 Andy McCall 4290
    let files = repo
4291
        .load_state(&repo.bookmark_heads().unwrap())
4292
        .unwrap()
4293
        .materialize()
4294
        .files;
4dee277c Andy McCall ↶ 4295
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
75167672 Andy McCall 4296
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
4297
        panic!()
4298
    };
4299
    assert_eq!(
4300
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
4301
        crate::subrepo::Pin::Git {
4302
            sha: sub_sha.clone(),
4303
            branch: "HEAD".into()
4304
        }
4305
    );
4306
    let modules =
4307
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4dee277c Andy McCall ↶ 4308
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
4309
    assert!(modules.entries["vendor/sub"].git);
75167672 Andy McCall 4310
    assert!(
4311
        files.contains_key(".gitmodules"),
4312
        "the Git file is kept for round trips"
4313
    );
4314
    assert!(
4315
        !dest.join("vendor/sub/.git").exists(),
4316
        "not cloned until update --init"
4317
    );
4dee277c Andy McCall ↶ 4318
    assert!(!repo.snapshot("status").unwrap().changed);
4319
    // update --init clones it at the pinned commit; status is unchanged.
75167672 Andy McCall 4320
    assert_eq!(
4321
        repo.submodule_update(true, &[]).unwrap(),
4322
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
4323
    );
4324
    assert_eq!(
4325
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
4326
        sub_sha
4327
    );
4dee277c Andy McCall ↶ 4328
    assert!(!repo.snapshot("status").unwrap().changed);
4329
    // Export writes the gitlink and .gitmodules back.
4330
    let mirror = root.join("mirror.git");
4331
    let rep = repo.git_export(&mirror).unwrap();
4332
    assert_eq!(rep.skipped_subrepos, 0);
4333
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
75167672 Andy McCall 4334
    assert!(
4335
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
4336
        "{ls}"
4337
    );
4338
    assert_eq!(
4339
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
4340
        ".gitmodules\nREADME.md\nvendor"
4341
    );
4dee277c Andy McCall ↶ 4342
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
75167672 Andy McCall 4343
    assert_eq!(
4344
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
4345
        orig_tree,
4346
        "tree round trip"
4347
    );
4dee277c Andy McCall ↶ 4348
}
4349
957fee30 Andy McCall ↶ 4350
#[test]
4351
fn partial_commits_by_path_and_by_hunk() {
4352
    hermetic();
4353
    let dir = tempfile::tempdir().unwrap();
4354
    let root = dir.path();
4355
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4356
    write(root, "a.txt", b"1\n2\n3\n");
4357
    write(root, "b.txt", b"b\n");
4358
    let h0 = repo.commit("base", &[]).unwrap();
4359
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
4360
    write(root, "b.txt", b"b\nbb\n");
4361
    write(root, "c.txt", b"c\n");
4362
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
75167672 Andy McCall 4363
    let h1 = repo
4364
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
4365
        .unwrap();
957fee30 Andy McCall ↶ 4366
    let c1 = repo.store().get_change(&h1).unwrap();
75167672 Andy McCall 4367
    assert!(
4368
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
4369
        "{:?}",
4370
        c1.tree_ops
4371
    );
957fee30 Andy McCall ↶ 4372
    assert_eq!(c1.deps, vec![h0]);
4373
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
75167672 Andy McCall 4374
    assert!(
4375
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
4376
    );
957fee30 Andy McCall ↶ 4377
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
4378
    assert!(!files.contains_key("c.txt"));
4379
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4380
    assert_eq!(
4381
        snap.statuses
4382
            .iter()
4383
            .map(|s| (s.path.as_str(), s.status))
4384
            .collect::<Vec<_>>(),
4385
        vec![
4386
            ("b.txt", ChangeStatus::Modified),
4387
            ("c.txt", ChangeStatus::Added)
4388
        ]
4389
    );
4390
    assert_eq!(
4391
        fs::read(root.join("b.txt")).unwrap(),
4392
        b"b\nbb\n",
4393
        "disk untouched"
4394
    );
957fee30 Andy McCall ↶ 4395
    // By hunk: pick the b.txt insert; c.txt's addition is left.
4396
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 4397
    let b_hunk = hunks
4398
        .iter()
4399
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
4400
        .unwrap()
4401
        .index;
4402
    let h2 = repo
4403
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4404
        .unwrap();
957fee30 Andy McCall ↶ 4405
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 4406
    assert!(
4407
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4408
    );
957fee30 Andy McCall ↶ 4409
    assert!(!files.contains_key("c.txt"));
4410
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4411
    assert_eq!(
4412
        snap.statuses
4413
            .iter()
4414
            .map(|s| s.path.as_str())
4415
            .collect::<Vec<_>>(),
4416
        vec!["c.txt"]
4417
    );
957fee30 Andy McCall ↶ 4418
    // Choosing only the content hunk of a file in a new directory pulls in
4419
    // the directory and file additions it needs.
4420
    write(root, "d/e.txt", b"e\n");
4421
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 4422
    let e_insert = hunks
4423
        .iter()
4424
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4425
        .unwrap()
4426
        .index;
4427
    let h3 = repo
4428
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4429
        .unwrap();
957fee30 Andy McCall ↶ 4430
    let c3 = repo.store().get_change(&h3).unwrap();
4431
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4432
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4433
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
d8c086ca Andy McCall ↶ 4434
    // Choosing a new file's addition hunk brings its content along.
4435
    write(root, "f/g.txt", b"g\n");
4436
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 4437
    let g_add = hunks
4438
        .iter()
4439
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4440
        .unwrap()
4441
        .index;
4442
    let h4 = repo
4443
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4444
        .unwrap();
d8c086ca Andy McCall ↶ 4445
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
75167672 Andy McCall 4446
    assert!(
4447
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4448
    );
4449
    assert!(!repo
4450
        .snapshot("status")
4451
        .unwrap()
4452
        .statuses
4453
        .iter()
4454
        .any(|s| s.path == "f/g.txt"));
957fee30 Andy McCall ↶ 4455
    // Everything left commits normally; the working copy is then clean.
4456
    repo.commit("the rest", &[]).unwrap();
4457
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 4458
    let files = repo
4459
        .load_state(&repo.bookmark_heads().unwrap())
4460
        .unwrap()
4461
        .materialize()
4462
        .files;
957fee30 Andy McCall ↶ 4463
    assert!(files.contains_key("c.txt"));
4464
}
4465
4466
#[test]
4467
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4468
    hermetic();
4469
    let dir = tempfile::tempdir().unwrap();
4470
    let root = dir.path();
4471
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 4472
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4473
        .unwrap();
957fee30 Andy McCall ↶ 4474
    write(root, "a.txt", b"one\n");
4475
    let h1 = repo.commit("first", &[]).unwrap();
4476
    write(root, "a.txt", b"one\ntwo\n");
4477
    let h2 = repo.commit("second", &[]).unwrap();
4478
    let b = repo.blame("a.txt").unwrap();
75167672 Andy McCall 4479
    assert_eq!(
4480
        b.iter()
4481
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4482
            .collect::<Vec<_>>(),
4483
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4484
    );
957fee30 Andy McCall ↶ 4485
    assert!(b.iter().all(|l| l.author == "Ada"));
75167672 Andy McCall 4486
    assert_eq!(
4487
        b[0].change_id,
4488
        repo.store().get_change(&h1).unwrap().change_id
4489
    );
957fee30 Andy McCall ↶ 4490
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4491
    repo.commit("rename", &[]).unwrap();
4492
    let b = repo.blame("b.txt").unwrap();
75167672 Andy McCall 4493
    assert_eq!(
4494
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4495
        vec![h1, h2],
4496
        "the node survives the rename"
4497
    );
957fee30 Andy McCall ↶ 4498
    assert!(repo.blame("a.txt").is_err());
4499
}
4500
4501
#[test]
4502
fn bisect_finds_the_first_bad_change() {
4503
    hermetic();
4504
    let dir = tempfile::tempdir().unwrap();
4505
    let root = dir.path();
4506
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4507
    let mut content = String::new();
4508
    let mut hashes = Vec::new();
4509
    for i in 1..=8 {
4510
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4511
        write(root, "f.txt", content.as_bytes());
4512
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4513
    }
4514
    // Each step appends after the previous line, so the chain is linear.
4515
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4516
    repo.bisect_start().unwrap();
75167672 Andy McCall 4517
    assert!(matches!(
4518
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4519
        BisectStep::NeedMarks { good: 1, bad: 0 }
4520
    ));
957fee30 Andy McCall ↶ 4521
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
75167672 Andy McCall 4522
    assert!(
4523
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4524
        "{step:?}"
4525
    );
957fee30 Andy McCall ↶ 4526
    // Automated: bad when the bug line is present.
75167672 Andy McCall 4527
    let step = repo
4528
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4529
        .unwrap();
957fee30 Andy McCall ↶ 4530
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
75167672 Andy McCall 4531
    assert_eq!(
4532
        repo.bisect_status().unwrap(),
4533
        Some(BisectStep::Found { culprit: hashes[4] })
4534
    );
957fee30 Andy McCall ↶ 4535
    repo.bisect_reset().unwrap();
4536
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4537
    assert!(repo.bisect_status().unwrap().is_none());
4538
    assert!(!repo.snapshot("status").unwrap().changed);
4539
    // Manual marks and a skip.
4540
    repo.bisect_start().unwrap();
4541
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4542
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4543
    let mut skipped_once = false;
4544
    let mut guard = 0;
4545
    while let BisectStep::Testing { .. } = step {
4546
        guard += 1;
4547
        assert!(guard < 20);
4548
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4549
        if !skipped_once && text.contains("line 6") {
4550
            // An untestable state away from the boundary: the search routes around it.
4551
            skipped_once = true;
4552
            step = repo.bisect_mark(None, &[]).unwrap();
4553
            continue;
4554
        }
4555
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4556
    }
4557
    assert!(skipped_once);
4558
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4559
    repo.bisect_reset().unwrap();
4560
    // Skipping the culprit itself leaves it among the candidates reported.
4561
    repo.bisect_start().unwrap();
4562
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4563
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4564
    let mut guard = 0;
4565
    while let BisectStep::Testing { heads, .. } = &step {
4566
        guard += 1;
4567
        assert!(guard < 20);
4568
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 4569
        let is_culprit_state =
4570
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4571
        step = if is_culprit_state {
4572
            repo.bisect_mark(None, &[]).unwrap()
4573
        } else {
4574
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4575
        };
957fee30 Andy McCall ↶ 4576
    }
4577
    match step {
75167672 Andy McCall 4578
        BisectStep::Inconclusive { candidates } => assert!(
4579
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4580
            "{candidates:?}"
4581
        ),
957fee30 Andy McCall ↶ 4582
        other => panic!("{other:?}"),
4583
    }
4584
    repo.bisect_reset().unwrap();
4585
}
4586
728da0f9 Andy McCall ↶ 4587
#[test]
4588
fn squash_folds_a_change_into_its_dependency() {
4589
    hermetic();
4590
    let dir = tempfile::tempdir().unwrap();
4591
    let root = dir.path();
4592
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4593
    write(root, "a.txt", b"1\n");
4594
    let a = repo.commit("A", &[]).unwrap();
4595
    write(root, "a.txt", b"1\n2\n");
4596
    let c = repo.commit("C", &[]).unwrap();
4597
    write(root, "a.txt", b"1\n2\n3\n");
4598
    let e = repo.commit("E", &[]).unwrap();
4599
    write(root, "b.txt", b"b\n");
4600
    let b = repo.commit("B", &[]).unwrap();
4601
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4602
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4603
    // E depends on C which A lacks: refused, naming it.
4604
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4605
    assert!(err.contains(&c.short(12)), "{err}");
4606
    // C into A: A' has both, C is gone, E follows and still reads the same.
4607
    let a2 = repo.squash(&c, &a).unwrap();
4608
    let a2c = repo.store().get_change(&a2).unwrap();
4609
    assert_eq!(a2c.change_id, id_a);
4610
    assert!(a2c.deps.is_empty());
4611
    let heads = repo.bookmark_heads().unwrap();
4612
    let st = repo.load_state(&heads).unwrap();
4613
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
75167672 Andy McCall 4614
    let e2 = st
4615
        .changes()
4616
        .find(|(_, m)| m.change_id == id_e)
4617
        .map(|(h, _)| *h)
4618
        .unwrap();
4619
    assert_eq!(
4620
        repo.store().get_change(&e2).unwrap().deps,
4621
        vec![a2],
4622
        "E now depends on A' alone"
4623
    );
728da0f9 Andy McCall ↶ 4624
    let files = st.materialize().files;
75167672 Andy McCall 4625
    assert!(
4626
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4627
    );
728da0f9 Andy McCall ↶ 4628
    assert!(files.contains_key("b.txt"));
4629
    assert!(st.contains(&b));
4630
    assert!(!repo.snapshot("status").unwrap().changed);
4631
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4632
    // Undo restores the three original changes.
4633
    repo.undo().unwrap();
4634
    repo.undo().unwrap();
4635
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4636
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4637
}
4638
4639
#[test]
4640
fn rebase_re_expresses_a_change_against_another_base() {
4641
    hermetic();
4642
    let dir = tempfile::tempdir().unwrap();
4643
    let root = dir.path();
4644
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4645
    write(root, "a.txt", b"1\n2\n");
4646
    let a = repo.commit("A", &[]).unwrap();
4647
    write(root, "a.txt", b"1\n2\n3\n");
4648
    let c = repo.commit("C: append 3", &[]).unwrap();
4649
    write(root, "a.txt", b"1\n2\n3\n4\n");
4650
    let e = repo.commit("E: append 4", &[]).unwrap();
4651
    // A different base: A plus a change that prepends a line.
4652
    repo.checkout(&[a], true, "checkout").unwrap();
4653
    write(root, "a.txt", b"0\n1\n2\n");
4654
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4655
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4656
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4657
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4658
    let c2 = repo.rebase(&c, &[d]).unwrap();
4659
    let c2c = repo.store().get_change(&c2).unwrap();
4660
    assert_eq!(c2c.change_id, id_c);
4661
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4662
    let heads = repo.bookmark_heads().unwrap();
4663
    let st = repo.load_state(&heads).unwrap();
4664
    assert!(!st.contains(&c) && st.contains(&d));
75167672 Andy McCall 4665
    let e2 = st
4666
        .changes()
4667
        .find(|(_, m)| m.change_id == id_e)
4668
        .map(|(h, _)| *h)
4669
        .unwrap();
728da0f9 Andy McCall ↶ 4670
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
75167672 Andy McCall 4671
    assert!(
4672
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4673
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4674
    );
728da0f9 Andy McCall ↶ 4675
    let files = st.materialize().files;
75167672 Andy McCall 4676
    assert!(
4677
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4678
        "{:?}",
4679
        files["a.txt"].content
4680
    );
728da0f9 Andy McCall ↶ 4681
    assert!(!files["a.txt"].is_conflicted());
4682
    // Rebasing onto a state that already contains the change is refused.
4683
    assert!(repo.rebase(&c2, &[c2]).is_err());
4684
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
75167672 Andy McCall 4685
    assert!(
4686
        err.contains("lacks dependencies"),
4687
        "E needs C, which D's state does not have: {err}"
4688
    );
728da0f9 Andy McCall ↶ 4689
}
4690
c792033a Andy McCall ↶ 4691
#[test]
4692
fn unsigned_tags_keep_their_message() {
4693
    hermetic();
4694
    let dir = tempfile::tempdir().unwrap();
4695
    let root = dir.path();
4696
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4697
    write(root, "a.txt", b"a\n");
4698
    repo.commit("a", &[]).unwrap();
4699
    assert!(repo.secret_key().unwrap().is_none());
75167672 Andy McCall 4700
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4701
        .unwrap();
c792033a Andy McCall ↶ 4702
    let tags = repo.tags().unwrap();
75167672 Andy McCall 4703
    assert_eq!(
4704
        (
4705
            tags[0].name.as_str(),
4706
            tags[0].message.as_str(),
4707
            tags[0].signer.as_deref()
4708
        ),
4709
        ("v1", "first release", None)
4710
    );
4711
    assert!(
4712
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4713
        "an unsigned attestation is not advertised"
4714
    );
c792033a Andy McCall ↶ 4715
}
387335ff Andy McCall ↶ 4716
4717
#[test]
4718
fn fsck_passes_a_sound_repository_and_names_each_fault() {
64818938 Andy McCall ↶ 4719
    // Files on disk are what this tests: tampering with them, and the
4720
    // directory store's crash points.
4721
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4722
        return;
4723
    }
387335ff Andy McCall ↶ 4724
    hermetic();
4725
    let dir = tempfile::tempdir().unwrap();
4726
    let root = dir.path();
4727
    let origin_path = root.join("origin");
4728
    let origin = Repo::init(&origin_path).unwrap();
4729
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4730
        .unwrap()
4731
        .with_home(root.join("home-a"));
4732
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4733
        .unwrap();
4734
    write(&root.join("a"), "f.txt", b"one\n");
4735
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4736
    let h1 = a.commit("first", &[]).unwrap();
4737
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4738
    let h2 = a.commit("second", &[]).unwrap();
4739
    a.tag_create("v1", &[h2], "first release").unwrap();
4740
    a.checkpoint().unwrap();
4741
    assert!(a.push("origin", false).unwrap()[0].ok);
4742
4743
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4744
    for repo in [&a, &origin] {
4745
        let rep = repo.fsck().unwrap();
4746
        assert_eq!(rep.problems, vec![], "{rep:?}");
4747
        // The two commits, plus the working copy's change in `a`.
4748
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4749
        assert!(rep.ops > 1 && rep.objects > 5);
4750
    }
4751
    assert!(origin.fsck().unwrap().attestations >= 1);
4752
4753
    // A flipped byte in a stored object is corruption, named by hash.
4754
    let c1 = a.store().path_for(&h1);
4755
    let pristine = fs::read(&c1).unwrap();
4756
    let mut bytes = pristine.clone();
4757
    *bytes.last_mut().unwrap() ^= 1;
4758
    fs::write(&c1, &bytes).unwrap();
4759
    let rep = a.fsck().unwrap();
4760
    assert!(rep.errors() >= 1);
4761
    assert!(
4762
        rep.problems
4763
            .iter()
4764
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4765
        "{rep:?}"
4766
    );
4767
    fs::write(&c1, &pristine).unwrap();
4768
    assert_eq!(a.fsck().unwrap().errors(), 0);
4769
4770
    // A missing change is named with what needed it.
4771
    fs::remove_file(&c1).unwrap();
4772
    let rep = a.fsck().unwrap();
4773
    assert!(
4774
        rep.problems.iter().any(|p| p.severity == Severity::Error
4775
            && p.object == Some(h1)
4776
            && p.what.contains("change missing, needed by change")),
4777
        "{rep:?}"
4778
    );
4779
    fs::write(&c1, &pristine).unwrap();
4780
4781
    // A missing blob is an error in a full clone.
4782
    let c2 = a.store().get_change(&h1).unwrap();
4783
    let blob = c2
4784
        .edits
4785
        .iter()
4786
        .find_map(|e| match e {
4787
            Edit::Replace { new: Some(b), .. } => Some(*b),
4788
            _ => None,
4789
        })
4790
        .expect("the binary file is a blob");
4791
    let bp = a.store().path_for(&blob);
4792
    let blob_bytes = fs::read(&bp).unwrap();
4793
    fs::remove_file(&bp).unwrap();
4794
    let rep = a.fsck().unwrap();
4795
    assert!(
4796
        rep.problems
4797
            .iter()
4798
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4799
        "{rep:?}"
4800
    );
4801
    fs::write(&bp, &blob_bytes).unwrap();
4802
4803
    // A broken op log head is reported, not a crash.
4804
    let head = root.join("a/.oxy/ops/head");
4805
    let saved = fs::read(&head).unwrap();
4806
    fs::write(&head, b"not a hash").unwrap();
4807
    let rep = a.fsck().unwrap();
4808
    assert!(
4809
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4810
        "{rep:?}"
4811
    );
4812
    fs::write(&head, saved).unwrap();
4813
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4814
}
4dcb8c09 Andy McCall ↶ 4815
4816
/// Copy a directory tree (for restoring a pristine repository).
4817
fn copy_tree(from: &Path, to: &Path) {
4818
    fs::create_dir_all(to).unwrap();
4819
    for e in fs::read_dir(from).unwrap() {
4820
        let e = e.unwrap();
4821
        let target = to.join(e.file_name());
4822
        if e.file_type().unwrap().is_dir() {
4823
            copy_tree(&e.path(), &target);
4824
        } else {
4825
            fs::copy(e.path(), &target).unwrap();
4826
        }
4827
    }
4828
}
4829
4830
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4831
/// would, and check that both repositories still open, pass `fsck`, and
4832
/// accept the same operation again.
4833
#[test]
4834
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
64818938 Andy McCall ↶ 4835
    // Files on disk are what this tests: tampering with them, and the
4836
    // directory store's crash points.
4837
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4838
        return;
4839
    }
4dcb8c09 Andy McCall ↶ 4840
    use crate::durable::failpoint;
4841
    hermetic();
4842
    let dir = tempfile::tempdir().unwrap();
4843
    let pristine = dir.path().join("pristine");
4844
    let origin_path = pristine.join("origin");
4845
    Repo::init(&origin_path).unwrap();
4846
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4847
        .unwrap()
4848
        .with_home(dir.path().join("home"));
4849
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4850
        .unwrap();
4851
    write(&pristine.join("a"), "f.txt", b"one\n");
4852
    a.commit("first", &[]).unwrap();
4853
    assert!(a.push("origin", false).unwrap()[0].ok);
4854
    drop(a);
4855
4856
    type Op = fn(&Repo) -> Result<()>;
4857
    let edit_and_commit: Op = |r| {
4858
        write(r.root(), "f.txt", b"one\ntwo\n");
4859
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4860
        r.commit("second", &[]).map(|_| ())
4861
    };
4862
    let push: Op = |r| {
4863
        let res = r.push("origin", false)?;
4864
        if res.iter().all(|x| x.ok) {
4865
            Ok(())
4866
        } else {
4867
            Err(RepoError::Msg(format!("{res:?}")))
4868
        }
4869
    };
4870
4871
    for (name, prepare, op) in [
4872
        ("commit", None, edit_and_commit),
4873
        ("push", Some(edit_and_commit), push),
4874
    ] {
4875
        let mut steps = 0;
4876
        for n in 1.. {
4877
            let run = dir.path().join(format!("{name}-{n}"));
4878
            copy_tree(&pristine, &run);
4879
            // Clones record their remote by path; point it at this copy.
4880
            let open = |p: &Path| {
4881
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4882
                r.config
4883
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4884
                    .unwrap();
4885
                r.save_config().unwrap();
4886
                r
4887
            };
4888
            let a = open(&run.join("a"));
4889
            if let Some(prep) = prepare {
4890
                prep(&a).unwrap();
4891
            }
4892
            failpoint::crash_after(n);
4893
            let outcome = op(&a);
4894
            let crashed = failpoint::disarm();
4895
            drop(a);
4896
            if !crashed {
4897
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4898
                steps = n - 1;
4899
                break;
4900
            }
4901
            assert!(
4902
                outcome.is_err(),
4903
                "{name}: a crash at step {n} was swallowed"
4904
            );
4905
            for repo in ["a", "origin"] {
4906
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4907
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4908
                });
4909
                let rep = r.fsck().unwrap();
4910
                assert_eq!(
4911
                    rep.errors(),
4912
                    0,
4913
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4914
                    rep.problems
4915
                );
4916
            }
4917
            // The interrupted operation can simply be run again.
4918
            let a = open(&run.join("a"));
4919
            // A crash after the commit point leaves the commit done.
4920
            let landed = a
4921
                .bookmark_heads()
4922
                .unwrap()
4923
                .iter()
4924
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4925
            let again = match (name, landed) {
4926
                ("commit", true) => Ok(()),
4927
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4928
                _ => op(&a),
4929
            };
4930
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4931
            assert_eq!(a.fsck().unwrap().errors(), 0);
4932
            fs::remove_dir_all(&run).unwrap();
4933
        }
4934
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4935
    }
4936
}
19555025 Andy McCall ↶ 4937
4938
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4939
/// running at the same time lose nothing: every commit ends up on the
4940
/// bookmark, locally and on the remote, and the repository passes fsck.
4941
#[test]
4942
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4943
    hermetic();
4944
    let dir = tempfile::tempdir().unwrap();
4945
    let root = dir.path();
4946
    let origin = root.join("origin");
4947
    Repo::init_bare_unbound(&origin).unwrap();
4948
    let main = root.join("main");
4949
    let mut repo = Repo::init(&main).unwrap();
4950
    repo.config
4951
        .set("remote.origin.url", &origin.to_string_lossy())
4952
        .unwrap();
4953
    repo.save_config().unwrap();
4954
    write(&main, "seed.txt", b"seed\n");
4955
    repo.commit("seed", &[]).unwrap();
4956
    let second = root.join("second");
4957
    repo.workspace_add(&second, None).unwrap();
4958
    drop(repo);
4959
4960
    const EACH: usize = 15;
4961
    std::thread::scope(|s| {
4962
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4963
            s.spawn(move || {
4964
                let r = Repo::open(&dir).unwrap();
4965
                for i in 0..EACH {
4966
                    write(
4967
                        &dir,
4968
                        &format!("{tag}-{i}.txt"),
4969
                        format!("{tag} {i}\n").as_bytes(),
4970
                    );
4971
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4972
                    if push && i % 5 == 4 {
4973
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4974
                        let _ = r.push("origin", false);
4975
                    }
4976
                }
4977
            });
4978
        }
4979
    });
4980
4981
    let repo = Repo::open(&main).unwrap();
4982
    let heads = repo.bookmark_heads().unwrap();
4983
    let state = repo.load_state(&heads).unwrap();
4984
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4985
    for tag in ["a", "b"] {
4986
        for i in 0..EACH {
4987
            assert!(
4988
                messages.contains(&format!("{tag} {i}")),
4989
                "lost commit {tag} {i}; have {messages:?}"
4990
            );
4991
        }
4992
    }
4993
    let rep = repo.fsck().unwrap();
4994
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4995
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4996
    let hosted = Repo::open(&origin).unwrap();
4997
    let hosted_heads = hosted.bookmark_heads().unwrap();
4998
    assert_eq!(
4999
        hosted.load_state(&hosted_heads).unwrap().len(),
5000
        state.len(),
5001
        "the remote has every commit"
5002
    );
5003
}
5004
5005
/// Two operations recorded from the same parent (what two processes do
5006
/// when they race) are merged: both bookmarks' heads survive, and a
5007
/// change made on one side only is kept.
5008
#[test]
5009
fn operations_from_the_same_parent_are_merged() {
5010
    hermetic();
5011
    let dir = tempfile::tempdir().unwrap();
5012
    let root = dir.path();
5013
    let repo = Repo::init(root).unwrap();
5014
    write(root, "a.txt", b"a\n");
5015
    let a = repo.commit("a", &[]).unwrap();
5016
    write(root, "b.txt", b"b\n");
5017
    let b = repo.commit("b", &[]).unwrap();
5018
    let (x, op) = repo.head_op().unwrap();
5019
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
5020
5021
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
5022
    let mut one = op.view.clone();
5023
    one.bookmarks.insert("main".into(), state(vec![a]));
5024
    one.bookmarks.insert("topic".into(), state(vec![a]));
5025
    let mut two = op.view.clone();
5026
    two.bookmarks.insert("main".into(), state(vec![b]));
5027
    repo.record_op(&[x], "one", one).unwrap();
5028
    let merged = repo.record_op(&[x], "two", two).unwrap();
5029
5030
    let (head, op) = repo.head_op().unwrap();
5031
    assert_eq!(head, merged);
5032
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
5033
    assert!(op.command.contains("merged with a concurrent operation"));
5034
    let mut main = repo
5035
        .store()
5036
        .get_state(&op.view.bookmarks["main"])
5037
        .unwrap()
5038
        .heads;
5039
    main.sort();
5040
    let mut want = vec![a, b];
5041
    want.sort();
5042
    assert_eq!(main, want, "both sides' heads are kept");
5043
    assert!(
5044
        op.view.bookmarks.contains_key("topic"),
5045
        "a one-sided change survives"
5046
    );
5047
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5048
}
3e5772cc Andy McCall ↶ 5049
5050
#[test]
5051
fn failed_requests_come_with_a_next_step() {
5052
    use crate::protocol::hint_for;
5053
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
5054
        .unwrap()
5055
        .contains("token"));
5056
    assert!(hint_for("…: HTTP 403: forbidden")
5057
        .unwrap()
5058
        .contains("repo:write"));
5059
    assert!(hint_for("…: HTTP 404: no such repository")
5060
        .unwrap()
5061
        .contains("owner and repository name"));
5062
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
5063
        .unwrap()
5064
        .contains("oxyhub-ca.pem"));
5065
    assert!(hint_for("Connect error: Connection refused (os error 111)")
5066
        .unwrap()
5067
        .contains("running"));
5068
    assert!(hint_for("Dns Failed: failed to lookup address information")
5069
        .unwrap()
5070
        .contains("resolve"));
5071
    assert_eq!(hint_for("something else entirely"), None);
5072
}
5073
5074
#[test]
5075
fn doctor_names_problems_and_what_to_do() {
5076
    hermetic();
5077
    let dir = tempfile::tempdir().unwrap();
5078
    let root = dir.path();
5079
    let origin = root.join("origin");
5080
    Repo::init_bare_unbound(&origin).unwrap();
5081
    let mut repo = Repo::init(&root.join("r"))
5082
        .unwrap()
5083
        .with_home(root.join("home"));
5084
    let find = |r: &DoctorReport, area: &str, h: Health| {
5085
        r.checks
5086
            .iter()
5087
            .find(|c| c.area == area && c.health == h)
5088
            .cloned()
5089
    };
5090
5091
    let r = repo.doctor(true);
5092
    assert!(find(&r, "identity", Health::Warn)
5093
        .unwrap()
5094
        .hint
5095
        .unwrap()
5096
        .contains("oxy identity create"));
5097
    assert!(find(&r, "repository", Health::Ok).is_some());
5098
5099
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5100
        .unwrap();
5101
    repo.config.set("author.name", "Ada").unwrap();
5102
    repo.config.set("author.email", "[email protected]").unwrap();
5103
    repo.config
5104
        .set("remote.origin.url", &origin.to_string_lossy())
5105
        .unwrap();
5106
    repo.config
5107
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
5108
        .unwrap();
5109
    repo.config.set("remote.down.token", "t").unwrap();
5110
    repo.config
5111
        .set("remote.badca.url", "https://example.invalid/a/b")
5112
        .unwrap();
5113
    repo.config
5114
        .set(
5115
            "remote.badca.ca",
5116
            &root.join("missing.pem").to_string_lossy(),
5117
        )
5118
        .unwrap();
5119
    repo.save_config().unwrap();
5120
5121
    let r = repo.doctor(true);
5122
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
5123
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
5124
    assert!(find(&r, "remote origin", Health::Ok)
5125
        .unwrap()
5126
        .message
5127
        .contains("first push binds it"));
5128
    let down = find(&r, "remote down", Health::Fail).unwrap();
5129
    assert!(
5130
        down.hint.as_deref().unwrap_or("").contains("running"),
5131
        "{down:?}"
5132
    );
5133
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
5134
    assert!(
5135
        badca.hint.unwrap().contains("remote.badca.ca"),
5136
        "the remote's own name is in the hint"
5137
    );
5138
    assert_eq!(r.worst(), Health::Fail);
5139
5140
    // Offline, nothing is contacted.
5141
    let r = repo.doctor(false);
5142
    assert!(find(&r, "remote down", Health::Fail).is_none());
5143
    assert!(find(&r, "remote down", Health::Ok)
5144
        .unwrap()
5145
        .message
5146
        .contains("not contacted"));
5147
}
62794ecc Andy McCall ↶ 5148
5149
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
5150
/// after it. Inserting after `b` and then deleting `b`, one commit after
5151
/// the other, must not leave a delete/insert conflict.
5152
#[test]
5153
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
5154
    hermetic();
5155
    let dir = tempfile::tempdir().unwrap();
5156
    let root = dir.path();
5157
    let repo = Repo::init(root).unwrap();
5158
    write(root, "f", b"a\nb\nc\n");
5159
    repo.commit("base", &[]).unwrap();
5160
    write(root, "f", b"a\nb\nx\nc\n");
5161
    let insert = repo.commit("insert x after b", &[]).unwrap();
5162
    write(root, "f", b"a\nx\nc\n");
5163
    let delete = repo.commit("delete b", &[]).unwrap();
5164
    assert!(
5165
        repo.store()
5166
            .get_change(&delete)
5167
            .unwrap()
5168
            .deps
5169
            .contains(&insert),
5170
        "the deletion depends on the insertion below the deleted line"
5171
    );
5172
    let heads = repo.bookmark_heads().unwrap();
5173
    assert_eq!(heads, vec![delete]);
5174
    let snap = repo.load_state(&heads).unwrap().materialize();
5175
    assert!(!snap.is_conflicted());
5176
    assert!(
5177
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
5178
    );
5179
}
5180
5181
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
5182
/// replacement depends on the change that set the blob it replaces.
5183
#[test]
5184
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
5185
    hermetic();
5186
    let dir = tempfile::tempdir().unwrap();
5187
    let root = dir.path();
5188
    let repo = Repo::init(root).unwrap();
5189
    write(root, "bin", b"\0A");
5190
    let v1 = repo.commit("v1", &[]).unwrap();
5191
    write(root, "bin", b"\0B");
5192
    let v2 = repo.commit("v2", &[]).unwrap();
5193
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
5194
    write(root, "bin", b"\0A");
5195
    let v3 = repo.commit("back to A", &[]).unwrap();
5196
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
5197
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
5198
    let state = repo.load_state(&[v3]).unwrap();
5199
    let snap = state.materialize();
5200
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
5201
        panic!("opaque")
5202
    };
5203
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
5204
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
5205
}
5206
5207
/// Spec §23: a binary file changed on two branches and merged in Git to
5208
/// one side's version comes back as that version at the merge, and the
5209
/// import verifies commit by commit.
5210
#[test]
5211
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
5212
    hermetic();
5213
    if std::process::Command::new("git")
5214
        .arg("--version")
5215
        .output()
5216
        .is_err()
5217
    {
5218
        eprintln!("git not installed; skipping");
5219
        return;
5220
    }
5221
    let dir = tempfile::tempdir().unwrap();
5222
    let root = dir.path();
5223
    let g = root.join("src.git");
5224
    fs::create_dir_all(&g).unwrap();
5225
    let git = |args: &[&str]| -> String {
5226
        let out = std::process::Command::new("git")
5227
            .arg("-C")
5228
            .arg(&g)
5229
            .args([
5230
                "-c",
5231
                "user.name=Grace",
5232
                "-c",
5233
                "[email protected]",
5234
                "-c",
5235
                "commit.gpgsign=false",
5236
            ])
5237
            .args(args)
5238
            .output()
5239
            .unwrap();
5240
        assert!(
5241
            out.status.success(),
5242
            "git {args:?}: {}",
5243
            String::from_utf8_lossy(&out.stderr)
5244
        );
5245
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5246
    };
5247
    git(&["init", "-q", "-b", "main"]);
5248
    write(&g, "logo.bin", b"\0base");
5249
    write(&g, "notes.txt", b"a\nb\nc\n");
5250
    git(&["add", "."]);
5251
    git(&["commit", "-qm", "base"]);
5252
    git(&["checkout", "-qb", "side"]);
5253
    write(&g, "logo.bin", b"\0side");
5254
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
5255
    git(&["commit", "-qam", "side"]);
5256
    git(&["checkout", "-q", "main"]);
5257
    write(&g, "logo.bin", b"\0main");
5258
    git(&["commit", "-qam", "main"]);
5259
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
5260
    let _ = std::process::Command::new("git")
5261
        .arg("-C")
5262
        .arg(&g)
5263
        .args([
5264
            "-c",
5265
            "user.name=G",
5266
            "-c",
5267
            "user.email=g@e",
5268
            "merge",
5269
            "-q",
5270
            "side",
5271
        ])
5272
        .output();
5273
    write(&g, "logo.bin", b"\0main");
5274
    git(&["add", "."]);
5275
    git(&["commit", "-qm", "merge side"]);
5276
    // Then a revert of the binary to its first version.
5277
    write(&g, "logo.bin", b"\0base");
5278
    git(&["commit", "-qam", "back to base"]);
5279
5280
    let repo = Repo::init(&root.join("o")).unwrap();
5281
    let rep = repo.import_git(&g, "main").unwrap();
5282
    assert_eq!(rep.merges, 1);
5283
    let v = repo.verify_git_import(&g, "main").unwrap();
5284
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
5285
    assert_eq!(v.commits, 5);
5286
    let snap = repo
5287
        .load_state(&repo.bookmark_heads().unwrap())
5288
        .unwrap()
5289
        .materialize();
5290
    assert!(!snap.is_conflicted());
5291
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
5292
        panic!("opaque")
5293
    };
5294
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
5295
}
c863c7a7 Andy McCall ↶ 5296
5297
/// Spec §7.7 on a file system without executable bits or symlinks: the
5298
/// recorded bit is kept, and a symlink checked out as a plain file holding
5299
/// its target is still that symlink.
5300
#[cfg(unix)]
5301
#[test]
5302
fn windows_file_systems_keep_exec_bits_and_symlinks() {
5303
    use crate::portable::Platform;
5304
    use std::os::unix::fs::PermissionsExt;
5305
    hermetic();
5306
    let dir = tempfile::tempdir().unwrap();
5307
    let root = dir.path();
5308
    let repo = Repo::init(root).unwrap();
5309
    write(root, "run.sh", b"#!/bin/sh\n");
5310
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
5311
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
5312
    repo.commit("script and link", &[]).unwrap();
5313
    drop(repo);
5314
5315
    // What checking out on Windows leaves: no exec bit, the link as a file.
5316
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
5317
    fs::remove_file(root.join("link")).unwrap();
5318
    write(root, "link", b"run.sh");
5319
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
5320
    let s = win.snapshot("oxy status").unwrap();
5321
    assert!(
5322
        s.statuses.is_empty(),
5323
        "nothing changed on Windows: {:?}",
5324
        statuses(&s)
5325
    );
5326
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
5327
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
5328
    write(root, "link", b"other");
5329
    let h = win.commit("edit on Windows", &[]).unwrap();
5330
    let snap = win.load_state(&[h]).unwrap().materialize();
5331
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
5332
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
5333
    // The same working copy read as Linux sees the lost bit and the plain file.
5334
    let linux = Repo::open(root).unwrap();
5335
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
5336
}
5337
5338
/// Paths that collide on case-insensitive or Windows file systems are
5339
/// named at checkout there, and by doctor everywhere.
5340
#[test]
5341
fn paths_other_platforms_cannot_hold_are_reported() {
5342
    use crate::portable::Platform;
5343
    hermetic();
5344
    let dir = tempfile::tempdir().unwrap();
5345
    let root = dir.path();
5346
    let repo = Repo::init(root).unwrap();
5347
    write(root, "README.md", b"a\n");
5348
    write(root, "readme.md", b"b\n");
5349
    write(root, "src/aux.c", b"int x;\n");
5350
    let h = repo.commit("unportable", &[]).unwrap();
5351
    let r = repo.doctor(false);
5352
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
5353
    assert_eq!(port.health, Health::Warn);
5354
    assert!(
5355
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
5356
        "{}",
5357
        port.message
5358
    );
5359
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
5360
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
5361
    assert!(
5362
        rep.notes
5363
            .iter()
5364
            .any(|n| n.contains("README.md and readme.md")),
5365
        "{:?}",
5366
        rep.notes
5367
    );
5368
    assert!(
5369
        !rep.notes.iter().any(|n| n.contains("aux.c")),
5370
        "macOS allows aux.c"
5371
    );
5372
}
bc489b6c Andy McCall ↶ 5373
5374
#[test]
5375
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
5376
    hermetic();
5377
    let dir = tempfile::tempdir().unwrap();
5378
    let repo = Repo::init(dir.path()).unwrap();
5379
    write(dir.path(), "a.txt", b"one\n");
5380
    write(dir.path(), "other.txt", b"x\n");
5381
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
5382
    repo.snapshot("t").unwrap();
5383
    let c1 = repo.commit("first", &[]).unwrap();
5384
    write(dir.path(), "other.txt", b"y\n");
5385
    repo.snapshot("t").unwrap();
5386
    repo.commit("other only", &[]).unwrap();
5387
    write(dir.path(), "a.txt", b"one\ntwo\n");
5388
    repo.snapshot("t").unwrap();
5389
    let c3 = repo.commit("second line", &[]).unwrap();
5390
    write(dir.path(), "other.txt", b"z\n");
5391
    repo.snapshot("t").unwrap();
5392
    repo.commit("other again", &[]).unwrap();
5393
5394
    let heads = repo.bookmark_heads().unwrap();
5395
    let state = repo.load_state(&heads).unwrap();
5396
    let full: Vec<ChangeHash> = repo
5397
        .log_for_path_in("a.txt", &heads)
5398
        .unwrap()
5399
        .iter()
5400
        .map(|e| e.hash)
5401
        .collect();
5402
    assert_eq!(
5403
        full,
5404
        vec![c3, c1],
5405
        "newest first, only changes touching the path"
5406
    );
5407
    let newest: Vec<ChangeHash> = repo
5408
        .log_for_path_of(&state, "a.txt", Some(1))
5409
        .unwrap()
5410
        .iter()
5411
        .map(|e| e.hash)
5412
        .collect();
5413
    assert_eq!(newest, vec![c3], "stops at the first");
5414
    assert_eq!(
5415
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5416
        2
5417
    );
5418
    assert!(repo
5419
        .log_for_path_of(&state, "missing.txt", Some(1))
5420
        .is_err());
5421
    assert_eq!(
5422
        repo.log_state(&heads).unwrap().len(),
5423
        repo.log_of(&state).len()
5424
    );
5425
5426
    let tree = state.tree().view();
5427
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5428
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5429
    assert_eq!(
5430
        via_state
5431
            .iter()
5432
            .map(|l| (l.hash, l.text.clone()))
5433
            .collect::<Vec<_>>(),
5434
        via_heads
5435
            .iter()
5436
            .map(|l| (l.hash, l.text.clone()))
5437
            .collect::<Vec<_>>()
5438
    );
5439
    assert_eq!(
5440
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5441
        vec![c1, c3]
5442
    );
5443
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5444
}
696bbf29 Andy McCall ↶ 5445
5446
/// A text file whose stat matches the manifest and whose recorded hash is
5447
/// the base's content is taken from the base without reading it; anything
5448
/// else is read, so no edit is missed (spec §12.3).
5449
#[cfg(unix)]
5450
#[test]
5451
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5452
    use std::os::unix::fs::PermissionsExt;
5453
    hermetic();
5454
    let dir = tempfile::tempdir().unwrap();
5455
    let root = dir.path();
5456
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5457
    write(root, "a.txt", b"one\ntwo\n");
5458
    write(root, "b.txt", b"bee\n");
5459
    repo.commit("base", &[]).unwrap();
5460
    let age = |p: &str| {
5461
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5462
        fs::File::options()
5463
            .write(true)
5464
            .open(root.join(p))
5465
            .unwrap()
5466
            .set_modified(old)
5467
            .unwrap();
5468
    };
5469
    age("a.txt");
5470
    age("b.txt");
5471
    assert!(
5472
        !repo.snapshot("status").unwrap().changed,
5473
        "records the aged stat"
5474
    );
5475
5476
    // Clean and equal to the base: not read at all.
5477
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5478
    let snap = repo.snapshot("status").unwrap();
5479
    assert!(
5480
        !snap.changed && snap.statuses.is_empty(),
5481
        "{:?}",
5482
        snap.statuses
5483
    );
5484
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5485
5486
    // An uncommitted edit that is older than the manifest: stat-clean, but
5487
    // its hash is not the base's, so it is read and stays visible.
5488
    write(root, "b.txt", b"bee edited\n");
5489
    age("b.txt");
5490
    let first = repo.snapshot("status").unwrap();
5491
    assert_eq!(
5492
        statuses(&first),
5493
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5494
    );
5495
    let again = repo.snapshot("status").unwrap();
5496
    assert_eq!(
5497
        statuses(&again),
5498
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5499
        "still seen once stat-clean"
5500
    );
5501
    assert!(!again.changed, "and the working copy hashes the same");
5502
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5503
    assert!(
5504
        repo.snapshot("status").is_err(),
5505
        "an edited file must be read, never taken from the base"
5506
    );
5507
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5508
5509
    // A same-size edit made just now is racy and read.
5510
    write(root, "a.txt", b"one\nTWO\n");
5511
    assert_eq!(
5512
        statuses(&repo.snapshot("status").unwrap()),
5513
        vec![
5514
            ("a.txt".to_string(), ChangeStatus::Modified),
5515
            ("b.txt".to_string(), ChangeStatus::Modified)
5516
        ]
5517
    );
5518
    // Committing makes the edits the base: both are clean and served from it again.
5519
    repo.commit("edits", &[]).unwrap();
5520
    age("a.txt");
5521
    age("b.txt");
5522
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5523
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5524
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5525
    let snap = repo.snapshot("status").unwrap();
5526
    assert!(!snap.changed && snap.statuses.is_empty());
5527
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5528
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5529
}
afaba5f1 Andy McCall ↶ 5530
5531
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5532
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5533
/// file is unchanged, and loading through the checkpoint equals a full load.
5534
#[test]
5535
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5536
    hermetic();
5537
    let dir = tempfile::tempdir().unwrap();
5538
    let root = dir.path();
5539
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5540
    let long: String = (0..300)
5541
        .map(|i| format!("line {i} of a long file\n"))
5542
        .collect();
5543
    write(root, "long.txt", long.as_bytes());
5544
    write(root, "short.txt", b"short\n");
5545
    repo.commit("base", &[]).unwrap();
5546
    let (r1, _, _) = repo.checkpoint().unwrap();
5547
    let cp1 = crate::objects::Checkpoint::decode(
5548
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5549
    )
5550
    .unwrap();
5551
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5552
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5553
5554
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5555
    repo.gc(true).unwrap();
5556
    assert!(repo.store().has(&graphs1[0]));
5557
    let report = repo.fsck().unwrap();
5558
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5559
5560
    // Loading through the checkpoint equals a full load.
5561
    write(root, "short.txt", b"short, edited\n");
5562
    repo.commit("edit the short file", &[]).unwrap();
5563
    let heads = repo.bookmark_heads().unwrap();
5564
    let fast = repo.load_state(&heads).unwrap();
5565
    let full = repo.load_state_full(&heads).unwrap();
5566
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5567
5568
    // The next checkpoint shares the unchanged long file's graph.
5569
    let (r2, _, _) = repo.checkpoint().unwrap();
5570
    let cp2 = crate::objects::Checkpoint::decode(
5571
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5572
    )
5573
    .unwrap();
5574
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5575
5576
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5577
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5578
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5579
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5580
5581
    // A version 1 checkpoint written by an older oxy still loads.
5582
    let state = repo.load_state_full(&heads).unwrap();
5583
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5584
    let cp_old = crate::objects::Checkpoint {
5585
        heads: cp2.heads.clone(),
5586
        count: cp2.count,
5587
        payload: old,
5588
    };
5589
    let r_old = repo
5590
        .store()
5591
        .put(ObjectType::Checkpoint, &cp_old.encode())
5592
        .unwrap();
5593
    repo.install_checkpoint("main", &r_old).unwrap();
5594
    assert_eq!(
5595
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5596
        full.checkpoint_payload()
5597
    );
5598
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5599
5600
    // A lost graph blob fails the load loudly rather than dropping the
5601
    // file, and fsck reports it (a fresh repository, objects still loose).
5602
    let dir2 = tempfile::tempdir().unwrap();
5603
    let root2 = dir2.path();
5604
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5605
    write(root2, "long.txt", long.as_bytes());
5606
    repo2.commit("base", &[]).unwrap();
5607
    let (r, _, _) = repo2.checkpoint().unwrap();
5608
    let cp = crate::objects::Checkpoint::decode(
5609
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5610
    )
5611
    .unwrap();
5612
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
64818938 Andy McCall ↶ 5613
    repo2.store().remove_loose_for_test(&graph).unwrap();
afaba5f1 Andy McCall ↶ 5614
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5615
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5616
}
e3d071ce Andy McCall ↶ 5617
5618
/// A new repository has not stored the user's identity yet (that happens
5619
/// at the first signed change); looking it up falls back to the key
5620
/// directory, and a file there that does not hash to the key is refused.
5621
#[test]
5622
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5623
    hermetic();
5624
    let dir = tempfile::tempdir().unwrap();
5625
    let home = dir.path().join("home");
5626
    let mut first = Repo::init(&dir.path().join("a"))
5627
        .unwrap()
5628
        .with_home(home.clone());
5629
    let (key, _) = first
5630
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5631
        .unwrap();
5632
    let fresh = Repo::init(&dir.path().join("b"))
5633
        .unwrap()
5634
        .with_home(home.clone());
5635
    assert!(!fresh.store().has(&key), "nothing stored yet");
5636
    let id = fresh.identity(&key).unwrap();
5637
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5638
    // A key file that is not this identity is an error, not a wrong answer.
5639
    let keys = fresh.keys_dir.clone();
5640
    let (other, _) = first
5641
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5642
        .unwrap();
5643
    fs::copy(
5644
        keys.join(format!("{}.identity", other.to_hex())),
5645
        keys.join(format!("{}.identity", key.to_hex())),
5646
    )
5647
    .unwrap();
5648
    assert!(fresh
5649
        .identity(&key)
5650
        .unwrap_err()
5651
        .to_string()
5652
        .contains("does not hold identity"));
5653
}
cc7a0056 Andy McCall ↶ 5654
5655
/// Status snapshots (spec §12.3): a text file whose stat matches the
5656
/// manifest, and whose base graph key is the one the manifest recorded it
5657
/// equal to, is neither read nor rendered; any edit, and any change to the
5658
/// file's graph in the base, brings it back.
5659
#[cfg(unix)]
5660
#[test]
5661
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5662
    use std::os::unix::fs::PermissionsExt;
5663
    hermetic();
5664
    let dir = tempfile::tempdir().unwrap();
5665
    let root = dir.path();
5666
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5667
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5668
        write(root, p, c.as_bytes());
5669
    }
5670
    repo.commit("base", &[]).unwrap();
5671
    let age = |p: &str| {
5672
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5673
        fs::File::options()
5674
            .write(true)
5675
            .open(root.join(p))
5676
            .unwrap()
5677
            .set_modified(old)
5678
            .unwrap();
5679
    };
5680
    let lock = |p: &str, mode: u32| {
5681
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5682
    };
5683
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5684
        age(p);
5685
    }
5686
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5687
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5688
    assert!(
5689
        m.entries.values().all(|e| e.graph.is_some()),
5690
        "keys recorded"
5691
    );
5692
5693
    // Unreadable files prove they are not read; the status snapshot does
5694
    // not render them either, and its base lacks their graphs.
5695
    lock("a.txt", 0o000);
5696
    lock("b.txt", 0o000);
5697
    let snap = repo.snapshot_status("status").unwrap();
5698
    assert!(!snap.changed && snap.statuses.is_empty());
5699
    assert_eq!(
5700
        snap.base_snapshot
5701
            .unrendered
5702
            .iter()
5703
            .cloned()
5704
            .collect::<Vec<_>>(),
5705
        vec!["a.txt", "b.txt", "d/c.txt"]
5706
    );
5707
    assert!(!snap.base.is_full());
5708
    assert!(!snap.base_snapshot.is_conflicted());
5709
    // A full snapshot does not read them either, but renders everything.
5710
    let full = repo.snapshot("status").unwrap();
5711
    assert!(full.statuses.is_empty() && full.base.is_full());
5712
    assert!(full.base_snapshot.unrendered.is_empty());
5713
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5714
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5715
5716
    // An edit is seen; the file is rendered, the others still are not.
5717
    write(root, "d/c.txt", b"sea edited\n");
5718
    let snap = repo.snapshot_status("status").unwrap();
5719
    assert_eq!(
5720
        statuses(&snap),
5721
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5722
    );
5723
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5724
    // So is a mode change of an unread file.
5725
    lock("b.txt", 0o100);
5726
    assert_eq!(
5727
        statuses(&repo.snapshot_status("status").unwrap()),
5728
        vec![
5729
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5730
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5731
        ]
5732
    );
5733
    lock("b.txt", 0o000);
5734
5735
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5736
    // stays unread, c.txt is read once and then skipped too.
5737
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5738
        .unwrap();
5739
    age("d/c.txt");
5740
    let snap = repo.snapshot_status("status").unwrap();
5741
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5742
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5743
    lock("d/c.txt", 0o000);
5744
    let snap = repo.snapshot_status("status").unwrap();
5745
    assert!(snap.statuses.is_empty());
5746
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5747
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5748
        lock(p, 0o644);
5749
    }
5750
}
5751
5752
/// Attributes decide how a file compares with the base, so a changed
5753
/// `.oxyattributes` makes every text file be compared again.
5754
#[cfg(unix)]
5755
#[test]
5756
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5757
    hermetic();
5758
    let dir = tempfile::tempdir().unwrap();
5759
    let root = dir.path();
5760
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5761
    write(root, "a.txt", b"crlf\r\n");
5762
    repo.commit("base", &[]).unwrap();
5763
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5764
    fs::File::options()
5765
        .write(true)
5766
        .open(root.join("a.txt"))
5767
        .unwrap()
5768
        .set_modified(old)
5769
        .unwrap();
5770
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5771
    assert!(repo
5772
        .snapshot_status("status")
5773
        .unwrap()
5774
        .base_snapshot
5775
        .unrendered
5776
        .contains("a.txt"));
5777
    // With eol=lf, a.txt as stored no longer equals the base.
5778
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5779
    let snap = repo.snapshot_status("status").unwrap();
5780
    assert_eq!(
5781
        statuses(&snap),
5782
        vec![
5783
            (".oxyattributes".to_string(), ChangeStatus::Added),
5784
            ("a.txt".to_string(), ChangeStatus::Modified)
5785
        ]
5786
    );
5787
}
54cd08a1 Andy McCall ↶ 5788
5789
/// Bookmarks with `/` in their names: pushing records their
5790
/// attestations, and checkpoints are kept for them, beside `feature`
5791
/// itself.
5792
#[test]
5793
fn bookmarks_with_slashes_push_and_checkpoint() {
5794
    hermetic();
5795
    let dir = tempfile::tempdir().unwrap();
5796
    let root = dir.path();
5797
    let origin = Repo::init(&root.join("origin")).unwrap();
5798
    let url = root.join("origin").to_string_lossy().to_string();
5799
    let mut repo = Repo::clone(&url, &root.join("r"))
5800
        .unwrap()
5801
        .with_home(root.join("home"));
5802
    // With an identity, pushes carry reference attestations: the case
5803
    // that failed, since the attestation is a file named after the bookmark.
5804
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5805
        .unwrap();
5806
    let r = root.join("r");
5807
    write(&r, "a.txt", b"a\n");
5808
    let h_a = repo.commit("a", &[]).unwrap();
5809
    assert!(repo.push("origin", false).unwrap()[0].ok);
5810
    repo.bookmark_create("feature", None).unwrap();
5811
    repo.bookmark_create("feature/x", None).unwrap();
5812
    repo.bookmark_switch("feature/x", false).unwrap();
5813
    write(&r, "b.txt", b"b\n");
5814
    let h_b = repo.commit("b", &[]).unwrap();
5815
    for name in ["feature", "feature/x"] {
5816
        let res = repo.push_bookmark("origin", name, false).unwrap();
5817
        assert!(res[0].ok, "{name}: {res:?}");
5818
    }
5819
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5820
    assert_eq!(
5821
        origin.resolve_heads("feature/x").unwrap(),
5822
        repo.resolve_heads("feature/x").unwrap()
5823
    );
5824
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5825
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5826
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5827
5828
    // A checkpoint of feature/x is found again when loading its state.
5829
    let (cp, _, _) = repo.checkpoint().unwrap();
5830
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5831
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5832
    let heads = repo.resolve_heads("feature/x").unwrap();
5833
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
f8c69576 Andy McCall ↶ 5834
}
5835
5836
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5837
/// never the remote's own bookmark, and a bookmark created again later is
5838
/// accepted although the deletion's attestation stays the latest.
5839
#[test]
5840
fn bookmarks_are_deleted_on_a_remote() {
5841
    hermetic();
5842
    let dir = tempfile::tempdir().unwrap();
5843
    let root = dir.path();
5844
    let origin = Repo::init(&root.join("origin")).unwrap();
5845
    let url = root.join("origin").to_string_lossy().to_string();
5846
    let mut repo = Repo::clone(&url, &root.join("r"))
5847
        .unwrap()
5848
        .with_home(root.join("home"));
5849
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5850
        .unwrap();
5851
    let r = root.join("r");
5852
    write(&r, "a.txt", b"a\n");
5853
    repo.commit("a", &[]).unwrap();
5854
    assert!(repo.push("origin", false).unwrap()[0].ok);
5855
    repo.bookmark_create("feature/x", None).unwrap();
5856
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5857
    assert!(origin.resolve_heads("feature/x").is_ok());
5858
5859
    let res = repo.push_delete("origin", "feature/x").unwrap();
5860
    assert!(res[0].ok, "{res:?}");
5861
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5862
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5863
    assert!(
5864
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5865
        "the deletion is attested"
5866
    );
5867
    assert!(
5868
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5869
        "the local bookmark stays"
5870
    );
5871
    assert!(!repo
5872
        .view()
5873
        .unwrap()
5874
        .remotes
5875
        .get("origin")
5876
        .is_some_and(|m| m.contains_key("feature/x")));
5877
5878
    // Pushing it again creates it again, past the deletion's serial.
5879
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5880
    assert!(res[0].ok, "{res:?}");
5881
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5882
5883
    // Nothing to delete, and never the remote's own bookmark.
5884
    assert!(repo.push_delete("origin", "nope").is_err());
5885
    let res = repo.push_delete("origin", "main").unwrap();
5886
    assert!(
5887
        !res[0].ok && res[0].reason.contains("default bookmark"),
5888
        "{res:?}"
5889
    );
5890
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
54cd08a1 Andy McCall ↶ 5891
}
61e3bce7 Andy McCall ↶ 5892
5893
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5894
/// when the target has the same versions of the files it touches, and is
5895
/// refused, untouched, when it has others.
5896
#[test]
5897
fn switching_bookmarks_carries_uncommitted_work() {
5898
    hermetic();
5899
    let dir = tempfile::tempdir().unwrap();
5900
    let root = dir.path();
5901
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5902
    write(root, "a.txt", b"a\n");
5903
    write(root, "b.txt", b"b\n");
5904
    write(root, "gone.txt", b"gone\n");
5905
    repo.commit("base", &[]).unwrap();
5906
    repo.bookmark_create("feature", None).unwrap();
5907
    // Started on main, belongs on feature: edit, add, remove.
5908
    write(root, "a.txt", b"a\nmore\n");
5909
    write(root, "new.txt", b"new\n");
5910
    fs::remove_file(root.join("gone.txt")).unwrap();
5911
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5912
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5913
    assert_eq!(repo.config.bookmark, "feature");
5914
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5915
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5916
    assert!(!root.join("gone.txt").exists());
5917
    let snap = repo.snapshot("status").unwrap();
5918
    assert_eq!(
5919
        statuses(&snap),
5920
        vec![
5921
            ("a.txt".to_string(), ChangeStatus::Modified),
5922
            ("gone.txt".to_string(), ChangeStatus::Removed),
5923
            ("new.txt".to_string(), ChangeStatus::Added)
5924
        ]
5925
    );
5926
    repo.commit("the work", &[]).unwrap();
5927
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5928
5929
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5930
    repo.bookmark_switch("main", false).unwrap();
5931
    write(root, "b.txt", b"b on main\n");
5932
    repo.commit("b on main", &[]).unwrap();
5933
    repo.bookmark_switch("feature", false).unwrap();
5934
    write(root, "b.txt", b"b edited\n");
5935
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5936
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5937
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5938
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5939
}
1c2bd9ab Andy McCall ↶ 5940
5941
/// Merging and checking out (feedback 3): a working copy without changes
5942
/// follows a merge whichever state it sat on; a refused checkout names
5943
/// what is in the way; `checkout --carry` takes the work along.
5944
#[test]
5945
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5946
    hermetic();
5947
    let dir = tempfile::tempdir().unwrap();
5948
    let root = dir.path();
5949
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5950
    write(root, "a.txt", b"a\n");
5951
    let h1 = repo.commit("a", &[]).unwrap();
5952
    write(root, "b.txt", b"b\n");
5953
    repo.commit("b", &[]).unwrap();
5954
    repo.bookmark_create("feature", None).unwrap();
5955
    repo.bookmark_switch("feature", false).unwrap();
5956
    write(root, "c.txt", b"c\n");
5957
    repo.commit("c on feature", &[]).unwrap();
5958
    repo.bookmark_switch("main", false).unwrap();
5959
    // The working copy sits on an older state than main's heads.
5960
    repo.checkout(&[h1], false, "checkout").unwrap();
5961
    assert!(!root.join("b.txt").exists());
5962
    let m = repo.merge("feature").unwrap();
5963
    assert!(m.checked_out, "a clean working copy follows the merge");
5964
    for f in ["a.txt", "b.txt", "c.txt"] {
5965
        assert!(root.join(f).exists(), "{f}");
5966
    }
5967
5968
    // A refusal says which paths are in the way and what to do.
5969
    fs::remove_file(root.join("b.txt")).unwrap();
5970
    write(root, "a.txt", b"a edited\n");
5971
    let err = repo
5972
        .checkout(&[h1], false, "checkout")
5973
        .unwrap_err()
5974
        .to_string();
5975
    assert!(
5976
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5977
        "{err}"
5978
    );
5979
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5980
    // is carried as absent (h1 has none either, so that is refused).
5981
    let err = repo
5982
        .checkout_carry(&[h1], "the first change", "checkout")
5983
        .unwrap_err()
5984
        .to_string();
5985
    assert!(
5986
        err.contains("b.txt") && err.contains("the first change"),
5987
        "{err}"
5988
    );
5989
    write(root, "b.txt", b"b\n");
5990
    let (_, carried) = repo
5991
        .checkout_carry(&[h1], "the first change", "checkout")
5992
        .unwrap();
5993
    assert_eq!(carried, vec!["a.txt"]);
5994
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5995
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5996
}
e7ac6c2e Andy McCall ↶ 5997
5998
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5999
/// user identity not stored in a new repository yet is fine while its
6000
/// secret key is there; an added subrepo is listed as not committed yet.
6001
#[test]
6002
fn a_new_repository_is_healthy_before_its_first_commit() {
6003
    hermetic();
6004
    let dir = tempfile::tempdir().unwrap();
6005
    let root = dir.path();
6006
    let home = root.join("home");
6007
    let mut first = Repo::init(&root.join("first"))
6008
        .unwrap()
6009
        .with_home(home.clone());
6010
    let (key, _) = first
6011
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6012
        .unwrap();
6013
    let repo = Repo::init(&root.join("second"))
6014
        .unwrap()
6015
        .with_home(home.clone());
6016
    // Only the secret key: no identity object anywhere this repository sees.
6017
    let keys = repo.keys_dir.clone();
6018
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
6019
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
6020
    let r = repo.doctor(true);
6021
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
6022
    assert_eq!(id.health, Health::Ok, "{}", id.message);
6023
    assert!(id.message.contains("first signed change"), "{}", id.message);
6024
6025
    // A subrepo added and not committed yet is listed, pinned where it is.
6026
    let lib = root.join("lib");
6027
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
6028
    write(&lib, "x.txt", b"x\n");
6029
    l.commit("x", &[]).unwrap();
6030
    let second = root.join("second");
6031
    write(&second, "a.txt", b"a\n");
6032
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
6033
        .unwrap();
6034
    let subs = repo.subrepos().unwrap();
6035
    assert_eq!(subs.len(), 1);
6036
    assert_eq!(
6037
        (subs[0].path.as_str(), subs[0].committed),
6038
        ("deps/lib", false)
6039
    );
6040
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
6041
    repo.commit("add lib", &[]).unwrap();
6042
    let subs = repo.subrepos().unwrap();
6043
    assert!(subs[0].committed, "committed now");
6044
}
8ab265dc Andy McCall ↶ 6045
6046
/// Commit, diff, hunks and discard use the partial snapshot: a file
6047
/// unchanged since the manifest is neither read nor rendered, and showing
6048
/// a change renders only what it edits, the same as from a full base.
6049
#[cfg(unix)]
6050
#[test]
6051
fn commits_and_diffs_leave_unchanged_files_alone() {
6052
    use std::os::unix::fs::PermissionsExt;
6053
    hermetic();
6054
    let dir = tempfile::tempdir().unwrap();
6055
    let root = dir.path();
6056
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6057
    write(root, "big.txt", b"lots\nof\nlines\n");
6058
    write(root, "a.txt", b"one\ntwo\n");
6059
    repo.commit("base", &[]).unwrap();
6060
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6061
    for f in ["big.txt", "a.txt"] {
6062
        fs::File::options()
6063
            .write(true)
6064
            .open(root.join(f))
6065
            .unwrap()
6066
            .set_modified(old)
6067
            .unwrap();
6068
    }
6069
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6070
    // big.txt cannot be read at all from here on.
6071
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6072
6073
    write(root, "a.txt", b"one\nTWO\nthree\n");
6074
    let diff = repo.diff_files(None).unwrap();
6075
    assert_eq!(
6076
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
6077
        ["a.txt"]
6078
    );
6079
    let (_, hunks) = repo.hunks().unwrap();
6080
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
6081
    let h = repo.commit("edit a", &[]).unwrap();
6082
6083
    // Showing the change needs only a.txt's graph, and renders as a full base does.
6084
    let c = repo.store().get_change(&h).unwrap();
6085
    let full = repo.load_state(&c.deps).unwrap();
6086
    let want = render_change(&c, &full, &full.materialize());
6087
    assert_eq!(repo.describe_change(&h).unwrap(), want);
6088
    let (base, snap) = repo.change_base(&c).unwrap();
6089
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
6090
6091
    // Discarding works the same way.
6092
    write(root, "a.txt", b"scratch\n");
6093
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
6094
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
6095
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6096
}
f7510b63 Andy McCall ↶ 6097
6098
/// A replace conflict (spec §9.3) is settled by a change that writes one
6099
/// candidate, or new bytes, at the path when the caller names it; a plain
6100
/// snapshot of a checkout never settles it on its own.
6101
#[test]
6102
fn replace_conflicts_are_settled_when_asked() {
6103
    hermetic();
6104
    let dir = tempfile::tempdir().unwrap();
6105
    let root = dir.path();
6106
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6107
    let blob = |n: u8| {
6108
        let mut v = vec![0u8; 64];
6109
        v[1] = n;
6110
        v
6111
    };
6112
    write(root, "img.bin", &blob(1));
6113
    repo.commit("add img", &[]).unwrap();
6114
    repo.bookmark_create("other", None).unwrap();
6115
    write(root, "img.bin", &blob(2));
6116
    repo.commit("img two", &[]).unwrap();
6117
    repo.bookmark_switch("other", false).unwrap();
6118
    write(root, "img.bin", &blob(3));
6119
    repo.commit("img three", &[]).unwrap();
6120
    repo.bookmark_switch("main", false).unwrap();
6121
    repo.merge("other").unwrap();
6122
    let heads = repo.bookmark_heads().unwrap();
6123
    let merged = repo.load_state(&heads).unwrap().materialize();
6124
    assert!(
6125
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
6126
        "a replace conflict"
6127
    );
6128
    // A snapshot of the checkout records nothing.
6129
    assert!(repo
6130
        .snapshot("status")
6131
        .unwrap()
6132
        .statuses
6133
        .iter()
6134
        .all(|s| s.path != "img.bin"));
6135
6136
    // Keeping candidate 3 settles it.
6137
    let author = repo.author();
6138
    let edits = [FileEdit {
6139
        path: "img.bin".into(),
6140
        content: Some(blob(3)),
6141
    }];
6142
    let c = repo
6143
        .build_change(&heads, &edits, "keep three", author)
6144
        .unwrap();
6145
    assert_eq!(c.kind, ChangeKind::Resolution);
6146
    let mut st = repo.load_state(&heads).unwrap();
6147
    for d in &c.deps {
6148
        assert!(st.contains(d));
6149
    }
6150
    assert!(
6151
        heads.iter().all(|h| c.deps.contains(h)),
6152
        "depends on both contributors"
6153
    );
6154
    st.add(c).unwrap();
6155
    let after = st.materialize();
6156
    assert!(!after.is_conflicted());
6157
    assert_eq!(
6158
        after.files["img.bin"].content,
6159
        FileContent::Opaque {
6160
            blobs: vec![Repo::blob_ref(&blob(3))]
6161
        }
6162
    );
6163
6164
    // New bytes settle it too.
6165
    let edits = [FileEdit {
6166
        path: "img.bin".into(),
6167
        content: Some(blob(9)),
6168
    }];
6169
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
6170
    let mut st = repo.load_state(&heads).unwrap();
6171
    st.add(c).unwrap();
6172
    assert_eq!(
6173
        st.materialize().files["img.bin"].content,
6174
        FileContent::Opaque {
6175
            blobs: vec![Repo::blob_ref(&blob(9))]
6176
        }
6177
    );
6178
}
83d61e80 Andy McCall ↶ 6179
6180
/// The history of a range of lines (spec §27): the changes that wrote
6181
/// or deleted its atoms, or deleted atoms from between them; edits outside
6182
/// the range and changes the range's lines survived are not in it.
6183
#[test]
6184
fn line_ranges_have_exact_histories() {
6185
    hermetic();
6186
    let dir = tempfile::tempdir().unwrap();
6187
    let root = dir.path();
6188
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6189
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
6190
    let base = repo.commit("add f", &[]).unwrap();
6191
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
6192
    let outside = repo.commit("change the import", &[]).unwrap();
6193
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
6194
    let inside = repo.commit("edit a line of a", &[]).unwrap();
6195
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
6196
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
6197
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
6198
    let after = repo.commit("add b after a", &[]).unwrap();
6199
    let heads = repo.bookmark_heads().unwrap();
6200
6201
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
6202
    let hist: Vec<ChangeHash> = repo
6203
        .line_history(&heads, "f.rs", 2, 4)
6204
        .unwrap()
6205
        .iter()
6206
        .map(|e| e.hash)
6207
        .collect();
6208
    for (h, what) in [
6209
        (base, "wrote it"),
6210
        (inside, "edited a line"),
6211
        (deleted, "deleted a line from inside"),
6212
    ] {
6213
        assert!(hist.contains(&h), "{what}");
6214
    }
6215
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
6216
        assert!(!hist.contains(&h), "{what}");
6217
    }
6218
    assert_eq!(hist[0], deleted, "newest first");
6219
    // One line: only what touched it.
6220
    let one: Vec<ChangeHash> = repo
6221
        .line_history(&heads, "f.rs", 1, 1)
6222
        .unwrap()
6223
        .iter()
6224
        .map(|e| e.hash)
6225
        .collect();
6226
    assert!(one.contains(&outside) && !one.contains(&inside));
6227
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
6228
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
6229
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
6230
}
fc1a466a Andy McCall ↶ 6231
6232
#[test]
6233
fn receipts_are_kept_with_their_state_and_verified() {
6234
    use crate::receipt::{Receipt, SignedReceipt};
6235
    hermetic();
6236
    let dir = tempfile::tempdir().unwrap();
6237
    let root = dir.path();
6238
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6239
    write(root, "a.txt", b"1\n");
6240
    repo.commit("A", &[]).unwrap();
6241
    let heads = repo.bookmark_heads().unwrap();
6242
    let state = repo
6243
        .store()
6244
        .put_state(&StateObject::new(heads.clone()))
6245
        .unwrap();
6246
    let out = repo.store_blob(b"built\n").unwrap();
6247
    let receipt = Receipt {
6248
        job_name: "build".into(),
6249
        pipeline_hash: ObjectRef([1; 32]),
6250
        scope_tree_hash: ObjectRef([2; 32]),
6251
        inputs: vec![],
6252
        environment: ObjectRef([3; 32]),
6253
        outputs: vec![out],
6254
        exit_code: 0,
6255
        duration_ms: 42,
6256
    };
6257
    let sk = SecretKey::generate();
6258
    let runner = sk.identity("earth-1", "runner@earth", 1);
6259
    let sr = SignedReceipt::sign(
6260
        receipt.clone(),
6261
        repo.id().unwrap(),
6262
        state,
6263
        "demo#1",
6264
        &runner,
6265
        &sk,
6266
    );
6267
6268
    let r = repo.add_receipt(&sr).unwrap();
6269
    let found = repo.receipts(&heads).unwrap();
6270
    assert_eq!(found.len(), 1);
6271
    assert_eq!(found[0].attest, r);
6272
    assert_eq!(found[0].signed, sr);
6273
    assert!(found[0].problem.is_none() && !found[0].revoked);
6274
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
6275
6276
    // Another repository's receipt, or a forged one, is refused.
6277
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
6278
    assert!(repo
6279
        .add_receipt(&elsewhere)
6280
        .unwrap_err()
6281
        .to_string()
6282
        .contains("another repository"));
6283
    let mut forged = sr.clone();
6284
    forged.receipt.exit_code = 1;
6285
    assert!(repo
6286
        .add_receipt(&forged)
6287
        .unwrap_err()
6288
        .to_string()
6289
        .contains("does not verify"));
6290
c63fed2e Andy McCall ↶ 6291
    // A receipt signed by a short-lived key keeps its certificate and the
6292
    // issuer's identity, and reads back with them (oxygenhub#241).
6293
    let hub_sk = SecretKey::generate();
6294
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
6295
    let job_sk = SecretKey::generate();
6296
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
6297
    let mut test_receipt = receipt.clone();
6298
    test_receipt.job_name = "test".into();
6299
    let plain = SignedReceipt::sign(
6300
        test_receipt,
6301
        repo.id().unwrap(),
6302
        state,
6303
        "demo#2",
6304
        &job,
6305
        &job_sk,
6306
    );
6307
    let now = plain.attest.hlc.wall_ms;
6308
    let cert = crate::cert::SignedCertificate::sign(
6309
        crate::cert::Certificate {
6310
            key: job.clone(),
6311
            issuer: hub.hash(),
6312
            subject: "repo:andy/demo:bookmark:main".into(),
6313
            claims: vec![],
6314
            scope: crate::identity::Scope::SEAL,
6315
            not_before: now - 1_000,
6316
            expires: now + 600_000,
a2387d54 Andy McCall ↶ 6317
            grant: None,
c63fed2e Andy McCall ↶ 6318
        },
6319
        &hub,
6320
        &hub_sk,
6321
    );
6322
    let certified = plain.with_certificate(cert, hub.clone());
6323
    repo.add_receipt(&certified).unwrap();
6324
    let found = repo.receipts(&heads).unwrap();
6325
    let got = found
6326
        .iter()
6327
        .find(|i| i.signed.receipt.job_name == "test")
6328
        .unwrap();
6329
    assert_eq!(got.signed, certified);
6330
    assert!(got.problem.is_none(), "{:?}", got.problem);
6331
6332
    // gc keeps the receipts, their runners, the certificate and its issuer,
6333
    // and the output while the state lives.
fc1a466a Andy McCall ↶ 6334
    repo.gc(true).unwrap();
c63fed2e Andy McCall ↶ 6335
    let found = repo.receipts(&heads).unwrap();
6336
    assert_eq!(found.len(), 2);
6337
    let got = found
6338
        .iter()
6339
        .find(|i| i.signed.receipt.job_name == "test")
6340
        .unwrap();
6341
    assert_eq!(got.signed, certified, "the certificate survives gc");
6342
    assert!(got.problem.is_none());
fc1a466a Andy McCall ↶ 6343
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
6344
    assert!(repo.fsck().unwrap().problems.is_empty());
dfb23a3a Andy McCall ↶ 6345
}
6346
6347
#[test]
6348
fn status_leaves_an_unchanged_manifest_alone() {
6349
    hermetic();
6350
    let dir = tempfile::tempdir().unwrap();
6351
    let root = dir.path();
6352
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6353
    write(root, "a.txt", b"1\n");
6354
    write(root, "b.txt", b"2\n");
6355
    repo.commit("A", &[]).unwrap();
6356
    // Files last touched well outside the racy window.
6357
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6358
    for f in ["a.txt", "b.txt"] {
6359
        fs::File::options()
6360
            .write(true)
6361
            .open(root.join(f))
6362
            .unwrap()
6363
            .set_modified(old)
6364
            .unwrap();
6365
    }
6366
    repo.snapshot_status("status").unwrap();
6367
    let path = repo.manifest_path();
6368
    let first = fs::read(&path).unwrap();
6369
    repo.snapshot_status("status").unwrap();
6370
    assert_eq!(
6371
        fs::read(&path).unwrap(),
6372
        first,
6373
        "an unchanged tree does not rewrite the manifest"
6374
    );
6375
    // A change rewrites it.
6376
    write(root, "a.txt", b"1\n2\n");
6377
    repo.snapshot_status("status").unwrap();
6378
    assert_ne!(fs::read(&path).unwrap(), first);
fc1a466a Andy McCall ↶ 6379
}
6f8aeb99 Andy McCall ↶ 6380
6381
#[test]
6382
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6383
    hermetic();
6384
    let dir = tempfile::tempdir().unwrap();
6385
    let root = dir.path();
6386
    let origin_path = root.join("origin");
6387
    Repo::init(&origin_path).unwrap();
6388
    let origin_url = origin_path.to_string_lossy().to_string();
6389
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6390
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6391
    write(&root.join("a"), "big.txt", big.as_bytes());
6392
    write(&root.join("a"), "small.txt", b"small\n");
6393
    let h1 = a.commit("large", &[]).unwrap();
6394
    let (_, body) = a.store().get(&h1).unwrap();
6395
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6396
    assert!(a.push("origin", false).unwrap()[0].ok);
6397
6398
    // A clone reads the text from the blobs that came with the change.
6399
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6400
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6401
    // An edit in the middle of the stored insert is an ordinary change.
6402
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6403
    write(&root.join("b"), "big.txt", edited.as_bytes());
6404
    let h2 = b.commit("edit", &[]).unwrap();
6405
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6406
    assert!(b.push("origin", false).unwrap()[0].ok);
6407
    assert!(a.pull("origin").unwrap().checked_out);
6408
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6409
    assert_eq!(
6410
        a.fsck().unwrap().errors(),
6411
        0,
6412
        "{:?}",
6413
        a.fsck().unwrap().problems
6414
    );
6415
6416
    // With zero retention gc keeps the text blobs of every kept change.
6417
    let mut a = Repo::open(&root.join("a")).unwrap();
6418
    a.config.set("core.op-retention", "0").unwrap();
6419
    a.save_config().unwrap();
6420
    let a = Repo::open(&root.join("a")).unwrap();
6421
    a.gc(true).unwrap();
6422
    let a = Repo::open(&root.join("a")).unwrap();
6423
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6424
    assert_eq!(
6425
        a.fsck().unwrap().errors(),
6426
        0,
6427
        "{:?}",
6428
        a.fsck().unwrap().problems
6429
    );
6430
    // And a clone of the packed repository reads them from its packs.
6431
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6432
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6433
    drop(c);
6caacfff Andy McCall ↶ 6434
}
6435
6436
#[test]
6437
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6438
    hermetic();
6439
    let dir = tempfile::tempdir().unwrap();
6440
    let root = dir.path();
6441
    let repo = Repo::init(root).unwrap();
6442
    write(root, "a.txt", b"a\n");
6443
    let a = repo.commit("a", &[]).unwrap();
6444
    write(root, "b.txt", b"b\n");
6445
    repo.commit("b", &[]).unwrap();
6446
    let (x, op) = repo.head_op().unwrap();
6447
    let ws = *op.view.workspaces.keys().next().unwrap();
6448
    let mut one = op.view.clone();
6449
    one.workspaces.insert(ws, a);
6450
    let mut two = op.view.clone();
6451
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6452
    let first = repo.record_op(&[x], "one", one).unwrap();
6453
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6454
    assert!(
6455
        e.to_string()
6456
            .contains("changed this working copy at the same time"),
6457
        "{e}"
6458
    );
6459
    assert_eq!(
6460
        repo.head_op().unwrap().0,
6461
        first,
6462
        "the second is not recorded"
6463
    );
6464
}
6465
6466
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6467
/// rewrote the working copy recorded the half-written files as edits, and
6468
/// its view replaced the switch's.
6469
#[test]
6470
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6471
    hermetic();
6472
    let dir = tempfile::tempdir().unwrap();
6473
    let root = dir.path().to_path_buf();
6474
    let mut repo = Repo::init(&root).unwrap();
6475
    write(&root, "keep.txt", b"keep\n");
6476
    repo.commit("base", &[]).unwrap();
6477
    repo.bookmark_create("small", None).unwrap();
6478
    for i in 0..300 {
6479
        write(
6480
            &root,
6481
            &format!("many/f{i}.txt"),
6482
            format!("file {i}\n").as_bytes(),
6483
        );
6484
    }
6485
    repo.commit("many", &[]).unwrap();
6486
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6487
    let watcher = {
6488
        let (root, stop) = (root.clone(), stop.clone());
6489
        std::thread::spawn(move || {
6490
            let r = Repo::open(&root).unwrap();
6491
            let mut ran = 0;
6492
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6493
                if r.snapshot_status("oxy status").is_ok() {
6494
                    ran += 1;
6495
                }
6496
            }
6497
            ran
6498
        })
6499
    };
6500
    for i in 0..20 {
6501
        let to = if i % 2 == 0 { "small" } else { "main" };
6502
        repo.bookmark_switch(to, false).unwrap();
6503
    }
6504
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6505
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6506
    // Back on main, clean, with every file where main has it.
6507
    let repo = Repo::open(&root).unwrap();
6508
    let s = repo.snapshot_status("oxy status").unwrap();
6509
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6510
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6511
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6512
    assert!(root.join("many/f299.txt").exists());
1a3b6203 Andy McCall ↶ 6513
}
6514
6515
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6516
/// put a subrepo that was ahead of its pin back at the pin and moved the
6517
/// subrepo's own bookmark backwards.
6518
#[test]
6519
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6520
    hermetic();
6521
    let dir = tempfile::tempdir().unwrap();
6522
    let root = dir.path();
6523
    Repo::init(&root.join("lib-origin")).unwrap();
6524
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6525
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6526
    write(&root.join("lib"), "lib.txt", b"v1\n");
6527
    lib.commit("lib v1", &[]).unwrap();
6528
    assert!(lib.push("origin", false).unwrap()[0].ok);
6529
6530
    let app_dir = root.join("app");
6531
    let mut app = Repo::init(&app_dir).unwrap();
6532
    write(&app_dir, "main.txt", b"app\n");
6533
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6534
    app.commit("app with lib", &[]).unwrap();
6535
    app.bookmark_create("feature", None).unwrap();
6536
6537
    // New work in the subrepo, not yet pinned by the parent.
6538
    let nested_dir = app_dir.join("libs/lib");
6539
    let nested = Repo::open(&nested_dir).unwrap();
6540
    write(&nested_dir, "new.txt", b"new\n");
6541
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6542
    drop(nested);
6543
6544
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6545
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6546
    let nested = Repo::open(&nested_dir).unwrap();
6547
    assert!(
6548
        nested.bookmark_heads().unwrap().contains(&l2),
6549
        "its bookmark kept its work"
6550
    );
6551
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6552
    let s = app.snapshot("status").unwrap();
6553
    assert_eq!(
6554
        statuses(&s),
6555
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6556
    );
6f8aeb99 Andy McCall ↶ 6557
}
7d9dab13 Andy McCall ↶ 6558
6559
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6560
/// moving `main` to a change this clone had pushed on another bookmark,
6561
/// the first `pull` said "Already up to date" while `main` was behind.
6562
#[test]
6563
fn pull_takes_a_remote_move_to_changes_already_here() {
6564
    hermetic();
6565
    let dir = tempfile::tempdir().unwrap();
6566
    let root = dir.path();
6567
    let origin_path = root.join("origin");
6568
    let origin = Repo::init(&origin_path).unwrap();
6569
    let url = origin_path.to_string_lossy().to_string();
6570
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6571
    write(&root.join("b"), "base.txt", b"base\n");
6572
    b.commit("base", &[]).unwrap();
6573
    assert!(b.push("origin", false).unwrap()[0].ok);
6574
6575
    // A feature bookmark with one change, pushed.
6576
    b.bookmark_create("feat", None).unwrap();
6577
    b.bookmark_switch("feat", false).unwrap();
6578
    write(&root.join("b"), "x.txt", b"x\n");
6579
    let x = b.commit("x", &[]).unwrap();
6580
    assert!(b.push("origin", false).unwrap()[0].ok);
6581
    b.bookmark_switch("main", false).unwrap();
6582
6583
    // The remote lands it: its main moves to the feature's state.
6584
    let feat = origin
6585
        .store()
6586
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6587
        .unwrap()
6588
        .heads;
6589
    origin.bookmark_set("main", &feat).unwrap();
6590
6591
    let r = b.pull("origin").unwrap();
6592
    assert!(r.changed, "{r:?}");
6593
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6594
    let main = b
6595
        .bookmarks()
6596
        .unwrap()
6597
        .into_iter()
6598
        .find(|m| m.name == "main")
6599
        .unwrap();
6600
    assert_eq!(main.behind, Some(0), "{main:?}");
6601
}
86e1824f Andy McCall ↶ 6602
14edbaaf Andy McCall ↶ 6603
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6604
/// to one only the remote has makes a local bookmark from it; a pull moves
6605
/// every local bookmark the remote has too; a clone checks out the remote's
6606
/// default bookmark.
6607
#[test]
6608
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6609
    hermetic();
6610
    let dir = tempfile::tempdir().unwrap();
6611
    let root = dir.path();
6612
    let origin_path = root.join("origin");
6613
    let mut origin = Repo::init(&origin_path).unwrap();
6614
    let url = origin_path.to_string_lossy().to_string();
6615
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6616
    write(&root.join("a"), "base.txt", b"base\n");
6617
    a.commit("base", &[]).unwrap();
6618
    assert!(a.push("origin", false).unwrap()[0].ok);
6619
    a.bookmark_create("develop", None).unwrap();
6620
    a.bookmark_switch("develop", false).unwrap();
6621
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6622
    let d1 = a.commit("d1", &[]).unwrap();
6623
    assert!(a.push("origin", false).unwrap()[0].ok);
6624
6625
    // A clone has main only; origin/develop is a name all the same.
6626
    let c_root = root.join("c");
6627
    let mut c = Repo::clone(&url, &c_root).unwrap();
6628
    assert_eq!(c.config.bookmark, "main");
6629
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6630
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6631
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6632
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6633
6634
    // Switching makes the local bookmark from origin's.
6635
    c.bookmark_switch("develop", false).unwrap();
6636
    assert_eq!(c.config.bookmark, "develop");
6637
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6638
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6639
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6640
    assert!(c.bookmark_switch("nowhere", false).is_err());
6641
6642
    // Both bookmarks move on the remote; one pull takes both.
6643
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6644
    let d2 = a.commit("d2", &[]).unwrap();
6645
    assert!(a.push("origin", false).unwrap()[0].ok);
6646
    a.bookmark_switch("main", false).unwrap();
6647
    write(&root.join("a"), "m.txt", b"m\n");
6648
    let m = a.commit("m", &[]).unwrap();
6649
    assert!(a.push("origin", false).unwrap()[0].ok);
6650
    let r = c.pull("origin").unwrap();
6651
    assert!(r.changed && r.checked_out, "{r:?}");
6652
    assert_eq!(r.heads, vec![d2]);
6653
    assert_eq!(r.others, vec!["main".to_string()]);
6654
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6655
    assert_eq!(
6656
        fs::read(c_root.join("base.txt")).unwrap(),
6657
        b"base\nd1\nd2\n"
6658
    );
6659
    let again = c.pull("origin").unwrap();
6660
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6661
6662
    // A clone checks out the remote's default bookmark.
6663
    origin.config.set("workspace.bookmark", "develop").unwrap();
6664
    origin.save_config().unwrap();
6665
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6666
    assert_eq!(e.config.bookmark, "develop");
6667
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6668
    let reopened = Repo::open(&root.join("e")).unwrap();
6669
    assert_eq!(reopened.config.bookmark, "develop");
6670
    // REMOTE/NAME names the remote's bookmark to switch to.
6671
    let mut e = reopened;
6672
    e.bookmark_switch("origin/main", false).unwrap();
6673
    assert_eq!(e.config.bookmark, "main");
6674
    assert!(e.bookmark_heads().unwrap().contains(&m));
6675
}
6676
98a1620a Andy McCall ↶ 6677
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6678
/// op restore goes back to an operation, files included, and undo takes
6679
/// the restore back whole; op revert undoes one operation alone; each
6680
/// operation's changes are described from the views.
6681
#[test]
6682
fn operations_can_be_read_restored_and_reverted() {
6683
    hermetic();
6684
    let dir = tempfile::tempdir().unwrap();
6685
    let root = dir.path();
6686
    let repo = Repo::init(root).unwrap();
6687
    write(root, "a.txt", b"a\n");
6688
    let first = repo.commit("first", &[]).unwrap();
6689
    write(root, "a.txt", b"a\nb\n");
6690
    let second = repo.commit("second", &[]).unwrap();
6691
    let at_second = repo.head_op().unwrap().0.to_hex();
6692
    repo.bookmark_create("keep", None).unwrap();
6693
    let created = repo.head_op().unwrap().0.to_hex();
6694
    write(root, "n.txt", b"n\n");
6695
    let third = repo.commit("third", &[]).unwrap();
6696
6697
    // What each operation changed.
6698
    let ops = repo.op_log().unwrap();
6699
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6700
    assert!(
6701
        changes
6702
            .iter()
6703
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6704
        "{changes:?}"
6705
    );
6706
    assert!(changes
6707
        .iter()
6708
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6709
6710
    // Reading at an earlier operation.
6711
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6712
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6713
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6714
    write(root, "z.txt", b"z\n");
6715
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6716
    fs::remove_file(root.join("z.txt")).unwrap();
6717
    assert!(repo.resolve_op("zz").is_err());
6718
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
6719
6720
    // Restore goes back, files and all; undo takes it back whole.
6721
    repo.op_restore(&at_second, false).unwrap();
6722
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
6723
    assert!(!root.join("n.txt").exists());
6724
    repo.undo().unwrap();
6725
    let mut heads = repo.bookmark_heads().unwrap();
6726
    heads.sort();
6727
    let mut want = vec![second, third];
6728
    want.sort();
6729
    assert_eq!(heads, want);
6730
    assert!(
6731
        root.join("n.txt").exists(),
6732
        "the files came back with the undo"
6733
    );
6734
6735
    // Revert the bookmark's creation alone: the commit after it stays.
6736
    let r = repo.op_revert(&created).unwrap();
6737
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6738
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6739
    assert!(repo
6740
        .load_state(&repo.bookmark_heads().unwrap())
6741
        .unwrap()
6742
        .contains(&third));
6743
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6744
    let _ = first;
6745
}
6746
36041796 Andy McCall ↶ 6747
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6748
/// from the status cache while every file is as the snapshot left it, and
6749
/// from a snapshot again as soon as one is not.
6750
#[test]
6751
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6752
    hermetic();
6753
    let dir = tempfile::tempdir().unwrap();
6754
    let root = dir.path();
6755
    let repo = Repo::init(root).unwrap();
6756
    write(root, "a.txt", b"a\n");
6757
    write(root, "b.txt", b"b\n");
6758
    repo.commit("base", &[]).unwrap();
6759
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6760
6761
    write(root, "a.txt", b"a\nmore\n");
6762
    assert_eq!(
6763
        repo.status_by_manifest().unwrap(),
6764
        None,
6765
        "no snapshot of the edit yet"
6766
    );
6767
    let snap = repo.snapshot_status("oxy status").unwrap();
6768
    assert_eq!(snap.statuses.len(), 1);
6769
    let cached = repo
6770
        .status_by_manifest()
6771
        .unwrap()
6772
        .expect("answered from the cache");
6773
    assert_eq!(cached.len(), 1);
6774
    assert_eq!(
6775
        (cached[0].path.as_str(), cached[0].status),
6776
        ("a.txt", ChangeStatus::Modified)
6777
    );
6778
6779
    // Any further change sends status back to a snapshot.
6780
    write(root, "a.txt", b"a\nmore\nand more\n");
6781
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6782
    repo.snapshot_status("oxy status").unwrap();
6783
    assert!(repo.status_by_manifest().unwrap().is_some());
6784
    write(root, "new.txt", b"n\n");
6785
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6786
    fs::remove_file(root.join("new.txt")).unwrap();
6787
    assert!(
6788
        repo.status_by_manifest().unwrap().is_some(),
6789
        "back as it was"
6790
    );
6791
    fs::remove_file(root.join("b.txt")).unwrap();
6792
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6793
    write(root, "b.txt", b"b\n");
6794
6795
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6796
    repo.snapshot_status("oxy status").unwrap();
6797
    repo.commit("more", &[]).unwrap();
6798
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6799
}
6800
77445673 Andy McCall ↶ 6801
/// oxygen#41: while the status cache holds, the working copy's diff is
6802
/// rendered from the stored working-copy change, and says exactly what a
6803
/// snapshot's diff says.
6804
#[test]
6805
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6806
    hermetic();
6807
    let dir = tempfile::tempdir().unwrap();
6808
    let root = dir.path();
6809
    let repo = Repo::init(root).unwrap();
6810
    write(root, "a.txt", b"one\ntwo\nthree\n");
6811
    write(root, "gone.txt", b"bye\n");
6812
    repo.commit("base", &[]).unwrap();
6813
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6814
    write(root, "new.txt", b"hello\n");
6815
    fs::remove_file(root.join("gone.txt")).unwrap();
6816
    let snap = repo.snapshot_status("oxy status").unwrap();
6817
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6818
    assert!(
6819
        repo.status_by_manifest().unwrap().is_some(),
6820
        "the cache holds"
6821
    );
6822
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6823
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6824
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6825
}
6826
1ec3f008 Andy McCall ↶ 6827
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6828
/// while none has moved, the check stats the tracked files without listing
6829
/// the tree, and a file added or removed anywhere moves its directory's
6830
/// time, so the tree is listed again.
6831
#[test]
6832
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6833
    hermetic();
6834
    let dir = tempfile::tempdir().unwrap();
6835
    let root = dir.path();
6836
    let repo = Repo::init(root).unwrap();
6837
    write(root, "a.txt", b"a\n");
6838
    write(root, "sub/deep/b.txt", b"b\n");
6839
    repo.commit("base", &[]).unwrap();
6840
    // Out of the racy window: every file and directory a minute old.
6841
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6842
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6843
        fs::File::open(root.join(p))
6844
            .unwrap()
6845
            .set_modified(old)
6846
            .unwrap();
6847
    }
6848
    repo.snapshot_status("oxy status").unwrap();
6849
    repo.write_manifest(false, false).unwrap();
6850
    let m = repo.read_manifest().unwrap().unwrap().2;
6851
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6852
    assert_eq!(
6853
        repo.disk_differs_by_dirs(&m),
6854
        Some(false),
6855
        "no listing needed"
6856
    );
6857
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6858
6859
    // A same-size edit with a new time: found by its stat.
6860
    write(root, "sub/deep/b.txt", b"c\n");
6861
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6862
    write(root, "sub/deep/b.txt", b"b\n");
6863
    fs::File::open(root.join("sub/deep/b.txt"))
6864
        .unwrap()
6865
        .set_modified(old)
6866
        .unwrap();
6867
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6868
6869
    // A new file moves its directory's time: the tree must be listed.
6870
    write(root, "sub/deep/new.txt", b"n\n");
6871
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6872
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6873
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6874
    // A removed one too.
6875
    fs::remove_file(root.join("a.txt")).unwrap();
6876
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6877
}
6878
e226a6cc Andy McCall ↶ 6879
/// oxygen#41: a commit right after a status takes the snapshot the status
6880
/// left (the status cache holds) rather than walking again, and commits
6881
/// exactly what a snapshot would have.
6882
#[test]
6883
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6884
    hermetic();
6885
    let dir = tempfile::tempdir().unwrap();
6886
    let root = dir.path();
6887
    let repo = Repo::init(root).unwrap();
6888
    write(root, "a.txt", b"a\nb\n");
6889
    write(root, ".oxyattributes", b"*.bin binary\n");
6890
    repo.commit("base", &[]).unwrap();
6891
    write(root, "a.txt", b"a\nB\n");
6892
    write(root, "new.txt", b"new\n");
6893
    let snap = repo.snapshot_status("oxy status").unwrap();
6894
    let cached = repo
6895
        .snapshot_from_cache()
6896
        .unwrap()
6897
        .expect("the cache holds");
6898
    assert_eq!(cached.wc_hash, snap.wc_hash);
6899
    assert_eq!(cached.statuses, snap.statuses);
6900
    assert!(
6901
        !cached.attributes.is_empty(),
6902
        "the .oxyattributes file was read"
6903
    );
6904
    let h = repo.commit("edit", &[]).unwrap();
6905
    let c = repo.store().get_change(&h).unwrap();
6906
    assert_eq!(
6907
        c.tree_ops.len() + c.edits.len(),
6908
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6909
    );
6910
    assert_eq!(
6911
        repo.status_by_manifest().unwrap(),
6912
        Some(vec![]),
6913
        "clean after the commit"
6914
    );
6915
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6916
}
6917
0389c3e8 Andy McCall ↶ 6918
/// oxygen#41: a clean check that verified racy entries restamps the
6919
/// manifest, so later checks can trust them, and a same-size rewrite
6920
/// straight afterwards is still found: entries within two seconds of the
6921
/// new time stay racy.
6922
#[test]
6923
fn a_verified_clean_check_restamps_the_manifest_safely() {
6924
    hermetic();
6925
    let dir = tempfile::tempdir().unwrap();
6926
    let root = dir.path();
6927
    let repo = Repo::init(root).unwrap();
6928
    write(root, "a.txt", b"one\n");
6929
    repo.commit("one", &[]).unwrap();
6930
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6931
    assert!(repo.clean_by_manifest().unwrap());
6932
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6933
    assert!(after > before, "restamped");
6934
    write(root, "a.txt", b"two\n");
6935
    assert!(
6936
        !repo.clean_by_manifest().unwrap(),
6937
        "a same-size rewrite is still seen"
6938
    );
6939
}
6940
86e1824f Andy McCall ↶ 6941
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6942
/// stored insert's text blob only when it builds that file's graph, and
6943
/// builds the same graph a full load does.
6944
#[test]
6945
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6946
    hermetic();
6947
    let dir = tempfile::tempdir().unwrap();
6948
    let root = dir.path();
6949
    let repo = Repo::init(root).unwrap();
6950
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6951
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6952
    write(root, "big.txt", big.as_bytes());
6953
    write(root, "other.txt", other.as_bytes());
6954
    let h = repo.commit("two large files", &[]).unwrap();
6955
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6956
    let h2 = repo.commit("append", &[]).unwrap();
6957
6958
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6959
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6960
        FileContent::Text { bytes, .. } => bytes.clone(),
6961
        other => panic!("{other:?}"),
6962
    };
6963
    // Built on demand, every graph renders as the full load's.
6964
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6965
    let big_node = full.files["big.txt"].node;
6966
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6967
    repo.load_all_graphs(&mut hist).unwrap();
6968
    let rendered = hist.materialize();
6969
    for p in ["big.txt", "other.txt"] {
6970
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6971
    }
6972
6973
    // Without other.txt's text blob, history still loads and big.txt still
6974
    // builds: nothing read the other text.
6975
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6976
    assert_eq!(texts.len(), 2);
6977
    let content = |r: &ObjectRef| -> Vec<u8> {
6978
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6979
        blob.chunks
6980
            .iter()
6981
            .flat_map(|c| repo.store().get(c).unwrap().1)
6982
            .collect()
6983
    };
6984
    let other_text = texts
6985
        .iter()
a4fad5b0 Andy McCall ↶ 6986
        .filter_map(|t| match t {
0f93f49c Andy McCall ↶ 6987
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
a4fad5b0 Andy McCall ↶ 6988
            _ => None,
6989
        })
86e1824f Andy McCall ↶ 6990
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6991
        .unwrap();
64818938 Andy McCall ↶ 6992
    repo.store().remove_loose_for_test(&other_text).unwrap();
86e1824f Andy McCall ↶ 6993
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6994
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6995
    assert!(repo
6996
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6997
        .is_err());
6998
}
6999
7000
/// oxygen#35: the first status after a commit read and rendered every
7001
/// file (79 s and more than 14 GB on the Linux tree), because the
7002
/// manifest had no graph keys for files the commit added.
7003
#[test]
7004
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
7005
    use std::os::unix::fs::PermissionsExt;
7006
    hermetic();
7007
    let dir = tempfile::tempdir().unwrap();
7008
    let root = dir.path();
7009
    let repo = Repo::init(root).unwrap();
7010
    let files = ["a.txt", "b.txt", "d/c.txt"];
7011
    for p in files {
7012
        write(root, p, format!("{p}\n").as_bytes());
7013
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7014
        fs::File::options()
7015
            .write(true)
7016
            .open(root.join(p))
7017
            .unwrap()
7018
            .set_modified(old)
7019
            .unwrap();
7020
    }
7021
    repo.commit("added", &[]).unwrap();
7022
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
7023
    assert!(
7024
        m.entries.values().all(|e| e.graph.is_some()),
7025
        "keys recorded at commit"
7026
    );
7027
    // Unreadable files prove the next status reads none of them.
7028
    for p in files {
7029
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
7030
    }
7031
    let snap = repo.snapshot_status("status").unwrap();
7032
    for p in files {
7033
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
7034
    }
7035
    assert!(!snap.changed && snap.statuses.is_empty());
7036
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
7037
}
c5ce0367 Andy McCall ↶ 7038
7039
/// oxygen#35: a checkout reads, renders and writes only the files whose
7040
/// graphs differ, and renders the rest a batch at a time.
7041
#[test]
7042
fn checkout_touches_only_what_differs_and_renders_in_batches() {
7043
    use std::os::unix::fs::PermissionsExt;
7044
    hermetic();
7045
    let dir = tempfile::tempdir().unwrap();
7046
    let root = dir.path();
7047
    let origin = root.join("origin");
7048
    let mut repo = Repo::init(&origin).unwrap();
7049
    // More files than one batch holds.
7050
    let n = 2100;
7051
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7052
    for i in 0..n {
7053
        let p = format!("f/{i:04}.txt");
7054
        write(&origin, &p, format!("file {i}\n").as_bytes());
7055
        fs::File::options()
7056
            .write(true)
7057
            .open(origin.join(&p))
7058
            .unwrap()
7059
            .set_modified(old)
7060
            .unwrap();
7061
    }
7062
    repo.commit("many", &[]).unwrap();
7063
    repo.bookmark_create("feature", None).unwrap();
7064
    repo.bookmark_switch("feature", false).unwrap();
7065
    write(&origin, "f/0007.txt", b"changed\n");
7066
    repo.commit("one change", &[]).unwrap();
7067
7068
    // Switching back to main must not read the unchanged files.
7069
    for i in 0..n {
7070
        if i != 7 {
7071
            let p = origin.join(format!("f/{i:04}.txt"));
7072
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
7073
        }
7074
    }
7075
    let r = repo.bookmark_switch("main", false).unwrap();
7076
    for i in 0..n {
7077
        let p = origin.join(format!("f/{i:04}.txt"));
7078
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
7079
    }
7080
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
7081
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
7082
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7083
7084
    // A clone renders every file, across batches.
7085
    let c = root.join("clone");
7086
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
7087
    for i in [0, 2047, 2048, n - 1] {
7088
        assert_eq!(
7089
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
7090
            format!("file {i}\n").as_bytes()
7091
        );
7092
    }
7093
    let cloned = Repo::open(&c).unwrap();
7094
    assert!(cloned
7095
        .snapshot_status("status")
7096
        .unwrap()
7097
        .statuses
7098
        .is_empty());
d3cd7ef9 Andy McCall ↶ 7099
}
7100
7101
/// A file written just before the manifest (inside the racy window) is
7102
/// checked by its hash: trusted when equal, caught when edited in place
7103
/// with the same size and time.
7104
#[test]
7105
fn a_racy_manifest_entry_is_checked_by_hash() {
7106
    hermetic();
7107
    let dir = tempfile::tempdir().unwrap();
7108
    let root = dir.path();
7109
    let repo = Repo::init(root).unwrap();
7110
    write(root, "a.txt", b"one\n");
7111
    repo.commit("fresh", &[]).unwrap();
7112
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
7113
    let t = fs::metadata(root.join("a.txt"))
7114
        .unwrap()
7115
        .modified()
7116
        .unwrap();
7117
    write(root, "a.txt", b"two\n");
7118
    fs::File::options()
7119
        .write(true)
7120
        .open(root.join("a.txt"))
7121
        .unwrap()
7122
        .set_modified(t)
7123
        .unwrap();
7124
    assert!(
7125
        !repo.clean_by_manifest().unwrap(),
7126
        "same size and time, other bytes"
7127
    );
7128
    assert_eq!(
7129
        statuses(&repo.snapshot_status("status").unwrap()),
7130
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
7131
    );
c5ce0367 Andy McCall ↶ 7132
}
2c75672f Andy McCall ↶ 7133
7134
/// A fetch on one machine moves changes as stored, text blobs among the
7135
/// objects; a change whose text blob did not come is refused, not stored.
7136
#[test]
7137
fn a_raw_bundle_without_a_changes_text_is_refused() {
7138
    hermetic();
7139
    let dir = tempfile::tempdir().unwrap();
7140
    let root = dir.path();
7141
    let a = Repo::init(&root.join("a")).unwrap();
7142
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7143
    write(&root.join("a"), "big.txt", big.as_bytes());
7144
    let h = a.commit("big", &[]).unwrap();
7145
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
7146
    assert_eq!(bundle.raw_changes.len(), 1);
7147
    assert!(bundle.changes.is_empty());
7148
    let b = Repo::init(&root.join("b")).unwrap();
7149
    let mut without = bundle.clone();
7150
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
7151
    let e = b.import_bundle(&without, false).unwrap_err();
7152
    assert!(e.to_string().contains("came without its text blob"), "{e}");
7153
    assert!(!b.store().has(&h));
7154
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
7155
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
7156
}
a87c7b9d Andy McCall ↶ 7157
7158
/// oxygen#30 (vscode): a directory deleted in one line of history and made
7159
/// again was a second node for one Git path, so a file moved into it on
7160
/// another line, where the first node still stood, ended up in two places.
7161
/// An import now brings the directory back rather than make a new one.
7162
#[test]
7163
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
7164
    hermetic();
7165
    if std::process::Command::new("git")
7166
        .arg("--version")
7167
        .output()
7168
        .is_err()
7169
    {
7170
        eprintln!("git not installed; skipping");
7171
        return;
7172
    }
7173
    let dir = tempfile::tempdir().unwrap();
7174
    let root = dir.path();
7175
    let g = root.join("src.git");
7176
    fs::create_dir_all(&g).unwrap();
7177
    let git = |args: &[&str]| -> String {
7178
        let out = std::process::Command::new("git")
7179
            .arg("-C")
7180
            .arg(&g)
7181
            .args([
7182
                "-c",
7183
                "user.name=Grace",
7184
                "-c",
7185
                "[email protected]",
7186
                "-c",
7187
                "commit.gpgsign=false",
7188
            ])
7189
            .args(args)
7190
            .output()
7191
            .unwrap();
7192
        assert!(
7193
            out.status.success(),
7194
            "git {args:?}: {}",
7195
            String::from_utf8_lossy(&out.stderr)
7196
        );
7197
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7198
    };
7199
    git(&["init", "-q", "-b", "main"]);
7200
    write(&g, "d/a.txt", b"a\n");
7201
    write(&g, "c/x.txt", b"x\n");
7202
    git(&["add", "."]);
7203
    git(&["commit", "-qm", "base"]);
7204
    // One line: move x into d while d still stands.
7205
    git(&["checkout", "-qb", "side"]);
7206
    git(&["mv", "c/x.txt", "d/x.txt"]);
7207
    git(&["commit", "-qm", "x into d"]);
7208
    // The other: d goes, comes back, and x moves into it too.
7209
    git(&["checkout", "-q", "main"]);
7210
    git(&["rm", "-q", "d/a.txt"]);
7211
    git(&["commit", "-qm", "d goes"]);
7212
    write(&g, "d/b.txt", b"b\n");
7213
    git(&["add", "."]);
7214
    git(&["commit", "-qm", "d comes back"]);
7215
    git(&["mv", "c/x.txt", "d/x.txt"]);
7216
    git(&["commit", "-qm", "x into d again"]);
7217
    git(&["merge", "-q", "--no-edit", "side"]);
7218
7219
    let repo = Repo::init(&root.join("o")).unwrap();
7220
    repo.import_git(&g, "main").unwrap();
7221
    let v = repo.verify_git_import(&g, "main").unwrap();
7222
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7223
    let st = repo
7224
        .load_state_history(&repo.bookmark_heads().unwrap())
7225
        .unwrap();
7226
    let view = st.tree().view();
7227
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7228
    // The directory is the one the first commit made.
7229
    // Commits made in one second tie on time: find the first by its message.
7230
    let first = repo
7231
        .log()
7232
        .unwrap()
7233
        .into_iter()
7234
        .find(|e| e.change.message.starts_with("base"))
7235
        .unwrap();
7236
    let base = repo
7237
        .load_state_history(&[first.hash])
7238
        .unwrap()
7239
        .tree()
7240
        .view();
7241
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
7242
}
7243
7244
/// oxygen#30, the rest: a placement left under a directory another line
7245
/// removed is out of sight, so no diff reaches it; the merge that settles
7246
/// where the file is retires it.
7247
#[test]
7248
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
7249
    hermetic();
7250
    if std::process::Command::new("git")
7251
        .arg("--version")
7252
        .output()
7253
        .is_err()
7254
    {
7255
        eprintln!("git not installed; skipping");
7256
        return;
7257
    }
7258
    let dir = tempfile::tempdir().unwrap();
7259
    let root = dir.path();
7260
    let g = root.join("src.git");
7261
    fs::create_dir_all(&g).unwrap();
7262
    let run = |args: &[&str]| {
7263
        std::process::Command::new("git")
7264
            .arg("-C")
7265
            .arg(&g)
7266
            .args([
7267
                "-c",
7268
                "user.name=Grace",
7269
                "-c",
7270
                "[email protected]",
7271
                "-c",
7272
                "commit.gpgsign=false",
7273
            ])
7274
            .args(args)
7275
            .output()
7276
            .unwrap()
7277
    };
7278
    let git = |args: &[&str]| {
7279
        let out = run(args);
7280
        assert!(
7281
            out.status.success(),
7282
            "git {args:?}: {}",
7283
            String::from_utf8_lossy(&out.stderr)
7284
        );
7285
    };
7286
    git(&["init", "-q", "-b", "main"]);
7287
    write(&g, "c/x.txt", b"x\n");
7288
    write(&g, "keep.txt", b"k\n");
7289
    git(&["add", "."]);
7290
    git(&["commit", "-qm", "base"]);
7291
    // One line renames the file within c; the other moves it out of c,
7292
    // which goes.
7293
    git(&["checkout", "-qb", "side"]);
7294
    git(&["mv", "c/x.txt", "c/y.txt"]);
7295
    git(&["commit", "-qm", "rename within c"]);
7296
    git(&["checkout", "-q", "main"]);
7297
    fs::create_dir_all(g.join("n")).unwrap();
7298
    git(&["mv", "c/x.txt", "n/x.txt"]);
7299
    git(&["commit", "-qm", "move out of c"]);
7300
    // Git cannot merge the two renames; the merge keeps n/x.txt.
7301
    let _ = run(&["merge", "-q", "side"]);
7302
    let _ = run(&[
7303
        "rm",
7304
        "-q",
7305
        "--cached",
7306
        "--ignore-unmatch",
7307
        "c/y.txt",
7308
        "c/x.txt",
7309
    ]);
7310
    let _ = std::fs::remove_dir_all(g.join("c"));
7311
    write(&g, "n/x.txt", b"x\n");
7312
    git(&["add", "-A"]);
7313
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
7314
7315
    let repo = Repo::init(&root.join("o")).unwrap();
7316
    repo.import_git(&g, "main").unwrap();
7317
    let v = repo.verify_git_import(&g, "main").unwrap();
7318
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7319
    let st = repo
7320
        .load_state_history(&repo.bookmark_heads().unwrap())
7321
        .unwrap();
7322
    let view = st.tree().view();
7323
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7324
    assert!(view.entries.contains_key("n/x.txt"));
7325
}
7326
7327
/// oxygen#30, orphans: a file added on one line into a directory the other
7328
/// line removed is placed where the tree cannot show it; Git's merge keeps
7329
/// the file, and the import's merge leaves exactly one of it.
7330
#[test]
7331
fn git_import_merge_leaves_no_orphan_behind() {
7332
    hermetic();
7333
    if std::process::Command::new("git")
7334
        .arg("--version")
7335
        .output()
7336
        .is_err()
7337
    {
7338
        eprintln!("git not installed; skipping");
7339
        return;
7340
    }
7341
    let dir = tempfile::tempdir().unwrap();
7342
    let root = dir.path();
7343
    let g = root.join("src.git");
7344
    fs::create_dir_all(&g).unwrap();
7345
    let git = |args: &[&str]| {
7346
        let out = std::process::Command::new("git")
7347
            .arg("-C")
7348
            .arg(&g)
7349
            .args([
7350
                "-c",
7351
                "user.name=Grace",
7352
                "-c",
7353
                "[email protected]",
7354
                "-c",
7355
                "commit.gpgsign=false",
7356
            ])
7357
            .args(args)
7358
            .output()
7359
            .unwrap();
7360
        assert!(
7361
            out.status.success(),
7362
            "git {args:?}: {}",
7363
            String::from_utf8_lossy(&out.stderr)
7364
        );
7365
    };
7366
    git(&["init", "-q", "-b", "main"]);
7367
    write(&g, "d/f.txt", b"f\n");
7368
    write(&g, "keep.txt", b"k\n");
7369
    git(&["add", "."]);
7370
    git(&["commit", "-qm", "base"]);
7371
    git(&["checkout", "-qb", "side"]);
7372
    write(&g, "d/new.txt", b"new\n");
7373
    git(&["add", "."]);
7374
    git(&["commit", "-qm", "add into d"]);
7375
    git(&["checkout", "-q", "main"]);
7376
    git(&["rm", "-q", "d/f.txt"]);
7377
    git(&["commit", "-qm", "d goes"]);
7378
    git(&["merge", "-q", "--no-edit", "side"]);
7379
7380
    let repo = Repo::init(&root.join("o")).unwrap();
7381
    repo.import_git(&g, "main").unwrap();
7382
    let v = repo.verify_git_import(&g, "main").unwrap();
7383
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7384
    let st = repo
7385
        .load_state_history(&repo.bookmark_heads().unwrap())
7386
        .unwrap();
7387
    let view = st.tree().view();
7388
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7389
    assert!(view.entries.contains_key("d/new.txt"));
7390
}
d77e1702 Andy McCall ↶ 7391
7392
/// fsck checks a change's text as the blobs it is stored in, without
7393
/// decoding it: a missing text blob is an error named for the change.
7394
#[test]
7395
fn fsck_names_a_missing_text_blob() {
7396
    hermetic();
7397
    let dir = tempfile::tempdir().unwrap();
7398
    let root = dir.path();
7399
    let repo = Repo::init(root).unwrap();
7400
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7401
    write(root, "big.txt", big.as_bytes());
7402
    let h = repo.commit("big", &[]).unwrap();
7403
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7404
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7405
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7406
        panic!("a stored text")
7407
    };
64818938 Andy McCall ↶ 7408
    repo.store().remove_loose_for_test(&b).unwrap();
d77e1702 Andy McCall ↶ 7409
    let rep = repo.fsck().unwrap();
7410
    assert!(rep.errors() > 0);
7411
    assert!(
7412
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7413
        "{:?}",
7414
        rep.problems
7415
    );
7416
}
a07f60a3 Andy McCall ↶ 7417
7418
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7419
/// reached with that remote's token and CA (a private subrepo then clones
7420
/// for anyone who can read the parent); another hub gets none of them.
7421
#[test]
7422
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7423
    hermetic();
7424
    let dir = tempfile::tempdir().unwrap();
7425
    let mut repo = Repo::init(dir.path()).unwrap();
7426
    repo.config
7427
        .set(
7428
            "remote.origin.url",
7429
            "https://Hub.example:7343/doomsdayone/metalgear",
7430
        )
7431
        .unwrap();
7432
    repo.config.set("remote.origin.token", "secret").unwrap();
7433
    repo.config
7434
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7435
        .unwrap();
7436
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7437
    assert_eq!(same.token.as_deref(), Some("secret"));
7438
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7439
    for other in [
7440
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7441
        "https://hub.example/doomsdayone/rstar-api",
7442
        "http://hub.example:7343/doomsdayone/rstar-api",
7443
    ] {
7444
        let o = repo.credentials_for(other);
7445
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7446
    }
7447
}
ce14f0d6 Andy McCall ↶ 7448
ff1f62fe Andy McCall ↶ 7449
/// oxygen#47: a remote with no token of its own uses the user's credential
7450
/// store for its hub, and a nested checkout finds its parent's remote
7451
/// token there instead of keeping a copy.
ce14f0d6 Andy McCall ↶ 7452
#[test]
ff1f62fe Andy McCall ↶ 7453
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7454
    hermetic();
7455
    let home = tempfile::tempdir().unwrap();
7456
    let dir = tempfile::tempdir().unwrap();
7457
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7458
    parent
7459
        .config
7460
        .set("remote.origin.url", "https://hub.example/o/parent")
7461
        .unwrap();
7462
    parent.save_config().unwrap();
7463
    assert_eq!(parent.remote_options("origin").token, None);
7464
    crate::credentials::Credentials::at(home.path())
7465
        .save("https://hub.example", "stored", Some("andy"), None)
7466
        .unwrap();
7467
    assert_eq!(
7468
        parent.remote_options("origin").token.as_deref(),
7469
        Some("stored")
7470
    );
7471
7472
    let empty_home = tempfile::tempdir().unwrap();
7473
    let nested = dir.path().join("deps").join("child");
7474
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7475
    child
7476
        .config
7477
        .set("remote.origin.url", "https://hub.example/o/child")
7478
        .unwrap();
7479
    child.save_config().unwrap();
7480
    assert_eq!(child.remote_options("origin").token, None);
7481
    parent
7482
        .config
7483
        .set("remote.origin.token", "checkout")
7484
        .unwrap();
7485
    parent.save_config().unwrap();
7486
    assert_eq!(
7487
        child.remote_options("origin").token.as_deref(),
7488
        Some("checkout")
7489
    );
7490
    // Another hub's checkout token is not borrowed.
7491
    child
7492
        .config
7493
        .set("remote.origin.url", "https://other.example/o/child")
7494
        .unwrap();
7495
    assert_eq!(child.remote_options("origin").token, None);
7496
}
7497
7498
#[test]
ce14f0d6 Andy McCall ↶ 7499
fn the_metadata_cache_survives_a_torn_tail() {
7500
    hermetic();
7501
    let dir = tempfile::tempdir().unwrap();
7502
    let root = dir.path();
7503
    let repo = Repo::init(root).unwrap();
7504
    write(root, "a.txt", b"1\n");
7505
    let h = repo.commit("first", &[]).unwrap();
7506
    let meta = repo.store().get_change_meta(&h).unwrap();
7507
    let cache = repo.store().dir().join("metas");
7508
    let len = fs::metadata(&cache).unwrap().len();
7509
    assert!(len > 0, "a change read is cached");
7510
    // A torn record at the end: the cache reads up to it and cuts it off.
7511
    fs::OpenOptions::new()
7512
        .append(true)
7513
        .open(&cache)
7514
        .unwrap()
7515
        .write_all(&[7; 20])
7516
        .unwrap();
7517
    let again = Repo::open(root).unwrap();
7518
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7519
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7520
}
f9466021 Andy McCall ↶ 7521
7522
#[test]
7523
fn a_manifest_that_does_not_check_reads_as_none() {
7524
    hermetic();
7525
    let dir = tempfile::tempdir().unwrap();
7526
    let root = dir.path();
7527
    let repo = Repo::init(root).unwrap();
7528
    write(root, "a.txt", b"1\n");
7529
    repo.commit("first", &[]).unwrap();
7530
    let path = repo.manifest_path();
7531
    let mut bytes = fs::read(&path).unwrap();
7532
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7533
    let last = bytes.len() - 1;
7534
    bytes[last] ^= 1;
7535
    fs::write(&path, &bytes).unwrap();
7536
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7537
    // The next status reads the files and writes it again.
7538
    let again = Repo::open(root).unwrap();
7539
    assert!(!again.snapshot("status").unwrap().changed);
7540
    assert!(again.read_manifest().unwrap().is_some());
7541
}
7542
7543
#[test]
7544
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7545
    hermetic();
7546
    let dir = tempfile::tempdir().unwrap();
7547
    let root = dir.path();
7548
    let repo = Repo::init(root).unwrap();
7549
    write(root, "a.txt", b"1\n");
7550
    write(root, "b.txt", b"2\n");
7551
    // b.txt outside the racy window, so snapshots take it as unchanged.
7552
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7553
    fs::File::options()
7554
        .write(true)
7555
        .open(root.join("b.txt"))
7556
        .unwrap()
7557
        .set_modified(old)
7558
        .unwrap();
7559
    repo.commit("first", &[]).unwrap();
7560
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7561
    repo.snapshot_status("status").unwrap();
7562
    write(root, "a.txt", b"1\n2\n");
7563
    repo.commit("second", &[]).unwrap();
7564
    assert!(
7565
        repo.clean_by_manifest().unwrap(),
7566
        "after a commit of one file"
7567
    );
7568
    // Edited, seen by a status, edited again, then committed: the status
7569
    // left the first edit's stat, which the commit must not keep.
7570
    write(root, "a.txt", b"1\n2\n3\n");
7571
    repo.snapshot_status("status").unwrap();
7572
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7573
    repo.commit("third", &[]).unwrap();
7574
    assert!(
7575
        repo.clean_by_manifest().unwrap(),
7576
        "after an edit a status saw"
7577
    );
7578
}
e266b7d4 Andy McCall ↶ 7579
7580
#[test]
7581
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7582
    hermetic();
7583
    let dir = tempfile::tempdir().unwrap();
7584
    let root = dir.path();
7585
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7586
    write(root, "a.txt", b"1\n2\n");
7587
    let a = repo.commit("A", &[]).unwrap();
7588
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7589
    write(root, "a.txt", b"1\nX\n");
7590
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7591
    repo.bookmark_switch("develop", false).unwrap();
7592
    write(root, "a.txt", b"1\nY\n");
7593
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7594
    repo.bookmark_switch("main", false).unwrap();
7595
7596
    let err = repo.rebase(&c, &[d]).unwrap_err();
7597
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7598
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7599
    assert!(r.changed && r.checked_out);
7600
    let snap = repo.snapshot_status("status").unwrap();
7601
    assert!(
7602
        snap.base_snapshot.is_conflicted(),
7603
        "the conflict is in the working copy"
7604
    );
7605
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7606
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7607
7608
    write(root, "a.txt", b"1\nXY\n");
7609
    repo.commit("Resolve", &[]).unwrap();
7610
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7611
    assert!(st.contains(&c) && st.contains(&d));
7612
    let files = st.materialize().files;
7613
    assert!(!files["a.txt"].is_conflicted());
7614
    assert!(
7615
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7616
    );
7617
7618
    // A change the current bookmark does not hold is refused.
7619
    repo.bookmark_switch("develop", false).unwrap();
7620
    write(root, "b.txt", b"b\n");
7621
    let e = repo.commit("E", &[]).unwrap();
7622
    repo.bookmark_switch("main", false).unwrap();
7623
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7624
    assert!(
7625
        err.to_string().contains("not on the current bookmark"),
7626
        "{err}"
7627
    );
7628
}
d4dbab97 Andy McCall ↶ 7629
7630
#[test]
7631
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7632
    hermetic();
7633
    let dir = tempfile::tempdir().unwrap();
7634
    let root = dir.path();
7635
    let repo = Repo::init(root).unwrap();
7636
    write(root, "a.txt", b"a\n");
7637
    write(root, "kept.log", b"tracked\n");
7638
    repo.commit("first", &[]).unwrap();
7639
    write(root, "build.log", b"made\n");
7640
    let snap = repo.snapshot_status("status").unwrap();
7641
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7642
    // A rule written afterwards leaves the added file out again, while the
7643
    // committed one stays tracked.
7644
    write(root, ".gitignore", b"*.log\n");
7645
    let snap = repo.snapshot_status("status").unwrap();
7646
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7647
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7648
    write(root, "kept.log", b"tracked, edited\n");
7649
    let snap = repo.snapshot_status("status").unwrap();
7650
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7651
}
fd280228 Andy McCall ↶ 7652
7653
#[test]
7654
fn shed_graphs_come_back_the_same() {
7655
    hermetic();
7656
    let dir = tempfile::tempdir().unwrap();
7657
    let root = dir.path();
7658
    let repo = Repo::init(root).unwrap();
7659
    write(root, "a.txt", b"1\n2\n3\n");
7660
    write(root, "b.txt", b"x\n");
7661
    repo.commit("first", &[]).unwrap();
7662
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7663
    repo.commit("second", &[]).unwrap();
7664
    let heads = repo.bookmark_heads().unwrap();
7665
    let mut st = repo.load_state_history(&heads).unwrap();
7666
    let view = st.tree().view();
7667
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7668
        .iter()
7669
        .map(|p| view.entries[*p].node)
7670
        .collect();
7671
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7672
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7673
    assert_eq!(st.built_count(), 2);
7674
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7675
    assert_eq!((shed, st.built_count()), (2, 0));
7676
    // A later change applies on top of the shed history.
7677
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7678
    let h3 = repo.commit("third", &[]).unwrap();
7679
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7680
    st.add_known(h3, skeleton, texts);
7681
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7682
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7683
    assert_eq!(after[1], before[1]);
7684
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7685
}
360aa74a Andy McCall ↶ 7686
7687
#[test]
7688
fn many_edited_files_diff_in_parallel() {
7689
    // Enough edited files that the builder diffs them in parallel; the
7690
    // commit must hold exactly what is on disk, and a second snapshot
7691
    // must find nothing left to commit.
7692
    hermetic();
7693
    let dir = tempfile::tempdir().unwrap();
7694
    let root = dir.path();
7695
    let repo = Repo::init(root).unwrap();
7696
    let text = |i: usize, round: usize| {
7697
        let mut s = String::new();
7698
        for line in 0..50 {
7699
            if round > 0 && line % 7 == i % 7 {
7700
                s.push_str(&format!("edited {round} {i} {line}\n"));
7701
            } else {
7702
                s.push_str(&format!("file {i} line {line}\n"));
7703
            }
7704
        }
7705
        if round > 0 && i.is_multiple_of(3) {
7706
            s.push_str("appended\n");
7707
        }
7708
        s
7709
    };
7710
    for i in 0..40 {
7711
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7712
    }
7713
    repo.commit("first", &[]).unwrap();
7714
    for i in 0..40 {
7715
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7716
    }
7717
    let h = repo.commit("edit every file", &[]).unwrap();
7718
    let snap = repo.load_state(&[h]).unwrap().materialize();
7719
    for i in 0..40 {
7720
        let want = text(i, 1);
7721
        assert!(
7722
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
7723
            "d/f{i}.txt as committed"
7724
        );
7725
    }
7726
    assert!(
7727
        repo.commit("nothing", &[]).is_err(),
7728
        "nothing left to commit"
7729
    );
7730
}
b35df36b Andy McCall ↶ 7731
7732
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7733
/// is known (fetch printed "up to date" while main was behind), a change
7734
/// only fetched resolves and says where it is, and a checkout whose only
7735
/// remote is not `origin` uses that one.
7736
#[test]
7737
fn a_fetched_change_shows_as_behind_and_resolves() {
7738
    hermetic();
7739
    let dir = tempfile::tempdir().unwrap();
7740
    let root = dir.path();
7741
    let origin = Repo::init(&root.join("origin")).unwrap();
7742
    drop(origin);
7743
    let url = root.join("origin").to_string_lossy().to_string();
7744
    let a = Repo::clone(&url, &root.join("a"))
7745
        .unwrap()
7746
        .with_home(root.join("home-a"));
7747
    write(&root.join("a"), "f.txt", b"one\n");
7748
    a.commit("one", &[]).unwrap();
7749
    a.push("origin", false).unwrap();
7750
    let b = Repo::clone(&url, &root.join("b"))
7751
        .unwrap()
7752
        .with_home(root.join("home-b"));
7753
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7754
7755
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7756
    let h2 = a.commit("two", &[]).unwrap();
7757
    a.push("origin", false).unwrap();
7758
    b.fetch("origin").unwrap();
7759
    // Fetched, not pulled: one behind, the change found and placed.
7760
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7761
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7762
    assert_eq!(
7763
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7764
            .unwrap(),
7765
        h2
7766
    );
7767
    assert_eq!(
7768
        b.remote_only_location(&h2).unwrap().as_deref(),
7769
        Some("origin/main")
7770
    );
7771
    // Fetching again changes nothing: still behind, which is what the
7772
    // CLI now says rather than "up to date".
7773
    b.fetch("origin").unwrap();
7774
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7775
    b.pull("origin").unwrap();
7776
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7777
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7778
7779
    // One remote, not called origin: it is the default.
7780
    let mut c = Repo::init(&root.join("c")).unwrap();
7781
    assert_eq!(c.default_remote(), "origin");
7782
    c.config.set("remote.earth.url", &url).unwrap();
7783
    assert_eq!(c.default_remote(), "earth");
7784
    c.config.set("remote.origin.url", &url).unwrap();
7785
    assert_eq!(c.default_remote(), "origin");
7786
}
827281ee Andy McCall ↶ 7787
7788
/// oxygen#57: a clone from a relative local path records the remote as an
7789
/// absolute path, so fetch still finds it from inside the clone.
7790
#[test]
7791
fn a_clone_from_a_relative_path_records_it_absolute() {
7792
    hermetic();
7793
    let dir = tempfile::tempdir().unwrap();
7794
    let root = dir.path();
7795
    Repo::init(&root.join("origin")).unwrap();
7796
    let rel = crate::protocol::stored_url("relative/repo");
7797
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7798
    assert_eq!(
7799
        crate::protocol::stored_url("https://hub.example/o/n"),
7800
        "https://hub.example/o/n"
7801
    );
7802
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8d803563 Andy McCall ↶ 7803
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7804
    // A bucket is kept as written: it is not a path.
7805
    assert_eq!(
7806
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7807
        "s3://bucket/prefix?profile=p"
7808
    );
827281ee Andy McCall ↶ 7809
    let url = root.join("origin").to_string_lossy().to_string();
7810
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7811
    assert_eq!(b.config.remotes["origin"], url);
7812
    b.fetch("origin").unwrap();
7813
}
a46f3e4f Andy McCall ↶ 7814
7815
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7816
/// and gets its subrepos at their pins from this workspace's copies, with
7817
/// their remotes pointing where the subrepos come from.
7818
#[test]
7819
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7820
    hermetic();
7821
    let dir = tempfile::tempdir().unwrap();
7822
    let root = dir.path();
7823
    Repo::init(&root.join("lib-origin")).unwrap();
7824
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7825
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7826
        .unwrap()
7827
        .with_home(root.join("home"));
7828
    write(&root.join("lib"), "lib.txt", b"v1\n");
7829
    let l1 = lib.commit("lib v1", &[]).unwrap();
7830
    assert!(lib.push("origin", false).unwrap()[0].ok);
7831
7832
    let app_dir = root.join("app");
7833
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7834
    write(&app_dir, "main.txt", b"app\n");
7835
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7836
    app.commit("app with lib", &[]).unwrap();
7837
    // A second bookmark, and the main workspace on another.
7838
    app.bookmark_create("develop", None).unwrap();
7839
    app.bookmark_create("feature", None).unwrap();
7840
    let mut app = app;
7841
    app.bookmark_switch("feature", false).unwrap();
7842
    assert_eq!(app.config.bookmark, "feature");
7843
7844
    // The library's origin goes away: the subrepo must come from here.
7845
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7846
    let heads = app.resolve_heads("develop").unwrap();
7847
    let ws = app
7848
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7849
        .unwrap();
7850
    assert_eq!(
7851
        ws.config.bookmark, "develop",
7852
        "the new workspace is on develop"
7853
    );
7854
    assert_eq!(
7855
        app.config.bookmark, "feature",
7856
        "and this one stays on its own"
7857
    );
7858
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7859
    assert_eq!(
7860
        sub.config.remotes["origin"], lib_url,
7861
        "its origin is the subrepo's URL"
7862
    );
7863
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7864
    assert_eq!(
7865
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7866
        b"v1\n"
7867
    );
7868
}
47ce8b8e Andy McCall ↶ 7869
7870
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7871
/// operators and the predicates, over a small graph with two heads and
7872
/// a rename.
7873
#[test]
7874
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7875
    hermetic();
7876
    let dir = tempfile::tempdir().unwrap();
7877
    let root = dir.path();
7878
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7879
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7880
        .unwrap();
7881
    write(root, "src/a.rs", b"one\n");
7882
    let a = repo.commit("first: add a", &[]).unwrap();
7883
    write(root, "src/a.rs", b"one\ntwo\n");
7884
    let b = repo.commit("second: grow a", &[]).unwrap();
7885
    // A second head, independent of b: a new file on top of a.
7886
    repo.checkout(&[a], false, "checkout a").unwrap();
7887
    write(root, "docs/notes.md", b"notes\n");
7888
    let c = repo.commit("third: notes", &[]).unwrap();
7889
    // Back to both heads, then rename a.rs: the node keeps its identity.
7890
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7891
        .unwrap();
7892
    fs::remove_file(root.join("src/a.rs")).unwrap();
7893
    write(root, "src/z.rs", b"one\ntwo\n");
7894
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7895
    let wc = repo.working_copy().unwrap().0;
7896
    // A saved revset is checked when set.
7897
    repo.set_user_config("revset.mine", "author(me) & ::main")
7898
        .unwrap();
7899
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7900
    let set = |src: &str| -> Vec<ChangeHash> {
7901
        let mut v = repo.revset(src).unwrap().hashes;
7902
        v.sort();
7903
        v
7904
    };
7905
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7906
        let mut v = hs.to_vec();
7907
        v.sort();
7908
        v
7909
    };
7910
7911
    // Changes commute: a new file depends on nothing and the rename on the
7912
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7913
    // copy on the three heads b, c, d.
7914
    let heads = sorted(&repo.bookmark_heads().unwrap());
7915
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7916
    assert!(heads.contains(&d) && heads.contains(&c));
7917
    // Symbols and closures.
7918
    assert_eq!(set("main"), heads);
7919
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7920
    assert_eq!(set("@"), vec![wc]);
7921
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7922
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7923
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7924
    assert_eq!(
7925
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7926
        sorted(&[a, b])
7927
    );
7928
    // Ranges: what main has beyond b, and `..` forms.
7929
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7930
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7931
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7932
    // Operators and precedence: ~ binds tighter than &, & than |.
7933
    assert_eq!(
7934
        set(&format!("::main ~ #{}", d.short(12))),
7935
        sorted(&[a, b, c])
7936
    );
7937
    assert_eq!(
7938
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7939
        sorted(&[b, c])
7940
    );
7941
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7942
    // Relations.
7943
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7944
    head_deps.sort();
7945
    head_deps.dedup();
7946
    assert_eq!(set("deps(main)"), head_deps);
7947
    let on_a: Vec<ChangeHash> = [b, c, d]
7948
        .into_iter()
7949
        .filter(|h| meta(h).deps.contains(&a))
7950
        .collect();
7951
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7952
    assert_eq!(set("heads(::main)"), heads);
7953
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7954
    assert_eq!(
7955
        set(&format!(
7956
            "heads(#{} | #{} | #{})",
7957
            a.short(12),
7958
            b.short(12),
7959
            c.short(12)
7960
        )),
7961
        sorted(&[b, c])
7962
    );
7963
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7964
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7965
    assert_eq!(set("none()"), vec![]);
7966
    // Predicates: author by name, email, key prefix and `me`.
7967
    let key = repo.config.author_key.unwrap();
7968
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7969
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7970
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7971
    assert_eq!(set("author(me) & ::main").len(), 4);
7972
    assert_eq!(set("author(nobody)"), vec![]);
7973
    assert_eq!(set("description(notes)"), vec![c]);
7974
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7975
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7976
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7977
    // touches follows the node through the rename, in the current state.
7978
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7979
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7980
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7981
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7982
    // Newest first in the result order.
7983
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7984
    // The saved revset, and errors that say what is wrong.
7985
    assert_eq!(set("mine()").len(), 4);
7986
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7987
    assert!(e.contains("unknown function nosuch()"), "{e}");
7988
    let e = repo.revset("main &").unwrap_err().to_string();
7989
    assert!(e.contains("at character"), "{e}");
7990
    let e = repo.revset("zzzz").unwrap_err().to_string();
7991
    assert!(e.contains("no change matches"), "{e}");
7992
    let e = repo
7993
        .revset_with_budget("::main", std::time::Duration::ZERO)
7994
        .unwrap_err()
7995
        .to_string();
7996
    assert!(e.contains("budget"), "{e}");
7997
    // The log entries carry the bookmark's heads and the working copy.
7998
    let entries = repo.log_revset("::@").unwrap();
7999
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
2c9ddac3 Andy McCall ↶ 8000
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
8001
    // push); then a signed change, a tag, and a revocation.
8002
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
8003
    assert_eq!(set("signed_by(me)"), vec![]);
8004
    repo.sign_change(&d).unwrap();
8005
    assert_eq!(set("signed_by(me)"), vec![d]);
8006
    assert_eq!(set("signed_by([email protected])"), vec![d]);
8007
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
8008
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
8009
    assert_eq!(set("delegated()"), vec![]);
8010
    assert_eq!(set("revoked()"), vec![]);
8011
    assert_eq!(set("attested(tag)"), vec![]);
8012
    repo.tag_create("v1", &[b], "first").unwrap();
8013
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
8014
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
8015
    assert_eq!(set("attested(receipt)"), vec![]);
8016
    assert_eq!(set("built(test)"), vec![]);
8017
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
8018
    assert!(e.contains("tag, receipt or ref"), "{e}");
8019
    repo.revoke_identity(&key, "test").unwrap();
8020
    assert_eq!(set("revoked()"), vec![d]);
8021
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
47ce8b8e Andy McCall ↶ 8022
}
614f55e1 Andy McCall ↶ 8023
8024
#[test]
8025
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
8026
    let dir = tempfile::tempdir().unwrap();
8027
    let root = dir.path();
8028
    let home = root.join("home");
8029
    // Ada's identity lives in the user file; repository `a` pins the same
8030
    // key in its own file, repository `b` names none.
8031
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
8032
    let (key, _) = a
8033
        .create_identity("Ada", "[email protected]", IdentityScope::User)
8034
        .unwrap();
8035
    a.config.set("author.key", &key.to_hex()).unwrap();
8036
    a.save_config().unwrap();
8037
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
8038
    let r = a
8039
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
8040
        .unwrap();
8041
    assert_eq!(
8042
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
8043
        r.new.to_hex(),
8044
        "the user file follows"
8045
    );
8046
    assert_eq!(
8047
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
8048
        r.new.to_hex(),
8049
        "the pinning repository follows"
8050
    );
8051
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
8052
    assert_eq!(
8053
        b.config.author_key,
8054
        Some(r.new),
8055
        "a checkout without a pin follows the user file"
8056
    );
8057
    // A repository-scoped identity leaves the user file alone.
8058
    let other_home = root.join("home2");
8059
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
8060
    let (ck, _) = c
8061
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
8062
        .unwrap();
8063
    assert!(!other_home.join("config.toml").exists());
8064
    let r2 = c.rotate_identity().unwrap();
8065
    assert_ne!(r2.new, ck);
8066
    assert_eq!(
8067
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
8068
        r2.new.to_hex()
8069
    );
8070
    assert!(
8071
        !other_home.join("config.toml").exists(),
8072
        "a repository-scoped identity stays repository-scoped"
8073
    );
8074
    // Several delegates in one rotation; a repeat is refused.
8075
    let (d1, d2) = (
8076
        SecretKey::generate().identity("D1", "d1@x", 1),
8077
        SecretKey::generate().identity("D2", "d2@x", 1),
8078
    );
8079
    let r3 = c
8080
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
8081
        .unwrap();
8082
    assert_eq!(r3.identity.delegates.len(), 2);
8083
    assert!(c
8084
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
8085
        .is_err());
8086
}
33be2409 Andy McCall ↶ 8087
8088
/// Two unrelated histories that both add the same file, joined by two
8089
/// independent merges on two branches, then those branches merged: Git
8090
/// merges identical additions cleanly, and the import must too (#71,
8091
/// found in VS Code's history).
8092
#[test]
8093
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
8094
    // Batches of one: every merge renders apart from the state, where a
8095
    // file whose graph the state had built came out empty (#71).
8096
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8097
    hermetic();
8098
    if std::process::Command::new("git")
8099
        .arg("--version")
8100
        .output()
8101
        .is_err()
8102
    {
8103
        eprintln!("git not installed; skipping");
8104
        return;
8105
    }
8106
    let dir = tempfile::tempdir().unwrap();
8107
    let root = dir.path();
8108
    let g = root.join("src.git");
8109
    fs::create_dir_all(&g).unwrap();
8110
    let git = |args: &[&str]| -> String {
8111
        let out = std::process::Command::new("git")
8112
            .arg("-C")
8113
            .arg(&g)
8114
            .args([
8115
                "-c",
8116
                "user.name=Grace",
8117
                "-c",
8118
                "[email protected]",
8119
                "-c",
8120
                "commit.gpgsign=false",
8121
            ])
8122
            .args(args)
8123
            .output()
8124
            .unwrap();
8125
        assert!(
8126
            out.status.success(),
8127
            "git {args:?}: {}",
8128
            String::from_utf8_lossy(&out.stderr)
8129
        );
8130
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8131
    };
8132
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
8133
    // History A: main.
8134
    git(&["init", "-q", "-b", "main"]);
8135
    write(&g, "gulpfile.js", text);
8136
    write(&g, "a.txt", b"a\n");
8137
    git(&["add", "."]);
8138
    git(&["commit", "-q", "-m", "A root"]);
8139
    // History B: an unrelated root adding the same file, identical.
8140
    git(&["checkout", "-q", "--orphan", "fork"]);
8141
    git(&["rm", "-q", "-r", "--cached", "."]);
8142
    for f in ["gulpfile.js", "a.txt"] {
8143
        let _ = fs::remove_file(g.join(f));
8144
    }
8145
    write(&g, "gulpfile.js", text);
8146
    write(&g, "b.txt", b"b\n");
8147
    git(&["add", "."]);
8148
    git(&["commit", "-q", "-m", "B root"]);
8149
    // Two branches from main, each joining B on its own.
8150
    git(&["checkout", "-q", "-b", "one", "main"]);
8151
    git(&[
8152
        "merge",
8153
        "-q",
8154
        "--no-ff",
8155
        "--allow-unrelated-histories",
8156
        "-m",
8157
        "join on one",
8158
        "fork",
8159
    ]);
8160
    git(&["checkout", "-q", "-b", "two", "main"]);
8161
    write(&g, "a.txt", b"a\ntwo\n");
8162
    git(&["commit", "-q", "-am", "work on two"]);
8163
    git(&[
8164
        "merge",
8165
        "-q",
8166
        "--no-ff",
8167
        "--allow-unrelated-histories",
8168
        "-m",
8169
        "join on two",
8170
        "fork",
8171
    ]);
8172
    // Then the two joins meet, and the file is reformatted after.
8173
    git(&["checkout", "-q", "main"]);
8174
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
8175
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8176
    write(
8177
        &g,
8178
        "gulpfile.js",
8179
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
8180
    );
8181
    git(&["commit", "-q", "-am", "after"]);
8182
8183
    let dest = root.join("dest");
8184
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8185
    repo.import_git(&g, "main").unwrap();
8186
    let v = repo.verify_git_import(&g, "main").unwrap();
8187
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8188
    assert_eq!(
8189
        fs::read(dest.join("gulpfile.js")).unwrap(),
8190
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
8191
    );
8192
}
8193
8194
/// As above, but the two joins keep different copies (each branch had a
8195
/// different version when it joined), and later work edits each copy:
8196
/// the shape of VS Code's c67ef57cda90 (#71).
8197
#[test]
8198
fn git_import_joins_where_each_join_kept_a_different_copy() {
8199
    // Batches of one: every merge renders apart from the state, where a
8200
    // file whose graph the state had built came out empty (#71).
8201
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8202
    hermetic();
8203
    if std::process::Command::new("git")
8204
        .arg("--version")
8205
        .output()
8206
        .is_err()
8207
    {
8208
        eprintln!("git not installed; skipping");
8209
        return;
8210
    }
8211
    let dir = tempfile::tempdir().unwrap();
8212
    let root = dir.path();
8213
    let g = root.join("src.git");
8214
    fs::create_dir_all(&g).unwrap();
8215
    let run = |args: &[&str]| {
8216
        std::process::Command::new("git")
8217
            .arg("-C")
8218
            .arg(&g)
8219
            .args([
8220
                "-c",
8221
                "user.name=Grace",
8222
                "-c",
8223
                "[email protected]",
8224
                "-c",
8225
                "commit.gpgsign=false",
8226
            ])
8227
            .args(args)
8228
            .output()
8229
            .unwrap()
8230
    };
8231
    let git = |args: &[&str]| -> String {
8232
        let out = run(args);
8233
        assert!(
8234
            out.status.success(),
8235
            "git {args:?}: {}",
8236
            String::from_utf8_lossy(&out.stderr)
8237
        );
8238
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8239
    };
8240
    git(&["init", "-q", "-b", "main"]);
8241
    write(
8242
        &g,
8243
        "gulpfile.js",
8244
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
8245
    );
8246
    git(&["add", "."]);
8247
    git(&["commit", "-q", "-m", "A root"]);
8248
    write(
8249
        &g,
8250
        "gulpfile.js",
8251
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
8252
    );
8253
    git(&["commit", "-q", "-am", "whitespace"]);
8254
    git(&["checkout", "-q", "--orphan", "fork"]);
8255
    git(&["rm", "-q", "-r", "--cached", "."]);
8256
    let _ = fs::remove_file(g.join("gulpfile.js"));
8257
    write(
8258
        &g,
8259
        "gulpfile.js",
8260
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
8261
    );
8262
    git(&["add", "."]);
8263
    git(&["commit", "-q", "-m", "B root"]);
8264
    // Branch one joins B keeping main's copy; branch two keeps B's.
8265
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
8266
        git(&["checkout", "-q", "-b", branch, "main"]);
8267
        let _ = run(&[
8268
            "merge",
8269
            "-q",
8270
            "--no-ff",
8271
            "--allow-unrelated-histories",
8272
            "-m",
8273
            "join",
8274
            "fork",
8275
        ]);
8276
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
8277
        git(&["add", "gulpfile.js"]);
8278
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
8279
    }
8280
    // Each branch then edits its copy.
8281
    git(&["checkout", "-q", "one"]);
8282
    write(
8283
        &g,
8284
        "gulpfile.js",
8285
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
8286
    );
8287
    git(&["commit", "-q", "-am", "tslint on one"]);
8288
    git(&["checkout", "-q", "two"]);
8289
    write(
8290
        &g,
8291
        "gulpfile.js",
8292
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
8293
    );
8294
    write(&g, "extra.txt", b"x\n");
8295
    write(&g, "more.txt", b"m\n");
8296
    git(&["add", "."]);
8297
    git(&["commit", "-q", "-am", "fmt on two"]);
8298
    // They meet: resolved by hand.
8299
    git(&["checkout", "-q", "one"]);
8300
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8301
    write(
8302
        &g,
8303
        "gulpfile.js",
8304
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
8305
    );
8306
    git(&["add", "gulpfile.js"]);
8307
    git(&["commit", "-q", "-m", "merge two into one"]);
8308
8309
    let dest = root.join("dest");
8310
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8311
    repo.import_git(&g, "one").unwrap();
8312
    let v = repo.verify_git_import(&g, "one").unwrap();
8313
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8314
}
dd21fd82 Andy McCall ↶ 8315
8316
/// oxygen#68: on a store that is not this disk's directory, the operation
8317
/// head is the store's reference record, moved by compare-and-swap. Two
8318
/// handles recording from the same head both get through, merged; a swap
8319
/// from a stale version is refused; a second repository cannot start on a
8320
/// store that already holds one.
8321
#[test]
8322
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8323
    use crate::strata::{MemoryStore, Store as _};
8324
    let backend = std::sync::Arc::new(MemoryStore::new());
8325
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8326
    let dir = tempfile::tempdir().unwrap();
8327
    let a = Repo::init(dir.path()).unwrap();
8328
    assert!(
8329
        !dir.path().join(".oxy/ops/head").exists(),
8330
        "the head is not a file"
8331
    );
8332
    let (h0, op0) = a.head_op().unwrap();
8333
    let record = backend
8334
        .read_ref(HEAD_RECORD)
8335
        .unwrap()
8336
        .expect("the head is the store's record");
8337
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8338
8339
    let b = Repo::open(dir.path()).unwrap();
8340
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8341
    let mut va = op0.view.clone();
8342
    va.bookmarks.insert("from-a".into(), state);
8343
    let mut vb = op0.view.clone();
8344
    vb.bookmarks.insert("from-b".into(), state);
8345
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8346
    assert_eq!(b.head_ref().unwrap(), rb);
8347
    // a recorded from h0 too: the head moved, so the two are merged.
8348
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8349
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8350
    assert_eq!(head, ra);
8351
    assert!(
8352
        op.command.ends_with("(merged with a concurrent operation)"),
8353
        "{}",
8354
        op.command
8355
    );
8356
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8357
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8358
8359
    // A swap from a version that is no longer current moves nothing.
8360
    let (h, v) = a.read_head().unwrap();
8361
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8362
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8363
    assert_eq!(a.head_ref().unwrap(), rb);
8364
8365
    let other = tempfile::tempdir().unwrap();
8366
    let err = Repo::init(other.path())
8367
        .err()
8368
        .expect("the store already holds a log")
8369
        .to_string();
8370
    assert!(
8371
        err.contains("already holds a repository's operation log"),
8372
        "{err}"
8373
    );
8374
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8375
}
d069701a Andy McCall ↶ 8376
8377
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8378
/// objects and operation head there, with `.oxy/cache` in front: it works
8379
/// as one on disk does, reopens, and survives losing its cache.
8380
#[test]
8381
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8382
    hermetic();
8383
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8384
        return;
8385
    }
8386
    let dir = tempfile::tempdir().unwrap();
8387
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8388
    let url = format!("dir://{}", bucket.display());
8389
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8390
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8391
    write(&root, "a.txt", b"one\n");
8392
    let h1 = repo.commit("First", &[]).unwrap();
8393
    write(&root, "a.txt", b"one\ntwo\n");
8394
    let h2 = repo.commit("Second", &[]).unwrap();
8395
    assert!(
8396
        !root.join(".oxy/ops/head").exists(),
8397
        "the head is in the store"
8398
    );
8399
    assert!(bucket.join("ops/head").is_file());
8400
    assert!(root.join(".oxy/cache").is_dir());
8401
    drop(repo);
8402
8403
    // Reopened, and again with no cache at all: everything comes from the store.
8404
    for drop_cache in [false, true] {
8405
        if drop_cache {
8406
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8407
        }
8408
        let repo = Repo::open(&root).unwrap();
8409
        let log: Vec<String> = repo
8410
            .op_log()
8411
            .unwrap()
8412
            .into_iter()
8413
            .map(|(_, op)| op.command)
8414
            .collect();
8415
        assert!(log.len() >= 3, "{log:?}");
8416
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8417
        let heads = repo
8418
            .store()
8419
            .get_state(&repo.view().unwrap().bookmarks["main"])
8420
            .unwrap()
8421
            .heads;
8422
        assert_eq!(heads, vec![h2]);
8423
        assert_eq!(
8424
            repo.load_state(&heads).unwrap().materialize().files.len(),
8425
            1
8426
        );
8427
    }
8428
8429
    // A second repository cannot start on the same store.
8430
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8431
        .err()
8432
        .unwrap()
8433
        .to_string();
8434
    assert!(
8435
        err.contains("already holds a repository's operation log"),
8436
        "{err}"
8437
    );
8438
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8439
        .err()
8440
        .unwrap()
8441
        .to_string();
8442
    assert!(err.contains("cannot open that kind of store"), "{err}");
8443
}
80677b7a Andy McCall ↶ 8444
8445
/// oxygen#75: the prompt's quick check agrees with status in a repository
8446
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8447
/// another state, clean again once that pin is committed. (It compared the
8448
/// subrepo's directory as if it were a file, so it was always dirty.)
8449
#[test]
8450
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8451
    hermetic();
8452
    let dir = tempfile::tempdir().unwrap();
8453
    let root = dir.path();
8454
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8455
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8456
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8457
        .unwrap()
8458
        .with_home(root.join("home"));
8459
    write(&root.join("lib"), "lib.txt", b"v1\n");
8460
    lib.commit("lib v1", &[]).unwrap();
8461
    assert!(lib.push("origin", false).unwrap()[0].ok);
8462
    let app_dir = root.join("app");
8463
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8464
    write(&app_dir, "main.txt", b"app\n");
8465
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8466
    app.commit("app with lib", &[]).unwrap();
8467
    // Out of the racy window, so the stat-only path decides.
8468
    std::thread::sleep(std::time::Duration::from_millis(2100));
8469
    let reopen = || Repo::open(&app_dir).unwrap();
8470
    assert_eq!(
8471
        reopen().quick_dirty().unwrap(),
8472
        Some(false),
8473
        "clean, as status says"
8474
    );
8475
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8476
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8477
    nested.commit("lib v2", &[]).unwrap();
8478
    assert_eq!(
8479
        reopen().quick_dirty().unwrap(),
8480
        Some(true),
8481
        "the subrepo moved"
8482
    );
8483
    reopen().commit("pin lib v2", &[]).unwrap();
8484
    std::thread::sleep(std::time::Duration::from_millis(2100));
8485
    assert_eq!(
8486
        reopen().quick_dirty().unwrap(),
8487
        Some(false),
8488
        "the new pin is committed"
8489
    );
8490
}
7993d465 Andy McCall ↶ 8491
8492
#[test]
8493
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8494
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8495
    hermetic();
8496
    let dir = tempfile::tempdir().unwrap();
8497
    let root = dir.path();
8498
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8499
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8500
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8501
        .unwrap()
8502
        .with_home(root.join("home"));
8503
    write(&root.join("lib"), "lib.txt", b"v1\n");
8504
    lib.commit("lib v1", &[]).unwrap();
8505
    assert!(lib.push("origin", false).unwrap()[0].ok);
8506
    let app_dir = root.join("app");
8507
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8508
    write(
8509
        &app_dir,
8510
        ".oxymodules",
8511
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8512
    );
8513
    let unpinned = app.unpinned_modules().unwrap();
8514
    assert_eq!(unpinned.len(), 1);
8515
    assert_eq!(unpinned[0].0, "libs/lib");
8516
    assert_eq!(unpinned[0].1.url, lib_url);
8517
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8518
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8519
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8520
}
bf3a6781 Andy McCall ↶ 8521
8522
#[test]
8523
fn the_bookmark_revset_function_names_only_bookmarks() {
8524
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8525
    hermetic();
8526
    let dir = tempfile::tempdir().unwrap();
8527
    let repo = Repo::init(dir.path()).unwrap();
8528
    write(dir.path(), "a.txt", b"a\n");
8529
    let a = repo.commit("A", &[]).unwrap();
8530
    write(dir.path(), "b.txt", b"b\n");
8531
    let b = repo.commit("B", &[]).unwrap();
8532
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8533
    heads.sort();
8534
    let mut want = repo.bookmark_heads().unwrap();
8535
    want.sort();
8536
    assert_eq!(heads, want);
8537
    assert!(heads.contains(&b));
8538
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8539
    // A change prefix is a symbol, not a bookmark.
8540
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8541
    assert!(repo.revset(&prefix).is_ok());
8542
    let e = repo
8543
        .revset(&format!("bookmark({prefix})"))
8544
        .unwrap_err()
8545
        .to_string();
8546
    assert!(e.contains("no such bookmark"), "{e}");
8547
}
72484195 Andy McCall ↶ 8548
8549
#[test]
8550
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8551
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8552
    // pinning the subrepo, and the nested repository on disk at that pin.
8553
    hermetic();
8554
    let dir = tempfile::tempdir().unwrap();
8555
    let root = dir.path();
8556
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8557
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8558
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8559
        .unwrap()
8560
        .with_home(root.join("home"));
8561
    write(&root.join("lib"), "lib.txt", b"v1\n");
8562
    lib.commit("lib v1", &[]).unwrap();
8563
    assert!(lib.push("origin", false).unwrap()[0].ok);
8564
    let app_dir = root.join("app");
8565
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8566
    write(&app_dir, "main.txt", b"app\n");
8567
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8568
    // The stale state: registered in .oxymodules, never pinned.
8569
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8570
    app.commit("initial", &[]).unwrap();
8571
    let stale = app.bookmark_heads().unwrap();
8572
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8573
    app.commit("pin lib", &[]).unwrap();
8574
    let newer = app.bookmark_heads().unwrap();
8575
    app.checkout(&stale, false, "test").unwrap();
8576
    write(&app_dir, "notes.txt", b"mine\n");
8577
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8578
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8579
    assert!(app_dir.join("notes.txt").exists());
8580
}
8581
8582
#[test]
8583
fn a_bookmark_only_behind_its_remote_catches_up() {
8584
    // oxygen#74: switch takes the remote's state rather than a stale one.
8585
    hermetic();
8586
    let dir = tempfile::tempdir().unwrap();
8587
    let root = dir.path();
8588
    let _origin = Repo::init(&root.join("origin")).unwrap();
8589
    let url = root.join("origin").to_string_lossy().to_string();
8590
    let one = Repo::clone(&url, &root.join("one"))
8591
        .unwrap()
8592
        .with_home(root.join("home"));
8593
    write(&root.join("one"), "a.txt", b"a\n");
8594
    one.commit("A", &[]).unwrap();
8595
    assert!(one.push("origin", false).unwrap()[0].ok);
8596
    let two = Repo::clone(&url, &root.join("two"))
8597
        .unwrap()
8598
        .with_home(root.join("home"));
8599
    write(&root.join("two"), "b.txt", b"b\n");
8600
    two.commit("B", &[]).unwrap();
8601
    assert!(two.push("origin", false).unwrap()[0].ok);
8602
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8603
    one.fetch("origin").unwrap();
8604
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8605
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8606
    // Local work the remote lacks: left alone.
8607
    write(&root.join("one"), "c.txt", b"c\n");
8608
    one.commit("C", &[]).unwrap();
8609
    write(&root.join("two"), "d.txt", b"d\n");
8610
    two.commit("D", &[]).unwrap();
8611
    assert!(two.push("origin", false).unwrap()[0].ok);
8612
    one.fetch("origin").unwrap();
8613
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8614
}
42ccf504 Andy McCall ↶ 8615
8616
#[test]
8617
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8618
    // oxygen#83: remotes earth and gcs, origin removed.
8619
    hermetic();
8620
    let dir = tempfile::tempdir().unwrap();
8621
    let root = dir.path();
8622
    let _up = Repo::init(&root.join("up")).unwrap();
8623
    let url = root.join("up").to_string_lossy().to_string();
8624
    let other = Repo::clone(&url, &root.join("other"))
8625
        .unwrap()
8626
        .with_home(root.join("home"));
8627
    write(&root.join("other"), "a.txt", b"a\n");
8628
    other.commit("a", &[]).unwrap();
8629
    assert!(other.push("origin", false).unwrap()[0].ok);
8630
    let mut one = Repo::clone(&url, &root.join("one"))
8631
        .unwrap()
8632
        .with_home(root.join("home"));
8633
    one.config.set("remote.earth.url", &url).unwrap();
8634
    one.config.set("remote.gcs.url", &url).unwrap();
8635
    one.config.set("remote.origin.url", "").unwrap();
8636
    one.save_config().unwrap();
8637
    write(&root.join("other"), "b.txt", b"b\n");
8638
    other.commit("b", &[]).unwrap();
8639
    assert!(other.push("origin", false).unwrap()[0].ok);
8640
    one.fetch("earth").unwrap();
8641
    let b = one
8642
        .bookmarks()
8643
        .unwrap()
8644
        .into_iter()
8645
        .find(|b| b.name == "main")
8646
        .unwrap();
8647
    assert_eq!(
8648
        (b.remote.as_deref(), b.behind),
8649
        (Some("earth"), Some(1)),
8650
        "a stale origin copy is not used"
8651
    );
8652
    assert_eq!(
8653
        one.default_remote(),
8654
        "origin",
8655
        "no default chosen among several"
8656
    );
8657
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8658
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8659
    one.config.set("core.remote", "earth").unwrap();
8660
    assert_eq!(one.default_remote(), "earth");
8661
}
cbe8499a Andy McCall ↶ 8662
8663
#[test]
8664
fn a_missing_author_identity_says_how_to_fix_it() {
8665
    // oxygen#82: an agent home's author.key naming an identity the
8666
    // repository does not hold.
8667
    hermetic();
8668
    let dir = tempfile::tempdir().unwrap();
8669
    let mut repo = Repo::init(dir.path()).unwrap();
8670
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8671
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8672
    let e = repo.identity(&missing).unwrap_err().to_string();
8673
    assert!(
8674
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8675
        "{e}"
8676
    );
8677
    assert!(e.contains("this repository's config"), "{e}");
8678
}
f6dccc45 Andy McCall ↶ 8679
8680
#[test]
8681
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8682
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8683
    // the working copy, a pull with nothing new left it there, and status
8684
    // said "clean".
8685
    hermetic();
8686
    let dir = tempfile::tempdir().unwrap();
8687
    let root = dir.path();
8688
    let _up = Repo::init(&root.join("up")).unwrap();
8689
    let url = root.join("up").to_string_lossy().to_string();
8690
    let other = Repo::clone(&url, &root.join("other"))
8691
        .unwrap()
8692
        .with_home(root.join("home"));
8693
    write(&root.join("other"), "a.txt", b"a\n");
8694
    other.commit("a", &[]).unwrap();
8695
    assert!(other.push("origin", false).unwrap()[0].ok);
8696
    let one = Repo::clone(&url, &root.join("one"))
8697
        .unwrap()
8698
        .with_home(root.join("home"));
8699
    write(&root.join("other"), "b.txt", b"b\n");
8700
    other.commit("b", &[]).unwrap();
8701
    assert!(other.push("origin", false).unwrap()[0].ok);
8702
    one.fetch("origin").unwrap();
8703
    // The bookmark moves; the working copy does not.
8704
    let theirs = one.resolve_heads("origin/main").unwrap();
8705
    one.bookmark_set("main", &theirs).unwrap();
8706
    assert!(!root.join("one/b.txt").exists());
8707
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8708
    let r = one.pull("origin").unwrap();
8709
    assert!(
8710
        !r.changed && r.checked_out,
8711
        "nothing new, but the working copy caught up"
8712
    );
8713
    assert!(root.join("one/b.txt").exists());
8714
    assert_eq!(one.working_copy_behind().unwrap(), None);
8715
}
170bb436 Andy McCall ↶ 8716
8717
#[test]
8718
fn touched_nodes_cache_answers_as_the_changes_do() {
8719
    hermetic();
8720
    let dir = tempfile::tempdir().unwrap();
8721
    let repo = Repo::init(dir.path()).unwrap();
8722
    write(dir.path(), "a.txt", b"one\n");
8723
    write(dir.path(), "b.txt", b"x\n");
8724
    repo.snapshot("t").unwrap();
8725
    let c1 = repo.commit("first", &[]).unwrap();
8726
    write(dir.path(), "b.txt", b"y\n");
8727
    repo.snapshot("t").unwrap();
8728
    repo.commit("b only", &[]).unwrap();
8729
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8730
    write(dir.path(), "c.txt", b"one\ntwo\n");
8731
    repo.snapshot("t").unwrap();
8732
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8733
    // Uncommitted work, so the working copy touches a file too.
8734
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8735
    repo.snapshot("t").unwrap();
8736
8737
    let path = dir.path().join(".oxy/index/touched");
8738
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8739
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8740
    assert!(path.exists(), "the first query writes the cache");
8741
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8742
    assert_eq!(cold, warm, "the cache answers as the changes do");
8743
    let (wc, _) = repo.working_copy().unwrap();
8744
    assert_eq!(
8745
        cold,
8746
        vec![wc, c3, c1],
8747
        "renames followed, the working copy included"
8748
    );
8749
8750
    // Working-copy changes are not kept: they are replaced by every snapshot.
8751
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8752
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8753
    assert!(cached.contains(&c1) && cached.contains(&c3));
8754
8755
    // A damaged cache is ignored, not trusted.
8756
    let mut bytes = fs::read(&path).unwrap();
8757
    let last = bytes.len() - 40;
8758
    bytes[last] ^= 1;
8759
    fs::write(&path, &bytes).unwrap();
8760
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8761
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8762
    assert_eq!(hashes(touches), vec![c3, c1]);
8763
}
e8e6e0ca Andy McCall ↶ 8764
8765
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8766
/// file back where it was leave two placements at one place, which the
8767
/// tree shows as one file. Removing it, and then its directory, retires
8768
/// both, so no copy is left under a directory that is gone.
8769
#[test]
8770
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8771
    hermetic();
8772
    if std::process::Command::new("git")
8773
        .arg("--version")
8774
        .output()
8775
        .is_err()
8776
    {
8777
        eprintln!("git not installed; skipping");
8778
        return;
8779
    }
8780
    let dir = tempfile::tempdir().unwrap();
8781
    let root = dir.path();
8782
    let g = root.join("src.git");
8783
    fs::create_dir_all(&g).unwrap();
8784
    let git = |args: &[&str]| {
8785
        let out = std::process::Command::new("git")
8786
            .arg("-C")
8787
            .arg(&g)
8788
            .args([
8789
                "-c",
8790
                "user.name=Grace",
8791
                "-c",
8792
                "[email protected]",
8793
                "-c",
8794
                "commit.gpgsign=false",
8795
            ])
8796
            .args(args)
8797
            .output()
8798
            .unwrap();
8799
        assert!(
8800
            out.status.success(),
8801
            "git {args:?}: {}",
8802
            String::from_utf8_lossy(&out.stderr)
8803
        );
8804
    };
8805
    git(&["init", "-q", "-b", "main"]);
8806
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8807
    write(&g, "keep.txt", b"k\n");
8808
    git(&["add", "."]);
8809
    git(&["commit", "-qm", "base"]);
8810
    fs::create_dir_all(g.join("d/sub")).unwrap();
8811
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8812
    git(&["commit", "-qm", "into sub"]);
8813
    git(&["checkout", "-qb", "side"]);
8814
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8815
    git(&["commit", "-qm", "back, on side"]);
8816
    git(&["checkout", "-q", "main"]);
8817
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8818
    git(&["commit", "-qm", "back, on main"]);
8819
    git(&["merge", "-q", "--no-edit", "side"]);
8820
    git(&["rm", "-rq", "d"]);
8821
    git(&["commit", "-qm", "d goes"]);
8822
8823
    let repo = Repo::init(&root.join("o")).unwrap();
8824
    repo.import_git(&g, "main").unwrap();
8825
    let v = repo.verify_git_import(&g, "main").unwrap();
8826
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8827
    let st = repo
8828
        .load_state_history(&repo.bookmark_heads().unwrap())
8829
        .unwrap();
8830
    let view = st.tree().view();
8831
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8832
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8833
}
5552e69c Andy McCall ↶ 8834
8835
/// oxygen#94: a state index's file histories are read, and checked by
8836
/// their own hashes, only when a file is built. One found damaged is an
8837
/// error that says so, the index is removed, and the next read rebuilds it.
8838
#[test]
8839
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8840
    hermetic();
8841
    let dir = tempfile::tempdir().unwrap();
8842
    let repo = Repo::init(dir.path()).unwrap();
8843
    for i in 0..6 {
8844
        write(
8845
            dir.path(),
8846
            &format!("f{i}.txt"),
8847
            format!("one {i}\n").as_bytes(),
8848
        );
8849
    }
8850
    repo.snapshot("t").unwrap();
8851
    repo.commit("first", &[]).unwrap();
8852
    for i in 0..6 {
8853
        write(
8854
            dir.path(),
8855
            &format!("f{i}.txt"),
8856
            format!("one {i}\ntwo\n").as_bytes(),
8857
        );
8858
    }
8859
    repo.snapshot("t").unwrap();
8860
    repo.commit("second", &[]).unwrap();
8861
    let want: Vec<Vec<u8>> = (0..6)
8862
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8863
        .collect();
8864
    // The index of the working copy's base, holding every file's history
8865
    // (a few changes behind, an index is replayed onto, not rewritten).
8866
    let (_, wc) = repo.working_copy().unwrap();
8867
    let base = repo.load_state_history(&wc.deps).unwrap();
8868
    repo.write_state_index(&wc.deps, &base);
8869
    for (i, w) in want.iter().enumerate() {
8870
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8871
    }
8872
    let index = repo.state_indexes();
8873
    assert!(!index.is_empty(), "a state index was written");
8874
    // The histories are last in the file: damage the last of them.
8875
    let mut bytes = fs::read(&index[0]).unwrap();
8876
    let last = bytes.len() - 1;
8877
    bytes[last] ^= 0x40;
8878
    fs::write(&index[0], &bytes).unwrap();
8879
8880
    let reads: Vec<_> = (0..6)
8881
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8882
        .collect();
8883
    let damaged: Vec<String> = reads
8884
        .iter()
8885
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8886
        .collect();
8887
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8888
    assert!(
8889
        damaged[0].contains("state index was damaged")
8890
            && damaged[0].contains("run the command again"),
8891
        "{}",
8892
        damaged[0]
8893
    );
8894
    // Every file reads right again, from an index rebuilt from history.
8895
    for (i, w) in want.iter().enumerate() {
8896
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8897
    }
8898
}
cb8b8082 Andy McCall ↶ 8899
8900
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8901
/// objects alone and in dependency order, and the last moves the bookmark.
8902
/// The remote ends with every change and the same state, and says how each
8903
/// part went.
8904
#[test]
8905
fn a_long_push_goes_in_parts() {
8906
    hermetic();
8907
    let dir = tempfile::tempdir().unwrap();
8908
    let root = dir.path();
8909
    let origin = root.join("origin");
8910
    Repo::init_bare_unbound(&origin).unwrap();
8911
    let main = root.join("main");
8912
    let mut repo = Repo::init(&main).unwrap();
8913
    repo.config
8914
        .set("remote.origin.url", &origin.to_string_lossy())
8915
        .unwrap();
8916
    // One byte: every change is a part of its own.
8917
    repo.config.set("push.batch-bytes", "1").unwrap();
8918
    repo.save_config().unwrap();
8919
    for i in 0..6 {
8920
        write(
8921
            &main,
8922
            &format!("f{i}.txt"),
8923
            format!("file {i}\n").as_bytes(),
8924
        );
8925
        repo.commit(&format!("c{i}"), &[]).unwrap();
8926
    }
8927
    let mut parts = Vec::new();
8928
    let results = repo
8929
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8930
        .unwrap();
8931
    assert!(
8932
        results.iter().any(|r| r.ok && r.name == "main"),
8933
        "{results:?}"
8934
    );
8935
    assert_eq!(parts.len(), 6, "{parts:?}");
8936
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8937
8938
    let remote = Repo::open(&origin).unwrap();
8939
    let heads = repo.bookmark_heads().unwrap();
8940
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8941
    assert_eq!(
8942
        remote.log_state(&heads).unwrap().len(),
8943
        repo.log_state(&heads).unwrap().len()
8944
    );
8945
    // A push of objects alone reports how it went, as `objects`.
8946
    let got = remote
8947
        .receive_push(Bundle::default(), vec![], None, vec![])
8948
        .unwrap();
8949
    assert_eq!(got.len(), 1);
8950
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8951
}
d6e0d5b8 Andy McCall ↶ 8952
8953
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8954
/// own commits (Git author email = its email, any case) with its key, and
8955
/// leaves anyone else's with the zero key; the history verifies as before.
8956
#[test]
8957
fn git_import_claims_your_own_commits() {
8958
    hermetic();
8959
    if std::process::Command::new("git")
8960
        .arg("--version")
8961
        .output()
8962
        .is_err()
8963
    {
8964
        eprintln!("git not installed; skipping");
8965
        return;
8966
    }
8967
    let dir = tempfile::tempdir().unwrap();
8968
    let root = dir.path();
8969
    let g = root.join("src.git");
8970
    fs::create_dir_all(&g).unwrap();
8971
    let git = |who: &str, args: &[&str]| {
8972
        let (name, email) = who.split_once(' ').unwrap();
8973
        let out = std::process::Command::new("git")
8974
            .arg("-C")
8975
            .arg(&g)
8976
            .args([
8977
                "-c",
8978
                &format!("user.name={name}"),
8979
                "-c",
8980
                &format!("user.email={email}"),
8981
                "-c",
8982
                "commit.gpgsign=false",
8983
            ])
8984
            .args(args)
8985
            .output()
8986
            .unwrap();
8987
        assert!(
8988
            out.status.success(),
8989
            "git {args:?}: {}",
8990
            String::from_utf8_lossy(&out.stderr)
8991
        );
8992
    };
8993
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8994
    write(&g, "a.txt", b"a\n");
8995
    git("Grace [email protected]", &["add", "."]);
8996
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8997
    write(&g, "b.txt", b"b\n");
8998
    git("Ada [email protected]", &["add", "."]);
8999
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
9000
9001
    let mut repo = Repo::init(&root.join("o")).unwrap();
9002
    let (key, _) = repo
9003
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
9004
        .unwrap();
9005
    repo.config.set("git.claim", "true").unwrap();
9006
    repo.save_config().unwrap();
9007
    let repo = Repo::open(&root.join("o")).unwrap();
9008
    repo.import_git(&g, "main").unwrap();
9009
    let v = repo.verify_git_import(&g, "main").unwrap();
9010
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9011
    let heads = repo.bookmark_heads().unwrap();
9012
    let by_message: std::collections::HashMap<String, KeyId> = repo
9013
        .log_state(&heads)
9014
        .unwrap()
9015
        .into_iter()
9016
        .map(|e| {
9017
            (
9018
                e.change.message.lines().next().unwrap_or("").to_string(),
9019
                e.change.author,
9020
            )
9021
        })
9022
        .collect();
9023
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
9024
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
9025
}
34fad4a9 Andy McCall ↶ 9026
9027
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
9028
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
9029
#[test]
9030
fn removing_a_remote_leaves_nothing_of_it() {
9031
    hermetic();
9032
    let dir = tempfile::tempdir().unwrap();
9033
    let origin = dir.path().join("origin");
9034
    Repo::init_bare_unbound(&origin).unwrap();
9035
    let main = dir.path().join("main");
9036
    let mut repo = Repo::init(&main).unwrap();
9037
    repo.config
9038
        .set("remote.origin.url", &origin.to_string_lossy())
9039
        .unwrap();
9040
    repo.config
9041
        .set("remote.origin.token", "secret-ish")
9042
        .unwrap();
9043
    repo.config
9044
        .set("remote.keep.url", &origin.to_string_lossy())
9045
        .unwrap();
9046
    repo.save_config().unwrap();
9047
    write(&main, "a.txt", b"a\n");
9048
    repo.commit("a", &[]).unwrap();
9049
    assert!(repo.push("origin", false).unwrap()[0].ok);
9050
    assert!(
9051
        repo.view().unwrap().remotes.contains_key("origin"),
9052
        "a tracking bookmark"
9053
    );
9054
9055
    repo.remove_remote("origin").unwrap();
9056
    let again = Repo::open(&main).unwrap();
9057
    assert!(
9058
        !again
9059
            .config
9060
            .repo_layer()
9061
            .keys()
9062
            .any(|k| k.starts_with("remote.origin.")),
9063
        "{:?}",
9064
        again.config.repo_layer()
9065
    );
9066
    assert!(!again.config.remotes.contains_key("origin"));
9067
    assert!(
9068
        !again.view().unwrap().remotes.contains_key("origin"),
9069
        "its tracking bookmarks go"
9070
    );
9071
    assert!(
9072
        again.config.remotes.contains_key("keep"),
9073
        "another remote stays"
9074
    );
9075
    let mut again = again;
9076
    assert!(
9077
        again.remove_remote("origin").is_err(),
9078
        "a second removal is refused"
9079
    );
9080
}
9d580f21 Andy McCall ↶ 9081
9082
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
9083
/// unreachable from history, so gc prunes it, unless the host names it:
9084
/// then it and its chunks stay, and it reads back whole.
9085
#[test]
9086
fn gc_keeps_the_blobs_a_host_names() {
9087
    hermetic();
9088
    let dir = tempfile::tempdir().unwrap();
9089
    let repo = Repo::init(dir.path()).unwrap();
9090
    write(dir.path(), "a.txt", b"a\n");
9091
    repo.commit("a", &[]).unwrap();
9092
    // Large enough to be several chunks.
9093
    let body: Vec<u8> = (0..400_000u32)
9094
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
9095
        .collect();
9096
    let kept = repo.store_blob(&body).unwrap();
9097
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
9098
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
9099
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
9100
    assert!(!repo.store().has(&lost), "not named: pruned");
9101
    repo.gc(true).unwrap();
9102
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
9103
}
530a0fc6 Andy McCall ↶ 9104
9105
/// oxygen#99: undo in one workspace undoes that workspace's last command,
9106
/// never another workspace's, says what it undid, and goes further back
9107
/// when run again.
9108
#[test]
9109
fn undo_is_scoped_to_its_workspace() {
9110
    hermetic();
9111
    let dir = tempfile::tempdir().unwrap();
9112
    let root = dir.path().join("main");
9113
    let a = Repo::init(&root).unwrap();
9114
    write(&root, "base.txt", b"base\n");
9115
    let base = a.commit("base", &[]).unwrap();
9116
    a.bookmark_create("feature", None).unwrap();
9117
    let ws_dir = dir.path().join("ws");
9118
    let heads = a.resolve_heads("feature").unwrap();
9119
    let b = a
9120
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
9121
        .unwrap();
9122
9123
    // A commits on main, then B commits on feature: B's is the newest.
9124
    write(&root, "a.txt", b"a\n");
9125
    let ca = a.commit("from a", &[]).unwrap();
9126
    write(&ws_dir, "b.txt", b"b\n");
9127
    let cb = b.commit("from b", &[]).unwrap();
9128
9129
    // A's undo undoes A's commit and leaves B's.
9130
    let u = a.undo().unwrap();
9131
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9132
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
9133
    assert!(!u.changes.is_empty());
9134
    let view = a.view().unwrap();
9135
    // (Independent changes commute, so a bookmark's heads may hold base too.)
9136
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
9137
    assert!(
9138
        a.heads_of(&view, "feature").unwrap().contains(&cb),
9139
        "B's commit stands"
9140
    );
9141
    assert!(
9142
        a.store().get_change(&ca).is_ok(),
9143
        "the change itself is still in the store"
9144
    );
9145
    // A's working copy was clean, so its files followed; B's are untouched.
9146
    assert!(!root.join("a.txt").exists());
9147
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
9148
    assert!(ws_dir.join("b.txt").exists());
9149
9150
    // B's undo still finds B's own commit, under A's undo.
9151
    let u = b.undo().unwrap();
9152
    assert_eq!(u.command, "oxy commit -m \"from b\"");
9153
    assert!(!b
9154
        .heads_of(&b.view().unwrap(), "feature")
9155
        .unwrap()
9156
        .contains(&cb));
9157
    assert_eq!(
9158
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
9159
        vec![base],
9160
        "A's undo stands"
9161
    );
9162
9163
    // A's next undo goes past the commit it already undid, to adding B's
9164
    // workspace: refused, since B has worked there since.
9165
    let e = a.undo().unwrap_err().to_string();
9166
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
9167
}
9168
9169
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
9170
/// own commit's head, and the other workspace's head stays.
9171
#[test]
9172
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
9173
    hermetic();
9174
    let dir = tempfile::tempdir().unwrap();
9175
    let root = dir.path().join("main");
9176
    let a = Repo::init(&root).unwrap();
9177
    write(&root, "base.txt", b"base\n");
9178
    a.commit("base", &[]).unwrap();
9179
    let ws_dir = dir.path().join("ws");
9180
    let b = a.workspace_add(&ws_dir, None).unwrap();
9181
    write(&root, "a.txt", b"a\n");
9182
    let ca = a.commit("from a", &[]).unwrap();
9183
    write(&ws_dir, "b.txt", b"b\n");
9184
    let cb = b.commit("from b", &[]).unwrap();
9185
    let u = a.undo().unwrap();
9186
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9187
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
9188
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
9189
}
9190
9191
/// oxygen#99: an undo that would also take back what another workspace
9192
/// did since to the same bookmark is refused, naming it.
9193
#[test]
9194
fn undo_refuses_to_take_back_another_workspaces_work() {
9195
    hermetic();
9196
    let dir = tempfile::tempdir().unwrap();
9197
    let root = dir.path().join("main");
9198
    let a = Repo::init(&root).unwrap();
9199
    write(&root, "base.txt", b"base\n");
9200
    a.commit("base", &[]).unwrap();
9201
    let ws_dir = dir.path().join("ws");
9202
    let b = a.workspace_add(&ws_dir, None).unwrap();
9203
    // Both on main: A commits, then B builds on it, editing A's file.
9204
    write(&root, "a.txt", b"a\n");
9205
    a.commit("from a", &[]).unwrap();
9206
    let heads = b.resolve_heads("main").unwrap();
9207
    b.checkout(&heads, false, "oxy checkout").unwrap();
9208
    write(&ws_dir, "a.txt", b"a, then b\n");
9209
    b.commit("from b", &[]).unwrap();
9210
    let e = a.undo().unwrap_err().to_string();
9211
    assert!(
9212
        e.contains("bookmark main") && e.contains("builds on"),
9213
        "{e}"
9214
    );
9215
    assert!(e.contains("oxy op restore"), "{e}");
9216
}
9217
9218
/// oxygen#99: undoing a commit that was already pushed says so: the remote
9219
/// still has it.
9220
#[test]
9221
fn undo_says_when_the_commit_was_pushed() {
9222
    hermetic();
9223
    let dir = tempfile::tempdir().unwrap();
9224
    let root = dir.path();
9225
    Repo::init(&root.join("origin")).unwrap();
9226
    let url = root.join("origin").to_string_lossy().to_string();
9227
    let repo = Repo::clone(&url, &root.join("work"))
9228
        .unwrap()
9229
        .with_home(root.join("home"));
9230
    write(&root.join("work"), "a.txt", b"a\n");
9231
    repo.commit("a", &[]).unwrap();
9232
    assert!(repo.push("origin", false).unwrap()[0].ok);
9233
    // The push itself is passed over: the remote keeps what it was sent.
9234
    let u = repo.undo().unwrap();
9235
    assert_eq!(u.command, "oxy commit -m \"a\"");
9236
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
9237
}