OXYGENHUB
# 4476cdbb0443 oxygen / crates / oxy-core / src / repo / tests.rs
374.6 KiB · Rust · last changed A big tree renders many times faster, and is not rendered twice (refs #137) 12 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,
9b723f69 Andy McCall ↶ 435
            removed_paths: vec!["bin.dat".into()],
75167672 Andy McCall 436
            conflicted: false,
d3cd7ef9 Andy McCall ↶ 437
            notes: vec![],
438
            lacks: 1,
75167672 Andy McCall 439
        }
440
    );
98286406 Andy McCall ↶ 441
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
442
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
443
    assert!(!root.join("bin.dat").exists());
444
    let (_, wc) = repo.working_copy().unwrap();
445
    assert_eq!(wc.deps, vec![h1]);
75167672 Andy McCall 446
    assert!(
447
        !repo.snapshot("status").unwrap().changed,
448
        "checkout leaves a clean working copy"
449
    );
98286406 Andy McCall ↶ 450
    // The bookmark still points at h2.
451
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
452
453
    // Dirty working copy refuses without --discard.
454
    write(root, "a.txt", b"dirty\n");
455
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
75167672 Andy McCall 456
    let r = repo
457
        .checkout(&[h2], true, "oxy checkout --discard")
458
        .unwrap();
98286406 Andy McCall ↶ 459
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
460
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
461
    assert!(!root.join("sub").exists(), "empty directories are pruned");
462
    assert_eq!(r.removed, 1);
463
    assert!(!repo.snapshot("status").unwrap().changed);
464
465
    // Refuses to write through a symlinked directory.
466
    #[cfg(unix)]
467
    {
468
        fs::remove_dir_all(root.join("sub")).ok();
469
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
470
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
471
    }
472
}
473
474
#[test]
475
fn large_files_are_chunked_and_read_back() {
476
    hermetic();
477
    let dir = tempfile::tempdir().unwrap();
478
    let repo = Repo::init(dir.path()).unwrap();
479
    let mut big = vec![0u8; 700 * 1024];
480
    for (i, b) in big.iter_mut().enumerate() {
481
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
482
    }
483
    let r = repo.store_blob(&big).unwrap();
484
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
485
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
486
    assert_eq!(repo.read_blob(&r).unwrap(), big);
487
    assert_eq!(Repo::blob_ref(&big), r);
488
}
489
490
#[test]
491
fn clone_push_pull_with_seals_and_attestations() {
492
    hermetic();
493
    let dir = tempfile::tempdir().unwrap();
494
    let root = dir.path();
495
    let origin_path = root.join("origin");
496
    let origin = Repo::init(&origin_path).unwrap();
497
    let origin_url = origin_path.to_string_lossy().to_string();
498
499
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
75167672 Andy McCall 500
    let mut a = Repo::clone(&origin_url, &root.join("a"))
501
        .unwrap()
502
        .with_home(root.join("home-a"));
98286406 Andy McCall ↶ 503
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
75167672 Andy McCall 504
    let (key_a, _) = a
505
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
506
        .unwrap();
98286406 Andy McCall ↶ 507
    write(&root.join("a"), "f.txt", b"a\n");
508
    let h1 = a.commit("first", &[]).unwrap();
509
    let results = a.push("origin", false).unwrap();
767ac6cd Andy McCall 510
    origin.refresh().unwrap();
98286406 Andy McCall ↶ 511
    assert!(results[0].ok, "{}", results[0].reason);
512
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
513
    // The change was sealed at push and the reference attested.
75167672 Andy McCall 514
    assert!(
515
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
516
    );
517
    assert_eq!(
518
        origin.verify_change(&h1).unwrap(),
519
        SignatureStatus::Unsigned
520
    );
f8c69576 Andy McCall ↶ 521
    let serial_of = |att: &SignedAttest| match att.attest.body {
522
        AttestBody::Ref { serial, .. } => serial,
523
        _ => unreachable!(),
524
    };
98286406 Andy McCall ↶ 525
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 526
    // A bookmark new to the remote starts at the clock (past any deleted
527
    // namesake's serial); later updates count up from there.
528
    let first = serial_of(&att);
529
    assert!(first > 1_000_000_000_000, "{first}");
98286406 Andy McCall ↶ 530
    let again = a.push("origin", false).unwrap();
767ac6cd Andy McCall 531
    origin.refresh().unwrap();
98286406 Andy McCall ↶ 532
    assert!(again[0].ok && again[0].reason.contains("up to date"));
533
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 534
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
98286406 Andy McCall ↶ 535
536
    // B clones and sees the file and the seal.
537
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
538
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
539
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
75167672 Andy McCall 540
    assert!(matches!(
541
        b.authenticate_change(&h1).unwrap(),
542
        SignatureStatus::Valid { sealed: true, .. }
543
    ));
98286406 Andy McCall ↶ 544
545
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
546
    write(&root.join("b"), "f.txt", b"a\nb\n");
547
    let h2 = b.commit("second", &[]).unwrap();
548
    assert!(b.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 549
    origin.refresh().unwrap();
98286406 Andy McCall ↶ 550
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
551
552
    // A commits an independent change; push is refused until A pulls.
553
    write(&root.join("a"), "g.txt", b"g\n");
554
    let h3 = a.commit("third", &[]).unwrap();
555
    assert!(a.push("origin", false).is_err());
556
    let pr = a.pull("origin").unwrap();
557
    assert!(pr.changed && pr.checked_out);
558
    let mut want = vec![h2, h3];
559
    want.sort();
560
    assert_eq!(pr.heads, want);
561
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
562
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
563
    let results = a.push("origin", false).unwrap();
767ac6cd Andy McCall 564
    origin.refresh().unwrap();
98286406 Andy McCall ↶ 565
    assert!(results[0].ok, "{}", results[0].reason);
566
    let mut origin_heads = origin.bookmark_heads().unwrap();
567
    origin_heads.sort();
568
    assert_eq!(origin_heads, want);
569
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 570
    assert_eq!(serial_of(&att), first + 1);
98286406 Andy McCall ↶ 571
572
    // B pulls and ends up identical.
573
    let pr = b.pull("origin").unwrap();
574
    assert_eq!(pr.heads, want);
575
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
576
    assert!(!b.snapshot("status").unwrap().changed);
577
578
    // Concurrent edits of the same line: the union is a reified conflict.
579
    write(&root.join("a"), "f.txt", b"a\nA\n");
580
    a.commit("a-edit", &[]).unwrap();
581
    a.push("origin", false).unwrap();
767ac6cd Andy McCall 582
    origin.refresh().unwrap();
98286406 Andy McCall ↶ 583
    write(&root.join("b"), "f.txt", b"a\nB\n");
584
    b.commit("b-edit", &[]).unwrap();
585
    let pr = b.pull("origin").unwrap();
586
    assert!(pr.changed && pr.checked_out);
587
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
588
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
589
    write(&root.join("b"), "f.txt", b"a\nAB\n");
590
    let hr = b.commit("resolve", &[]).unwrap();
75167672 Andy McCall 591
    assert_eq!(
592
        b.store().get_change(&hr).unwrap().kind,
593
        ChangeKind::Resolution
594
    );
98286406 Andy McCall ↶ 595
    assert!(b.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 596
    origin.refresh().unwrap();
98286406 Andy McCall ↶ 597
    a.pull("origin").unwrap();
598
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
599
    // The resolution depends on the conflicting edits, but nothing depends
600
    // on "third" (it only added g.txt), so it stays a head beside it.
601
    let mut want = vec![hr, h3];
602
    want.sort();
603
    assert_eq!(a.bookmark_heads().unwrap(), want);
604
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
605
}
606
607
#[test]
608
fn receive_push_rejects_bad_updates() {
609
    hermetic();
610
    let dir = tempfile::tempdir().unwrap();
611
    let root = dir.path();
612
    let origin = Repo::init(&root.join("origin")).unwrap();
613
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 614
    let mut a = Repo::clone(&url, &root.join("a"))
615
        .unwrap()
616
        .with_home(root.join("home"));
617
    let (key, _) = a
618
        .create_identity("Ada", "a@b", IdentityScope::Repo)
619
        .unwrap();
98286406 Andy McCall ↶ 620
    write(&root.join("a"), "f.txt", b"x\n");
621
    let h1 = a.commit("one", &[]).unwrap();
622
    assert!(a.push("origin", false).unwrap()[0].ok);
623
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
75167672 Andy McCall 624
    let s1 = origin
625
        .store()
626
        .put_state(&StateObject::new(vec![h1]))
627
        .unwrap();
98286406 Andy McCall ↶ 628
629
    // Missing head.
75167672 Andy McCall 630
    let ghost = origin
631
        .store()
632
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
633
        .unwrap();
634
    let r = origin
635
        .receive_push(
636
            Bundle::default(),
637
            vec![RefUpdate {
638
                name: "main".into(),
639
                old_state: s1,
640
                new_state: ghost,
641
                force: false,
642
                attestation: None,
643
            }],
644
            None,
645
            vec![],
646
        )
647
        .unwrap();
648
    assert!(
649
        !r[0].ok && r[0].reason.contains("missing"),
650
        "{}",
651
        r[0].reason
652
    );
98286406 Andy McCall ↶ 653
654
    // Stale old_state.
75167672 Andy McCall 655
    let r = origin
656
        .receive_push(
657
            Bundle::default(),
658
            vec![RefUpdate {
659
                name: "main".into(),
660
                old_state: empty,
661
                new_state: s1,
662
                force: false,
663
                attestation: None,
664
            }],
665
            None,
666
            vec![],
667
        )
668
        .unwrap();
98286406 Andy McCall ↶ 669
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
670
671
    // Non-fast-forward without force is refused; with force it passes.
75167672 Andy McCall 672
    let r = origin
673
        .receive_push(
674
            Bundle::default(),
675
            vec![RefUpdate {
676
                name: "main".into(),
677
                old_state: s1,
678
                new_state: empty,
679
                force: false,
680
                attestation: None,
681
            }],
682
            None,
683
            vec![],
684
        )
685
        .unwrap();
686
    assert!(
687
        !r[0].ok && r[0].reason.contains("fast-forward"),
688
        "{}",
689
        r[0].reason
690
    );
691
    let r = origin
692
        .receive_push(
693
            Bundle::default(),
694
            vec![RefUpdate {
695
                name: "main".into(),
696
                old_state: s1,
697
                new_state: empty,
698
                force: true,
699
                attestation: None,
700
            }],
701
            None,
702
            vec![],
703
        )
704
        .unwrap();
98286406 Andy McCall ↶ 705
    assert!(r[0].ok);
706
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
707
708
    // Attestation with a stale serial is a rollback and is refused.
75167672 Andy McCall 709
    let sa = a
710
        .sign_attest(&Attest {
711
            repo: a.id().unwrap(),
712
            hlc: Hlc::now(),
713
            body: AttestBody::Ref {
714
                name: "main".into(),
715
                old_state: empty,
716
                new_state: s1,
717
                serial: 1,
718
            },
719
        })
720
        .unwrap();
721
    let r = origin
722
        .receive_push(
723
            Bundle::default(),
724
            vec![RefUpdate {
725
                name: "main".into(),
726
                old_state: empty,
727
                new_state: s1,
728
                force: false,
729
                attestation: Some(sa.clone()),
730
            }],
731
            None,
732
            vec![],
733
        )
734
        .unwrap();
735
    assert!(
736
        !r[0].ok && r[0].reason.contains("serial"),
737
        "{}",
738
        r[0].reason
739
    );
98286406 Andy McCall ↶ 740
    // An attestation for a different update is refused too.
75167672 Andy McCall 741
    let sa2 = a
742
        .sign_attest(&Attest {
743
            repo: a.id().unwrap(),
744
            hlc: Hlc::now(),
745
            body: AttestBody::Ref {
746
                name: "main".into(),
747
                old_state: s1,
748
                new_state: empty,
749
                serial: 5,
750
            },
751
        })
752
        .unwrap();
753
    let r = origin
754
        .receive_push(
755
            Bundle::default(),
756
            vec![RefUpdate {
757
                name: "main".into(),
758
                old_state: empty,
759
                new_state: s1,
760
                force: false,
761
                attestation: Some(sa2),
762
            }],
763
            None,
764
            vec![],
765
        )
766
        .unwrap();
767
    assert!(
768
        !r[0].ok && r[0].reason.contains("describe"),
769
        "{}",
770
        r[0].reason
771
    );
98286406 Andy McCall ↶ 772
    let _ = key;
773
}
774
775
#[test]
776
fn user_config_supplies_defaults_and_clones_sign() {
777
    hermetic();
778
    let dir = tempfile::tempdir().unwrap();
779
    let root = dir.path();
780
    let home = root.join("home");
781
    let origin = Repo::init(&root.join("origin")).unwrap();
782
    let url = root.join("origin").to_string_lossy().to_string();
783
784
    // Identity at user scope: the repository file stays free of author keys.
785
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
75167672 Andy McCall 786
    let (key, _) = a
787
        .create_identity("Ada", "[email protected]", IdentityScope::User)
788
        .unwrap();
98286406 Andy McCall ↶ 789
    assert!(!a.config.repo_layer().contains_key("author.key"));
790
    assert_eq!(a.config.author_key, Some(key));
791
    assert!(home.join("config.toml").exists());
792
    a.set_user_config("core.sign", "change").unwrap();
793
    assert!(a.config.sign_changes);
794
795
    // Repository settings override user settings and are the only ones saved.
796
    a.config.set("core.sign", "seal").unwrap();
797
    a.save_config().unwrap();
798
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
799
    assert!(!again.config.sign_changes);
800
    assert_eq!(again.config.author_key, Some(key));
75167672 Andy McCall 801
    assert_eq!(
802
        read_config_file(&root.join("a/.oxy/config"))
803
            .unwrap()
804
            .get("core.sign")
805
            .map(String::as_str),
806
        Some("seal")
807
    );
98286406 Andy McCall ↶ 808
809
    // A fresh clone made by this user signs with the user-level identity,
810
    // even though the clone's store has never seen the identity object.
811
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
812
    assert!(b.config.sign_changes);
813
    write(&root.join("b"), "f.txt", b"f\n");
814
    let h = b.commit("signed from a clone", &[]).unwrap();
75167672 Andy McCall 815
    assert!(
816
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
817
    );
98286406 Andy McCall ↶ 818
    assert!(b.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 819
    assert!(matches!(
820
        origin.verify_change(&h).unwrap(),
821
        SignatureStatus::Valid { .. }
822
    ));
98286406 Andy McCall ↶ 823
}
824
825
#[test]
826
fn format1_repositories_are_migrated_on_open() {
827
    hermetic();
828
    use crate::oplog::{Format1Op, Format1View};
829
    let dir = tempfile::tempdir().unwrap();
830
    let root = dir.path();
831
    let repo = Repo::init(root).unwrap();
832
    write(root, "a.txt", b"a\n");
833
    let h1 = repo.commit("one", &[]).unwrap();
834
    let (wc_hash, _) = repo.working_copy().unwrap();
835
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
836
    let mut v1 = Format1View::default();
837
    v1.bookmarks.insert("main".into(), vec![]);
838
    v1.workspaces.insert(repo.workspace(), wc_hash);
75167672 Andy McCall 839
    let init = Format1Op {
840
        parents: vec![],
841
        hlc: Hlc::default(),
842
        command: "oxy init".into(),
843
        view: v1.clone(),
844
    };
98286406 Andy McCall ↶ 845
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
846
    v1.bookmarks.insert("main".into(), vec![h1]);
75167672 Andy McCall 847
    let commit = Format1Op {
848
        parents: vec![init_ref],
849
        hlc: Hlc::default(),
850
        command: "oxy commit".into(),
851
        view: v1,
852
    };
98286406 Andy McCall ↶ 853
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
854
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
855
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
856
    drop(repo);
857
858
    let repo = Repo::open(root).unwrap();
75167672 Andy McCall 859
    assert_eq!(
860
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
861
        FORMAT_LINE
862
    );
98286406 Andy McCall ↶ 863
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
864
    let ops = repo.op_log().unwrap();
75167672 Andy McCall 865
    assert_eq!(
866
        ops.iter()
867
            .map(|(_, o)| o.command.as_str())
868
            .collect::<Vec<_>>(),
869
        ["oxy commit", "oxy init"]
870
    );
98286406 Andy McCall ↶ 871
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
872
    assert!(!repo.snapshot("status").unwrap().changed);
873
    // Reopening again is a no-op.
874
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
875
}
876
877
#[test]
878
fn undo_skips_snapshot_operations() {
879
    hermetic();
880
    let dir = tempfile::tempdir().unwrap();
881
    let root = dir.path();
882
    let repo = Repo::init(root).unwrap();
883
    write(root, "a.txt", b"a\n");
884
    let h1 = repo.commit("a", &[]).unwrap();
885
    // A later command snapshots new edits on top of the commit.
886
    write(root, "b.txt", b"b\n");
887
    let s = repo.snapshot("oxy status").unwrap();
888
    assert!(s.changed);
889
    assert!(repo.head_op().unwrap().1.is_snapshot());
890
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
891
    // Undo must undo the commit, not the snapshot.
892
    repo.undo().unwrap();
893
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
894
    let s = repo.snapshot("oxy status").unwrap();
895
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
75167672 Andy McCall 896
    assert_eq!(
897
        paths,
898
        ["a.txt", "b.txt"],
899
        "both files are back in the working copy"
900
    );
98286406 Andy McCall ↶ 901
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
902
    // Only snapshots remain above `init`, so there is nothing left to undo.
903
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
904
    assert!(repo.undo().is_err());
905
}
906
907
#[test]
908
fn independent_changes_commute_and_make_multiple_heads() {
909
    hermetic();
910
    let dir = tempfile::tempdir().unwrap();
911
    let root = dir.path();
912
    let repo = Repo::init(root).unwrap();
913
    write(root, "a.txt", b"a\n");
914
    let h1 = repo.commit("a", &[]).unwrap();
915
    write(root, "b.txt", b"b\n");
916
    let h2 = repo.commit("b", &[]).unwrap();
917
    let c2 = repo.store().get_change(&h2).unwrap();
918
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
919
    let mut heads = repo.bookmark_heads().unwrap();
920
    heads.sort();
921
    let mut want = vec![h1, h2];
922
    want.sort();
923
    assert_eq!(heads, want);
924
    // Editing a.txt depends on h1 only.
925
    write(root, "a.txt", b"a\na2\n");
926
    let h3 = repo.commit("a2", &[]).unwrap();
927
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
928
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
929
    assert_eq!(heads, [h2, h3].into_iter().collect());
930
    // Explicit dependency.
931
    write(root, "c.txt", b"c\n");
932
    let h4 = repo.commit("c", &[h2]).unwrap();
933
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
934
}
935
936
#[test]
937
fn mode_change_and_text_binary_switch() {
938
    hermetic();
939
    let dir = tempfile::tempdir().unwrap();
940
    let root = dir.path();
941
    let repo = Repo::init(root).unwrap();
942
    write(root, "run.sh", b"#!/bin/sh\n");
943
    repo.commit("add script", &[]).unwrap();
944
    #[cfg(unix)]
945
    {
946
        use std::os::unix::fs::PermissionsExt;
947
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
948
        let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 949
        assert_eq!(
950
            statuses(&s),
951
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
952
        );
98286406 Andy McCall ↶ 953
        let h = repo.commit("exec", &[]).unwrap();
954
        let snap = repo.load_state(&[h]).unwrap().materialize();
955
        assert!(snap.files["run.sh"].mode.exec);
956
    }
957
    // Text → binary → text.
958
    write(root, "run.sh", b"\0binary");
959
    let h = repo.commit("binary", &[]).unwrap();
960
    let snap = repo.load_state(&[h]).unwrap().materialize();
961
    assert!(snap.files["run.sh"].mode.opaque);
962
    write(root, "run.sh", b"text again\n");
963
    let h = repo.commit("text", &[]).unwrap();
964
    let snap = repo.load_state(&[h]).unwrap().materialize();
965
    assert!(!snap.files["run.sh"].mode.opaque);
75167672 Andy McCall 966
    assert!(
967
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
968
    );
98286406 Andy McCall ↶ 969
    assert!(!snap.is_conflicted());
970
}
83e0677b Andy McCall ↶ 971
6eae06b6 Andy McCall ↶ 972
/// oxygen#87: a binary file given new contents and the executable bit in
973
/// one commit kept the contents and lost the bit.
974
#[cfg(unix)]
975
#[test]
976
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
977
    use std::os::unix::fs::PermissionsExt;
978
    hermetic();
979
    let dir = tempfile::tempdir().unwrap();
980
    let root = dir.path();
981
    let repo = Repo::init(root).unwrap();
982
    write(root, "tool.exe", b"MZ\0one");
983
    repo.commit("add", &[]).unwrap();
984
    write(root, "tool.exe", b"MZ\0two");
985
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
986
    let h = repo.commit("update and +x", &[]).unwrap();
987
    let snap = repo.load_state(&[h]).unwrap().materialize();
988
    let f = &snap.files["tool.exe"];
989
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
990
    assert!(
991
        repo.snapshot("status").unwrap().statuses.is_empty(),
992
        "nothing left to commit"
993
    );
994
}
995
f0a517d2 Andy McCall ↶ 996
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
997
/// key whose certificate an issuer gave pushes when the policy grants its
998
/// subject, and a fetch accepts what it attested; an expired certificate,
999
/// or a subject the policy does not grant, may not move the bookmark.
83e0677b Andy McCall ↶ 1000
#[test]
f0a517d2 Andy McCall ↶ 1001
fn a_certified_key_pushes_under_a_subject_grant() {
1002
    use crate::cert::{Certificate, SignedCertificate};
1003
    use crate::identity::Scope;
1004
    hermetic();
1005
    let dir = tempfile::tempdir().unwrap();
1006
    let root = dir.path();
1007
    let _origin = Repo::init(&root.join("origin")).unwrap();
1008
    let url = root.join("origin").to_string_lossy().to_string();
1009
    let mut a = Repo::clone(&url, &root.join("a"))
1010
        .unwrap()
1011
        .with_home(root.join("home-a"));
1012
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1013
        .unwrap();
1014
    write(&root.join("a"), "a.txt", b"a\n");
1015
    a.commit("a", &[]).unwrap();
1016
    a.policy_init().unwrap();
1017
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1018
    let hub_sk = SecretKey::generate();
1019
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1020
    a.policy_grant_subject(
1021
        "agent:claude@ada",
1022
        hub.clone(),
1023
        Scope::CHANGES | Scope::REFS,
1024
        None,
1025
    )
1026
    .unwrap();
1027
    assert!(a
1028
        .push("origin", false)
1029
        .unwrap()
1030
        .iter()
1031
        .any(|r| r.name == "policy" && r.ok));
1032
1033
    let now = Hlc::now().wall_ms;
1034
    // An agent repository whose key the hub certified for `subject`, from
1035
    // `from` to `to`.
1036
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1037
        let mut r = Repo::clone(&url, &root.join(name))
1038
            .unwrap()
1039
            .with_home(root.join(format!("home-{name}")));
1040
        let (_, id) = r
1041
            .create_identity(name, "[email protected]", IdentityScope::User)
1042
            .unwrap();
1043
        let cert = SignedCertificate::sign(
1044
            Certificate {
1045
                key: id,
1046
                issuer: hub.hash(),
1047
                subject: subject.into(),
1048
                claims: vec![],
1049
                scope: Scope::CHANGES | Scope::REFS,
1050
                not_before: from,
1051
                expires: to,
a2387d54 Andy McCall ↶ 1052
                grant: None,
f0a517d2 Andy McCall ↶ 1053
            },
1054
            &hub,
1055
            &hub_sk,
1056
        );
1057
        r.store().put_identity(&hub).unwrap();
1058
        r.store().put_certificate(&cert).unwrap();
1059
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1060
        r.commit("work", &[]).unwrap();
1061
        r
1062
    };
1063
1064
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1065
    let r = claude.push("origin", false).unwrap();
1066
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1067
    // Ada's fetch accepts the bookmark the certified key attested.
1068
    a.pull("origin").unwrap();
1069
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1070
        .store()
1071
        .get_change(h)
1072
        .map(|c| c.message == "work")
1073
        .unwrap_or(false)));
1074
f53cbe7a Andy McCall ↶ 1075
    // Step 4c: a host with an acceptor key records when it accepted the
1076
    // certified update and serves it; a fetch checks the certificate at
1077
    // that time only when the certificate's issuer signed it for exactly
1078
    // this attestation, else at the attestation's own time.
1079
    let host = Repo::open(&root.join("origin"))
1080
        .unwrap()
1081
        .with_acceptor(hub.clone(), hub_sk.clone());
1082
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1083
    host.record_acceptance(&attest_ref).unwrap();
1084
    let served = host.remote_refs().unwrap();
1085
    let acc = served
1086
        .refs
1087
        .iter()
1088
        .find(|r| r.name == "main")
1089
        .unwrap()
1090
        .accepted
1091
        .clone()
1092
        .expect("served with the refs");
1093
    let signer = sa.sigs[0].key;
1094
    assert_eq!(
1095
        a.certified_time(&signer, &sa, Some(&acc)),
1096
        acc.attest.hlc.wall_ms
1097
    );
1098
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1099
    let stranger_sk = SecretKey::generate();
1100
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1101
    let mut forged = acc.clone();
1102
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1103
    assert_eq!(
1104
        a.certified_time(&signer, &sa, Some(&forged)),
1105
        sa.attest.hlc.wall_ms,
1106
        "not the issuer's"
1107
    );
1108
    let mut elsewhere = acc.clone();
1109
    elsewhere.attest.body = AttestBody::Accepted {
1110
        attest: ObjectRef([7; 32]),
1111
    };
1112
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1113
    assert_eq!(
1114
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1115
        sa.attest.hlc.wall_ms,
1116
        "another attestation's"
1117
    );
1118
    a.pull("origin").unwrap();
1119
    // gc keeps the acceptance with the attestation.
1120
    host.gc(true).unwrap();
1121
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1122
f0a517d2 Andy McCall ↶ 1123
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1124
    let r = late.push("origin", false).unwrap();
1125
    assert!(
1126
        !r[0].ok && r[0].reason.contains("may not update"),
1127
        "an expired certificate: {r:?}"
1128
    );
1129
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1130
    let r = other.push("origin", false).unwrap();
1131
    assert!(
1132
        !r[0].ok && r[0].reason.contains("may not update"),
1133
        "a subject not granted: {r:?}"
1134
    );
1135
}
1136
d8524a9f Andy McCall ↶ 1137
/// A tag made under one short-lived key and pushed under another: its
1138
/// signer travels with the push (identity and certificate), so a receiver
1139
/// that has never seen that key accepts it. A tag-only push by a keyless
1140
/// agent was refused "unknown key" (found releasing OxygenFlow 0.2.0).
1141
#[test]
1142
fn a_tag_signed_by_an_earlier_short_lived_key_is_pushed() {
1143
    use crate::cert::{Certificate, SignedCertificate};
1144
    use crate::identity::Scope;
1145
    hermetic();
1146
    let dir = tempfile::tempdir().unwrap();
1147
    let root = dir.path();
1148
    let _origin = Repo::init(&root.join("origin")).unwrap();
1149
    let url = root.join("origin").to_string_lossy().to_string();
1150
    let mut a = Repo::clone(&url, &root.join("a"))
1151
        .unwrap()
1152
        .with_home(root.join("home-a"));
1153
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1154
        .unwrap();
1155
    write(&root.join("a"), "a.txt", b"a\n");
1156
    a.commit("a", &[]).unwrap();
1157
    a.policy_init().unwrap();
1158
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1159
    let hub_sk = SecretKey::generate();
1160
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1161
    a.policy_grant_subject(
1162
        "agent:claude@ada",
1163
        hub.clone(),
1164
        Scope::CHANGES | Scope::REFS,
1165
        Some("*"),
1166
    )
1167
    .unwrap();
1168
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1169
1170
    let now = Hlc::now().wall_ms;
1171
    let mut agent = Repo::clone(&url, &root.join("agent"))
1172
        .unwrap()
1173
        .with_home(root.join("home-agent"));
1174
    agent.store().put_identity(&hub).unwrap();
1175
    let certify = |agent: &Repo, id| {
1176
        let cert = SignedCertificate::sign(
1177
            Certificate {
1178
                key: id,
1179
                issuer: hub.hash(),
1180
                subject: "agent:claude@ada".into(),
1181
                claims: vec![],
1182
                scope: Scope::CHANGES | Scope::REFS,
1183
                not_before: now - 60_000,
1184
                expires: now + 600_000,
1185
                grant: None,
1186
            },
1187
            &hub,
1188
            &hub_sk,
1189
        );
1190
        agent.store().put_certificate(&cert).unwrap();
1191
    };
1192
    // The tag, under the first short-lived key.
1193
    let (first, first_id) = agent
1194
        .create_identity("claude", "[email protected]", IdentityScope::User)
1195
        .unwrap();
1196
    certify(&agent, first_id);
1197
    let heads = agent.bookmark_heads().unwrap();
1198
    agent.tag_create("v1", &heads, "first").unwrap();
1199
    // The push, under a second one (a later process's ten-minute key).
1200
    let (second, second_id) = agent
1201
        .create_identity("claude", "[email protected]", IdentityScope::User)
1202
        .unwrap();
1203
    assert_ne!(first, second);
1204
    certify(&agent, second_id);
1205
    agent
1206
        .set_user_config("author.signer", &second.to_hex())
1207
        .unwrap();
1208
    let host = Repo::open(&root.join("origin")).unwrap();
1ec6fdbc Andy McCall ↶ 1209
    assert!(
1210
        host.store().get_identity(&first).is_err(),
1211
        "the host has never seen the tag's key"
1212
    );
d8524a9f Andy McCall ↶ 1213
    let r = agent.push("origin", false).unwrap();
1ec6fdbc Andy McCall ↶ 1214
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1215
    let host = Repo::open(&root.join("origin")).unwrap();
1216
    assert!(
1217
        host.tag_refs().unwrap().iter().any(|t| t.name == "v1"),
1218
        "the tag arrived"
1219
    );
1220
}
1221
1222
/// oxygen#129: a short-lived key's tag is checked on a fetch at a time its
1223
/// signer did not choose, its issuer's acceptance, never at the time it
1224
/// claims nor at the fetch's (when the ten-minute certificate has long
1225
/// expired). Without an acceptance it is left out and said so; with one
1226
/// inside the certificate's window it is fetched however much later, and
1227
/// a host it is pushed on to keeps and serves the acceptance.
1228
#[test]
1229
fn a_short_lived_key_s_tag_is_fetched_at_its_issuer_s_acceptance() {
1230
    use crate::cert::{Certificate, SignedCertificate};
1231
    use crate::identity::Scope;
1232
    hermetic();
1233
    let dir = tempfile::tempdir().unwrap();
1234
    let root = dir.path();
1235
    let _origin = Repo::init(&root.join("origin")).unwrap();
1236
    let url = root.join("origin").to_string_lossy().to_string();
1237
    let mut a = Repo::clone(&url, &root.join("a"))
1238
        .unwrap()
1239
        .with_home(root.join("home-a"));
1240
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1241
        .unwrap();
1242
    write(&root.join("a"), "a.txt", b"a\n");
1243
    a.commit("a", &[]).unwrap();
1244
    a.policy_init().unwrap();
1245
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1246
    let hub_sk = SecretKey::generate();
1247
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1248
    a.policy_grant_subject(
1249
        "agent:claude@ada",
1250
        hub.clone(),
1251
        Scope::CHANGES | Scope::REFS,
1252
        Some("*"),
1253
    )
1254
    .unwrap();
1255
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1256
1257
    let now = Hlc::now().wall_ms;
1258
    // An agent whose key the hub certified from `from` to `to`.
1259
    let agent = |name: &str, from: u64, to: u64| {
1260
        let mut r = Repo::clone(&url, &root.join(name))
1261
            .unwrap()
1262
            .with_home(root.join(format!("home-{name}")));
1263
        r.store().put_identity(&hub).unwrap();
1264
        let (_, id) = r
1265
            .create_identity(name, "[email protected]", IdentityScope::User)
1266
            .unwrap();
1267
        let cert = SignedCertificate::sign(
1268
            Certificate {
1269
                key: id,
1270
                issuer: hub.hash(),
1271
                subject: "agent:claude@ada".into(),
1272
                claims: vec![],
1273
                scope: Scope::CHANGES | Scope::REFS,
1274
                not_before: from,
1275
                expires: to,
1276
                grant: None,
1277
            },
1278
            &hub,
1279
            &hub_sk,
1280
        );
1281
        r.store().put_certificate(&cert).unwrap();
1282
        r
1283
    };
1284
1285
    // A tag by a key certified now, pushed to a host that records no
1286
    // acceptance (a path on disk): it lands, but a fetch has no time to
1287
    // check its certificate at, so it is left out and the fetch goes on.
1288
    let claude = agent("claude", now - 60_000, now + 600_000);
1289
    let heads = claude.bookmark_heads().unwrap();
1290
    claude.tag_create("v1", &heads, "one").unwrap();
1291
    let r = claude.push("origin", false).unwrap();
d8524a9f Andy McCall ↶ 1292
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1ec6fdbc Andy McCall ↶ 1293
    let b = Repo::clone(&url, &root.join("b"))
1294
        .unwrap()
1295
        .with_home(root.join("home-b"));
1296
    let rep = b.fetch("origin").unwrap();
1297
    assert!(
1298
        rep.skipped
1299
            .iter()
1300
            .any(|(n, why)| n == "tags/v1" && why.contains("no time to check its certificate at")),
1301
        "{rep:?}"
1302
    );
1303
    assert_eq!(b.tag_heads("v1").unwrap(), None);
1304
1305
    // The host's acceptance, signed by the certificate's issuer, served
1306
    // with the tag: fetched.
1307
    let host = Repo::open(&root.join("origin"))
1308
        .unwrap()
1309
        .with_acceptor(hub.clone(), hub_sk.clone());
1310
    let (v1, _) = host.tag_attest("v1").unwrap().unwrap();
1311
    host.record_acceptance(&v1).unwrap();
1312
    let served = host.tag_refs().unwrap();
1313
    assert!(served
1314
        .iter()
1315
        .any(|t| t.name == "v1" && t.accepted.is_some()));
1316
    let rep = b.fetch("origin").unwrap();
1317
    assert!(rep.skipped.is_empty(), "{rep:?}");
1318
    assert_eq!(b.tag_heads("v1").unwrap(), Some(heads.clone()));
1319
    // gc keeps the acceptance with the tag.
1320
    host.gc(true).unwrap();
1321
    assert!(host.acceptance_of(&v1).unwrap().is_some());
1322
1323
    // Long after: a key whose certificate expired an hour ago may not
1324
    // create a tag now.
1325
    let late = agent("late", now - 7_200_000, now - 3_600_000);
1326
    late.tag_create("v2", &heads, "two").unwrap();
1327
    let r = late.push("origin", false).unwrap();
1328
    assert!(
1329
        r.iter()
1330
            .any(|x| x.name == "tags/v2" && !x.ok && x.reason.contains("may not create")),
1331
        "{r:?}"
1332
    );
1333
    // With its issuer's acceptance from inside the window (as a hub gave
1334
    // it then, passed on to another host), it is taken at that time: by
1335
    // the host it is pushed to, which keeps it, and by a fresh clone.
1336
    let (v2, _) = late.tag_attest("v2").unwrap().unwrap();
1337
    let acc = Attest {
1338
        repo: late.id().unwrap(),
1339
        hlc: Hlc {
1340
            wall_ms: now - 5_400_000,
1341
            logical: 0,
1342
        },
1343
        body: AttestBody::Accepted { attest: v2 },
1344
    };
1345
    let sig = hub_sk.sign(Domain::Attest, &hub.hash(), &acc.hash());
1346
    // One by any other key gives no time.
1347
    let stranger_sk = SecretKey::generate();
1348
    let stranger = stranger_sk.identity("stranger", "[email protected]", 1);
1349
    let forged = stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.hash());
1350
    late.keep_acceptance(
1351
        &v2,
1352
        &SignedAttest {
1353
            attest: acc.clone(),
1354
            sigs: vec![forged],
1355
        },
1356
    )
1357
    .unwrap();
1358
    let r = late.push("origin", false).unwrap();
1359
    assert!(
1360
        r.iter().any(|x| x.name == "tags/v2" && !x.ok),
1361
        "not the issuer's: {r:?}"
1362
    );
1363
    let theirs = SignedAttest {
1364
        attest: acc,
1365
        sigs: vec![sig],
1366
    };
1367
    // Kept beside the stranger's: the issuer's is the one sent.
1368
    late.keep_acceptance(&v2, &theirs).unwrap();
1369
    let r = late.push("origin", false).unwrap();
1370
    // (Its re-attestation of main is refused: an expired key moves no
1371
    // bookmark.)
1372
    assert!(r.iter().any(|x| x.name == "tags/v2" && x.ok), "{r:?}");
d8524a9f Andy McCall ↶ 1373
    let host = Repo::open(&root.join("origin")).unwrap();
1ec6fdbc Andy McCall ↶ 1374
    let (hv2, _) = host.tag_attest("v2").unwrap().unwrap();
1375
    assert_eq!(hv2, v2);
1376
    assert!(host
1377
        .store()
1378
        .index_get_pub("accepted", &v2)
1379
        .unwrap()
1380
        .contains(&theirs.attest.hash()));
1381
    let c = Repo::clone(&url, &root.join("c"))
1382
        .unwrap()
1383
        .with_home(root.join("home-c"));
1384
    assert_eq!(c.tag_heads("v2").unwrap(), Some(heads.clone()));
1385
    assert_eq!(c.tag_heads("v1").unwrap(), Some(heads));
d8524a9f Andy McCall ↶ 1386
}
1387
d36ba2f7 Andy McCall ↶ 1388
/// oxygenhub#266: a short-lived key its issuer certified moves a bookmark
1389
/// and signs no change (a keyless agent naming a bookmark). A third
1390
/// party's clone gets the key's identity, its certificate and the
1391
/// issuer's identity with the fetch, so the policy's subject grant
1392
/// authorizes the move and the signature verifies.
1393
#[test]
1394
fn a_bookmark_moved_by_a_certified_key_alone_is_fetched() {
1395
    use crate::cert::{Certificate, SignedCertificate};
1396
    use crate::identity::Scope;
1397
    hermetic();
1398
    let dir = tempfile::tempdir().unwrap();
1399
    let root = dir.path();
1400
    let _origin = Repo::init(&root.join("origin")).unwrap();
1401
    let url = root.join("origin").to_string_lossy().to_string();
1402
    let mut a = Repo::clone(&url, &root.join("a"))
1403
        .unwrap()
1404
        .with_home(root.join("home-a"));
1405
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1406
        .unwrap();
1407
    write(&root.join("a"), "a.txt", b"a\n");
1408
    a.commit("a", &[]).unwrap();
1409
    a.policy_init().unwrap();
1410
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1411
    let hub_sk = SecretKey::generate();
1412
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1413
    a.policy_grant_subject(
1414
        "agent:claude@ada",
1415
        hub.clone(),
1416
        Scope::CHANGES | Scope::REFS,
1417
        None,
1418
    )
1419
    .unwrap();
1420
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1421
1422
    let now = Hlc::now().wall_ms;
1423
    let mut agent = Repo::clone(&url, &root.join("agent"))
1424
        .unwrap()
1425
        .with_home(root.join("home-agent"));
1426
    let (key, id) = agent
1427
        .create_identity("claude", "[email protected]", IdentityScope::User)
1428
        .unwrap();
1429
    let cert = SignedCertificate::sign(
1430
        Certificate {
1431
            key: id,
1432
            issuer: hub.hash(),
1433
            subject: "agent:claude@ada".into(),
1434
            claims: vec![],
1435
            scope: Scope::CHANGES | Scope::REFS,
1436
            not_before: now - 60_000,
1437
            expires: now + 600_000,
1438
            grant: None,
1439
        },
1440
        &hub,
1441
        &hub_sk,
1442
    );
1443
    agent.store().put_identity(&hub).unwrap();
1444
    agent.store().put_certificate(&cert).unwrap();
1445
    let heads = agent.bookmark_heads().unwrap();
1446
    agent.bookmark_create("agent-work", Some(&heads)).unwrap();
1447
    let r = agent.push_bookmark("origin", "agent-work", false).unwrap();
1448
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1449
    let host = Repo::open(&root.join("origin")).unwrap();
1450
    let (_, sa) = host.latest_ref_attest("agent-work").unwrap().unwrap();
1451
    assert_eq!(sa.sigs[0].key, key, "the certified key alone moved it");
1452
1453
    // A fetch naming no change brings the certificate and both identities.
1454
    let bundle = host.bundle_raw_for(&[], None).unwrap();
1455
    assert!(bundle.changes.is_empty() && bundle.raw_changes.is_empty());
1456
    assert_eq!(bundle.certificates.len(), 1);
1457
    for k in [key, hub.hash()] {
1458
        assert!(bundle
1459
            .objects
1460
            .iter()
1461
            .any(|(t, b)| *t == ObjectType::Identity && hash_object(*t, b) == k));
1462
    }
1463
1464
    let c = Repo::clone(&url, &root.join("c")).unwrap();
1465
    let tracked = c.view().unwrap().remotes["origin"].clone();
1466
    assert_eq!(
1467
        tracked.get("agent-work"),
1468
        host.view().unwrap().bookmarks.get("agent-work")
1469
    );
1470
    assert!(c.store().certificate_of(&key).unwrap().is_some());
1471
}
1472
028545df Andy McCall ↶ 1473
/// Trusted time (oxygenhub#240, spec §14.8): a fetched attestation by a
1474
/// short-lived key is judged at its integrated time, the earliest time a
1475
/// pinned witness cosigned a checkpoint holding it. A certificate valid
1476
/// then but expired now passes; a witness this user does not trust gives
1477
/// no time (the earlier rule, said so); a backdated attestation is noted;
1478
/// an answer without the new fields is judged as before.
1479
#[test]
1480
fn a_fetched_attestation_is_judged_at_its_integrated_time() {
1481
    use super::transparency::LogCheck;
1482
    use crate::cert::{Certificate, SignedCertificate};
1483
    use crate::identity::Scope;
1484
    use crate::protocol::{Integration, Logged, RefsResponse, RemoteRef};
1485
    use crate::tlog::{self, Checkpoint, Entry, Hash, Integrated, Note};
1486
    hermetic();
1487
    let dir = tempfile::tempdir().unwrap();
1488
    let root = dir.path();
1489
    let mut a = Repo::init(&root.join("a"))
1490
        .unwrap()
1491
        .with_home(root.join("home-a"));
1492
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1493
        .unwrap();
1494
    write(&root.join("a"), "a.txt", b"a\n");
1495
    a.commit("a", &[]).unwrap();
1496
    a.policy_init().unwrap();
1497
    let issuer_sk = SecretKey::generate();
1498
    let issuer = issuer_sk.identity("hub", "[email protected]", 1);
1499
    a.policy_grant_subject(
1500
        "agent:claude@ada",
1501
        issuer.clone(),
1502
        Scope::CHANGES | Scope::REFS,
1503
        None,
1504
    )
1505
    .unwrap();
1506
    let p = a.current_policy().unwrap().unwrap().1.policy;
1507
1508
    // An agent key the issuer certified for ten minutes two hours ago.
1509
    let now = Hlc::now().wall_ms;
1510
    let t0 = now - 2 * 3_600_000;
1511
    let agent_sk = SecretKey::generate();
1512
    let agent = agent_sk.identity("claude", "[email protected]", t0);
1513
    let cert = SignedCertificate::sign(
1514
        Certificate {
1515
            key: agent.clone(),
1516
            issuer: issuer.hash(),
1517
            subject: "agent:claude@ada".into(),
1518
            claims: vec![],
1519
            scope: Scope::CHANGES | Scope::REFS,
1520
            not_before: t0,
1521
            expires: t0 + 600_000,
1522
            grant: None,
1523
        },
1524
        &issuer,
1525
        &issuer_sk,
1526
    );
1527
    a.store().put_identity(&agent).unwrap();
1528
    a.store().put_certificate(&cert).unwrap();
1529
    let signer = agent.hash();
1530
    let attested = |claimed: u64| {
1531
        let attest = Attest {
1532
            repo: a.id().unwrap(),
1533
            hlc: Hlc {
1534
                wall_ms: claimed,
1535
                logical: 0,
1536
            },
1537
            body: AttestBody::Ref {
1538
                name: "main".into(),
1539
                old_state: ObjectRef([1; 32]),
1540
                new_state: ObjectRef([2; 32]),
1541
                serial: 1,
1542
            },
1543
        };
1544
        let sig = agent_sk.sign(Domain::Attest, &signer, &attest.hash());
1545
        SignedAttest {
1546
            attest,
1547
            sigs: vec![sig],
1548
        }
1549
    };
1550
1551
    // The hub's log: eight entries, the attestation's at 3, the latest
1552
    // checkpoint of 8, and one of 4 that witnesses cosigned.
1553
    let log_sk = SecretKey::generate();
1554
    let log_key = log_sk.identity("hub.example", "[email protected]", 1);
1555
    let origin = "hub.example/log";
1556
    let hub = "https://hub.example";
1557
    let url = "https://hub.example/ada/a";
1558
    let w_sk = SecretKey::generate();
1559
    let w = w_sk.identity("w", "[email protected]", 1);
1560
    let stranger_sk = SecretKey::generate();
1561
    let stranger = stranger_sk.identity("s", "[email protected]", 1);
1562
    let sa = attested(t0 + 300_000);
1563
    let entry_of = |i: u64| {
1564
        let (kind, object) = if i == 3 {
1565
            ("ref", sa.attest.hash())
1566
        } else {
1567
            ("seal", ObjectRef([i as u8; 32]))
1568
        };
1569
        Entry {
1570
            kind: kind.into(),
1571
            repo: sa.attest.repo,
1572
            object,
1573
            signers: vec![signer],
1574
            received: t0 + 300_000,
1575
        }
1576
        .encode()
1577
    };
1578
    let mut stored: Vec<Hash> = Vec::new();
1579
    for i in 0..8 {
1580
        let add = tlog::stored_hashes_for_leaf(i, tlog::leaf_hash(&entry_of(i)), &stored).unwrap();
1581
        stored.extend(add);
1582
    }
1583
    let note_of = |n: u64, cosigners: &[(&str, &Identity, &SecretKey, u64)]| {
1584
        let mut note = Checkpoint {
1585
            origin: origin.into(),
1586
            size: n,
1587
            root: tlog::tree_hash(n, &stored).unwrap(),
1588
            extensions: vec![],
1589
        }
1590
        .sign(&log_key, &log_sk)
1591
        .unwrap();
1592
        for (name, id, sk, t) in cosigners {
1593
            note.sigs
1594
                .extend(tlog::cosign(&note.text, name, id, sk, *t).unwrap());
1595
        }
1596
        note.encode()
1597
    };
1598
    let latest = note_of(8, &[]);
1599
    let witnessed_at = (t0 + 360_000) / 1000;
1600
    let cosigned = note_of(
1601
        4,
1602
        &[
1603
            ("w.example", &w, &w_sk, witnessed_at),
1604
            ("s.example", &stranger, &stranger_sk, 1),
1605
        ],
1606
    );
1607
    let answer = |integration: Vec<Integration>, witnesses: Vec<(String, Vec<u8>)>| RefsResponse {
1608
        refs: vec![RemoteRef {
1609
            name: "main".into(),
1610
            state: ObjectRef([2; 32]),
1611
            heads: vec![],
1612
            attestation: Some(sa.clone()),
1613
            last_serial: None,
1614
            accepted: None,
1615
            logged: Some(Logged {
1616
                index: 3,
1617
                entry: entry_of(3),
1618
                proof: tlog::prove_inclusion(8, 3, &stored).unwrap(),
1619
            }),
1620
            integration,
1621
        }],
1622
        log: Some(latest.clone()),
1623
        witnesses,
1624
        ..RefsResponse::default()
1625
    };
1626
    let proof4 = tlog::prove_inclusion(4, 3, &stored).unwrap();
1627
    let served = vec![Integration {
1628
        note: cosigned.clone(),
1629
        proof: proof4.clone(),
1630
    }];
1631
    let listed = vec![("w.example".to_string(), w.encode())];
1632
    // This user saw the hub's log before (pinned, so nothing is fetched).
1633
    a.remember_log(hub, &log_key, &Note::parse(&latest).unwrap())
1634
        .unwrap();
1635
1636
    // The witness is pinned on first sight, silently; the stranger's
1637
    // earlier cosignature counts for nothing.
1638
    let resp = answer(served.clone(), listed.clone());
1639
    let lc = a.check_log(url, None, &resp).unwrap();
1640
    assert!(lc.notes.is_empty(), "{:?}", lc.notes);
1641
    let t = lc.time_of("main").unwrap();
1642
    assert_eq!((t.time, t.witness.as_str()), (witnessed_at, "w.example"));
1643
    // The certificate expired an hour and fifty minutes ago, but covered
1644
    // the integrated time: accepted, and nothing to say.
1645
    assert!(cert.cert.expires < now);
1646
    let mut notes = Vec::new();
1647
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1648
        .unwrap();
1649
    assert!(notes.is_empty(), "{notes:?}");
1650
1651
    // Only the stranger cosigned: no witnessed time, so the earlier rule
1652
    // (the attestation's own time, inside the window), said so.
1653
    let lonely = vec![Integration {
1654
        note: note_of(4, &[("s.example", &stranger, &stranger_sk, 1)]),
1655
        proof: proof4.clone(),
1656
    }];
1657
    let resp = answer(lonely, vec![]);
1658
    let lc = a.check_log(url, None, &resp).unwrap();
1659
    assert!(lc
1660
        .time_of("main")
1661
        .unwrap_err()
1662
        .contains("no witness this user trusts"));
1663
    let mut notes = Vec::new();
1664
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1665
        .unwrap();
1666
    assert!(
1667
        notes.len() == 1 && notes[0].contains("not at a witnessed time"),
1668
        "{notes:?}"
1669
    );
1670
1671
    // A witness listed later under the pinned name with another key is
1672
    // pinned with a note, as a new log key is.
1673
    let resp = answer(
1674
        served.clone(),
1675
        vec![("w.example".into(), stranger.encode())],
1676
    );
1677
    let lc = a.check_log(url, None, &resp).unwrap();
1678
    assert!(
1679
        lc.notes.iter().any(|n| n.contains("another key")),
1680
        "{:?}",
1681
        lc.notes
1682
    );
1683
    assert!(
1684
        lc.time_of("main").is_err(),
1685
        "w's cosignature is by its old key"
1686
    );
1687
    a.check_log(url, None, &answer(served.clone(), listed.clone()))
1688
        .unwrap();
1689
1690
    // An old peer's answer: no log, no witnesses, no integration. Judged
1691
    // as before, silently.
1692
    let mut old = answer(vec![], vec![]);
1693
    old.log = None;
1694
    old.refs[0].logged = None;
1695
    let lc = a.check_log(url, None, &old).unwrap();
1696
    assert!(!lc.kept && lc.notes.is_empty());
1697
    let mut notes = Vec::new();
1698
    a.authorize_in_time(&p, "origin", &old.refs[0], &sa, &signer, &lc, &mut notes)
1699
        .unwrap();
1700
    assert!(notes.is_empty(), "{notes:?}");
1701
1702
    // Judged at given integrated times.
1703
    let at = |secs_after_t0: u64| {
1704
        let mut times = std::collections::HashMap::new();
1705
        times.insert(
1706
            "main".to_string(),
1707
            Ok(Integrated {
1708
                time: (t0 + secs_after_t0 * 1000) / 1000,
1709
                witness: "w.example".into(),
1710
                size: 4,
1711
            }),
1712
        );
1713
        LogCheck {
1714
            kept: true,
1715
            times,
1716
            ..LogCheck::default()
1717
        }
1718
    };
1719
    let judged = |sa: &SignedAttest, lc: &LogCheck| {
1720
        let mut notes = Vec::new();
1721
        a.authorize_in_time(&p, "origin", &old.refs[0], sa, &signer, lc, &mut notes)
1722
            .map(|_| notes)
1723
    };
1724
    // Claimed inside the window, first witnessed an hour later, after
1725
    // the certificate expired: backdated, or held back. Accepted by the
1726
    // earlier rule while logs are new, with both said.
1727
    let notes = judged(&sa, &at(3600)).unwrap();
1728
    assert!(
1729
        notes
1730
            .iter()
1731
            .any(|n| n.contains("had lapsed when witness w.example"))
1732
            && notes
1733
                .iter()
1734
                .any(|n| n.contains("55 minutes before witness")),
1735
        "{notes:?}"
1736
    );
1737
    // Claimed after the certificate expired, but witnessed inside its
1738
    // window: the clock the signer did not choose decides. The gap is
1739
    // still noted.
1740
    let fast = attested(now);
1741
    let notes = judged(&fast, &at(400)).unwrap();
1742
    assert!(
1743
        notes.len() == 1 && notes[0].contains("after witness w.example saw it"),
1744
        "{notes:?}"
1745
    );
1746
    // Claimed and witnessed after it expired: refused, as before.
1747
    assert!(judged(&fast, &at(3600)).is_err());
1748
    // A gap within ten minutes is nothing to note.
1749
    assert!(judged(&sa, &at(500)).unwrap().is_empty());
1750
}
1751
a2387d54 Andy McCall ↶ 1752
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1753
/// subject the author granted, seals changes in the author's name; with
1754
/// no grant, a stranger's, or one that had ended, it is neither the
1755
/// author nor a delegate.
45a6f5ec Andy McCall ↶ 1756
/// oxygen#135: an owner renews or rotates with every delegation, and a
1757
/// repository may name the newest key as the author; the agent's grant by
1758
/// the earlier key still counts, but not one that key made after.
f0a517d2 Andy McCall ↶ 1759
#[test]
45a6f5ec Andy McCall ↶ 1760
fn a_grant_outlives_its_owner_s_rotation() {
1761
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1762
    use crate::identity::Scope;
1763
    hermetic();
1764
    let dir = tempfile::tempdir().unwrap();
1765
    let root = dir.path();
1766
    let mut a = Repo::init(&root.join("a"))
1767
        .unwrap()
1768
        .with_home(root.join("home-a"));
1769
    let (old, _) = a
1770
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1771
        .unwrap();
1772
    let (_, old_sk) = a.secret_key().unwrap().unwrap();
1773
    let old_id = a.identity(&old).unwrap();
1774
    let hub_sk = SecretKey::generate();
1775
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1776
    let now = Hlc::now().wall_ms;
1777
    let grant = |from: u64| {
1778
        SignedGrant::sign(
1779
            Grant {
1780
                grantor: old,
1781
                subject: "agent:claude@ada".into(),
1782
                issuer: hub.hash(),
1783
                scope: Scope::CHANGES | Scope::SEAL,
1784
                not_before: from,
1785
                expires: now + 86_400_000,
1786
            },
1787
            &old_id,
1788
            &old_sk,
1789
        )
1790
    };
1791
    let before = grant(now - 60_000);
1792
    let after = grant(now + 60_000);
1793
    let rot = a.renew_identity(None).unwrap();
1794
    assert_ne!(rot.new, old);
1795
    let agent = |name: &str, g: SignedGrant| {
1796
        let mut r = Repo::init(&root.join(name))
1797
            .unwrap()
1798
            .with_home(root.join(format!("home-{name}")));
1799
        let (key, id) = r
1800
            .create_identity(name, "[email protected]", IdentityScope::User)
1801
            .unwrap();
1802
        for i in [&old_id, &rot.identity, &hub] {
1803
            r.store().put_identity(i).unwrap();
1804
        }
1805
        r.set_user_config("author.key", &rot.new.to_hex()).unwrap();
1806
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1807
        let cert = SignedCertificate::sign(
1808
            Certificate {
1809
                key: id,
1810
                issuer: hub.hash(),
1811
                subject: "agent:claude@ada".into(),
1812
                claims: vec![],
1813
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1814
                not_before: now - 60_000,
1815
                expires: now + 600_000,
1816
                grant: Some(g),
1817
            },
1818
            &hub,
1819
            &hub_sk,
1820
        );
1821
        r.store().put_certificate(&cert).unwrap();
1822
        write(&root.join(name), "work.txt", b"agent work\n");
1823
        let h = r.commit("work", &[]).unwrap();
1824
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, rot.new);
1825
        r.seal(&[h]).unwrap();
1826
        (r, h)
1827
    };
1828
    let (r, h) = agent("kept", before);
1829
    assert!(
1830
        matches!(
1831
            r.authenticate_change(&h).unwrap(),
1832
            SignatureStatus::Valid { .. }
1833
        ),
1834
        "{:?}",
1835
        r.authenticate_change(&h).unwrap()
1836
    );
1837
    let (r, h) = agent("late", after);
1838
    assert!(
1839
        matches!(r.authenticate_change(&h).unwrap(), SignatureStatus::Invalid(e) if e.contains("neither")),
1840
        "a grant the old key made after the rotation: {:?}",
1841
        r.authenticate_change(&h).unwrap()
1842
    );
1843
}
1844
1845
#[test]
a2387d54 Andy McCall ↶ 1846
fn a_certified_key_acts_for_its_author_under_a_grant() {
1847
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1848
    use crate::identity::{Identity, Scope};
1849
    hermetic();
1850
    let dir = tempfile::tempdir().unwrap();
1851
    let root = dir.path();
1852
    let _origin = Repo::init(&root.join("origin")).unwrap();
1853
    let url = root.join("origin").to_string_lossy().to_string();
1854
    let mut a = Repo::clone(&url, &root.join("a"))
1855
        .unwrap()
1856
        .with_home(root.join("home-a"));
1857
    let (ada, _) = a
1858
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1859
        .unwrap();
1860
    write(&root.join("a"), "a.txt", b"a\n");
1861
    a.commit("a", &[]).unwrap();
1862
    a.policy_init().unwrap();
1863
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1864
    let hub_sk = SecretKey::generate();
1865
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1866
    a.policy_grant_subject(
1867
        "agent:claude@ada",
1868
        hub.clone(),
1869
        Scope::CHANGES | Scope::REFS,
1870
        None,
1871
    )
1872
    .unwrap();
1873
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1874
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1875
    let ada_id = a.identity(&ada).unwrap();
1876
1877
    let now = Hlc::now().wall_ms;
1878
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1879
        SignedGrant::sign(
1880
            Grant {
1881
                grantor: by.hash(),
1882
                subject: "agent:claude@ada".into(),
1883
                issuer: hub.hash(),
1884
                scope: Scope::CHANGES | Scope::SEAL,
1885
                not_before: from,
1886
                expires: to,
1887
            },
1888
            by,
1889
            sk,
1890
        )
1891
    };
1892
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1893
    // certified (with `g` inside) the signer.
1894
    let agent = |name: &str, g: Option<SignedGrant>| {
1895
        let mut r = Repo::clone(&url, &root.join(name))
1896
            .unwrap()
1897
            .with_home(root.join(format!("home-{name}")));
1898
        let (key, id) = r
1899
            .create_identity(name, "[email protected]", IdentityScope::User)
1900
            .unwrap();
1901
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1902
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1903
        let cert = SignedCertificate::sign(
1904
            Certificate {
1905
                key: id,
1906
                issuer: hub.hash(),
1907
                subject: "agent:claude@ada".into(),
1908
                claims: vec![],
1909
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1910
                not_before: now - 60_000,
1911
                expires: now + 600_000,
1912
                grant: g,
1913
            },
1914
            &hub,
1915
            &hub_sk,
1916
        );
1917
        r.store().put_identity(&hub).unwrap();
1918
        r.store().put_certificate(&cert).unwrap();
1919
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1920
        let h = r.commit("work", &[]).unwrap();
1921
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1922
        (r, key, h)
1923
    };
1924
1925
    let (claude, key, h) = agent(
1926
        "claude",
1927
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1928
    );
1929
    let r = claude.push("origin", false).unwrap();
1930
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1931
    let host = Repo::open(&root.join("origin")).unwrap();
68dcf21f Andy McCall ↶ 1932
    assert!(
1933
        matches!(
1934
            host.authenticate_change(&h).unwrap(),
1935
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
1936
        ),
1937
        "named by its certificate's subject"
1938
    );
a2387d54 Andy McCall ↶ 1939
    a.pull("origin").unwrap();
1940
    assert!(matches!(
1941
        a.authenticate_change(&h).unwrap(),
1942
        SignatureStatus::Valid { key: k, .. } if k == key
1943
    ));
1944
1945
    let (none, _, _) = agent("none", None);
1946
    let r = none.push("origin", false).unwrap();
1947
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1948
    let mallory_sk = SecretKey::generate();
1949
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1950
    let (stranger, _, _) = agent(
1951
        "stranger",
1952
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1953
    );
1954
    let r = stranger.push("origin", false).unwrap();
1955
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1956
    let (ended, _, eh) = agent(
1957
        "ended",
1958
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1959
    );
1960
    let r = ended.push("origin", false).unwrap();
1961
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1962
    assert!(matches!(
1963
        ended.authenticate_change(&eh).unwrap(),
1964
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1965
    ));
1966
}
1967
1968
#[test]
83e0677b Andy McCall ↶ 1969
fn trust_policy_governs_pushes_and_fetches() {
1970
    hermetic();
1971
    let dir = tempfile::tempdir().unwrap();
1972
    let root = dir.path();
1973
    let origin = Repo::init(&root.join("origin")).unwrap();
1974
    let url = root.join("origin").to_string_lossy().to_string();
1975
1976
    // A is the root. Before the policy, an unsigned push from B is fine.
75167672 Andy McCall 1977
    let mut a = Repo::clone(&url, &root.join("a"))
1978
        .unwrap()
1979
        .with_home(root.join("home-a"));
1980
    let (key_a, _) = a
1981
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1982
        .unwrap();
1983
    let mut b = Repo::clone(&url, &root.join("b"))
1984
        .unwrap()
1985
        .with_home(root.join("home-b"));
83e0677b Andy McCall ↶ 1986
    write(&root.join("b"), "b.txt", b"b\n");
1987
    b.commit("unsigned before policy", &[]).unwrap();
1988
    assert!(b.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 1989
    origin.refresh().unwrap();
83e0677b Andy McCall ↶ 1990
1991
    // A creates the policy and pushes it; origin now enforces it.
1992
    write(&root.join("a"), "a.txt", b"a\n");
1993
    a.commit("a", &[]).unwrap();
1994
    let sp = a.policy_init().unwrap();
1995
    assert_eq!(sp.policy.serial, 1);
1996
    a.pull("origin").unwrap();
1997
    let results = a.push("origin", false).unwrap();
767ac6cd Andy McCall 1998
    origin.refresh().unwrap();
83e0677b Andy McCall ↶ 1999
    assert!(results.iter().all(|r| r.ok), "{results:?}");
2000
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
2001
2002
    // B pulls the policy. Without an identity B cannot push at all.
2003
    b.pull("origin").unwrap();
75167672 Andy McCall 2004
    assert!(
2005
        b.current_policy().unwrap().is_some(),
2006
        "the policy arrived with the fetch"
2007
    );
83e0677b Andy McCall ↶ 2008
    assert!(b.push("origin", false).is_err());
2009
    // With an identity the policy does not list, the push is rejected by origin.
75167672 Andy McCall 2010
    let (key_b, id_b) = b
2011
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2012
        .unwrap();
83e0677b Andy McCall ↶ 2013
    write(&root.join("b"), "b.txt", b"b2\n");
2014
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
2015
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
2016
    let r = b.push("origin", false).unwrap();
767ac6cd Andy McCall 2017
    origin.refresh().unwrap();
75167672 Andy McCall 2018
    assert!(
2019
        !r[0].ok && r[0].reason.contains("may not update"),
2020
        "{:?}",
2021
        r
2022
    );
83e0677b Andy McCall ↶ 2023
2024
    // A grants B (identity handed over as a file) and publishes the policy.
2025
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
2026
    assert_eq!(sp.policy.serial, 2);
2027
    let r = a.push("origin", false).unwrap();
767ac6cd Andy McCall 2028
    origin.refresh().unwrap();
83e0677b Andy McCall ↶ 2029
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2030
    // B must fetch the new policy before pushing.
75167672 Andy McCall 2031
    assert!(b
2032
        .push("origin", false)
2033
        .unwrap_or_else(|e| vec![RefResult {
2034
            name: "main".into(),
2035
            ok: false,
2036
            reason: e.to_string()
2037
        }])
2038
        .iter()
2039
        .all(|x| !x.ok));
83e0677b Andy McCall ↶ 2040
    b.pull("origin").unwrap();
2041
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
2042
    let r = b.push("origin", false).unwrap();
767ac6cd Andy McCall 2043
    origin.refresh().unwrap();
83e0677b Andy McCall ↶ 2044
    assert!(r[0].ok, "{:?}", r);
2045
    // Origin verified B's change under the policy.
2046
    let heads = origin.bookmark_heads().unwrap();
2047
    for h in &heads {
2048
        let c = origin.store().get_change(h).unwrap();
2049
        if c.author == key_b {
75167672 Andy McCall 2050
            origin
2051
                .change_allowed(
2052
                    h,
2053
                    &origin.current_policy().unwrap().unwrap().1.policy,
2054
                    "main",
2055
                )
2056
                .unwrap();
83e0677b Andy McCall ↶ 2057
        }
2058
    }
2059
2060
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
2061
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
2062
    forged.serial = 3;
2063
    forged.roots = vec![key_b];
2064
    let fh = forged.hash();
2065
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 2066
    let forged = SignedPolicy {
2067
        policy: forged,
2068
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
2069
    };
2070
    let r = origin
2071
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
2072
        .unwrap();
83e0677b Andy McCall ↶ 2073
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
2074
    let stale = a.current_policy().unwrap().unwrap().1;
2075
    let mut old = stale.clone();
2076
    old.policy.serial = 1;
75167672 Andy McCall 2077
    let r = origin
2078
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
2079
        .unwrap();
83e0677b Andy McCall ↶ 2080
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
2081
2082
    // A revokes B; after B pulls the policy, B's pushes are refused again.
2083
    a.pull("origin").unwrap();
2084
    a.policy_revoke(&key_b).unwrap();
2085
    let r = a.push("origin", false).unwrap();
767ac6cd Andy McCall 2086
    origin.refresh().unwrap();
83e0677b Andy McCall ↶ 2087
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2088
    b.pull("origin").unwrap();
2089
    write(&root.join("b"), "b.txt", b"b3\n");
2090
    b.commit("b3", &[]).unwrap();
2091
    let r = b.push("origin", false).unwrap();
767ac6cd Andy McCall 2092
    origin.refresh().unwrap();
83e0677b Andy McCall ↶ 2093
    assert!(!r[0].ok, "{:?}", r);
2094
2095
    // A clone by a third party receives and verifies everything.
75167672 Andy McCall 2096
    let c = Repo::clone(&url, &root.join("c"))
2097
        .unwrap()
2098
        .with_home(root.join("home-c"));
83e0677b Andy McCall ↶ 2099
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
75167672 Andy McCall 2100
    assert!(c
2101
        .current_policy()
2102
        .unwrap()
2103
        .unwrap()
2104
        .1
2105
        .policy
2106
        .roots
2107
        .contains(&key_a));
83e0677b Andy McCall ↶ 2108
    assert!(!c.snapshot("status").unwrap().changed);
2109
}
d02e545d Andy McCall ↶ 2110
9ae4d15a Andy McCall ↶ 2111
/// oxygen#66: a gc says what it is doing, phase by phase.
d02e545d Andy McCall ↶ 2112
#[test]
9ae4d15a Andy McCall ↶ 2113
fn gc_reports_its_phases() {
2114
    hermetic();
2115
    let dir = tempfile::tempdir().unwrap();
2116
    let repo = Repo::init(dir.path()).unwrap();
2117
    for i in 0..3 {
2118
        write(
2119
            dir.path(),
2120
            &format!("f{i}.txt"),
2121
            format!("{i}\n").as_bytes(),
2122
        );
2123
        repo.commit(&format!("c{i}"), &[]).unwrap();
2124
    }
2125
    let mut phases = Vec::new();
2126
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
2127
        .unwrap();
2128
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
2129
    assert!(
2130
        phases.iter().any(|p| p.starts_with("pruning")),
2131
        "{phases:?}"
2132
    );
2133
    assert!(
2134
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
2135
        "{phases:?}"
2136
    );
2137
    assert!(
2138
        phases
2139
            .iter()
2140
            .any(|p| p.starts_with("writing the index of ")),
2141
        "{phases:?}"
2142
    );
2143
}
2144
2145
#[test]
d02e545d Andy McCall ↶ 2146
fn gc_packs_objects_and_history_still_works() {
2147
    hermetic();
2148
    let dir = tempfile::tempdir().unwrap();
2149
    let root = dir.path();
2150
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2151
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2152
        .unwrap();
d02e545d Andy McCall ↶ 2153
    repo.set_user_config("core.sign", "change").unwrap();
2154
    write(root, "a.txt", b"one\n");
2155
    let h1 = repo.commit("one", &[]).unwrap();
2156
    write(root, "a.txt", b"two\n");
2157
    write(root, "big.bin", &vec![0u8; 100_000]);
2158
    let h2 = repo.commit("two", &[]).unwrap();
ba160f60 Andy McCall ↶ 2159
    // Several snapshots leave superseded working-copy versions behind.
2160
    for i in 0..5 {
2161
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
2162
        repo.snapshot("status").unwrap();
2163
    }
2164
    write(root, "a.txt", b"two\n");
2165
    repo.snapshot("status").unwrap();
d02e545d Andy McCall ↶ 2166
    let before = repo.store().list().unwrap();
2167
    assert!(repo.store().loose_count().unwrap() > 0);
ba160f60 Andy McCall ↶ 2168
2169
    // With the default retention every operation's view is a root: nothing prunes.
2170
    let r = repo.gc(true).unwrap();
2171
    assert_eq!(r.packed.objects, before.len());
2172
    assert_eq!(r.pruned.objects, 0);
d02e545d Andy McCall ↶ 2173
    assert_eq!(repo.store().loose_count().unwrap(), 0);
2174
    assert_eq!(repo.store().list().unwrap(), before);
ba160f60 Andy McCall ↶ 2175
2176
    // With zero retention only the current view is a root: superseded
2177
    // working copies go, everything reachable stays.
2178
    repo.config.set("core.op-retention", "0").unwrap();
2179
    repo.save_config().unwrap();
21b2aec2 Andy McCall ↶ 2180
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
ba160f60 Andy McCall ↶ 2181
    let r = repo.gc(true).unwrap();
2182
    assert!(r.pruned.objects >= 5, "{r:?}");
2183
    let after = repo.store().list().unwrap();
2184
    assert!(after.len() < before.len());
2185
    assert!(after.contains(&h1) && after.contains(&h2));
2186
    for (_, op) in repo.op_log().unwrap() {
2187
        assert!(!op.command.is_empty(), "operation objects are all kept");
2188
    }
2189
    // Everything still works from the pruned, packed store.
d02e545d Andy McCall ↶ 2190
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
75167672 Andy McCall 2191
    assert!(matches!(
2192
        repo.verify_change(&h2).unwrap(),
2193
        SignatureStatus::Valid { .. }
2194
    ));
d02e545d Andy McCall ↶ 2195
    assert_eq!(repo.log().unwrap().len(), 3);
2196
    repo.checkout(&[h1], false, "checkout").unwrap();
2197
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
2198
    repo.checkout(&[h2], false, "checkout").unwrap();
2199
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
2200
    assert!(!repo.snapshot("status").unwrap().changed);
ba160f60 Andy McCall ↶ 2201
    // Grace period defers pruning of young garbage.
d02e545d Andy McCall ↶ 2202
    write(root, "a.txt", b"three\n");
2203
    repo.commit("three", &[]).unwrap();
ba160f60 Andy McCall ↶ 2204
    let r = repo.gc(false).unwrap();
2205
    assert_eq!(r.pruned.objects, 0);
2206
    assert!(r.pruned.deferred > 0);
2207
    let r = repo.gc(true).unwrap();
2208
    assert!(r.pruned.objects > 0);
2209
    assert_eq!(repo.log().unwrap().len(), 4);
21b2aec2 Andy McCall ↶ 2210
    // Restoring the default retention makes the old views roots again; the
2211
    // working copies they name were pruned, which gc tolerates.
2212
    repo.config.set("core.op-retention", "90").unwrap();
2213
    repo.save_config().unwrap();
2214
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2215
    let r = repo.gc(false).unwrap();
2216
    assert_eq!(r.pruned.objects, 0);
2217
    assert_eq!(repo.log().unwrap().len(), 4);
d02e545d Andy McCall ↶ 2218
}
614541c3 Andy McCall ↶ 2219
2220
#[test]
2221
fn describe_amend_abandon_heads() {
2222
    hermetic();
2223
    let dir = tempfile::tempdir().unwrap();
2224
    let root = dir.path();
2225
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2226
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2227
        .unwrap();
614541c3 Andy McCall ↶ 2228
    repo.set_user_config("core.sign", "change").unwrap();
2229
    write(root, "a.txt", b"one\n");
2230
    let h1 = repo.commit("first", &[]).unwrap();
2231
    write(root, "a.txt", b"one\ntwo\n");
2232
    let h2 = repo.commit("secnod", &[]).unwrap();
2233
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
2234
2235
    // describe: same ChangeId, new hash, bookmark and working copy follow.
2236
    let h2b = repo.describe(&h2, "second").unwrap();
2237
    assert_ne!(h2b, h2);
2238
    let c = repo.store().get_change(&h2b).unwrap();
75167672 Andy McCall 2239
    assert_eq!(
2240
        (c.change_id, c.message.as_str(), c.deps.clone()),
2241
        (id2, "second", vec![h1])
2242
    );
614541c3 Andy McCall ↶ 2243
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
75167672 Andy McCall 2244
    assert!(matches!(
2245
        repo.verify_change(&h2b).unwrap(),
2246
        SignatureStatus::Valid { .. }
2247
    ));
614541c3 Andy McCall ↶ 2248
    let s = repo.snapshot("status").unwrap();
2249
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
75167672 Andy McCall 2250
    assert_eq!(
2251
        repo.resolve_change(&id2.short(8)).unwrap(),
2252
        h2b,
2253
        "the old object is no longer reachable from the log"
2254
    );
c07e0e7d Andy McCall ↶ 2255
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
2256
    let h1b = repo.describe(&h1, "first, described").unwrap();
2257
    assert_ne!(h1b, h1);
2258
    let heads = repo.bookmark_heads().unwrap();
2259
    assert_eq!(heads.len(), 1);
2260
    let top = repo.store().get_change(&heads[0]).unwrap();
2261
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
75167672 Andy McCall 2262
    assert!(
2263
        matches!(
2264
            repo.verify_change(&heads[0]).unwrap(),
2265
            SignatureStatus::Valid { .. }
2266
        ),
2267
        "rewritten own change is re-signed"
2268
    );
c07e0e7d Andy McCall ↶ 2269
    let (_, wc) = repo.working_copy().unwrap();
75167672 Andy McCall 2270
    assert_eq!(
2271
        wc.deps,
2272
        vec![heads[0]],
2273
        "the working copy follows the rewrite"
2274
    );
c07e0e7d Andy McCall ↶ 2275
    assert!(!repo.snapshot("status").unwrap().changed);
2276
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 2277
    assert!(
2278
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
2279
    );
614541c3 Andy McCall ↶ 2280
2281
    // amend: fold an edit into the head; the result is one change from h1.
2282
    write(root, "a.txt", b"one\ntwo\nthree\n");
2283
    write(root, "b.txt", b"b\n");
2284
    let h2c = repo.amend(None).unwrap();
2285
    let c = repo.store().get_change(&h2c).unwrap();
2286
    assert_eq!(c.change_id, id2);
2287
    assert_eq!(c.message, "second");
2288
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
75167672 Andy McCall 2289
    assert_eq!(
2290
        repo.log().unwrap().len(),
2291
        3,
2292
        "working copy, amended head, first"
2293
    );
614541c3 Andy McCall ↶ 2294
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
75167672 Andy McCall 2295
    assert!(
2296
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
2297
    );
614541c3 Andy McCall ↶ 2298
    assert!(snap.files.contains_key("b.txt"));
2299
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 2300
    assert!(
2301
        repo.amend(None).is_err(),
2302
        "clean working copy and no message"
2303
    );
614541c3 Andy McCall ↶ 2304
    let h2d = repo.amend(Some("second, amended")).unwrap();
75167672 Andy McCall 2305
    assert_eq!(
2306
        repo.store().get_change(&h2d).unwrap().message,
2307
        "second, amended"
2308
    );
614541c3 Andy McCall ↶ 2309
2310
    // abandon: the head goes, its content stays as uncommitted work.
2311
    repo.abandon(&h2d).unwrap();
75167672 Andy McCall 2312
    assert_eq!(
2313
        repo.bookmark_heads().unwrap(),
2314
        vec![h1b],
2315
        "the described first change is the head again"
2316
    );
614541c3 Andy McCall ↶ 2317
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 2318
    let paths: Vec<_> = s
2319
        .statuses
2320
        .iter()
2321
        .map(|p| (p.path.as_str(), p.status))
2322
        .collect();
2323
    assert_eq!(
2324
        paths,
2325
        vec![
2326
            ("a.txt", ChangeStatus::Modified),
2327
            ("b.txt", ChangeStatus::Added)
2328
        ]
2329
    );
614541c3 Andy McCall ↶ 2330
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
2331
    let h3 = repo.commit("recommitted", &[]).unwrap();
2332
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
2333
    // undo brings the abandoned head back.
2334
    repo.undo().unwrap();
2335
    repo.undo().unwrap();
2336
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
c07e0e7d Andy McCall ↶ 2337
6706bdcf Andy McCall ↶ 2338
    // Abandoning a non-head whose dependent references its atoms reifies
2339
    // the references (here: a.txt vanishes with it, so the dependent's edit
2340
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
c07e0e7d Andy McCall ↶ 2341
    let base = repo.bookmark_heads().unwrap()[0];
2342
    let base_change = repo.store().get_change(&base).unwrap();
2343
    let h1_now = base_change.deps[0];
6706bdcf Andy McCall ↶ 2344
    let notes = repo.abandon(&h1_now).unwrap();
75167672 Andy McCall 2345
    assert!(
2346
        !notes.is_empty(),
2347
        "the dependent's edit of a.txt was reified"
2348
    );
6706bdcf Andy McCall ↶ 2349
    let heads = repo.bookmark_heads().unwrap();
2350
    let after = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 2351
    assert!(
2352
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
2353
        "{:?}",
2354
        after.files.keys()
2355
    );
6706bdcf Andy McCall ↶ 2356
    repo.undo().unwrap();
2357
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
c07e0e7d Andy McCall ↶ 2358
    write(root, "c.txt", b"c\n");
2359
    let hc = repo.commit("c", &[]).unwrap();
2360
    write(root, "d.txt", b"d\n");
2361
    let hd = repo.commit("d", &[hc]).unwrap();
2362
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
2363
    repo.abandon(&hc).unwrap();
2364
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2365
    assert!(!heads.contains(&hc));
75167672 Andy McCall 2366
    let d_now = heads
2367
        .iter()
2368
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
2369
        .copied()
2370
        .unwrap();
2371
    assert!(
2372
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
2373
        "d inherited c's (empty) dependencies"
2374
    );
c07e0e7d Andy McCall ↶ 2375
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 2376
    assert_eq!(
2377
        s.statuses
2378
            .iter()
2379
            .map(|p| p.path.as_str())
2380
            .collect::<Vec<_>>(),
2381
        vec!["c.txt"],
2382
        "c's content is now uncommitted work"
2383
    );
614541c3 Andy McCall ↶ 2384
}
79ab8528 Andy McCall ↶ 2385
2386
#[test]
2387
fn git_export_mirrors_history() {
2388
    hermetic();
75167672 Andy McCall 2389
    if std::process::Command::new("git")
2390
        .arg("--version")
2391
        .output()
2392
        .is_err()
2393
    {
79ab8528 Andy McCall ↶ 2394
        eprintln!("git not installed; skipping");
2395
        return;
2396
    }
2397
    let dir = tempfile::tempdir().unwrap();
2398
    let root = dir.path();
75167672 Andy McCall 2399
    let mut repo = Repo::init(&root.join("r"))
2400
        .unwrap()
2401
        .with_home(root.join("home"));
2402
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
2403
        .unwrap();
79ab8528 Andy McCall ↶ 2404
    let r = root.join("r");
2405
    write(&r, "README.md", b"hello\n");
2406
    write(&r, "src/main.rs", b"fn main() {}\n");
2407
    let h1 = repo.commit("first", &[]).unwrap();
2408
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
2409
    write(&r, "logo.png", b"\x89PNG\0\0");
2410
    let h2 = repo.commit("second", &[]).unwrap();
2411
2412
    let git_dir = root.join("mirror.git");
2413
    let rep = repo.git_export(&git_dir).unwrap();
2414
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
2415
    let git = |args: &[&str]| -> String {
75167672 Andy McCall 2416
        let out = std::process::Command::new("git")
2417
            .arg("-C")
2418
            .arg(&git_dir)
2419
            .args(args)
2420
            .output()
2421
            .unwrap();
2422
        assert!(
2423
            out.status.success(),
2424
            "{}",
2425
            String::from_utf8_lossy(&out.stderr)
2426
        );
79ab8528 Andy McCall ↶ 2427
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2428
    };
2429
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
2430
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2431
    assert_eq!(git(&["show", "main:README.md"]), "hello");
2432
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 2433
    assert!(
2434
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
2435
        "{body}"
2436
    );
79ab8528 Andy McCall ↶ 2437
    assert!(body.contains("Change-Id: "), "{body}");
75167672 Andy McCall 2438
    assert_eq!(
2439
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
2440
        "Ada Lovelace <[email protected]>"
2441
    );
2442
    assert_eq!(
2443
        git(&["ls-tree", "--name-only", "main"]),
2444
        "README.md\nlogo.png\nsrc"
2445
    );
79ab8528 Andy McCall ↶ 2446
2447
    // Re-export is incremental.
2448
    let rep = repo.git_export(&git_dir).unwrap();
2449
    assert_eq!((rep.exported, rep.skipped), (0, 2));
2450
2451
    // An independent change makes two heads; the next state is one more
2452
    // commit on the linear branch whose tree is the union.
2453
    repo.checkout(&[h1], false, "checkout").unwrap();
2454
    write(&r, "other.txt", b"o\n");
2455
    let h3 = repo.commit("third", &[]).unwrap();
2456
    let rep = repo.git_export(&git_dir).unwrap();
2457
    assert_eq!((rep.exported, rep.heads), (1, 2));
2458
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
2459
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
2460
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
2461
    assert_eq!(git(&["show", "main:other.txt"]), "o");
2462
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
75167672 Andy McCall 2463
    assert_eq!(
2464
        git(&["ls-tree", "--name-only", "main"]),
2465
        "README.md\nlogo.png\nother.txt\nsrc"
2466
    );
79ab8528 Andy McCall ↶ 2467
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 2468
    assert!(
2469
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
2470
        "{body}"
2471
    );
79ab8528 Andy McCall ↶ 2472
    // A rewrite is a new state whose one new change is the rewritten one.
2473
    repo.describe(&h3, "third, described").unwrap();
2474
    let rep = repo.git_export(&git_dir).unwrap();
2475
    assert_eq!(rep.exported, 1);
75167672 Andy McCall 2476
    assert_eq!(
2477
        git(&["log", "-1", "--format=%s", "main"]),
2478
        "third, described"
2479
    );
79ab8528 Andy McCall ↶ 2480
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
2481
    let _ = h2;
2482
}
c3069537 Andy McCall ↶ 2483
2484
#[test]
2485
fn git_import_reproduces_trees() {
c3d2ef61 Andy McCall ↶ 2486
    git_import_reproduces_trees_with(None);
2487
}
2488
2489
/// The same import with every merge rendered in batches of one file
2490
/// (oxygen#25): what a merge onto a base of thousands of files takes.
2491
#[test]
2492
fn git_import_reproduces_trees_in_batches() {
2493
    git_import_reproduces_trees_with(Some(1));
2494
}
2495
2496
fn git_import_reproduces_trees_with(batch: Option<usize>) {
2497
    crate::repo::git::set_merge_batch_for_tests(batch);
c3069537 Andy McCall ↶ 2498
    hermetic();
75167672 Andy McCall 2499
    if std::process::Command::new("git")
2500
        .arg("--version")
2501
        .output()
2502
        .is_err()
2503
    {
c3069537 Andy McCall ↶ 2504
        eprintln!("git not installed; skipping");
2505
        return;
2506
    }
2507
    let dir = tempfile::tempdir().unwrap();
2508
    let root = dir.path();
2509
    let g = root.join("src.git");
2510
    fs::create_dir_all(&g).unwrap();
2511
    let git = |args: &[&str]| -> String {
2512
        let out = std::process::Command::new("git")
2513
            .arg("-C")
2514
            .arg(&g)
75167672 Andy McCall 2515
            .args([
2516
                "-c",
2517
                "user.name=Grace",
2518
                "-c",
2519
                "[email protected]",
2520
                "-c",
2521
                "commit.gpgsign=false",
2522
            ])
c3069537 Andy McCall ↶ 2523
            .args(args)
2524
            .output()
2525
            .unwrap();
75167672 Andy McCall 2526
        assert!(
2527
            out.status.success(),
2528
            "git {args:?}: {}",
2529
            String::from_utf8_lossy(&out.stderr)
2530
        );
c3069537 Andy McCall ↶ 2531
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2532
    };
2533
    git(&["init", "-q", "-b", "main"]);
2534
    write(&g, "README.md", b"# Hi\n");
2535
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
2536
    git(&["add", "."]);
2537
    git(&["commit", "-q", "-m", "initial"]);
2538
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2539
    write(&g, "run.sh", b"#!/bin/sh\n");
2540
    #[cfg(unix)]
2541
    {
2542
        use std::os::unix::fs::PermissionsExt;
2543
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
2544
    }
2545
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
2546
    git(&["add", "."]);
75167672 Andy McCall 2547
    git(&[
2548
        "commit",
2549
        "-q",
2550
        "-m",
2551
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
2552
    ]);
c3069537 Andy McCall ↶ 2553
    // A branch that edits README, merged back with a conflict-free merge.
2554
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
2555
    write(&g, "README.md", b"# Hi\n\nMore.\n");
2556
    git(&["commit", "-q", "-am", "readme"]);
2557
    git(&["checkout", "-q", "main"]);
2558
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
2559
    // A branch from the initial commit inserting at the same place as
2560
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
2561
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
2562
    git(&["checkout", "-q", "-b", "clash", &initial]);
2563
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
2564
    git(&["commit", "-q", "-am", "clash"]);
2565
    git(&["checkout", "-q", "main"]);
75167672 Andy McCall 2566
    let _ = std::process::Command::new("git")
2567
        .arg("-C")
2568
        .arg(&g)
2569
        .args(["merge", "-q", "clash"])
2570
        .output();
2571
    write(
2572
        &g,
2573
        "src/lib.rs",
2574
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2575
    );
c3069537 Andy McCall ↶ 2576
    git(&["add", "."]);
2577
    git(&["commit", "-q", "-m", "resolve clash"]);
2578
    git(&["rm", "-q", "logo.png"]);
2579
    git(&["commit", "-q", "-m", "drop logo"]);
6e723b81 Andy McCall ↶ 2580
    // A rename with a small edit is imported as a move of the same node.
2581
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
75167672 Andy McCall 2582
    write(
2583
        &g,
2584
        "src/lib2.rs",
2585
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
2586
    );
6e723b81 Andy McCall ↶ 2587
    git(&["add", "."]);
2588
    git(&["commit", "-q", "-m", "rename lib"]);
958fb27d Andy McCall ↶ 2589
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
2590
    // run.sh is the same as in the first parent's tree, but the merged
2591
    // change touched it, so the importer must compare it, not skip it.
2592
    git(&["checkout", "-q", "-b", "discarded"]);
2593
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
2594
    git(&["commit", "-q", "-am", "discarded edit"]);
2595
    git(&["checkout", "-q", "main"]);
314db9b4 Andy McCall ↶ 2596
    git(&[
2597
        "merge",
2598
        "-q",
2599
        "-s",
2600
        "ours",
2601
        "-m",
2602
        "merge discarded, keeping ours",
2603
        "discarded",
2604
    ]);
c3069537 Andy McCall ↶ 2605
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
2606
2607
    let dest = root.join("oxy");
2608
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
2609
    let rep = repo.import_git(&g, "main").unwrap();
2610
    assert_eq!(rep.commits, expected_count);
958fb27d Andy McCall ↶ 2611
    assert_eq!(rep.merges, 3);
314db9b4 Andy McCall ↶ 2612
    assert_eq!(
2613
        fs::read(dest.join("run.sh")).unwrap(),
2614
        b"#!/bin/sh\n",
2615
        "the ours merge kept main's run.sh"
2616
    );
958fb27d Andy McCall ↶ 2617
    let v = repo.verify_git_import(&g, "main").unwrap();
2618
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
2619
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
c3069537 Andy McCall ↶ 2620
    // The working copy equals the Git tree at main.
75167672 Andy McCall 2621
    assert_eq!(
2622
        fs::read(dest.join("src/lib2.rs")).unwrap(),
2623
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2624
    );
6e723b81 Andy McCall ↶ 2625
    assert!(!dest.join("src/lib.rs").exists());
75167672 Andy McCall 2626
    assert_eq!(
2627
        fs::read(dest.join("README.md")).unwrap(),
2628
        b"# Hi\n\nMore.\n"
2629
    );
c3069537 Andy McCall ↶ 2630
    assert!(!dest.join("logo.png").exists());
2631
    #[cfg(unix)]
2632
    {
2633
        use std::os::unix::fs::PermissionsExt;
75167672 Andy McCall 2634
        assert!(
2635
            fs::metadata(dest.join("run.sh"))
2636
                .unwrap()
2637
                .permissions()
2638
                .mode()
2639
                & 0o111
2640
                != 0
2641
        );
c3069537 Andy McCall ↶ 2642
    }
75167672 Andy McCall 2643
    assert!(
2644
        !repo.snapshot("status").unwrap().changed,
2645
        "clean after import"
2646
    );
c3069537 Andy McCall ↶ 2647
    let heads = repo.bookmark_heads().unwrap();
2648
    let st = repo.load_state(&heads).unwrap();
2649
    assert!(!st.materialize().is_conflicted());
2650
    assert_eq!(st.len(), expected_count);
75167672 Andy McCall 2651
    let tip = repo
2652
        .log()
2653
        .unwrap()
2654
        .into_iter()
2655
        .find(|e| e.change.message.starts_with("rename lib"))
2656
        .unwrap();
6e723b81 Andy McCall ↶ 2657
    let c = repo.store().get_change(&tip.hash).unwrap();
75167672 Andy McCall 2658
    assert!(
2659
        c.tree_ops
2660
            .iter()
2661
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
2662
        "{:?}",
2663
        c.tree_ops
2664
    );
2665
    assert!(!c
2666
        .tree_ops
2667
        .iter()
2668
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
c3069537 Andy McCall ↶ 2669
    // Messages carry Git trailers; the Change-Id trailer was honoured.
2670
    let log = repo.log().unwrap();
75167672 Andy McCall 2671
    let second = log
2672
        .iter()
2673
        .find(|e| e.change.message.starts_with("second"))
2674
        .unwrap();
2675
    assert_eq!(
2676
        second.change.change_id,
2677
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
2678
    );
2679
    assert!(second
2680
        .change
2681
        .message
2682
        .contains("Git-Author: Grace <[email protected]>"));
2683
    let resolve = log
2684
        .iter()
2685
        .find(|e| e.change.message.starts_with("resolve clash"))
2686
        .unwrap();
2687
    assert_eq!(
2688
        resolve.change.kind,
2689
        ChangeKind::Resolution,
2690
        "a conflicting Git merge becomes a resolution"
2691
    );
c3069537 Andy McCall ↶ 2692
    // Re-importing into another fresh repository gives the same ChangeIds.
75167672 Andy McCall 2693
    let repo2 = Repo::init(&root.join("oxy2"))
2694
        .unwrap()
2695
        .with_home(root.join("home"));
c3069537 Andy McCall ↶ 2696
    repo2.import_git(&g, "main").unwrap();
dfb23a3a Andy McCall ↶ 2697
    // New nodes' identifiers derive from the commit (spec §23), so the
2698
    // re-import is not just the same ChangeIds but the same changes.
2699
    assert_eq!(
2700
        repo2.bookmark_heads().unwrap(),
2701
        repo.bookmark_heads().unwrap()
2702
    );
75167672 Andy McCall 2703
    let ids: BTreeSet<ChangeId> = repo
2704
        .log()
2705
        .unwrap()
2706
        .iter()
2707
        .filter(|e| !e.is_working_copy)
2708
        .map(|e| e.change.change_id)
2709
        .collect();
2710
    let ids2: BTreeSet<ChangeId> = repo2
2711
        .log()
2712
        .unwrap()
2713
        .iter()
2714
        .filter(|e| !e.is_working_copy)
2715
        .map(|e| e.change.change_id)
2716
        .collect();
c3069537 Andy McCall ↶ 2717
    assert_eq!(ids, ids2);
2718
    // Round trip back out to Git reproduces the tip tree.
2719
    let mirror = root.join("mirror.git");
2720
    repo.git_export(&mirror).unwrap();
75167672 Andy McCall 2721
    let out = std::process::Command::new("git")
2722
        .arg("-C")
2723
        .arg(&mirror)
2724
        .args(["show", "main:src/lib2.rs"])
2725
        .output()
2726
        .unwrap();
2727
    assert_eq!(
2728
        String::from_utf8_lossy(&out.stdout),
2729
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2730
    );
2731
    let out = std::process::Command::new("git")
2732
        .arg("-C")
2733
        .arg(&mirror)
2734
        .args(["show", "main:src/lib.rs"])
2735
        .output()
2736
        .unwrap();
2737
    assert!(
2738
        !out.status.success(),
2739
        "the old path is gone from the export"
2740
    );
c3069537 Andy McCall ↶ 2741
}
252e8cb2 Andy McCall ↶ 2742
2743
#[test]
2744
fn checkpoints_accelerate_loading_and_stay_correct() {
2745
    hermetic();
2746
    let dir = tempfile::tempdir().unwrap();
2747
    let root = dir.path();
2748
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2749
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2750
    repo.save_config().unwrap();
2751
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2752
    let mut hashes = Vec::new();
2753
    for i in 0..12 {
75167672 Andy McCall 2754
        write(
2755
            root,
2756
            "a.txt",
2757
            format!(
2758
                "{}\n",
2759
                (0..=i)
2760
                    .map(|k| k.to_string())
2761
                    .collect::<Vec<_>>()
2762
                    .join("\n")
2763
            )
2764
            .as_bytes(),
2765
        );
252e8cb2 Andy McCall ↶ 2766
        write(root, &format!("f{i}.txt"), b"x\n");
2767
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2768
    }
75167672 Andy McCall 2769
    let (_, cp) = repo
2770
        .latest_checkpoint("main")
2771
        .unwrap()
2772
        .expect("automatic checkpoint");
252e8cb2 Andy McCall ↶ 2773
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2774
    // Loading through the checkpoint equals loading everything.
2775
    let heads = repo.bookmark_heads().unwrap();
2776
    let fast = repo.load_state(&heads).unwrap();
2777
    let full = repo.load_state_full(&heads).unwrap();
2778
    assert_eq!(fast.len(), full.len());
2779
    assert_eq!(fast.heads(), full.heads());
2780
    let (a, b) = (fast.materialize(), full.materialize());
75167672 Andy McCall 2781
    assert_eq!(
2782
        a.files.keys().collect::<Vec<_>>(),
2783
        b.files.keys().collect::<Vec<_>>()
2784
    );
252e8cb2 Andy McCall ↶ 2785
    for (p, f) in &a.files {
2786
        assert_eq!(f.content, b.files[p].content, "{p}");
2787
    }
2788
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2789
    // A head set that does not contain the checkpoint's heads falls back.
75167672 Andy McCall 2790
    assert!(repo
2791
        .load_state_checkpointed(&[hashes[0]])
2792
        .unwrap()
2793
        .is_none());
252e8cb2 Andy McCall ↶ 2794
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2795
    // Everything else keeps working on top of the checkpoint.
2796
    assert!(!repo.snapshot("status").unwrap().changed);
2797
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2798
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2799
    let (r, n, bytes) = repo.checkpoint().unwrap();
2800
    assert!(n >= 12 && bytes > 0);
2801
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2802
    write(root, "a.txt", b"after\n");
2803
    let h_after = repo.commit("after", &[]).unwrap();
2804
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2805
    assert!(st.contains(&h_after));
75167672 Andy McCall 2806
    assert!(
2807
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2808
    );
252e8cb2 Andy McCall ↶ 2809
    assert_eq!(repo.log().unwrap().len(), 14);
2810
    // Checkpoints survive gc.
2811
    repo.gc(true).unwrap();
2812
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
75167672 Andy McCall 2813
    assert!(repo
2814
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2815
        .unwrap()
2816
        .is_some());
252e8cb2 Andy McCall ↶ 2817
}
135212de Andy McCall ↶ 2818
2819
#[test]
2820
fn quick_status_for_prompts() {
2821
    hermetic();
2822
    let dir = tempfile::tempdir().unwrap();
2823
    let root = dir.path();
2824
    let origin = Repo::init(&root.join("origin")).unwrap();
2825
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2826
    let a = Repo::clone(&url, &root.join("a"))
2827
        .unwrap()
2828
        .with_home(root.join("home"));
135212de Andy McCall ↶ 2829
    let ops_before = a.op_log().unwrap().len();
2830
    let info = a.quick_status().unwrap();
75167672 Andy McCall 2831
    assert_eq!(
2832
        (
2833
            info.bookmark.as_str(),
2834
            info.heads,
2835
            info.dirty,
2836
            info.conflicted,
2837
            info.ahead,
2838
            info.behind
2839
        ),
2840
        ("main", 0, false, false, Some(0), Some(0))
2841
    );
135212de Andy McCall ↶ 2842
    write(&root.join("a"), "f.txt", b"f\n");
2843
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
75167672 Andy McCall 2844
    assert_eq!(
2845
        a.op_log().unwrap().len(),
2846
        ops_before,
2847
        "quick_status records nothing"
2848
    );
135212de Andy McCall ↶ 2849
    // A snapshotted but uncommitted change is still dirty.
2850
    a.snapshot("status").unwrap();
2851
    assert!(a.quick_status().unwrap().dirty);
2852
    a.commit("f", &[]).unwrap();
2853
    let info = a.quick_status().unwrap();
2854
    assert!(!info.dirty, "clean right after a commit");
2855
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
75167672 Andy McCall 2856
    assert_eq!(
2857
        info.format("%b %c%d%x%A%D"),
2858
        format!("main {}+1", info.change_id)
2859
    );
135212de Andy McCall ↶ 2860
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2861
    // Touching a file without changing it is not dirty; changing content of
2862
    // the same size is.
2863
    let p = root.join("a/f.txt");
2864
    let content = fs::read(&p).unwrap();
2865
    fs::write(&p, &content).unwrap();
2866
    assert!(!a.quick_status().unwrap().dirty);
2867
    fs::write(&p, b"g\n").unwrap();
2868
    assert!(a.quick_status().unwrap().dirty);
2869
    fs::write(&p, b"f\n").unwrap();
2870
    // Push, then a second clone commits and pushes: we are behind.
2871
    assert!(a.push("origin", false).unwrap()[0].ok);
2872
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
75167672 Andy McCall 2873
    let b = Repo::clone(&url, &root.join("b"))
2874
        .unwrap()
2875
        .with_home(root.join("home-b"));
135212de Andy McCall ↶ 2876
    write(&root.join("b"), "g.txt", b"g\n");
2877
    b.commit("g", &[]).unwrap();
2878
    b.push("origin", false).unwrap();
2879
    a.fetch("origin").unwrap();
2880
    let info = a.quick_status().unwrap();
2881
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2882
    assert_eq!(info.format("%A%D"), "-1");
2883
    let _ = origin;
2884
}
b3c5a59a Andy McCall ↶ 2885
2886
#[test]
2887
fn lazy_blobs_are_fetched_on_first_read() {
2888
    hermetic();
2889
    let dir = tempfile::tempdir().unwrap();
2890
    let root = dir.path();
2891
    let origin_dir = root.join("origin");
75167672 Andy McCall 2892
    let origin = Repo::init(&origin_dir)
2893
        .unwrap()
2894
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 2895
    let url = origin_dir.to_string_lossy().to_string();
2896
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2897
    write(&origin_dir, "big.bin", &big);
2898
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2899
    write(&origin_dir, "t.txt", b"t\n");
2900
    let h = origin.commit("blobs", &[]).unwrap();
2901
    let big_ref = Repo::blob_ref(&big);
2902
2903
    // Fetch only (no checkout) with a filter: the big blob stays absent.
75167672 Andy McCall 2904
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2905
        .unwrap()
2906
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 2907
    let a = {
2908
        let mut a = a;
2909
        a.config.set("remote.origin.url", &url).unwrap();
2910
        a.config.set("filter.max-blob", "100K").unwrap();
2911
        a.save_config().unwrap();
2912
        a
2913
    };
2914
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2915
    a.fetch("origin").unwrap();
2916
    assert!(a.store().has(&h));
2917
    assert!(!a.store().has(&big_ref), "withheld");
75167672 Andy McCall 2918
    assert!(
2919
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2920
        "small blob came along"
2921
    );
b3c5a59a Andy McCall ↶ 2922
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2923
2924
    // status and commit do not need it: adopt the state, edit a text file, commit.
2925
    let (op_ref, op) = a.head_op().unwrap();
2926
    let mut view = op.view.clone();
75167672 Andy McCall 2927
    view.bookmarks.insert(
2928
        "main".into(),
2929
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2930
    );
b3c5a59a Andy McCall ↶ 2931
    a.record_op(&[op_ref], "adopt", view).unwrap();
2932
    // Checkout reads the blob lazily, which fetches it.
2933
    a.checkout(&[h], true, "checkout").unwrap();
2934
    assert!(a.store().has(&big_ref), "fetched on first read");
2935
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2936
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2937
    write(&root.join("a"), "t.txt", b"t2\n");
2938
    a.commit("text edit", &[]).unwrap();
2939
2940
    // clone --max-blob records the filter; the checkout fetches lazily.
7421309f Andy McCall ↶ 2941
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
b3c5a59a Andy McCall ↶ 2942
    assert_eq!(b.config.max_blob, Some(1024));
2943
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2944
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2945
    assert!(parse_size("lots").is_err());
2946
}
7421309f Andy McCall ↶ 2947
2948
#[test]
2949
fn sparse_checkout_materializes_only_chosen_paths() {
2950
    hermetic();
2951
    let dir = tempfile::tempdir().unwrap();
2952
    let root = dir.path();
2953
    let origin_dir = root.join("origin");
75167672 Andy McCall 2954
    let origin = Repo::init(&origin_dir)
2955
        .unwrap()
2956
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 2957
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2958
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2959
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2960
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2961
    write(&origin_dir, "docs/logo.png", &logo);
2962
    write(&origin_dir, "README.md", b"# top\n");
2963
    let h1 = origin.commit("tree", &[]).unwrap();
2964
    let url = origin_dir.to_string_lossy().to_string();
2965
75167672 Andy McCall 2966
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2967
        .unwrap()
2968
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 2969
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2970
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2971
    assert!(root.join("a/src/main.rs").exists());
2972
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
75167672 Andy McCall 2973
    assert!(
2974
        !a.store().has(&Repo::blob_ref(&logo)),
2975
        "out-of-scope blob never fetched"
2976
    );
2977
    assert!(
2978
        !a.snapshot("status").unwrap().changed,
2979
        "out-of-scope files are not removals"
2980
    );
05e71ed6 Andy McCall ↶ 2981
    assert!(!a.quick_status().unwrap().dirty);
7421309f Andy McCall ↶ 2982
2983
    // Edits in scope commit normally and keep the rest of the tree intact.
75167672 Andy McCall 2984
    write(
2985
        &root.join("a"),
2986
        "src/lib.rs",
2987
        b"pub fn a() {}\npub fn b() {}\n",
2988
    );
7421309f Andy McCall ↶ 2989
    let h2 = a.commit("edit lib", &[]).unwrap();
2990
    let st = a.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 2991
    assert!(
2992
        st.files.contains_key("docs/guide.md"),
2993
        "the state still has everything"
2994
    );
7421309f Andy McCall ↶ 2995
    assert!(a.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 2996
    origin.refresh().unwrap();
7421309f Andy McCall ↶ 2997
    // Files created outside the scope are ignored by status.
2998
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2999
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
3000
3001
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
3002
    let mut a = a;
3003
    a.config.set("filter.paths", "src,docs").unwrap();
3004
    a.save_config().unwrap();
75167672 Andy McCall 3005
    let r = a
3006
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
3007
        .unwrap();
7421309f Andy McCall ↶ 3008
    assert!(r.written >= 2);
75167672 Andy McCall 3009
    assert_eq!(
3010
        fs::read(root.join("a/docs/logo.png")).unwrap(),
3011
        logo,
3012
        "now fetched lazily"
3013
    );
7421309f Andy McCall ↶ 3014
    assert!(!root.join("a/README.md").exists());
3015
    // Origin sees the change made under a sparse checkout with the full tree intact.
3016
    origin.pull("origin").err();
75167672 Andy McCall 3017
    let full = origin
3018
        .load_state(&origin.bookmark_heads().unwrap())
3019
        .unwrap()
3020
        .materialize();
3021
    assert!(
3022
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
3023
    );
7421309f Andy McCall ↶ 3024
    assert!(full.files.contains_key("README.md"));
3025
    let _ = h1;
3026
}
2863456a Andy McCall ↶ 3027
7bd805ff Andy McCall ↶ 3028
/// #137: a depth-0 clone takes no change, so the blobs of the state's
3029
/// binary files came with nothing and the checkout failed ("object … not
3030
/// found"); they are fetched with the checkpoint, or left lazy under
3031
/// `--max-blob`.
2863456a Andy McCall ↶ 3032
#[test]
7bd805ff Andy McCall ↶ 3033
fn a_depth_0_clone_brings_its_binary_files() {
3034
    hermetic();
3035
    let dir = tempfile::tempdir().unwrap();
3036
    let root = dir.path();
3037
    let origin_dir = root.join("origin");
3038
    let origin = Repo::init(&origin_dir)
3039
        .unwrap()
3040
        .with_home(root.join("home"));
3041
    let png: Vec<u8> = (0..4000u32)
3042
        .map(|i| (i * 7 % 251) as u8)
3043
        .chain([0, 0xff])
3044
        .collect();
3045
    // The logo comes with a.txt's first line, and the head edits that line,
3046
    // so the change that set the logo is below the head, not a head itself.
3047
    write(&origin_dir, "logo.png", &png);
3048
    write(&origin_dir, "a.txt", b"first\n");
3049
    origin.commit("logo", &[]).unwrap();
3050
    write(&origin_dir, "a.txt", b"later\n");
3051
    origin.commit("later", &[]).unwrap();
3052
    assert_eq!(origin.bookmark_heads().unwrap().len(), 1);
3053
    let url = origin_dir.to_string_lossy().to_string();
3054
    Repo::clone_shallow(&url, &root.join("a"), 0, None, &[]).unwrap();
3055
    assert_eq!(fs::read(root.join("a/logo.png")).unwrap(), png);
3056
    let lazy = Repo::clone_shallow(&url, &root.join("b"), 0, Some(0), &[]).unwrap();
3057
    assert_eq!(fs::read(root.join("b/a.txt")).unwrap(), b"later\n");
3058
    let blob = {
3059
        let heads = lazy.bookmark_heads().unwrap();
3060
        let st = lazy.load_state_history(&heads).unwrap();
3061
        st.opaque_nodes()
3062
            .iter()
3063
            .flat_map(|n| st.live_blobs(n))
3064
            .next()
3065
            .unwrap()
3066
    };
3067
    assert_eq!(lazy.read_blob(&blob).unwrap(), png, "fetched on read");
3068
}
3069
3070
#[test]
2863456a Andy McCall ↶ 3071
fn shallow_clone_and_deepen() {
3072
    hermetic();
3073
    let dir = tempfile::tempdir().unwrap();
3074
    let root = dir.path();
3075
    let origin_dir = root.join("origin");
75167672 Andy McCall 3076
    let origin = Repo::init(&origin_dir)
3077
        .unwrap()
3078
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 3079
    let mut hashes = Vec::new();
3080
    for i in 0..8 {
75167672 Andy McCall 3081
        write(
3082
            &origin_dir,
3083
            "a.txt",
3084
            format!(
3085
                "{}\n",
3086
                (0..=i)
3087
                    .map(|k| k.to_string())
3088
                    .collect::<Vec<_>>()
3089
                    .join("\n")
3090
            )
3091
            .as_bytes(),
3092
        );
2863456a Andy McCall ↶ 3093
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
3094
    }
3095
    let url = origin_dir.to_string_lossy().to_string();
75167672 Andy McCall 3096
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
3097
        .unwrap()
3098
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 3099
    assert!(a.is_shallow());
75167672 Andy McCall 3100
    assert_eq!(
3101
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
3102
        "0\n1\n2\n3\n4\n5\n6\n7\n"
3103
    );
3104
    assert!(
3105
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
3106
        "three levels present"
3107
    );
2863456a Andy McCall ↶ 3108
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
3109
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
75167672 Andy McCall 3110
    assert_eq!(
3111
        a.log().unwrap().len(),
3112
        9,
3113
        "the log shows every change from the checkpoint's metadata"
3114
    );
2863456a Andy McCall ↶ 3115
    assert!(!a.snapshot("status").unwrap().changed);
3116
    assert_eq!(a.quick_status().unwrap().heads, 1);
3117
3118
    // Work continues on top of the shallow history and pushes back.
3119
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
3120
    let h_new = a.commit("c8", &[]).unwrap();
3121
    assert!(a.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 3122
    origin.refresh().unwrap();
2863456a Andy McCall ↶ 3123
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
3124
    // Fetching new work from origin into the shallow clone works too.
3125
    write(&origin_dir, "b.txt", b"b\n");
3126
    origin.pull("origin").err();
3127
    let (_, wc) = origin.working_copy().unwrap();
3128
    let _ = wc;
75167672 Andy McCall 3129
    origin
3130
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
3131
        .unwrap();
2863456a Andy McCall ↶ 3132
    write(&origin_dir, "b.txt", b"b\n");
3133
    let h_b = origin.commit("b", &[]).unwrap();
3134
    let pr = a.pull("origin").unwrap();
3135
    assert!(pr.changed);
3136
    assert!(a.store().has(&h_b));
3137
    assert!(root.join("a/b.txt").exists());
3138
3139
    // Deepening fetches older history until the boundary is gone.
3140
    // Every commit also depends on the change that created the file, so two
3141
    // levels below the boundary hold h4, h3, and the root.
3142
    assert!(a.deepen("origin", 2).unwrap() >= 2);
3143
    assert!(a.store().has(&hashes[3]));
3144
    assert!(a.is_shallow());
3145
    a.deepen("origin", 100).unwrap();
3146
    assert!(!a.is_shallow(), "boundary reached the root");
3147
    assert!(a.store().has(&hashes[0]));
75167672 Andy McCall 3148
    assert_eq!(
3149
        a.load_state_full(&a.bookmark_heads().unwrap())
3150
            .unwrap()
3151
            .len(),
3152
        10
3153
    );
2863456a Andy McCall ↶ 3154
}
132b884b Andy McCall ↶ 3155
3156
#[test]
3157
fn tags_are_immutable_named_states_and_travel() {
3158
    hermetic();
3159
    let dir = tempfile::tempdir().unwrap();
3160
    let root = dir.path();
3161
    let origin = Repo::init(&root.join("origin")).unwrap();
3162
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3163
    let mut a = Repo::clone(&url, &root.join("a"))
3164
        .unwrap()
3165
        .with_home(root.join("home-a"));
3166
    let (key_a, _) = a
3167
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3168
        .unwrap();
132b884b Andy McCall ↶ 3169
    write(&root.join("a"), "f.txt", b"1\n");
3170
    let h1 = a.commit("one", &[]).unwrap();
3171
    write(&root.join("a"), "f.txt", b"1\n2\n");
3172
    let h2 = a.commit("two", &[]).unwrap();
3173
3174
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
75167672 Andy McCall 3175
    assert_eq!(
3176
        (t.heads.clone(), t.signer.as_deref()),
3177
        (vec![h1], Some("Ada"))
3178
    );
132b884b Andy McCall ↶ 3179
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
3180
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
3181
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
3182
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
3183
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
3184
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
3185
    assert_eq!(sa.sigs[0].key, key_a);
ee130dd9 Andy McCall ↶ 3186
    // Without a policy every client is sent every tag, whatever features
3187
    // it declares (oxygen#131).
3188
    let mut refs = a.remote_refs().unwrap();
3189
    a.refs_for_client(&mut refs, None);
3190
    assert_eq!(refs.tags.len(), 1);
132b884b Andy McCall ↶ 3191
    // Checkout by tag.
75167672 Andy McCall 3192
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
3193
        .unwrap();
132b884b Andy McCall ↶ 3194
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
75167672 Andy McCall 3195
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
3196
        .unwrap();
132b884b Andy McCall ↶ 3197
3198
    // Push carries the tag; a second attestation for the name is refused.
3199
    let r = a.push("origin", false).unwrap();
767ac6cd Andy McCall 3200
    origin.refresh().unwrap();
132b884b Andy McCall ↶ 3201
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
3202
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
75167672 Andy McCall 3203
    let mut forged = a
3204
        .tag_refs()
3205
        .unwrap()
3206
        .into_iter()
3207
        .find(|t| t.name == "v1")
3208
        .unwrap();
3209
    forged.state = origin
3210
        .store()
3211
        .put_state(&StateObject::new(vec![h2]))
3212
        .unwrap();
132b884b Andy McCall ↶ 3213
    forged.heads = vec![h2];
3214
    forged.attestation = None;
75167672 Andy McCall 3215
    let r = origin
3216
        .receive_push(Bundle::default(), vec![], None, vec![forged])
3217
        .unwrap();
132b884b Andy McCall ↶ 3218
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
3219
3220
    // A clone gets the tag; a later tag arrives on fetch.
75167672 Andy McCall 3221
    let b = Repo::clone(&url, &root.join("b"))
3222
        .unwrap()
3223
        .with_home(root.join("home-b"));
132b884b Andy McCall ↶ 3224
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3225
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
3226
    a.tag_create("v2", &[h2], "second").unwrap();
3227
    a.push("origin", false).unwrap();
767ac6cd Andy McCall 3228
    origin.refresh().unwrap();
132b884b Andy McCall ↶ 3229
    let rep = b.fetch("origin").unwrap();
3230
    assert_eq!(rep.new_tags, 1);
3231
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
3232
3233
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
3234
    a.policy_init().unwrap();
3235
    a.push("origin", false).unwrap();
767ac6cd Andy McCall 3236
    origin.refresh().unwrap();
1ec6fdbc Andy McCall ↶ 3237
    let unattested = crate::protocol::TagRef::new(
3238
        "v3".into(),
3239
        origin
75167672 Andy McCall 3240
            .store()
3241
            .put_state(&StateObject::new(vec![h2]))
3242
            .unwrap(),
1ec6fdbc Andy McCall ↶ 3243
        vec![h2],
3244
        None,
3245
    );
75167672 Andy McCall 3246
    let r = origin
3247
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
3248
        .unwrap();
132b884b Andy McCall ↶ 3249
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
3250
    a.tag_create("v3", &[h2], "").unwrap();
3251
    let r = a.push("origin", false).unwrap();
767ac6cd Andy McCall 3252
    origin.refresh().unwrap();
132b884b Andy McCall ↶ 3253
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
3254
    assert!(a.gc(true).is_ok());
3255
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
e5d9b051 Andy McCall ↶ 3256
3257
    // After a rotation the policy names only the new key, yet a fresh clone
3258
    // still takes the tags the old key made before it; the old key makes
3259
    // nothing new.
3260
    let rot = a.rotate_identity().unwrap();
3261
    let r = a.push("origin", false).unwrap();
767ac6cd Andy McCall 3262
    origin.refresh().unwrap();
e5d9b051 Andy McCall ↶ 3263
    assert!(r.iter().all(|x| x.ok), "{r:?}");
3264
    let c = Repo::clone(&url, &root.join("c"))
3265
        .unwrap()
3266
        .with_home(root.join("home-c"));
3267
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
3268
    let (_, sp) = c.current_policy().unwrap().unwrap();
3269
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
3270
    let made = c.identity(&rot.new).unwrap().created;
3271
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
3272
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
3273
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
132b884b Andy McCall ↶ 3274
}
4e88e774 Andy McCall ↶ 3275
3276
#[test]
3277
fn multiple_workspaces_share_a_repository() {
3278
    hermetic();
3279
    let dir = tempfile::tempdir().unwrap();
3280
    let root = dir.path();
3281
    let main_dir = root.join("main");
3282
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
3283
    write(&main_dir, "a.txt", b"a\n");
3284
    let h1 = repo.commit("a", &[]).unwrap();
3285
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3286
3287
    // A second workspace elsewhere, checked out on the bookmark.
3288
    let ws_dir = root.join("ws2");
4476cdbb Andy McCall ↶ 3289
    let ops = repo.op_log().unwrap().len();
4e88e774 Andy McCall ↶ 3290
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
4476cdbb Andy McCall ↶ 3291
    assert_eq!(
3292
        ws.op_log().unwrap().len(),
3293
        ops + 2,
3294
        "the add and its checkout, and no snapshot finding the tree deleted (oxygen#137)"
3295
    );
4e88e774 Andy McCall ↶ 3296
    assert!(ws_dir.join(".oxy").is_file());
3297
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
3298
    assert_ne!(ws.workspace(), repo.workspace());
3299
    let list = repo.workspaces().unwrap();
3300
    assert_eq!(list.len(), 2);
75167672 Andy McCall 3301
    assert!(list
3302
        .iter()
3303
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
4e88e774 Andy McCall ↶ 3304
    assert!(!ws.snapshot("status").unwrap().changed);
3305
3306
    // Work in the second workspace: its own working copy, shared bookmark.
3307
    write(&ws_dir, "b.txt", b"b\n");
3308
    let s = ws.snapshot("status").unwrap();
3309
    assert_eq!(s.statuses.len(), 1);
75167672 Andy McCall 3310
    assert!(
3311
        !repo.snapshot("status").unwrap().changed,
3312
        "the first workspace is untouched"
3313
    );
4e88e774 Andy McCall ↶ 3314
    let h2 = ws.commit("b from ws2", &[]).unwrap();
767ac6cd Andy McCall 3315
    repo.refresh().unwrap();
4e88e774 Andy McCall ↶ 3316
    let mut heads = repo.bookmark_heads().unwrap();
3317
    heads.sort();
3318
    let mut want = vec![h1, h2];
3319
    want.sort();
3320
    assert_eq!(heads, want, "both workspaces see the bookmark move");
3321
    assert!(!main_dir.join("b.txt").exists());
75167672 Andy McCall 3322
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
3323
        .unwrap();
4e88e774 Andy McCall ↶ 3324
    assert!(main_dir.join("b.txt").exists());
3325
3326
    // Reopening from inside the second workspace finds the shared repository.
3327
    let reopened = Repo::open(&ws_dir).unwrap();
3328
    assert_eq!(reopened.workspace(), ws.workspace());
3329
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
3330
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
3331
3332
    // Workspaces cannot nest; forget drops one from the view but keeps files.
3333
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
3334
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
3335
    repo.workspace_forget(&ws.workspace()).unwrap();
3336
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3337
    assert!(ws_dir.join("b.txt").exists());
75167672 Andy McCall 3338
    assert!(
3339
        ws.snapshot("status").is_err(),
3340
        "a forgotten workspace is no longer in the view"
3341
    );
4e88e774 Andy McCall ↶ 3342
6caacfff Andy McCall ↶ 3343
    // The working-copy lock: re-entrant in a thread; a lock whose process
3344
    // is gone is taken over, and a live process's is not, however old.
4e88e774 Andy McCall ↶ 3345
    let lock = repo.lock_snapshot().unwrap();
6caacfff Andy McCall ↶ 3346
    let again = repo.lock_working_copy().unwrap();
3347
    drop(again);
4e88e774 Andy McCall ↶ 3348
    drop(lock);
75167672 Andy McCall 3349
    let lock_path = main_dir
3350
        .join(".oxy/workspaces")
3351
        .join(repo.workspace().to_hex())
3352
        .join("lock");
4e88e774 Andy McCall ↶ 3353
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
6caacfff Andy McCall ↶ 3354
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
3355
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
3356
    age(&lock_path);
3357
    assert!(
3358
        !super::workspace::lock_is_stale(&lock_path),
3359
        "a live process keeps its lock"
3360
    );
3361
    fs::write(&lock_path, "4294967295").unwrap();
3362
    age(&lock_path);
4e88e774 Andy McCall ↶ 3363
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
3364
}
cdb5beba Andy McCall ↶ 3365
3366
#[test]
3367
fn attributes_binary_eol_nocompress_lockable() {
3368
    hermetic();
3369
    let dir = tempfile::tempdir().unwrap();
3370
    let root = dir.path();
3371
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3372
    write(
3373
        root,
3374
        ".oxyattributes",
3375
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
3376
    );
cdb5beba Andy McCall ↶ 3377
    write(root, "plain.dat", b"no nul bytes here\n");
3378
    write(root, "notes.txt", b"one\r\ntwo\r\n");
3379
    write(root, "assets/model.bin", b"\0model");
3380
    let h = repo.commit("attrs", &[]).unwrap();
3381
    let snap = repo.load_state(&[h]).unwrap().materialize();
75167672 Andy McCall 3382
    assert!(
3383
        snap.files["plain.dat"].mode.opaque,
3384
        "binary attribute forces opaque without NUL bytes"
3385
    );
3386
    assert!(
3387
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3388
        "stored with LF"
3389
    );
3390
    assert!(
3391
        !repo.snapshot("status").unwrap().changed,
3392
        "CRLF on disk equals LF in the state"
3393
    );
cdb5beba Andy McCall ↶ 3394
    // nocompress chunks pack raw.
3395
    let r = repo.gc(true).unwrap();
3396
    assert!(r.packed.objects > 0);
3397
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
3398
    fs::remove_file(root.join("notes.txt")).unwrap();
3399
    repo.checkout(&[h], true, "co").unwrap();
3400
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
75167672 Andy McCall 3401
    assert!(fs::metadata(root.join("assets/model.bin"))
3402
        .unwrap()
3403
        .permissions()
3404
        .readonly());
cdb5beba Andy McCall ↶ 3405
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
3406
    repo.lock_path("assets/model.bin").unwrap();
75167672 Andy McCall 3407
    assert!(!fs::metadata(root.join("assets/model.bin"))
3408
        .unwrap()
3409
        .permissions()
3410
        .readonly());
cdb5beba Andy McCall ↶ 3411
    assert!(repo.is_locked("assets/model.bin"));
3412
    write(root, "assets/model.bin", b"\0model2");
3413
    repo.commit("edit model", &[]).unwrap();
3414
    repo.unlock_path("assets/model.bin").unwrap();
75167672 Andy McCall 3415
    assert!(fs::metadata(root.join("assets/model.bin"))
3416
        .unwrap()
3417
        .permissions()
3418
        .readonly());
cdb5beba Andy McCall ↶ 3419
    // A later checkout can still overwrite a read-only lockable file.
3420
    repo.checkout(&[h], true, "co").unwrap();
3421
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
3422
}
6d3eefbc Andy McCall ↶ 3423
3424
#[cfg(unix)]
3425
#[test]
3426
fn hooks_can_veto_observe_and_add_dependencies() {
3427
    use std::os::unix::fs::PermissionsExt;
3428
    hermetic();
3429
    let dir = tempfile::tempdir().unwrap();
3430
    let root = dir.path();
3431
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3432
    let hooks = root.join(".oxy/hooks");
3433
    fs::create_dir_all(&hooks).unwrap();
3434
    let hook = |name: &str, body: &str| {
3435
        let p = hooks.join(name);
3436
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
3437
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
3438
    };
3439
    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");
3440
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
3441
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
3442
    hook("pre-push", "echo pushing blocked >&2; exit 3");
3443
    write(root, ".oxyignore", b".last-*\n");
3444
    write(root, "a.txt", b"a\n");
3445
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
3446
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
3447
    let h1 = repo.commit("first", &[]).unwrap();
3448
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
75167672 Andy McCall 3449
    assert!(
3450
        pre.contains("\"event\":\"pre-commit\"")
3451
            && pre.contains("\"path\":\"a.txt\"")
3452
            && pre.contains("\"message\":\"first\""),
3453
        "{pre}"
3454
    );
6d3eefbc Andy McCall ↶ 3455
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
3456
    assert!(post.contains(&h1.to_hex()), "{post}");
3457
    repo.checkout(&[h1], false, "co").unwrap();
75167672 Andy McCall 3458
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
3459
        .unwrap()
3460
        .contains("post-checkout"));
6d3eefbc Andy McCall ↶ 3461
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
3462
    repo.save_config().unwrap();
3463
    let err = repo.push("origin", false).unwrap_err().to_string();
3464
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
3465
3466
    // semantic-deps: only when enabled; adds an explicit dependency.
3467
    write(root, "b.txt", b"b\n");
75167672 Andy McCall 3468
    hook(
3469
        "semantic-deps",
3470
        &format!(
3471
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
3472
            h1.to_hex()
3473
        ),
3474
    );
6d3eefbc Andy McCall ↶ 3475
    let h2 = repo.commit("b without hook", &[]).unwrap();
75167672 Andy McCall 3476
    assert!(
3477
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
3478
        "hook disabled by default"
3479
    );
6d3eefbc Andy McCall ↶ 3480
    repo.config.set("hooks.semantic-deps", "true").unwrap();
3481
    repo.save_config().unwrap();
3482
    write(root, "c.txt", b"c\n");
3483
    let h3 = repo.commit("c with hook", &[]).unwrap();
3484
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
3485
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
75167672 Andy McCall 3486
    assert!(
3487
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
3488
        "{sem}"
3489
    );
6d3eefbc Andy McCall ↶ 3490
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
3491
}
23b217d7 Andy McCall ↶ 3492
3493
#[test]
3494
fn amend_into_older_change_and_split() {
3495
    hermetic();
3496
    let dir = tempfile::tempdir().unwrap();
3497
    let root = dir.path();
3498
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3499
    repo.create_identity("Ada", "a@b", IdentityScope::User)
3500
        .unwrap();
23b217d7 Andy McCall ↶ 3501
    repo.set_user_config("core.sign", "change").unwrap();
3502
    write(root, "a.txt", b"one\ntwo\n");
3503
    let h0 = repo.commit("base", &[]).unwrap();
3504
    write(root, "a.txt", b"one\nTWO\n");
3505
    let h1 = repo.commit("edit two", &[]).unwrap();
3506
    write(root, "a.txt", b"one\nTWO\nthree\n");
3507
    let h2 = repo.commit("add three", &[]).unwrap();
3508
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3509
3510
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
3511
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3512
    let h1b = repo.amend_into(&h1, None).unwrap();
3513
    assert_ne!(h1b, h1);
3514
    let c1b = repo.store().get_change(&h1b).unwrap();
3515
    assert_eq!(c1b.change_id, id1);
3516
    assert_eq!(c1b.deps, vec![h0]);
75167672 Andy McCall 3517
    assert!(matches!(
3518
        repo.verify_change(&h1b).unwrap(),
3519
        SignatureStatus::Valid { .. }
3520
    ));
23b217d7 Andy McCall ↶ 3521
    let heads = repo.bookmark_heads().unwrap();
3522
    assert_eq!(heads.len(), 1);
3523
    let top = repo.store().get_change(&heads[0]).unwrap();
3524
    assert_eq!(top.message, "add three");
75167672 Andy McCall 3525
    assert_eq!(
3526
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
3527
        [h0, h1b].into_iter().collect(),
3528
        "depends on the file's creator and the rewritten line"
3529
    );
23b217d7 Andy McCall ↶ 3530
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 3531
    assert!(
3532
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
3533
    );
3534
    assert!(
3535
        !repo.snapshot("status").unwrap().changed,
3536
        "the working copy is clean after folding"
3537
    );
23b217d7 Andy McCall ↶ 3538
    // Only h1b's own state shows the fix without "three".
3539
    let only = repo.load_state(&[h1b]).unwrap().materialize();
75167672 Andy McCall 3540
    assert!(
3541
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
3542
    );
23b217d7 Andy McCall ↶ 3543
    assert_eq!(repo.log().unwrap().len(), 4);
3544
3545
    // An edit to a line introduced by h2 cannot fold into h1.
3546
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
3547
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
3548
    assert!(err.contains("introduced after"), "{err}");
75167672 Andy McCall 3549
    assert!(
3550
        repo.snapshot("status").unwrap().statuses.len() == 1,
3551
        "nothing was changed by the refusal"
3552
    );
23b217d7 Andy McCall ↶ 3553
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3554
3555
    // Split the head that touches two files.
3556
    write(root, "b.txt", b"b\n");
3557
    write(root, "c.txt", b"c\n");
3558
    let h3 = repo.commit("b and c", &[]).unwrap();
3559
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
3560
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
3561
    let c_1 = repo.store().get_change(&p1).unwrap();
3562
    let c_2 = repo.store().get_change(&p2).unwrap();
3563
    assert!(c_1.message.contains("part 1: b.txt"));
3564
    assert_eq!(c_2.change_id, id3);
3565
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
75167672 Andy McCall 3566
    assert!(
3567
        heads.contains(&p1) && heads.contains(&p2),
3568
        "independent parts are both heads"
3569
    );
3570
    let snap = repo
3571
        .load_state(&repo.bookmark_heads().unwrap())
3572
        .unwrap()
3573
        .materialize();
23b217d7 Andy McCall ↶ 3574
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
3575
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
3576
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
3577
    assert!(!repo.snapshot("status").unwrap().changed);
3578
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
3579
    let _ = h2;
3580
}
28fc23d7 Andy McCall ↶ 3581
3582
#[test]
3583
fn identity_lifecycle() {
3584
    hermetic();
3585
    let dir = tempfile::tempdir().unwrap();
3586
    let root = dir.path();
3587
    let origin = Repo::init(&root.join("origin")).unwrap();
3588
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3589
    let mut a = Repo::clone(&url, &root.join("a"))
3590
        .unwrap()
3591
        .with_home(root.join("home-a"));
28fc23d7 Andy McCall ↶ 3592
    a.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 3593
    let (key_a, _) = a
3594
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3595
        .unwrap();
28fc23d7 Andy McCall ↶ 3596
    write(&root.join("a"), "a.txt", b"a\n");
3597
    let h1 = a.commit("one", &[]).unwrap();
3598
    assert!(a.policy_init().unwrap().applied);
3599
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
767ac6cd Andy McCall 3600
    origin.refresh().unwrap();
28fc23d7 Andy McCall ↶ 3601
3602
    // Expiry: an identity that had expired when the change was made does not authenticate it.
75167672 Andy McCall 3603
    let mut e = Repo::init(&root.join("e"))
3604
        .unwrap()
3605
        .with_home(root.join("home-e"));
28fc23d7 Andy McCall ↶ 3606
    e.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 3607
    e.create_identity_with(
3608
        "Eve",
3609
        "[email protected]",
3610
        IdentityScope::User,
3611
        Some(Hlc::now().wall_ms - 1),
3612
    )
3613
    .unwrap();
28fc23d7 Andy McCall ↶ 3614
    write(&root.join("e"), "e.txt", b"e\n");
3615
    let he = e.commit("late", &[]).unwrap();
75167672 Andy McCall 3616
    assert!(
3617
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
3618
    );
28fc23d7 Andy McCall ↶ 3619
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
75167672 Andy McCall 3620
    let r = e
3621
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
3622
        .unwrap();
28fc23d7 Andy McCall ↶ 3623
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
3624
    write(&root.join("e"), "e.txt", b"e2\n");
3625
    let he2 = e.commit("in time", &[]).unwrap();
75167672 Andy McCall 3626
    assert!(
3627
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
3628
    );
28fc23d7 Andy McCall ↶ 3629
3630
    // Rotation: a fresh key; the old change still verifies; the policy follows.
3631
    let r = a.rotate_identity().unwrap();
3632
    assert_eq!(r.old, key_a);
3633
    assert_eq!(a.config.author_key, Some(r.new));
3634
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
3635
    assert!(r.policy.as_ref().unwrap().applied);
3636
    let (_, sp) = a.current_policy().unwrap().unwrap();
75167672 Andy McCall 3637
    assert_eq!(
3638
        (sp.policy.serial, sp.policy.roots.clone()),
3639
        (2, vec![r.new])
3640
    );
3641
    assert!(
3642
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
3643
        "superseded, not revoked"
3644
    );
28fc23d7 Andy McCall ↶ 3645
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
75167672 Andy McCall 3646
    assert!(
3647
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
3648
    );
28fc23d7 Andy McCall ↶ 3649
    write(&root.join("a"), "a.txt", b"a2\n");
3650
    let h2 = a.commit("two", &[]).unwrap();
75167672 Andy McCall 3651
    assert!(
3652
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
3653
    );
28fc23d7 Andy McCall ↶ 3654
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
3655
    let res = a.push("origin", false).unwrap();
767ac6cd Andy McCall 3656
    origin.refresh().unwrap();
28fc23d7 Andy McCall ↶ 3657
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3658
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
3659
    let key_a = r.new;
3660
3661
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
3662
    // identity object, so Ada's KeyId changes while her keys stay the same.
75167672 Andy McCall 3663
    let mut b = Repo::clone(&url, &root.join("b"))
3664
        .unwrap()
3665
        .with_home(root.join("home-b"));
3666
    let (key_b, id_b) = b
3667
        .create_identity("Bob", "[email protected]", IdentityScope::User)
3668
        .unwrap();
7ba155f2 Andy McCall ↶ 3669
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
28fc23d7 Andy McCall ↶ 3670
    assert_eq!(r.old, key_a);
3671
    let key_a2 = r.new;
75167672 Andy McCall 3672
    assert_eq!(
7ba155f2 Andy McCall ↶ 3673
        a.identity(&key_a2).unwrap().delegates,
3674
        vec![Delegate::full(key_b)]
3675
    );
3676
    assert_eq!(
75167672 Andy McCall 3677
        a.identity(&key_a2).unwrap().ed25519_pk,
3678
        a.identity(&key_a).unwrap().ed25519_pk
7ba155f2 Andy McCall ↶ 3679
    );
3680
    assert!(
3681
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
3682
        "already a delegate"
75167672 Andy McCall 3683
    );
28fc23d7 Andy McCall ↶ 3684
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
767ac6cd Andy McCall 3685
    origin.refresh().unwrap();
28fc23d7 Andy McCall ↶ 3686
    write(&root.join("a"), "a.txt", b"a3\n");
3687
    let h3 = a.commit("three", &[]).unwrap();
75167672 Andy McCall 3688
    assert!(
3689
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
3690
        "the same secret signs under the new KeyId"
3691
    );
28fc23d7 Andy McCall ↶ 3692
    // A change authored by Ada but signed only by Bob verifies through the delegation.
3693
    a.set_user_config("core.sign", "seal").unwrap();
3694
    write(&root.join("a"), "a.txt", b"a4\n");
3695
    let h4 = a.commit("four", &[]).unwrap();
3696
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
3697
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 3698
    a.store()
3699
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
3700
        .unwrap();
3701
    assert!(
3702
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
3703
    );
28fc23d7 Andy McCall ↶ 3704
    a.set_user_config("core.sign", "change").unwrap();
3705
    // Withdrawing the delegation re-issues the identity again.
3706
    let r = a.delegate_remove(&key_b).unwrap();
3707
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
3708
    assert!(a.delegate_remove(&key_b).is_err());
3709
    let key_a3 = r.new;
3710
    let res = a.push("origin", false).unwrap();
767ac6cd Andy McCall 3711
    origin.refresh().unwrap();
28fc23d7 Andy McCall ↶ 3712
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3713
3714
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
3715
    // both applied under the old threshold of 1. A grant then needs Bob too.
3716
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
3717
    assert!(a.policy_root_add(id_b.clone()).is_err());
3718
    assert!(a.policy_set_threshold(3).is_err());
3719
    assert!(a.policy_set_threshold(2).unwrap().applied);
3720
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
767ac6cd Andy McCall 3721
    origin.refresh().unwrap();
28fc23d7 Andy McCall ↶ 3722
    b.pull("origin").unwrap();
75167672 Andy McCall 3723
    assert_eq!(
3724
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
3725
        2
3726
    );
3727
    let mut c = Repo::init(&root.join("c"))
3728
        .unwrap()
3729
        .with_home(root.join("home-c"));
3730
    let (key_c, id_c) = c
3731
        .create_identity("Cy", "[email protected]", IdentityScope::User)
3732
        .unwrap();
28fc23d7 Andy McCall ↶ 3733
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
3734
    let proposal = a.policy_grant(id_c, None).unwrap();
3735
    assert!(!proposal.applied && proposal.sigs.len() == 1);
3736
    assert_eq!(proposal.policy.serial, serial_before + 1);
75167672 Andy McCall 3737
    assert_eq!(
3738
        a.current_policy().unwrap().unwrap().1.policy.serial,
3739
        serial_before,
3740
        "a proposal changes nothing yet"
3741
    );
28fc23d7 Andy McCall ↶ 3742
    // Bob signs the proposal, handed over as a file, and it applies for him.
3743
    let bytes = proposal.signed().encode();
75167672 Andy McCall 3744
    let signed = b
3745
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
3746
        .unwrap();
28fc23d7 Andy McCall ↶ 3747
    assert!(signed.applied && signed.sigs.len() == 2);
75167672 Andy McCall 3748
    assert!(b
3749
        .current_policy()
3750
        .unwrap()
3751
        .unwrap()
3752
        .1
3753
        .policy
3754
        .authorizes(&key_c, "main"));
3755
    assert!(
3756
        b.policy_sign(signed.signed()).is_err(),
3757
        "a stale proposal is refused"
3758
    );
28fc23d7 Andy McCall ↶ 3759
    // Bob publishes it and Ada picks it up.
75167672 Andy McCall 3760
    assert!(b
3761
        .push("origin", false)
3762
        .unwrap()
3763
        .iter()
3764
        .any(|x| x.name == "policy" && x.ok));
767ac6cd Andy McCall 3765
    origin.refresh().unwrap();
28fc23d7 Andy McCall ↶ 3766
    a.pull("origin").unwrap();
75167672 Andy McCall 3767
    assert_eq!(
3768
        a.current_policy().unwrap().unwrap().1.policy.serial,
3769
        serial_before + 1
3770
    );
28fc23d7 Andy McCall ↶ 3771
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3772
    assert!(a.policy_revoke(&key_a3).is_err());
75167672 Andy McCall 3773
    let u = a
3774
        .revoke_identity(&key_c, "left the project")
3775
        .unwrap()
3776
        .unwrap();
28fc23d7 Andy McCall ↶ 3777
    assert!(!u.applied);
3778
    assert!(a.is_revoked(&key_c).unwrap());
3779
    assert!(!b.is_revoked(&key_c).unwrap());
3780
    let u = b.policy_sign(u.signed()).unwrap();
3781
    assert!(u.applied && u.policy.is_revoked(&key_c));
3782
    assert!(b.is_revoked(&key_c).unwrap());
3783
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
75167672 Andy McCall 3784
    assert!(
3785
        b.policy_revoke(&key_a3).is_err(),
3786
        "would leave one root for a threshold of 2"
3787
    );
28fc23d7 Andy McCall ↶ 3788
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3789
    let key_c_own = c.config.author_key.unwrap();
75167672 Andy McCall 3790
    assert!(c
3791
        .revoke_identity(&key_c_own, "lost laptop")
3792
        .unwrap()
3793
        .is_none());
28fc23d7 Andy McCall ↶ 3794
    assert!(c.is_revoked(&key_c_own).unwrap());
3795
    assert_eq!(key_c_own, key_c);
3796
}
3797
6e723b81 Andy McCall ↶ 3798
#[test]
3799
fn renames_are_detected_and_tracked_as_moves() {
3800
    hermetic();
3801
    let dir = tempfile::tempdir().unwrap();
3802
    let root = dir.path();
3803
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3804
    write(
3805
        root,
3806
        "src/old.rs",
3807
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3808
    );
6e723b81 Andy McCall ↶ 3809
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3810
    write(root, "tiny.txt", b"x\n");
3811
    let h1 = repo.commit("base", &[]).unwrap();
3812
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3813
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3814
3815
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3816
    // that shares nothing with the removed file.
3817
    fs::remove_file(root.join("src/old.rs")).unwrap();
75167672 Andy McCall 3818
    write(
3819
        root,
3820
        "lib/new.rs",
3821
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3822
    );
6e723b81 Andy McCall ↶ 3823
    fs::remove_file(root.join("img.bin")).unwrap();
3824
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3825
    fs::remove_file(root.join("tiny.txt")).unwrap();
3826
    write(root, "other.txt", b"completely different\n");
3827
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3828
    let statuses: Vec<(&str, ChangeStatus)> = snap
3829
        .statuses
3830
        .iter()
3831
        .map(|s| (s.path.as_str(), s.status))
3832
        .collect();
6e723b81 Andy McCall ↶ 3833
    assert_eq!(
3834
        statuses,
75167672 Andy McCall 3835
        vec![
3836
            ("assets/img.bin", ChangeStatus::Renamed),
3837
            ("lib/new.rs", ChangeStatus::Renamed),
3838
            ("other.txt", ChangeStatus::Added),
3839
            ("src", ChangeStatus::Removed),
3840
            ("tiny.txt", ChangeStatus::Removed)
3841
        ]
6e723b81 Andy McCall ↶ 3842
    );
3843
    let h2 = repo.commit("move things", &[]).unwrap();
3844
    let c = repo.store().get_change(&h2).unwrap();
75167672 Andy McCall 3845
    let moves: Vec<_> = c
3846
        .tree_ops
3847
        .iter()
3848
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3849
        .collect();
6e723b81 Andy McCall ↶ 3850
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
75167672 Andy McCall 3851
    assert!(c.tree_ops.iter().any(
3852
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3853
    ));
3854
    assert!(c.tree_ops.iter().any(
3855
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3856
    ));
6e723b81 Andy McCall ↶ 3857
    let snap = repo.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 3858
    assert_eq!(
3859
        snap.files["lib/new.rs"].node, node_old,
3860
        "the node survives the rename"
3861
    );
3862
    assert!(
3863
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3864
    );
6e723b81 Andy McCall ↶ 3865
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
75167672 Andy McCall 3866
    assert!(render_change(
3867
        &c,
3868
        &repo.load_state(&[h1]).unwrap(),
3869
        &repo.load_state(&[h1]).unwrap().materialize()
3870
    )
3871
    .contains("R "));
6e723b81 Andy McCall ↶ 3872
    // A fresh checkout reproduces the tree.
3873
    let other = tempfile::tempdir().unwrap();
3874
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
75167672 Andy McCall 3875
    assert_eq!(
3876
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3877
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3878
    );
6e723b81 Andy McCall ↶ 3879
    assert!(!other.path().join("src").exists());
3880
    assert!(!clone.snapshot("status").unwrap().changed);
3881
    // Similarity is line based, byte weighted.
3882
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3883
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3884
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3885
    assert_eq!(similarity(b"", b"x\n"), 0);
3886
}
3887
30ea9c1e Andy McCall ↶ 3888
#[test]
3889
fn git_fetch_and_push_round_trip() {
3890
    hermetic();
75167672 Andy McCall 3891
    if std::process::Command::new("git")
3892
        .arg("--version")
3893
        .output()
3894
        .is_err()
3895
    {
30ea9c1e Andy McCall ↶ 3896
        eprintln!("git not installed; skipping");
3897
        return;
3898
    }
3899
    let dir = tempfile::tempdir().unwrap();
3900
    let root = dir.path();
3901
    let git_in = |d: &Path, args: &[&str]| -> String {
3902
        let out = std::process::Command::new("git")
3903
            .arg("-C")
3904
            .arg(d)
75167672 Andy McCall 3905
            .args([
3906
                "-c",
3907
                "user.name=Grace",
3908
                "-c",
3909
                "[email protected]",
3910
                "-c",
3911
                "commit.gpgsign=false",
3912
            ])
30ea9c1e Andy McCall ↶ 3913
            .args(args)
3914
            .output()
3915
            .unwrap();
75167672 Andy McCall 3916
        assert!(
3917
            out.status.success(),
3918
            "git {args:?}: {}",
3919
            String::from_utf8_lossy(&out.stderr)
3920
        );
30ea9c1e Andy McCall ↶ 3921
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3922
    };
3923
    // A bare "remote" and a work tree that pushes to it.
3924
    let remote = root.join("remote.git");
3925
    fs::create_dir_all(&remote).unwrap();
3926
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3927
    let work = root.join("work");
75167672 Andy McCall 3928
    git_in(
3929
        root,
3930
        &[
3931
            "clone",
3932
            "-q",
3933
            remote.to_str().unwrap(),
3934
            work.to_str().unwrap(),
3935
        ],
3936
    );
30ea9c1e Andy McCall ↶ 3937
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3938
    write(&work, "README.md", b"# Project\n");
3939
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3940
    git_in(&work, &["add", "."]);
3941
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3942
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3943
    git_in(&work, &["commit", "-q", "-am", "second"]);
3944
    git_in(&work, &["push", "-q", "origin", "main"]);
3945
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3946
3947
    // Fetch into a fresh oxy repository.
3948
    let o = root.join("oxy");
3949
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3950
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3951
        .unwrap();
30ea9c1e Andy McCall ↶ 3952
    let url = remote.to_string_lossy().to_string();
3953
    let r = repo.git_fetch(&url, "main").unwrap();
3954
    assert_eq!((r.commits, r.heads), (2, 1));
75167672 Andy McCall 3955
    assert_eq!(
3956
        fs::read(o.join("src/lib.rs")).unwrap(),
3957
        b"pub fn a() {}\npub fn b() {}\n"
3958
    );
30ea9c1e Andy McCall ↶ 3959
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 3960
    assert_eq!(
3961
        repo.git_fetch(&url, "main").unwrap().commits,
3962
        0,
3963
        "nothing new"
3964
    );
30ea9c1e Andy McCall ↶ 3965
3966
    // An oxy change, pushed back: one commit on top of the Git tip.
75167672 Andy McCall 3967
    write(
3968
        &o,
3969
        "src/lib.rs",
3970
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3971
    );
30ea9c1e Andy McCall ↶ 3972
    write(&o, "NOTES.md", b"from oxy\n");
3973
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3974
    let r = repo.git_push(&url, "main").unwrap();
3975
    assert_eq!(r.exported, 1, "{r:?}");
3976
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
75167672 Andy McCall 3977
    assert_eq!(
3978
        git_in(&work, &["log", "--format=%s", "main"]),
3979
        "add c and notes\nsecond\ninitial"
3980
    );
30ea9c1e Andy McCall ↶ 3981
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3982
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3983
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
75167672 Andy McCall 3984
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3985
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3986
    assert_eq!(
3987
        repo.git_push(&url, "main").unwrap().exported,
3988
        0,
3989
        "already pushed"
3990
    );
30ea9c1e Andy McCall ↶ 3991
3992
    // Git moves on; pushing without fetching is refused, fetching brings
3993
    // the commit in and the working copy follows.
3994
    write(&work, "README.md", b"# Project\n\nMore.\n");
3995
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3996
    git_in(&work, &["push", "-q", "origin", "main"]);
3997
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
75167672 Andy McCall 3998
    assert!(repo
3999
        .git_push(&url, "main")
4000
        .unwrap_err()
4001
        .to_string()
4002
        .contains("fetch"));
30ea9c1e Andy McCall ↶ 4003
    let r = repo.git_fetch(&url, "main").unwrap();
75167672 Andy McCall 4004
    assert_eq!(
4005
        (r.commits, r.heads),
4006
        (1, 2),
4007
        "the Git change and the oxy change commute"
4008
    );
4009
    assert_eq!(
4010
        fs::read(o.join("README.md")).unwrap(),
4011
        b"# Project\n\nMore.\n"
4012
    );
30ea9c1e Andy McCall ↶ 4013
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
4014
    assert!(!repo.snapshot("status").unwrap().changed);
4015
    // Another oxy change pushes on top of Git's newest commit.
4016
    write(&o, "NOTES.md", b"from oxy\nagain\n");
4017
    repo.commit("notes again", &[]).unwrap();
4018
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
4019
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
4020
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
75167672 Andy McCall 4021
    assert_eq!(
4022
        fs::read(work.join("NOTES.md")).unwrap(),
4023
        b"from oxy\nagain\n"
4024
    );
4025
    assert_eq!(
4026
        git_in(&work, &["log", "--format=%s", "main"])
4027
            .lines()
4028
            .count(),
4029
        5
4030
    );
30ea9c1e Andy McCall ↶ 4031
}
4032
2b872d07 Andy McCall ↶ 4033
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
4034
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
4035
#[test]
4036
#[ignore]
4037
fn bench_one_gibibyte_file() {
4038
    hermetic();
4039
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
4040
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
4041
        Some(d) => tempfile::tempdir_in(d).unwrap(),
4042
        None => tempfile::tempdir().unwrap(),
4043
    };
4044
    let root = dir.path();
75167672 Andy McCall 4045
    let repo = Repo::init(&root.join("r"))
4046
        .unwrap()
4047
        .with_home(root.join("home"));
2b872d07 Andy McCall ↶ 4048
    let size = 1usize << 30;
4049
    let mut data = vec![0u8; size];
4050
    let mut x = 0x9e3779b97f4a7c15u64;
4051
    for chunk in data.chunks_mut(8) {
4052
        x ^= x << 13;
4053
        x ^= x >> 7;
4054
        x ^= x << 17;
4055
        let b = x.to_le_bytes();
4056
        chunk.copy_from_slice(&b[..chunk.len()]);
4057
    }
4058
    let t = std::time::Instant::now();
4059
    write(&root.join("r"), "big.bin", &data);
4060
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
4061
    let t = std::time::Instant::now();
4062
    let h = repo.commit("big", &[]).unwrap();
4063
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
4064
    let t = std::time::Instant::now();
4065
    assert!(!repo.snapshot("status").unwrap().changed);
4066
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
4067
    let t = std::time::Instant::now();
4068
    let objects = repo.store().list().unwrap().len();
4069
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
4070
    let t = std::time::Instant::now();
4071
    let g = repo.gc(true).unwrap();
4072
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
4073
    let t = std::time::Instant::now();
4074
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
4075
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
4076
    let t = std::time::Instant::now();
4077
    let back = fs::read(root.join("c/big.bin")).unwrap();
4078
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
4079
    eprintln!("read back and verify: {:.2?}", t.elapsed());
4080
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
4081
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
75167672 Andy McCall 4082
    eprintln!(
4083
        "store size: {:.1} MiB for 1 GiB of data",
4084
        store_bytes as f64 / (1024.0 * 1024.0)
4085
    );
2b872d07 Andy McCall ↶ 4086
}
4087
4088
fn walkdir_size(p: &Path) -> u64 {
4089
    let mut total = 0;
4090
    if let Ok(rd) = fs::read_dir(p) {
4091
        for e in rd.flatten() {
4092
            let path = e.path();
4093
            if path.is_dir() {
4094
                total += walkdir_size(&path);
4095
            } else if let Ok(m) = fs::metadata(&path) {
4096
                total += m.len();
4097
            }
4098
        }
4099
    }
4100
    total
4101
}
4102
b7f102fc Andy McCall ↶ 4103
/// An opaque file whose size and mtime match the manifest is not read on
4104
/// the next snapshot: its blob comes from the manifest's stat cache.
4105
#[cfg(unix)]
4106
#[test]
4107
fn stat_cache_skips_reading_unchanged_opaque_files() {
4108
    use std::os::unix::fs::PermissionsExt;
4109
    hermetic();
4110
    let dir = tempfile::tempdir().unwrap();
4111
    let root = dir.path();
4112
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4113
    let mut big = vec![0u8; 300 * 1024];
4114
    for (i, b) in big.iter_mut().enumerate() {
4115
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
4116
    }
4117
    big[0] = 0;
4118
    write(root, "big.bin", &big);
4119
    write(root, "a.txt", b"text\n");
4120
    let h1 = repo.commit("base", &[]).unwrap();
4121
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
75167672 Andy McCall 4122
    assert!(
4123
        m.entries["big.bin"].blob.is_some(),
4124
        "opaque files record their blob"
4125
    );
b7f102fc Andy McCall ↶ 4126
    assert!(m.entries["a.txt"].blob.is_none());
4127
    let blob = m.entries["big.bin"].blob.unwrap();
4128
    assert!(repo.store().has(&blob));
4129
4130
    // Files modified within two seconds of the manifest are racy and still
4131
    // read; age the file so the cache applies, then snapshot to record it.
4132
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
75167672 Andy McCall 4133
    fs::File::options()
4134
        .write(true)
4135
        .open(root.join("big.bin"))
4136
        .unwrap()
4137
        .set_modified(old)
4138
        .unwrap();
b7f102fc Andy McCall ↶ 4139
    assert!(!repo.snapshot("status").unwrap().changed);
4140
    // Now the file cannot be read at all; the snapshot succeeds without it.
4141
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
4142
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4143
    assert!(
4144
        !snap.changed && snap.statuses.is_empty(),
4145
        "{:?}",
4146
        snap.statuses
4147
    );
b7f102fc Andy McCall ↶ 4148
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
4149
    // A real change (new mtime, new content) is seen and committed correctly.
4150
    let mut big2 = big.clone();
4151
    big2[10] ^= 0xff;
4152
    write(root, "big.bin", &big2);
4153
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4154
    assert_eq!(
4155
        snap.statuses
4156
            .iter()
4157
            .map(|s| (s.path.as_str(), s.status))
4158
            .collect::<Vec<_>>(),
4159
        vec![("big.bin", ChangeStatus::Modified)]
4160
    );
b7f102fc Andy McCall ↶ 4161
    let h2 = repo.commit("edit", &[]).unwrap();
4162
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 4163
    assert_eq!(
4164
        files["big.bin"].content,
4165
        FileContent::Opaque {
4166
            blobs: vec![Repo::blob_ref(&big2)]
4167
        }
4168
    );
b7f102fc Andy McCall ↶ 4169
    // Checkout writes a manifest with blobs too, so the next status is cached.
4170
    repo.checkout(&[h1], false, "checkout").unwrap();
4171
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4172
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
4173
    assert!(!repo.snapshot("status").unwrap().changed);
4174
}
4175
50a046e4 Andy McCall ↶ 4176
#[test]
4177
fn status_json_lists_conflicts_with_contributors() {
4178
    hermetic();
4179
    let dir = tempfile::tempdir().unwrap();
4180
    let root = dir.path();
4181
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4182
    write(root, "a.txt", b"one\n");
4183
    let h1 = repo.commit("base", &[]).unwrap();
4184
    write(root, "a.txt", b"one\nleft\n");
4185
    let ha = repo.commit("left", &[]).unwrap();
4186
    repo.checkout(&[h1], true, "checkout").unwrap();
4187
    write(root, "a.txt", b"one\nright\n");
4188
    let hb = repo.commit("right", &[]).unwrap();
4189
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
4190
    let snap = repo.snapshot("status").unwrap();
4191
    assert!(snap.base_snapshot.is_conflicted());
4192
    let json = repo.status_json(&snap).unwrap();
4193
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
4194
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
4195
    assert!(json.contains("\"conflicted\":true"), "{json}");
75167672 Andy McCall 4196
    assert!(
4197
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
4198
        "{json}"
4199
    );
50a046e4 Andy McCall ↶ 4200
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
4201
    assert!(json.contains("\"resolved\":false"), "{json}");
4202
    assert!(json.starts_with('{') && json.ends_with('}'));
4203
    // Resolve and the report says so; a clean copy has no conflicts.
4204
    write(root, "a.txt", b"one\nleft\nright\n");
4205
    let snap = repo.snapshot("status").unwrap();
4206
    let json = repo.status_json(&snap).unwrap();
4207
    assert!(json.contains("\"resolved\":true"), "{json}");
4208
    repo.commit("resolve", &[]).unwrap();
4209
    let snap = repo.snapshot("status").unwrap();
4210
    let json = repo.status_json(&snap).unwrap();
75167672 Andy McCall 4211
    assert!(
4212
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
4213
        "{json}"
4214
    );
50a046e4 Andy McCall ↶ 4215
}
4216
9ac1fbe2 Andy McCall ↶ 4217
#[test]
4218
fn ignore_rules_do_not_untrack_files() {
4219
    hermetic();
4220
    let dir = tempfile::tempdir().unwrap();
4221
    let root = dir.path();
4222
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4223
    write(root, "src.c", b"int x;\n");
4224
    write(root, "build/out.o", b"\0obj");
4225
    write(root, "sub/keep.log", b"keep\n");
4226
    write(root, "sub/junk.log", b"junk\n");
4227
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
4228
    let snap = repo.snapshot("status").unwrap();
4229
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 4230
    assert_eq!(
4231
        added,
4232
        vec![".oxyignore", "src.c", "sub/keep.log"],
4233
        "anchored, glob, and negated rules"
4234
    );
9ac1fbe2 Andy McCall ↶ 4235
    let h1 = repo.commit("base", &[]).unwrap();
4236
    // Ignoring a tracked file changes nothing about it.
4237
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
4238
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4239
    assert_eq!(
4240
        snap.statuses
4241
            .iter()
4242
            .map(|s| s.path.as_str())
4243
            .collect::<Vec<_>>(),
4244
        vec![".oxyignore"]
4245
    );
9ac1fbe2 Andy McCall ↶ 4246
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
75167672 Andy McCall 4247
    assert!(repo
4248
        .load_state(&[h2])
4249
        .unwrap()
4250
        .materialize()
4251
        .files
4252
        .contains_key("src.c"));
9ac1fbe2 Andy McCall ↶ 4253
    // Its edits are still seen, by status and by the prompt.
4254
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
4255
    write(root, "src.c", b"int x, y;\n");
4256
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
4257
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4258
    assert_eq!(
4259
        snap.statuses
4260
            .iter()
4261
            .map(|s| (s.path.as_str(), s.status))
4262
            .collect::<Vec<_>>(),
4263
        vec![("src.c", ChangeStatus::Modified)]
4264
    );
9ac1fbe2 Andy McCall ↶ 4265
    let h3 = repo.commit("edit src.c", &[]).unwrap();
75167672 Andy McCall 4266
    assert!(
4267
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
4268
    );
9ac1fbe2 Andy McCall ↶ 4269
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
4270
    fs::remove_file(root.join("src.c")).unwrap();
4271
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4272
    assert_eq!(
4273
        snap.statuses
4274
            .iter()
4275
            .map(|s| (s.path.as_str(), s.status))
4276
            .collect::<Vec<_>>(),
4277
        vec![("src.c", ChangeStatus::Removed)]
4278
    );
9ac1fbe2 Andy McCall ↶ 4279
    repo.checkout(&[h3], true, "checkout").unwrap();
4280
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
4281
    assert!(!repo.snapshot("status").unwrap().changed);
4282
    let _ = h1;
4283
}
4284
b837d2b5 Andy McCall ↶ 4285
#[test]
4286
fn split_works_on_non_heads_by_node() {
4287
    hermetic();
4288
    let dir = tempfile::tempdir().unwrap();
4289
    let root = dir.path();
4290
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4291
    write(root, "a.txt", b"one\n");
4292
    write(root, "junk/x.lock", b"lock\n");
4293
    let h1 = repo.commit("work plus junk", &[]).unwrap();
4294
    write(root, "a.txt", b"one\ntwo\n");
4295
    let h2 = repo.commit("more work", &[]).unwrap();
4296
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
4297
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
4298
    // h1 is not a head: split it by node.
4299
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
4300
    assert_ne!(h1b, h1);
75167672 Andy McCall 4301
    assert_eq!(
4302
        repo.store().get_change(&h1b).unwrap().change_id,
4303
        id1,
4304
        "the rest keeps the ChangeId"
4305
    );
b837d2b5 Andy McCall ↶ 4306
    let junk = repo.store().get_change(&hj).unwrap();
75167672 Andy McCall 4307
    assert!(junk.tree_ops.iter().all(
4308
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
4309
    ));
b837d2b5 Andy McCall ↶ 4310
    let heads = repo.bookmark_heads().unwrap();
75167672 Andy McCall 4311
    assert!(
4312
        heads.contains(&hj),
4313
        "the split-off part is a head of its own"
4314
    );
b837d2b5 Andy McCall ↶ 4315
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 4316
    assert!(
4317
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
4318
        "the dependent was rewritten onto the new hash"
4319
    );
b837d2b5 Andy McCall ↶ 4320
    assert!(snap.files.contains_key("junk/x.lock"));
75167672 Andy McCall 4321
    let h2b = heads
4322
        .iter()
4323
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
4324
        .copied()
4325
        .unwrap();
b837d2b5 Andy McCall ↶ 4326
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
4327
    assert!(!repo.snapshot("status").unwrap().changed);
4328
    // Abandoning the split-off head removes the junk from history.
4329
    repo.abandon(&hj).unwrap();
4330
    let heads = repo.bookmark_heads().unwrap();
4331
    let snap = repo.load_state(&heads).unwrap().materialize();
4332
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
4333
    assert!(snap.files.contains_key("a.txt"));
4334
    // A dependent that touches the split-off paths blocks the split.
4335
    write(root, "junk/y.lock", b"y\n");
4336
    let hb = repo.commit("junk base", &[]).unwrap();
4337
    write(root, "junk/y.lock", b"yy\n");
4338
    write(root, "b.txt", b"b\n");
4339
    repo.commit("touches junk", &[]).unwrap();
4340
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
4341
    assert!(err.contains("depends on the split-off paths"), "{err}");
4342
}
4343
7b9809e6 Andy McCall ↶ 4344
#[test]
4345
fn bookmarks_switch_merge_and_push() {
4346
    hermetic();
4347
    let dir = tempfile::tempdir().unwrap();
4348
    let root = dir.path();
4349
    let origin = Repo::init(&root.join("origin")).unwrap();
4350
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 4351
    let mut repo = Repo::clone(&url, &root.join("r"))
4352
        .unwrap()
4353
        .with_home(root.join("home"));
7b9809e6 Andy McCall ↶ 4354
    let r = root.join("r");
4355
    write(&r, "a.txt", b"a\n");
4356
    let h_a = repo.commit("a", &[]).unwrap();
4357
    assert!(repo.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 4358
    origin.refresh().unwrap();
7b9809e6 Andy McCall ↶ 4359
4360
    // A bookmark at the working copy's base, then work on it.
4361
    assert!(repo.bookmark_create("bad name..", None).is_err());
4362
    assert!(repo.bookmark_create("-x", None).is_err());
4363
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
4364
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
4365
    repo.bookmark_switch("feature", false).unwrap();
4366
    assert_eq!(repo.config.bookmark, "feature");
4367
    write(&r, "a.txt", b"a\nb\n");
4368
    write(&r, "b.txt", b"b\n");
4369
    let h_b = repo.commit("b on feature", &[]).unwrap();
75167672 Andy McCall 4370
    assert_eq!(
4371
        repo.bookmark_heads().unwrap(),
4372
        vec![h_b],
4373
        "b edits a.txt, so it depends on a"
4374
    );
4375
    assert_eq!(
4376
        repo.resolve_heads("main").unwrap(),
4377
        vec![h_a],
4378
        "main is untouched"
4379
    );
4380
    assert_eq!(
4381
        repo.resolve_change("feature").unwrap(),
4382
        h_b,
4383
        "a one-head bookmark names its change"
4384
    );
7b9809e6 Andy McCall ↶ 4385
    // Reopening keeps the workspace's bookmark.
4386
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
4387
    assert_eq!(reopened.config.bookmark, "feature");
4388
    // Back to main: b.txt goes away; work there.
4389
    repo.bookmark_switch("main", false).unwrap();
4390
    assert!(!r.join("b.txt").exists());
4391
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
4392
    write(&r, "c.txt", b"c\n");
4393
    let h_c = repo.commit("c on main", &[]).unwrap();
4394
    let list = repo.bookmarks().unwrap();
75167672 Andy McCall 4395
    assert_eq!(
4396
        list.iter()
4397
            .map(|b| (b.name.as_str(), b.current))
4398
            .collect::<Vec<_>>(),
4399
        vec![("feature", false), ("main", true)]
4400
    );
4401
    assert_eq!(
4402
        list.iter().find(|b| b.name == "main").unwrap().ahead,
4403
        Some(1),
4404
        "c is not on origin yet"
4405
    );
7b9809e6 Andy McCall ↶ 4406
    // Merge feature into main: the union, both heads, no merge change.
4407
    let m = repo.merge("feature").unwrap();
4408
    assert!(m.changed && m.checked_out);
4409
    let mut want = vec![h_b, h_c];
4410
    want.sort();
4411
    assert_eq!(m.heads, want);
4412
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
4413
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
4414
    assert!(repo.merge("main").is_err());
4415
    // The other bookmark can be pushed by name and appears at origin.
4416
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
767ac6cd Andy McCall 4417
    origin.refresh().unwrap();
7b9809e6 Andy McCall ↶ 4418
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
4419
    assert!(repo.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 4420
    origin.refresh().unwrap();
75167672 Andy McCall 4421
    assert_eq!(
4422
        repo.bookmarks()
4423
            .unwrap()
4424
            .iter()
4425
            .find(|b| b.name == "main")
4426
            .unwrap()
4427
            .ahead,
4428
        Some(0)
4429
    );
7b9809e6 Andy McCall ↶ 4430
    // A second workspace inherits the current bookmark and can switch independently.
4431
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
4432
    assert_eq!(ws.config.bookmark, "main");
4433
    let mut ws = ws;
4434
    ws.bookmark_switch("feature", false).unwrap();
75167672 Andy McCall 4435
    assert_eq!(
4436
        Repo::open(&r).unwrap().config.bookmark,
4437
        "main",
4438
        "the first workspace is unaffected"
4439
    );
4440
    assert!(
4441
        repo.bookmark_delete("feature").is_err(),
4442
        "current bookmark of another workspace"
4443
    );
7b9809e6 Andy McCall ↶ 4444
    ws.bookmark_switch("main", false).unwrap();
4445
    // Set and delete.
4446
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
4447
    assert!(repo.bookmark_delete("main").is_err(), "current here");
4448
    repo.bookmark_delete("feature").unwrap();
4449
    assert!(repo.resolve_heads("feature").is_err());
4450
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
75167672 Andy McCall 4451
    assert!(
4452
        repo.checkout(&[h_a], false, "checkout").is_ok(),
4453
        "changes of a deleted bookmark remain"
4454
    );
7b9809e6 Andy McCall ↶ 4455
}
4456
4dee277c Andy McCall ↶ 4457
#[test]
4458
fn oxygen_subrepos_pin_follow_and_update() {
4459
    hermetic();
4460
    let dir = tempfile::tempdir().unwrap();
4461
    let root = dir.path();
4462
    // A library repository with two commits, and a bare-ish origin for it.
4463
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
4464
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
75167672 Andy McCall 4465
    let lib = Repo::clone(&lib_url, &root.join("lib"))
4466
        .unwrap()
4467
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 4468
    write(&root.join("lib"), "lib.txt", b"v1\n");
4469
    let l1 = lib.commit("lib v1", &[]).unwrap();
4470
    assert!(lib.push("origin", false).unwrap()[0].ok);
4471
    let _ = lib_origin;
4472
4473
    // The application (a clone of its own origin) adds it as a subrepo.
4474
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
4475
    let app_url = root.join("app-origin").to_string_lossy().to_string();
4476
    let _ = app_origin;
4477
    let app_dir = root.join("app");
75167672 Andy McCall 4478
    let app = Repo::clone(&app_url, &app_dir)
4479
        .unwrap()
4480
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 4481
    write(&app_dir, "main.txt", b"app\n");
4482
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
4483
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
4484
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
4485
    let snap = app.snapshot("status").unwrap();
4486
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 4487
    assert_eq!(
4488
        paths,
4489
        vec![".oxymodules", "libs/lib", "main.txt"],
4490
        "the nested files are not walked"
4491
    );
4dee277c Andy McCall ↶ 4492
    let a1 = app.commit("app with lib", &[]).unwrap();
4493
    let files = app.load_state(&[a1]).unwrap().materialize().files;
4494
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
4495
    assert!(!files.contains_key("libs/lib/lib.txt"));
4496
    assert!(!app.snapshot("status").unwrap().changed);
4497
    let subs = app.subrepos().unwrap();
4498
    assert_eq!(subs.len(), 1);
4499
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
4500
4501
    // Advance the nested repository: the parent sees a modified pin.
75167672 Andy McCall 4502
    let nested = Repo::open(&app_dir.join("libs/lib"))
4503
        .unwrap()
4504
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 4505
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
4506
    let l2 = nested.commit("lib v2", &[]).unwrap();
4507
    assert!(nested.push("origin", false).unwrap()[0].ok);
4508
    let snap = app.snapshot("status").unwrap();
75167672 Andy McCall 4509
    assert_eq!(
4510
        snap.statuses
4511
            .iter()
4512
            .map(|s| (s.path.as_str(), s.status))
4513
            .collect::<Vec<_>>(),
4514
        vec![("libs/lib", ChangeStatus::Modified)]
4515
    );
4dee277c Andy McCall ↶ 4516
    let a2 = app.commit("bump lib", &[]).unwrap();
1a3b6203 Andy McCall ↶ 4517
    // Checking out the older app state brings the nested working copy back
4518
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4dee277c Andy McCall ↶ 4519
    let r = app.checkout(&[a1], false, "checkout").unwrap();
1a3b6203 Andy McCall ↶ 4520
    assert!(
4521
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
4522
        "{:?}",
4523
        r.notes
4524
    );
4dee277c Andy McCall ↶ 4525
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
1a3b6203 Andy McCall ↶ 4526
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
4527
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
4528
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4dee277c Andy McCall ↶ 4529
    assert!(!app.snapshot("status").unwrap().changed);
4530
    // A dirty nested repository is left alone and reported.
4531
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
4532
    let r = app.checkout(&[a2], false, "checkout").unwrap();
75167672 Andy McCall 4533
    assert!(
4534
        r.notes.iter().any(|n| n.contains("uncommitted")),
4535
        "{:?}",
4536
        r.notes
4537
    );
4dee277c Andy McCall ↶ 4538
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4539
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
4540
    let r = app.submodule_update(false, &[]).unwrap();
4541
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
4542
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
4543
    let _ = l2;
4544
4545
    // A fresh clone of the app has the pin but no nested repository until update --init.
4546
    assert!(app.push("origin", false).unwrap()[0].ok);
4547
    let clone_dir = root.join("app-clone");
75167672 Andy McCall 4548
    let clone = Repo::clone(&app_url, &clone_dir)
4549
        .unwrap()
4550
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 4551
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
75167672 Andy McCall 4552
    assert_eq!(
4553
        clone.submodule_update(false, &[]).unwrap(),
4554
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
4555
    );
4556
    assert_eq!(
4557
        clone.submodule_update(true, &[]).unwrap(),
4558
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
4559
    );
4560
    assert_eq!(
4561
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
4562
        b"v2\n"
4563
    );
4dee277c Andy McCall ↶ 4564
    assert!(!clone.snapshot("status").unwrap().changed);
4565
    // Removing the subrepo leaves the directory and drops the node.
4566
    clone.submodule_remove("libs/lib").unwrap();
4567
    let snap = clone.snapshot("status").unwrap();
75167672 Andy McCall 4568
    assert!(
4569
        snap.statuses
4570
            .iter()
4571
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
4572
        "{:?}",
4573
        snap.statuses
4574
    );
4dee277c Andy McCall ↶ 4575
    let c = clone.commit("drop lib", &[]).unwrap();
75167672 Andy McCall 4576
    assert!(!clone
4577
        .load_state(&[c])
4578
        .unwrap()
4579
        .materialize()
4580
        .files
4581
        .contains_key("libs/lib"));
4dee277c Andy McCall ↶ 4582
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
75167672 Andy McCall 4583
    assert!(
4584
        !clone.snapshot("status").unwrap().changed,
4585
        "an unregistered nested repository is ignored"
4586
    );
4dee277c Andy McCall ↶ 4587
}
4588
4589
#[test]
4590
fn git_submodules_import_and_export_as_gitlinks() {
4591
    hermetic();
75167672 Andy McCall 4592
    if std::process::Command::new("git")
4593
        .arg("--version")
4594
        .output()
4595
        .is_err()
4596
    {
4dee277c Andy McCall ↶ 4597
        eprintln!("git not installed; skipping");
4598
        return;
4599
    }
4600
    let dir = tempfile::tempdir().unwrap();
4601
    let root = dir.path();
4602
    let git_in = |d: &Path, args: &[&str]| -> String {
4603
        let out = std::process::Command::new("git")
4604
            .arg("-C")
4605
            .arg(d)
75167672 Andy McCall 4606
            .args([
4607
                "-c",
4608
                "user.name=Grace",
4609
                "-c",
4610
                "[email protected]",
4611
                "-c",
4612
                "commit.gpgsign=false",
4613
                "-c",
4614
                "protocol.file.allow=always",
4615
            ])
4dee277c Andy McCall ↶ 4616
            .args(args)
4617
            .output()
4618
            .unwrap();
75167672 Andy McCall 4619
        assert!(
4620
            out.status.success(),
4621
            "git {args:?}: {}",
4622
            String::from_utf8_lossy(&out.stderr)
4623
        );
4dee277c Andy McCall ↶ 4624
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4625
    };
4626
    let sub = root.join("sub");
4627
    fs::create_dir_all(&sub).unwrap();
4628
    git_in(&sub, &["init", "-q", "-b", "main"]);
4629
    write(&sub, "s.txt", b"sub\n");
4630
    git_in(&sub, &["add", "."]);
4631
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
4632
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
4633
    let g = root.join("main.git");
4634
    fs::create_dir_all(&g).unwrap();
4635
    git_in(&g, &["init", "-q", "-b", "main"]);
4636
    write(&g, "README.md", b"# app\n");
4637
    git_in(&g, &["add", "."]);
4638
    git_in(&g, &["commit", "-q", "-m", "initial"]);
75167672 Andy McCall 4639
    git_in(
4640
        &g,
4641
        &[
4642
            "submodule",
4643
            "add",
4644
            "-q",
4645
            sub.to_str().unwrap(),
4646
            "vendor/sub",
4647
        ],
4648
    );
4dee277c Andy McCall ↶ 4649
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
4650
4651
    let dest = root.join("oxy");
4652
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
4653
    let rep = repo.import_git(&g, "main").unwrap();
4654
    assert_eq!((rep.commits, rep.submodules), (2, 1));
75167672 Andy McCall 4655
    let files = repo
4656
        .load_state(&repo.bookmark_heads().unwrap())
4657
        .unwrap()
4658
        .materialize()
4659
        .files;
4dee277c Andy McCall ↶ 4660
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
75167672 Andy McCall 4661
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
4662
        panic!()
4663
    };
4664
    assert_eq!(
4665
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
4666
        crate::subrepo::Pin::Git {
4667
            sha: sub_sha.clone(),
4668
            branch: "HEAD".into()
4669
        }
4670
    );
4671
    let modules =
4672
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4dee277c Andy McCall ↶ 4673
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
4674
    assert!(modules.entries["vendor/sub"].git);
75167672 Andy McCall 4675
    assert!(
4676
        files.contains_key(".gitmodules"),
4677
        "the Git file is kept for round trips"
4678
    );
4679
    assert!(
4680
        !dest.join("vendor/sub/.git").exists(),
4681
        "not cloned until update --init"
4682
    );
4dee277c Andy McCall ↶ 4683
    assert!(!repo.snapshot("status").unwrap().changed);
4684
    // update --init clones it at the pinned commit; status is unchanged.
75167672 Andy McCall 4685
    assert_eq!(
4686
        repo.submodule_update(true, &[]).unwrap(),
4687
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
4688
    );
4689
    assert_eq!(
4690
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
4691
        sub_sha
4692
    );
4dee277c Andy McCall ↶ 4693
    assert!(!repo.snapshot("status").unwrap().changed);
4694
    // Export writes the gitlink and .gitmodules back.
4695
    let mirror = root.join("mirror.git");
4696
    let rep = repo.git_export(&mirror).unwrap();
4697
    assert_eq!(rep.skipped_subrepos, 0);
4698
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
75167672 Andy McCall 4699
    assert!(
4700
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
4701
        "{ls}"
4702
    );
4703
    assert_eq!(
4704
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
4705
        ".gitmodules\nREADME.md\nvendor"
4706
    );
4dee277c Andy McCall ↶ 4707
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
75167672 Andy McCall 4708
    assert_eq!(
4709
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
4710
        orig_tree,
4711
        "tree round trip"
4712
    );
4dee277c Andy McCall ↶ 4713
}
4714
957fee30 Andy McCall ↶ 4715
#[test]
4716
fn partial_commits_by_path_and_by_hunk() {
4717
    hermetic();
4718
    let dir = tempfile::tempdir().unwrap();
4719
    let root = dir.path();
4720
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4721
    write(root, "a.txt", b"1\n2\n3\n");
4722
    write(root, "b.txt", b"b\n");
4723
    let h0 = repo.commit("base", &[]).unwrap();
4724
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
4725
    write(root, "b.txt", b"b\nbb\n");
4726
    write(root, "c.txt", b"c\n");
4727
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
75167672 Andy McCall 4728
    let h1 = repo
4729
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
4730
        .unwrap();
957fee30 Andy McCall ↶ 4731
    let c1 = repo.store().get_change(&h1).unwrap();
75167672 Andy McCall 4732
    assert!(
4733
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
4734
        "{:?}",
4735
        c1.tree_ops
4736
    );
957fee30 Andy McCall ↶ 4737
    assert_eq!(c1.deps, vec![h0]);
4738
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
75167672 Andy McCall 4739
    assert!(
4740
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
4741
    );
957fee30 Andy McCall ↶ 4742
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
4743
    assert!(!files.contains_key("c.txt"));
4744
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4745
    assert_eq!(
4746
        snap.statuses
4747
            .iter()
4748
            .map(|s| (s.path.as_str(), s.status))
4749
            .collect::<Vec<_>>(),
4750
        vec![
4751
            ("b.txt", ChangeStatus::Modified),
4752
            ("c.txt", ChangeStatus::Added)
4753
        ]
4754
    );
4755
    assert_eq!(
4756
        fs::read(root.join("b.txt")).unwrap(),
4757
        b"b\nbb\n",
4758
        "disk untouched"
4759
    );
957fee30 Andy McCall ↶ 4760
    // By hunk: pick the b.txt insert; c.txt's addition is left.
4761
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 4762
    let b_hunk = hunks
4763
        .iter()
4764
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
4765
        .unwrap()
4766
        .index;
4767
    let h2 = repo
4768
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4769
        .unwrap();
957fee30 Andy McCall ↶ 4770
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 4771
    assert!(
4772
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4773
    );
957fee30 Andy McCall ↶ 4774
    assert!(!files.contains_key("c.txt"));
4775
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4776
    assert_eq!(
4777
        snap.statuses
4778
            .iter()
4779
            .map(|s| s.path.as_str())
4780
            .collect::<Vec<_>>(),
4781
        vec!["c.txt"]
4782
    );
957fee30 Andy McCall ↶ 4783
    // Choosing only the content hunk of a file in a new directory pulls in
4784
    // the directory and file additions it needs.
4785
    write(root, "d/e.txt", b"e\n");
4786
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 4787
    let e_insert = hunks
4788
        .iter()
4789
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4790
        .unwrap()
4791
        .index;
4792
    let h3 = repo
4793
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4794
        .unwrap();
957fee30 Andy McCall ↶ 4795
    let c3 = repo.store().get_change(&h3).unwrap();
4796
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4797
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4798
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
d8c086ca Andy McCall ↶ 4799
    // Choosing a new file's addition hunk brings its content along.
4800
    write(root, "f/g.txt", b"g\n");
4801
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 4802
    let g_add = hunks
4803
        .iter()
4804
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4805
        .unwrap()
4806
        .index;
4807
    let h4 = repo
4808
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4809
        .unwrap();
d8c086ca Andy McCall ↶ 4810
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
75167672 Andy McCall 4811
    assert!(
4812
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4813
    );
4814
    assert!(!repo
4815
        .snapshot("status")
4816
        .unwrap()
4817
        .statuses
4818
        .iter()
4819
        .any(|s| s.path == "f/g.txt"));
957fee30 Andy McCall ↶ 4820
    // Everything left commits normally; the working copy is then clean.
4821
    repo.commit("the rest", &[]).unwrap();
4822
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 4823
    let files = repo
4824
        .load_state(&repo.bookmark_heads().unwrap())
4825
        .unwrap()
4826
        .materialize()
4827
        .files;
957fee30 Andy McCall ↶ 4828
    assert!(files.contains_key("c.txt"));
4829
}
4830
4831
#[test]
4832
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4833
    hermetic();
4834
    let dir = tempfile::tempdir().unwrap();
4835
    let root = dir.path();
4836
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 4837
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4838
        .unwrap();
957fee30 Andy McCall ↶ 4839
    write(root, "a.txt", b"one\n");
4840
    let h1 = repo.commit("first", &[]).unwrap();
4841
    write(root, "a.txt", b"one\ntwo\n");
4842
    let h2 = repo.commit("second", &[]).unwrap();
4843
    let b = repo.blame("a.txt").unwrap();
75167672 Andy McCall 4844
    assert_eq!(
4845
        b.iter()
4846
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4847
            .collect::<Vec<_>>(),
4848
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4849
    );
957fee30 Andy McCall ↶ 4850
    assert!(b.iter().all(|l| l.author == "Ada"));
75167672 Andy McCall 4851
    assert_eq!(
4852
        b[0].change_id,
4853
        repo.store().get_change(&h1).unwrap().change_id
4854
    );
957fee30 Andy McCall ↶ 4855
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4856
    repo.commit("rename", &[]).unwrap();
4857
    let b = repo.blame("b.txt").unwrap();
75167672 Andy McCall 4858
    assert_eq!(
4859
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4860
        vec![h1, h2],
4861
        "the node survives the rename"
4862
    );
957fee30 Andy McCall ↶ 4863
    assert!(repo.blame("a.txt").is_err());
4864
}
4865
4866
#[test]
4867
fn bisect_finds_the_first_bad_change() {
4868
    hermetic();
4869
    let dir = tempfile::tempdir().unwrap();
4870
    let root = dir.path();
4871
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4872
    let mut content = String::new();
4873
    let mut hashes = Vec::new();
4874
    for i in 1..=8 {
4875
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4876
        write(root, "f.txt", content.as_bytes());
4877
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4878
    }
4879
    // Each step appends after the previous line, so the chain is linear.
4880
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4881
    repo.bisect_start().unwrap();
75167672 Andy McCall 4882
    assert!(matches!(
4883
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4884
        BisectStep::NeedMarks { good: 1, bad: 0 }
4885
    ));
957fee30 Andy McCall ↶ 4886
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
75167672 Andy McCall 4887
    assert!(
4888
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4889
        "{step:?}"
4890
    );
957fee30 Andy McCall ↶ 4891
    // Automated: bad when the bug line is present.
75167672 Andy McCall 4892
    let step = repo
4893
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4894
        .unwrap();
957fee30 Andy McCall ↶ 4895
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
75167672 Andy McCall 4896
    assert_eq!(
4897
        repo.bisect_status().unwrap(),
4898
        Some(BisectStep::Found { culprit: hashes[4] })
4899
    );
957fee30 Andy McCall ↶ 4900
    repo.bisect_reset().unwrap();
4901
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4902
    assert!(repo.bisect_status().unwrap().is_none());
4903
    assert!(!repo.snapshot("status").unwrap().changed);
4904
    // Manual marks and a skip.
4905
    repo.bisect_start().unwrap();
4906
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4907
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4908
    let mut skipped_once = false;
4909
    let mut guard = 0;
4910
    while let BisectStep::Testing { .. } = step {
4911
        guard += 1;
4912
        assert!(guard < 20);
4913
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4914
        if !skipped_once && text.contains("line 6") {
4915
            // An untestable state away from the boundary: the search routes around it.
4916
            skipped_once = true;
4917
            step = repo.bisect_mark(None, &[]).unwrap();
4918
            continue;
4919
        }
4920
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4921
    }
4922
    assert!(skipped_once);
4923
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4924
    repo.bisect_reset().unwrap();
4925
    // Skipping the culprit itself leaves it among the candidates reported.
4926
    repo.bisect_start().unwrap();
4927
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4928
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4929
    let mut guard = 0;
4930
    while let BisectStep::Testing { heads, .. } = &step {
4931
        guard += 1;
4932
        assert!(guard < 20);
4933
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 4934
        let is_culprit_state =
4935
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4936
        step = if is_culprit_state {
4937
            repo.bisect_mark(None, &[]).unwrap()
4938
        } else {
4939
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4940
        };
957fee30 Andy McCall ↶ 4941
    }
4942
    match step {
75167672 Andy McCall 4943
        BisectStep::Inconclusive { candidates } => assert!(
4944
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4945
            "{candidates:?}"
4946
        ),
957fee30 Andy McCall ↶ 4947
        other => panic!("{other:?}"),
4948
    }
4949
    repo.bisect_reset().unwrap();
4950
}
4951
728da0f9 Andy McCall ↶ 4952
#[test]
4953
fn squash_folds_a_change_into_its_dependency() {
4954
    hermetic();
4955
    let dir = tempfile::tempdir().unwrap();
4956
    let root = dir.path();
4957
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4958
    write(root, "a.txt", b"1\n");
4959
    let a = repo.commit("A", &[]).unwrap();
4960
    write(root, "a.txt", b"1\n2\n");
4961
    let c = repo.commit("C", &[]).unwrap();
4962
    write(root, "a.txt", b"1\n2\n3\n");
4963
    let e = repo.commit("E", &[]).unwrap();
4964
    write(root, "b.txt", b"b\n");
4965
    let b = repo.commit("B", &[]).unwrap();
4966
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4967
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4968
    // E depends on C which A lacks: refused, naming it.
4969
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4970
    assert!(err.contains(&c.short(12)), "{err}");
4971
    // C into A: A' has both, C is gone, E follows and still reads the same.
4972
    let a2 = repo.squash(&c, &a).unwrap();
4973
    let a2c = repo.store().get_change(&a2).unwrap();
4974
    assert_eq!(a2c.change_id, id_a);
4975
    assert!(a2c.deps.is_empty());
4976
    let heads = repo.bookmark_heads().unwrap();
4977
    let st = repo.load_state(&heads).unwrap();
4978
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
75167672 Andy McCall 4979
    let e2 = st
4980
        .changes()
4981
        .find(|(_, m)| m.change_id == id_e)
4982
        .map(|(h, _)| *h)
4983
        .unwrap();
4984
    assert_eq!(
4985
        repo.store().get_change(&e2).unwrap().deps,
4986
        vec![a2],
4987
        "E now depends on A' alone"
4988
    );
728da0f9 Andy McCall ↶ 4989
    let files = st.materialize().files;
75167672 Andy McCall 4990
    assert!(
4991
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4992
    );
728da0f9 Andy McCall ↶ 4993
    assert!(files.contains_key("b.txt"));
4994
    assert!(st.contains(&b));
4995
    assert!(!repo.snapshot("status").unwrap().changed);
4996
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4997
    // Undo restores the three original changes.
4998
    repo.undo().unwrap();
4999
    repo.undo().unwrap();
5000
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
5001
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
5002
}
5003
5004
#[test]
5005
fn rebase_re_expresses_a_change_against_another_base() {
5006
    hermetic();
5007
    let dir = tempfile::tempdir().unwrap();
5008
    let root = dir.path();
5009
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5010
    write(root, "a.txt", b"1\n2\n");
5011
    let a = repo.commit("A", &[]).unwrap();
5012
    write(root, "a.txt", b"1\n2\n3\n");
5013
    let c = repo.commit("C: append 3", &[]).unwrap();
5014
    write(root, "a.txt", b"1\n2\n3\n4\n");
5015
    let e = repo.commit("E: append 4", &[]).unwrap();
5016
    // A different base: A plus a change that prepends a line.
5017
    repo.checkout(&[a], true, "checkout").unwrap();
5018
    write(root, "a.txt", b"0\n1\n2\n");
5019
    let d = repo.commit("D: prepend 0", &[]).unwrap();
5020
    let id_c = repo.store().get_change(&c).unwrap().change_id;
5021
    let id_e = repo.store().get_change(&e).unwrap().change_id;
5022
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
5023
    let c2 = repo.rebase(&c, &[d]).unwrap();
5024
    let c2c = repo.store().get_change(&c2).unwrap();
5025
    assert_eq!(c2c.change_id, id_c);
5026
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
5027
    let heads = repo.bookmark_heads().unwrap();
5028
    let st = repo.load_state(&heads).unwrap();
5029
    assert!(!st.contains(&c) && st.contains(&d));
75167672 Andy McCall 5030
    let e2 = st
5031
        .changes()
5032
        .find(|(_, m)| m.change_id == id_e)
5033
        .map(|(h, _)| *h)
5034
        .unwrap();
728da0f9 Andy McCall ↶ 5035
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
75167672 Andy McCall 5036
    assert!(
5037
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
5038
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
5039
    );
728da0f9 Andy McCall ↶ 5040
    let files = st.materialize().files;
75167672 Andy McCall 5041
    assert!(
5042
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
5043
        "{:?}",
5044
        files["a.txt"].content
5045
    );
728da0f9 Andy McCall ↶ 5046
    assert!(!files["a.txt"].is_conflicted());
5047
    // Rebasing onto a state that already contains the change is refused.
5048
    assert!(repo.rebase(&c2, &[c2]).is_err());
5049
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
75167672 Andy McCall 5050
    assert!(
5051
        err.contains("lacks dependencies"),
5052
        "E needs C, which D's state does not have: {err}"
5053
    );
728da0f9 Andy McCall ↶ 5054
}
5055
c792033a Andy McCall ↶ 5056
#[test]
5057
fn unsigned_tags_keep_their_message() {
5058
    hermetic();
5059
    let dir = tempfile::tempdir().unwrap();
5060
    let root = dir.path();
5061
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5062
    write(root, "a.txt", b"a\n");
5063
    repo.commit("a", &[]).unwrap();
5064
    assert!(repo.secret_key().unwrap().is_none());
75167672 Andy McCall 5065
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
5066
        .unwrap();
c792033a Andy McCall ↶ 5067
    let tags = repo.tags().unwrap();
75167672 Andy McCall 5068
    assert_eq!(
5069
        (
5070
            tags[0].name.as_str(),
5071
            tags[0].message.as_str(),
5072
            tags[0].signer.as_deref()
5073
        ),
5074
        ("v1", "first release", None)
5075
    );
5076
    assert!(
5077
        repo.tag_refs().unwrap()[0].attestation.is_none(),
5078
        "an unsigned attestation is not advertised"
5079
    );
c792033a Andy McCall ↶ 5080
}
387335ff Andy McCall ↶ 5081
5082
#[test]
5083
fn fsck_passes_a_sound_repository_and_names_each_fault() {
64818938 Andy McCall ↶ 5084
    // Files on disk are what this tests: tampering with them, and the
5085
    // directory store's crash points.
5086
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5087
        return;
5088
    }
387335ff Andy McCall ↶ 5089
    hermetic();
5090
    let dir = tempfile::tempdir().unwrap();
5091
    let root = dir.path();
5092
    let origin_path = root.join("origin");
5093
    let origin = Repo::init(&origin_path).unwrap();
5094
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
5095
        .unwrap()
5096
        .with_home(root.join("home-a"));
5097
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5098
        .unwrap();
5099
    write(&root.join("a"), "f.txt", b"one\n");
5100
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
5101
    let h1 = a.commit("first", &[]).unwrap();
5102
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
5103
    let h2 = a.commit("second", &[]).unwrap();
5104
    a.tag_create("v1", &[h2], "first release").unwrap();
5105
    a.checkpoint().unwrap();
5106
    assert!(a.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 5107
    origin.refresh().unwrap();
387335ff Andy McCall ↶ 5108
5109
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
5110
    for repo in [&a, &origin] {
5111
        let rep = repo.fsck().unwrap();
5112
        assert_eq!(rep.problems, vec![], "{rep:?}");
5113
        // The two commits, plus the working copy's change in `a`.
5114
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
5115
        assert!(rep.ops > 1 && rep.objects > 5);
5116
    }
5117
    assert!(origin.fsck().unwrap().attestations >= 1);
5118
5119
    // A flipped byte in a stored object is corruption, named by hash.
5120
    let c1 = a.store().path_for(&h1);
5121
    let pristine = fs::read(&c1).unwrap();
5122
    let mut bytes = pristine.clone();
5123
    *bytes.last_mut().unwrap() ^= 1;
5124
    fs::write(&c1, &bytes).unwrap();
5125
    let rep = a.fsck().unwrap();
5126
    assert!(rep.errors() >= 1);
5127
    assert!(
5128
        rep.problems
5129
            .iter()
5130
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
5131
        "{rep:?}"
5132
    );
5133
    fs::write(&c1, &pristine).unwrap();
5134
    assert_eq!(a.fsck().unwrap().errors(), 0);
5135
5136
    // A missing change is named with what needed it.
5137
    fs::remove_file(&c1).unwrap();
5138
    let rep = a.fsck().unwrap();
5139
    assert!(
5140
        rep.problems.iter().any(|p| p.severity == Severity::Error
5141
            && p.object == Some(h1)
5142
            && p.what.contains("change missing, needed by change")),
5143
        "{rep:?}"
5144
    );
5145
    fs::write(&c1, &pristine).unwrap();
5146
5147
    // A missing blob is an error in a full clone.
5148
    let c2 = a.store().get_change(&h1).unwrap();
5149
    let blob = c2
5150
        .edits
5151
        .iter()
5152
        .find_map(|e| match e {
5153
            Edit::Replace { new: Some(b), .. } => Some(*b),
5154
            _ => None,
5155
        })
5156
        .expect("the binary file is a blob");
5157
    let bp = a.store().path_for(&blob);
5158
    let blob_bytes = fs::read(&bp).unwrap();
5159
    fs::remove_file(&bp).unwrap();
5160
    let rep = a.fsck().unwrap();
5161
    assert!(
5162
        rep.problems
5163
            .iter()
5164
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
5165
        "{rep:?}"
5166
    );
5167
    fs::write(&bp, &blob_bytes).unwrap();
5168
5169
    // A broken op log head is reported, not a crash.
5170
    let head = root.join("a/.oxy/ops/head");
5171
    let saved = fs::read(&head).unwrap();
5172
    fs::write(&head, b"not a hash").unwrap();
5173
    let rep = a.fsck().unwrap();
5174
    assert!(
5175
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
5176
        "{rep:?}"
5177
    );
5178
    fs::write(&head, saved).unwrap();
5179
    assert_eq!(a.fsck().unwrap().problems, vec![]);
5180
}
4dcb8c09 Andy McCall ↶ 5181
5182
/// Copy a directory tree (for restoring a pristine repository).
5183
fn copy_tree(from: &Path, to: &Path) {
5184
    fs::create_dir_all(to).unwrap();
5185
    for e in fs::read_dir(from).unwrap() {
5186
        let e = e.unwrap();
5187
        let target = to.join(e.file_name());
5188
        if e.file_type().unwrap().is_dir() {
5189
            copy_tree(&e.path(), &target);
5190
        } else {
5191
            fs::copy(e.path(), &target).unwrap();
5192
        }
5193
    }
5194
}
5195
5196
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
5197
/// would, and check that both repositories still open, pass `fsck`, and
5198
/// accept the same operation again.
5199
#[test]
5200
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
64818938 Andy McCall ↶ 5201
    // Files on disk are what this tests: tampering with them, and the
5202
    // directory store's crash points.
5203
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5204
        return;
5205
    }
4dcb8c09 Andy McCall ↶ 5206
    use crate::durable::failpoint;
5207
    hermetic();
5208
    let dir = tempfile::tempdir().unwrap();
5209
    let pristine = dir.path().join("pristine");
5210
    let origin_path = pristine.join("origin");
5211
    Repo::init(&origin_path).unwrap();
5212
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
5213
        .unwrap()
5214
        .with_home(dir.path().join("home"));
5215
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5216
        .unwrap();
5217
    write(&pristine.join("a"), "f.txt", b"one\n");
5218
    a.commit("first", &[]).unwrap();
5219
    assert!(a.push("origin", false).unwrap()[0].ok);
5220
    drop(a);
5221
5222
    type Op = fn(&Repo) -> Result<()>;
5223
    let edit_and_commit: Op = |r| {
5224
        write(r.root(), "f.txt", b"one\ntwo\n");
5225
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
5226
        r.commit("second", &[]).map(|_| ())
5227
    };
5228
    let push: Op = |r| {
5229
        let res = r.push("origin", false)?;
5230
        if res.iter().all(|x| x.ok) {
5231
            Ok(())
5232
        } else {
5233
            Err(RepoError::Msg(format!("{res:?}")))
5234
        }
5235
    };
5236
5237
    for (name, prepare, op) in [
5238
        ("commit", None, edit_and_commit),
5239
        ("push", Some(edit_and_commit), push),
5240
    ] {
5241
        let mut steps = 0;
5242
        for n in 1.. {
5243
            let run = dir.path().join(format!("{name}-{n}"));
5244
            copy_tree(&pristine, &run);
5245
            // Clones record their remote by path; point it at this copy.
5246
            let open = |p: &Path| {
5247
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
5248
                r.config
5249
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
5250
                    .unwrap();
5251
                r.save_config().unwrap();
5252
                r
5253
            };
5254
            let a = open(&run.join("a"));
5255
            if let Some(prep) = prepare {
5256
                prep(&a).unwrap();
5257
            }
5258
            failpoint::crash_after(n);
5259
            let outcome = op(&a);
5260
            let crashed = failpoint::disarm();
5261
            drop(a);
5262
            if !crashed {
5263
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
5264
                steps = n - 1;
5265
                break;
5266
            }
5267
            assert!(
5268
                outcome.is_err(),
5269
                "{name}: a crash at step {n} was swallowed"
5270
            );
5271
            for repo in ["a", "origin"] {
5272
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
5273
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
5274
                });
5275
                let rep = r.fsck().unwrap();
5276
                assert_eq!(
5277
                    rep.errors(),
5278
                    0,
5279
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
5280
                    rep.problems
5281
                );
5282
            }
5283
            // The interrupted operation can simply be run again.
5284
            let a = open(&run.join("a"));
5285
            // A crash after the commit point leaves the commit done.
5286
            let landed = a
5287
                .bookmark_heads()
5288
                .unwrap()
5289
                .iter()
5290
                .any(|h| a.store().get_change(h).unwrap().message == "second");
5291
            let again = match (name, landed) {
5292
                ("commit", true) => Ok(()),
5293
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
5294
                _ => op(&a),
5295
            };
5296
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
5297
            assert_eq!(a.fsck().unwrap().errors(), 0);
5298
            fs::remove_dir_all(&run).unwrap();
5299
        }
5300
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
5301
    }
5302
}
19555025 Andy McCall ↶ 5303
5304
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
5305
/// running at the same time lose nothing: every commit ends up on the
5306
/// bookmark, locally and on the remote, and the repository passes fsck.
5307
#[test]
5308
fn concurrent_commits_in_two_workspaces_lose_nothing() {
5309
    hermetic();
5310
    let dir = tempfile::tempdir().unwrap();
5311
    let root = dir.path();
5312
    let origin = root.join("origin");
5313
    Repo::init_bare_unbound(&origin).unwrap();
5314
    let main = root.join("main");
5315
    let mut repo = Repo::init(&main).unwrap();
5316
    repo.config
5317
        .set("remote.origin.url", &origin.to_string_lossy())
5318
        .unwrap();
5319
    repo.save_config().unwrap();
5320
    write(&main, "seed.txt", b"seed\n");
5321
    repo.commit("seed", &[]).unwrap();
5322
    let second = root.join("second");
5323
    repo.workspace_add(&second, None).unwrap();
5324
    drop(repo);
5325
5326
    const EACH: usize = 15;
5327
    std::thread::scope(|s| {
5328
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
5329
            s.spawn(move || {
5330
                let r = Repo::open(&dir).unwrap();
5331
                for i in 0..EACH {
5332
                    write(
5333
                        &dir,
5334
                        &format!("{tag}-{i}.txt"),
5335
                        format!("{tag} {i}\n").as_bytes(),
5336
                    );
5337
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
5338
                    if push && i % 5 == 4 {
5339
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
5340
                        let _ = r.push("origin", false);
5341
                    }
5342
                }
5343
            });
5344
        }
5345
    });
5346
5347
    let repo = Repo::open(&main).unwrap();
5348
    let heads = repo.bookmark_heads().unwrap();
5349
    let state = repo.load_state(&heads).unwrap();
5350
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
5351
    for tag in ["a", "b"] {
5352
        for i in 0..EACH {
5353
            assert!(
5354
                messages.contains(&format!("{tag} {i}")),
5355
                "lost commit {tag} {i}; have {messages:?}"
5356
            );
5357
        }
5358
    }
5359
    let rep = repo.fsck().unwrap();
5360
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
5361
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
5362
    let hosted = Repo::open(&origin).unwrap();
5363
    let hosted_heads = hosted.bookmark_heads().unwrap();
5364
    assert_eq!(
5365
        hosted.load_state(&hosted_heads).unwrap().len(),
5366
        state.len(),
5367
        "the remote has every commit"
5368
    );
5369
}
5370
5371
/// Two operations recorded from the same parent (what two processes do
5372
/// when they race) are merged: both bookmarks' heads survive, and a
5373
/// change made on one side only is kept.
5374
#[test]
5375
fn operations_from_the_same_parent_are_merged() {
5376
    hermetic();
5377
    let dir = tempfile::tempdir().unwrap();
5378
    let root = dir.path();
5379
    let repo = Repo::init(root).unwrap();
5380
    write(root, "a.txt", b"a\n");
5381
    let a = repo.commit("a", &[]).unwrap();
5382
    write(root, "b.txt", b"b\n");
5383
    let b = repo.commit("b", &[]).unwrap();
5384
    let (x, op) = repo.head_op().unwrap();
5385
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
5386
5387
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
5388
    let mut one = op.view.clone();
5389
    one.bookmarks.insert("main".into(), state(vec![a]));
5390
    one.bookmarks.insert("topic".into(), state(vec![a]));
5391
    let mut two = op.view.clone();
5392
    two.bookmarks.insert("main".into(), state(vec![b]));
5393
    repo.record_op(&[x], "one", one).unwrap();
5394
    let merged = repo.record_op(&[x], "two", two).unwrap();
5395
5396
    let (head, op) = repo.head_op().unwrap();
5397
    assert_eq!(head, merged);
5398
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
5399
    assert!(op.command.contains("merged with a concurrent operation"));
5400
    let mut main = repo
5401
        .store()
5402
        .get_state(&op.view.bookmarks["main"])
5403
        .unwrap()
5404
        .heads;
5405
    main.sort();
5406
    let mut want = vec![a, b];
5407
    want.sort();
5408
    assert_eq!(main, want, "both sides' heads are kept");
5409
    assert!(
5410
        op.view.bookmarks.contains_key("topic"),
5411
        "a one-sided change survives"
5412
    );
5413
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5414
}
3e5772cc Andy McCall ↶ 5415
5416
#[test]
5417
fn failed_requests_come_with_a_next_step() {
5418
    use crate::protocol::hint_for;
5419
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
5420
        .unwrap()
5421
        .contains("token"));
5422
    assert!(hint_for("…: HTTP 403: forbidden")
5423
        .unwrap()
5424
        .contains("repo:write"));
5425
    assert!(hint_for("…: HTTP 404: no such repository")
5426
        .unwrap()
5427
        .contains("owner and repository name"));
5428
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
5429
        .unwrap()
5430
        .contains("oxyhub-ca.pem"));
5431
    assert!(hint_for("Connect error: Connection refused (os error 111)")
5432
        .unwrap()
5433
        .contains("running"));
5434
    assert!(hint_for("Dns Failed: failed to lookup address information")
5435
        .unwrap()
5436
        .contains("resolve"));
5437
    assert_eq!(hint_for("something else entirely"), None);
5438
}
5439
5440
#[test]
5441
fn doctor_names_problems_and_what_to_do() {
5442
    hermetic();
5443
    let dir = tempfile::tempdir().unwrap();
5444
    let root = dir.path();
5445
    let origin = root.join("origin");
5446
    Repo::init_bare_unbound(&origin).unwrap();
5447
    let mut repo = Repo::init(&root.join("r"))
5448
        .unwrap()
5449
        .with_home(root.join("home"));
5450
    let find = |r: &DoctorReport, area: &str, h: Health| {
5451
        r.checks
5452
            .iter()
5453
            .find(|c| c.area == area && c.health == h)
5454
            .cloned()
5455
    };
5456
5457
    let r = repo.doctor(true);
5458
    assert!(find(&r, "identity", Health::Warn)
5459
        .unwrap()
5460
        .hint
5461
        .unwrap()
5462
        .contains("oxy identity create"));
5463
    assert!(find(&r, "repository", Health::Ok).is_some());
5464
5465
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5466
        .unwrap();
5467
    repo.config.set("author.name", "Ada").unwrap();
5468
    repo.config.set("author.email", "[email protected]").unwrap();
5469
    repo.config
5470
        .set("remote.origin.url", &origin.to_string_lossy())
5471
        .unwrap();
5472
    repo.config
5473
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
5474
        .unwrap();
5475
    repo.config.set("remote.down.token", "t").unwrap();
5476
    repo.config
5477
        .set("remote.badca.url", "https://example.invalid/a/b")
5478
        .unwrap();
5479
    repo.config
5480
        .set(
5481
            "remote.badca.ca",
5482
            &root.join("missing.pem").to_string_lossy(),
5483
        )
5484
        .unwrap();
5485
    repo.save_config().unwrap();
5486
5487
    let r = repo.doctor(true);
5488
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
5489
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
5490
    assert!(find(&r, "remote origin", Health::Ok)
5491
        .unwrap()
5492
        .message
5493
        .contains("first push binds it"));
5494
    let down = find(&r, "remote down", Health::Fail).unwrap();
5495
    assert!(
5496
        down.hint.as_deref().unwrap_or("").contains("running"),
5497
        "{down:?}"
5498
    );
5499
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
5500
    assert!(
5501
        badca.hint.unwrap().contains("remote.badca.ca"),
5502
        "the remote's own name is in the hint"
5503
    );
5504
    assert_eq!(r.worst(), Health::Fail);
5505
5506
    // Offline, nothing is contacted.
5507
    let r = repo.doctor(false);
5508
    assert!(find(&r, "remote down", Health::Fail).is_none());
5509
    assert!(find(&r, "remote down", Health::Ok)
5510
        .unwrap()
5511
        .message
5512
        .contains("not contacted"));
5513
}
62794ecc Andy McCall ↶ 5514
5515
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
5516
/// after it. Inserting after `b` and then deleting `b`, one commit after
5517
/// the other, must not leave a delete/insert conflict.
5518
#[test]
5519
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
5520
    hermetic();
5521
    let dir = tempfile::tempdir().unwrap();
5522
    let root = dir.path();
5523
    let repo = Repo::init(root).unwrap();
5524
    write(root, "f", b"a\nb\nc\n");
5525
    repo.commit("base", &[]).unwrap();
5526
    write(root, "f", b"a\nb\nx\nc\n");
5527
    let insert = repo.commit("insert x after b", &[]).unwrap();
5528
    write(root, "f", b"a\nx\nc\n");
5529
    let delete = repo.commit("delete b", &[]).unwrap();
5530
    assert!(
5531
        repo.store()
5532
            .get_change(&delete)
5533
            .unwrap()
5534
            .deps
5535
            .contains(&insert),
5536
        "the deletion depends on the insertion below the deleted line"
5537
    );
5538
    let heads = repo.bookmark_heads().unwrap();
5539
    assert_eq!(heads, vec![delete]);
5540
    let snap = repo.load_state(&heads).unwrap().materialize();
5541
    assert!(!snap.is_conflicted());
5542
    assert!(
5543
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
5544
    );
5545
}
5546
5547
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
5548
/// replacement depends on the change that set the blob it replaces.
5549
#[test]
5550
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
5551
    hermetic();
5552
    let dir = tempfile::tempdir().unwrap();
5553
    let root = dir.path();
5554
    let repo = Repo::init(root).unwrap();
5555
    write(root, "bin", b"\0A");
5556
    let v1 = repo.commit("v1", &[]).unwrap();
5557
    write(root, "bin", b"\0B");
5558
    let v2 = repo.commit("v2", &[]).unwrap();
5559
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
5560
    write(root, "bin", b"\0A");
5561
    let v3 = repo.commit("back to A", &[]).unwrap();
5562
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
5563
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
5564
    let state = repo.load_state(&[v3]).unwrap();
5565
    let snap = state.materialize();
5566
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
5567
        panic!("opaque")
5568
    };
5569
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
5570
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
5571
}
5572
5573
/// Spec §23: a binary file changed on two branches and merged in Git to
5574
/// one side's version comes back as that version at the merge, and the
5575
/// import verifies commit by commit.
5576
#[test]
5577
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
5578
    hermetic();
5579
    if std::process::Command::new("git")
5580
        .arg("--version")
5581
        .output()
5582
        .is_err()
5583
    {
5584
        eprintln!("git not installed; skipping");
5585
        return;
5586
    }
5587
    let dir = tempfile::tempdir().unwrap();
5588
    let root = dir.path();
5589
    let g = root.join("src.git");
5590
    fs::create_dir_all(&g).unwrap();
5591
    let git = |args: &[&str]| -> String {
5592
        let out = std::process::Command::new("git")
5593
            .arg("-C")
5594
            .arg(&g)
5595
            .args([
5596
                "-c",
5597
                "user.name=Grace",
5598
                "-c",
5599
                "[email protected]",
5600
                "-c",
5601
                "commit.gpgsign=false",
5602
            ])
5603
            .args(args)
5604
            .output()
5605
            .unwrap();
5606
        assert!(
5607
            out.status.success(),
5608
            "git {args:?}: {}",
5609
            String::from_utf8_lossy(&out.stderr)
5610
        );
5611
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5612
    };
5613
    git(&["init", "-q", "-b", "main"]);
5614
    write(&g, "logo.bin", b"\0base");
5615
    write(&g, "notes.txt", b"a\nb\nc\n");
5616
    git(&["add", "."]);
5617
    git(&["commit", "-qm", "base"]);
5618
    git(&["checkout", "-qb", "side"]);
5619
    write(&g, "logo.bin", b"\0side");
5620
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
5621
    git(&["commit", "-qam", "side"]);
5622
    git(&["checkout", "-q", "main"]);
5623
    write(&g, "logo.bin", b"\0main");
5624
    git(&["commit", "-qam", "main"]);
5625
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
5626
    let _ = std::process::Command::new("git")
5627
        .arg("-C")
5628
        .arg(&g)
5629
        .args([
5630
            "-c",
5631
            "user.name=G",
5632
            "-c",
5633
            "user.email=g@e",
5634
            "merge",
5635
            "-q",
5636
            "side",
5637
        ])
5638
        .output();
5639
    write(&g, "logo.bin", b"\0main");
5640
    git(&["add", "."]);
5641
    git(&["commit", "-qm", "merge side"]);
5642
    // Then a revert of the binary to its first version.
5643
    write(&g, "logo.bin", b"\0base");
5644
    git(&["commit", "-qam", "back to base"]);
5645
5646
    let repo = Repo::init(&root.join("o")).unwrap();
5647
    let rep = repo.import_git(&g, "main").unwrap();
5648
    assert_eq!(rep.merges, 1);
5649
    let v = repo.verify_git_import(&g, "main").unwrap();
5650
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
5651
    assert_eq!(v.commits, 5);
5652
    let snap = repo
5653
        .load_state(&repo.bookmark_heads().unwrap())
5654
        .unwrap()
5655
        .materialize();
5656
    assert!(!snap.is_conflicted());
5657
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
5658
        panic!("opaque")
5659
    };
5660
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
5661
}
c863c7a7 Andy McCall ↶ 5662
5663
/// Spec §7.7 on a file system without executable bits or symlinks: the
5664
/// recorded bit is kept, and a symlink checked out as a plain file holding
5665
/// its target is still that symlink.
5666
#[cfg(unix)]
5667
#[test]
5668
fn windows_file_systems_keep_exec_bits_and_symlinks() {
5669
    use crate::portable::Platform;
5670
    use std::os::unix::fs::PermissionsExt;
5671
    hermetic();
5672
    let dir = tempfile::tempdir().unwrap();
5673
    let root = dir.path();
5674
    let repo = Repo::init(root).unwrap();
5675
    write(root, "run.sh", b"#!/bin/sh\n");
5676
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
5677
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
5678
    repo.commit("script and link", &[]).unwrap();
5679
    drop(repo);
5680
5681
    // What checking out on Windows leaves: no exec bit, the link as a file.
5682
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
5683
    fs::remove_file(root.join("link")).unwrap();
5684
    write(root, "link", b"run.sh");
5685
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
5686
    let s = win.snapshot("oxy status").unwrap();
5687
    assert!(
5688
        s.statuses.is_empty(),
5689
        "nothing changed on Windows: {:?}",
5690
        statuses(&s)
5691
    );
5692
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
5693
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
5694
    write(root, "link", b"other");
5695
    let h = win.commit("edit on Windows", &[]).unwrap();
5696
    let snap = win.load_state(&[h]).unwrap().materialize();
5697
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
5698
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
5699
    // The same working copy read as Linux sees the lost bit and the plain file.
5700
    let linux = Repo::open(root).unwrap();
5701
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
5702
}
5703
5704
/// Paths that collide on case-insensitive or Windows file systems are
5705
/// named at checkout there, and by doctor everywhere.
5706
#[test]
5707
fn paths_other_platforms_cannot_hold_are_reported() {
5708
    use crate::portable::Platform;
5709
    hermetic();
5710
    let dir = tempfile::tempdir().unwrap();
5711
    let root = dir.path();
5712
    let repo = Repo::init(root).unwrap();
5713
    write(root, "README.md", b"a\n");
5714
    write(root, "readme.md", b"b\n");
5715
    write(root, "src/aux.c", b"int x;\n");
5716
    let h = repo.commit("unportable", &[]).unwrap();
5717
    let r = repo.doctor(false);
5718
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
5719
    assert_eq!(port.health, Health::Warn);
5720
    assert!(
5721
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
5722
        "{}",
5723
        port.message
5724
    );
5725
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
5726
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
5727
    assert!(
5728
        rep.notes
5729
            .iter()
5730
            .any(|n| n.contains("README.md and readme.md")),
5731
        "{:?}",
5732
        rep.notes
5733
    );
5734
    assert!(
5735
        !rep.notes.iter().any(|n| n.contains("aux.c")),
5736
        "macOS allows aux.c"
5737
    );
5738
}
bc489b6c Andy McCall ↶ 5739
5740
#[test]
5741
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
5742
    hermetic();
5743
    let dir = tempfile::tempdir().unwrap();
5744
    let repo = Repo::init(dir.path()).unwrap();
5745
    write(dir.path(), "a.txt", b"one\n");
5746
    write(dir.path(), "other.txt", b"x\n");
5747
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
5748
    repo.snapshot("t").unwrap();
5749
    let c1 = repo.commit("first", &[]).unwrap();
5750
    write(dir.path(), "other.txt", b"y\n");
5751
    repo.snapshot("t").unwrap();
5752
    repo.commit("other only", &[]).unwrap();
5753
    write(dir.path(), "a.txt", b"one\ntwo\n");
5754
    repo.snapshot("t").unwrap();
5755
    let c3 = repo.commit("second line", &[]).unwrap();
5756
    write(dir.path(), "other.txt", b"z\n");
5757
    repo.snapshot("t").unwrap();
5758
    repo.commit("other again", &[]).unwrap();
5759
5760
    let heads = repo.bookmark_heads().unwrap();
5761
    let state = repo.load_state(&heads).unwrap();
5762
    let full: Vec<ChangeHash> = repo
5763
        .log_for_path_in("a.txt", &heads)
5764
        .unwrap()
5765
        .iter()
5766
        .map(|e| e.hash)
5767
        .collect();
5768
    assert_eq!(
5769
        full,
5770
        vec![c3, c1],
5771
        "newest first, only changes touching the path"
5772
    );
5773
    let newest: Vec<ChangeHash> = repo
5774
        .log_for_path_of(&state, "a.txt", Some(1))
5775
        .unwrap()
5776
        .iter()
5777
        .map(|e| e.hash)
5778
        .collect();
5779
    assert_eq!(newest, vec![c3], "stops at the first");
5780
    assert_eq!(
5781
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5782
        2
5783
    );
5784
    assert!(repo
5785
        .log_for_path_of(&state, "missing.txt", Some(1))
5786
        .is_err());
5787
    assert_eq!(
5788
        repo.log_state(&heads).unwrap().len(),
5789
        repo.log_of(&state).len()
5790
    );
5791
5792
    let tree = state.tree().view();
5793
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5794
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5795
    assert_eq!(
5796
        via_state
5797
            .iter()
5798
            .map(|l| (l.hash, l.text.clone()))
5799
            .collect::<Vec<_>>(),
5800
        via_heads
5801
            .iter()
5802
            .map(|l| (l.hash, l.text.clone()))
5803
            .collect::<Vec<_>>()
5804
    );
5805
    assert_eq!(
5806
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5807
        vec![c1, c3]
5808
    );
5809
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5810
}
696bbf29 Andy McCall ↶ 5811
5812
/// A text file whose stat matches the manifest and whose recorded hash is
5813
/// the base's content is taken from the base without reading it; anything
5814
/// else is read, so no edit is missed (spec §12.3).
5815
#[cfg(unix)]
5816
#[test]
5817
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5818
    use std::os::unix::fs::PermissionsExt;
5819
    hermetic();
5820
    let dir = tempfile::tempdir().unwrap();
5821
    let root = dir.path();
5822
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5823
    write(root, "a.txt", b"one\ntwo\n");
5824
    write(root, "b.txt", b"bee\n");
5825
    repo.commit("base", &[]).unwrap();
5826
    let age = |p: &str| {
5827
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5828
        fs::File::options()
5829
            .write(true)
5830
            .open(root.join(p))
5831
            .unwrap()
5832
            .set_modified(old)
5833
            .unwrap();
5834
    };
5835
    age("a.txt");
5836
    age("b.txt");
5837
    assert!(
5838
        !repo.snapshot("status").unwrap().changed,
5839
        "records the aged stat"
5840
    );
5841
5842
    // Clean and equal to the base: not read at all.
5843
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5844
    let snap = repo.snapshot("status").unwrap();
5845
    assert!(
5846
        !snap.changed && snap.statuses.is_empty(),
5847
        "{:?}",
5848
        snap.statuses
5849
    );
5850
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5851
5852
    // An uncommitted edit that is older than the manifest: stat-clean, but
5853
    // its hash is not the base's, so it is read and stays visible.
5854
    write(root, "b.txt", b"bee edited\n");
5855
    age("b.txt");
5856
    let first = repo.snapshot("status").unwrap();
5857
    assert_eq!(
5858
        statuses(&first),
5859
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5860
    );
5861
    let again = repo.snapshot("status").unwrap();
5862
    assert_eq!(
5863
        statuses(&again),
5864
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5865
        "still seen once stat-clean"
5866
    );
5867
    assert!(!again.changed, "and the working copy hashes the same");
5868
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5869
    assert!(
5870
        repo.snapshot("status").is_err(),
5871
        "an edited file must be read, never taken from the base"
5872
    );
5873
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5874
5875
    // A same-size edit made just now is racy and read.
5876
    write(root, "a.txt", b"one\nTWO\n");
5877
    assert_eq!(
5878
        statuses(&repo.snapshot("status").unwrap()),
5879
        vec![
5880
            ("a.txt".to_string(), ChangeStatus::Modified),
5881
            ("b.txt".to_string(), ChangeStatus::Modified)
5882
        ]
5883
    );
5884
    // Committing makes the edits the base: both are clean and served from it again.
5885
    repo.commit("edits", &[]).unwrap();
5886
    age("a.txt");
5887
    age("b.txt");
5888
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5889
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5890
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5891
    let snap = repo.snapshot("status").unwrap();
5892
    assert!(!snap.changed && snap.statuses.is_empty());
5893
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5894
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5895
}
afaba5f1 Andy McCall ↶ 5896
5897
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5898
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5899
/// file is unchanged, and loading through the checkpoint equals a full load.
5900
#[test]
5901
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5902
    hermetic();
5903
    let dir = tempfile::tempdir().unwrap();
5904
    let root = dir.path();
5905
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5906
    let long: String = (0..300)
5907
        .map(|i| format!("line {i} of a long file\n"))
5908
        .collect();
5909
    write(root, "long.txt", long.as_bytes());
5910
    write(root, "short.txt", b"short\n");
5911
    repo.commit("base", &[]).unwrap();
5912
    let (r1, _, _) = repo.checkpoint().unwrap();
5913
    let cp1 = crate::objects::Checkpoint::decode(
5914
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5915
    )
5916
    .unwrap();
5917
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5918
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5919
5920
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5921
    repo.gc(true).unwrap();
5922
    assert!(repo.store().has(&graphs1[0]));
5923
    let report = repo.fsck().unwrap();
5924
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5925
5926
    // Loading through the checkpoint equals a full load.
5927
    write(root, "short.txt", b"short, edited\n");
5928
    repo.commit("edit the short file", &[]).unwrap();
5929
    let heads = repo.bookmark_heads().unwrap();
5930
    let fast = repo.load_state(&heads).unwrap();
5931
    let full = repo.load_state_full(&heads).unwrap();
5932
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5933
5934
    // The next checkpoint shares the unchanged long file's graph.
5935
    let (r2, _, _) = repo.checkpoint().unwrap();
5936
    let cp2 = crate::objects::Checkpoint::decode(
5937
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5938
    )
5939
    .unwrap();
5940
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5941
5942
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5943
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5944
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5945
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5946
5947
    // A version 1 checkpoint written by an older oxy still loads.
5948
    let state = repo.load_state_full(&heads).unwrap();
5949
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5950
    let cp_old = crate::objects::Checkpoint {
5951
        heads: cp2.heads.clone(),
5952
        count: cp2.count,
5953
        payload: old,
5954
    };
5955
    let r_old = repo
5956
        .store()
5957
        .put(ObjectType::Checkpoint, &cp_old.encode())
5958
        .unwrap();
5959
    repo.install_checkpoint("main", &r_old).unwrap();
5960
    assert_eq!(
5961
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5962
        full.checkpoint_payload()
5963
    );
5964
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5965
5966
    // A lost graph blob fails the load loudly rather than dropping the
5967
    // file, and fsck reports it (a fresh repository, objects still loose).
5968
    let dir2 = tempfile::tempdir().unwrap();
5969
    let root2 = dir2.path();
5970
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5971
    write(root2, "long.txt", long.as_bytes());
5972
    repo2.commit("base", &[]).unwrap();
5973
    let (r, _, _) = repo2.checkpoint().unwrap();
5974
    let cp = crate::objects::Checkpoint::decode(
5975
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5976
    )
5977
    .unwrap();
5978
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
64818938 Andy McCall ↶ 5979
    repo2.store().remove_loose_for_test(&graph).unwrap();
afaba5f1 Andy McCall ↶ 5980
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5981
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5982
}
e3d071ce Andy McCall ↶ 5983
5984
/// A new repository has not stored the user's identity yet (that happens
5985
/// at the first signed change); looking it up falls back to the key
5986
/// directory, and a file there that does not hash to the key is refused.
5987
#[test]
5988
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5989
    hermetic();
5990
    let dir = tempfile::tempdir().unwrap();
5991
    let home = dir.path().join("home");
5992
    let mut first = Repo::init(&dir.path().join("a"))
5993
        .unwrap()
5994
        .with_home(home.clone());
5995
    let (key, _) = first
5996
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5997
        .unwrap();
5998
    let fresh = Repo::init(&dir.path().join("b"))
5999
        .unwrap()
6000
        .with_home(home.clone());
6001
    assert!(!fresh.store().has(&key), "nothing stored yet");
6002
    let id = fresh.identity(&key).unwrap();
6003
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
6004
    // A key file that is not this identity is an error, not a wrong answer.
6005
    let keys = fresh.keys_dir.clone();
6006
    let (other, _) = first
6007
        .create_identity("Bob", "[email protected]", IdentityScope::User)
6008
        .unwrap();
6009
    fs::copy(
6010
        keys.join(format!("{}.identity", other.to_hex())),
6011
        keys.join(format!("{}.identity", key.to_hex())),
6012
    )
6013
    .unwrap();
6014
    assert!(fresh
6015
        .identity(&key)
6016
        .unwrap_err()
6017
        .to_string()
6018
        .contains("does not hold identity"));
6019
}
cc7a0056 Andy McCall ↶ 6020
6021
/// Status snapshots (spec §12.3): a text file whose stat matches the
6022
/// manifest, and whose base graph key is the one the manifest recorded it
6023
/// equal to, is neither read nor rendered; any edit, and any change to the
6024
/// file's graph in the base, brings it back.
6025
#[cfg(unix)]
6026
#[test]
6027
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
6028
    use std::os::unix::fs::PermissionsExt;
6029
    hermetic();
6030
    let dir = tempfile::tempdir().unwrap();
6031
    let root = dir.path();
6032
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6033
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
6034
        write(root, p, c.as_bytes());
6035
    }
6036
    repo.commit("base", &[]).unwrap();
6037
    let age = |p: &str| {
6038
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6039
        fs::File::options()
6040
            .write(true)
6041
            .open(root.join(p))
6042
            .unwrap()
6043
            .set_modified(old)
6044
            .unwrap();
6045
    };
6046
    let lock = |p: &str, mode: u32| {
6047
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
6048
    };
6049
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6050
        age(p);
6051
    }
6052
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6053
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6054
    assert!(
6055
        m.entries.values().all(|e| e.graph.is_some()),
6056
        "keys recorded"
6057
    );
6058
6059
    // Unreadable files prove they are not read; the status snapshot does
6060
    // not render them either, and its base lacks their graphs.
6061
    lock("a.txt", 0o000);
6062
    lock("b.txt", 0o000);
6063
    let snap = repo.snapshot_status("status").unwrap();
6064
    assert!(!snap.changed && snap.statuses.is_empty());
6065
    assert_eq!(
6066
        snap.base_snapshot
6067
            .unrendered
6068
            .iter()
6069
            .cloned()
6070
            .collect::<Vec<_>>(),
6071
        vec!["a.txt", "b.txt", "d/c.txt"]
6072
    );
6073
    assert!(!snap.base.is_full());
6074
    assert!(!snap.base_snapshot.is_conflicted());
6075
    // A full snapshot does not read them either, but renders everything.
6076
    let full = repo.snapshot("status").unwrap();
6077
    assert!(full.statuses.is_empty() && full.base.is_full());
6078
    assert!(full.base_snapshot.unrendered.is_empty());
6079
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
6080
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
6081
6082
    // An edit is seen; the file is rendered, the others still are not.
6083
    write(root, "d/c.txt", b"sea edited\n");
6084
    let snap = repo.snapshot_status("status").unwrap();
6085
    assert_eq!(
6086
        statuses(&snap),
6087
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
6088
    );
6089
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
6090
    // So is a mode change of an unread file.
6091
    lock("b.txt", 0o100);
6092
    assert_eq!(
6093
        statuses(&repo.snapshot_status("status").unwrap()),
6094
        vec![
6095
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
6096
            ("d/c.txt".to_string(), ChangeStatus::Modified)
6097
        ]
6098
    );
6099
    lock("b.txt", 0o000);
6100
6101
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
6102
    // stays unread, c.txt is read once and then skipped too.
6103
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
6104
        .unwrap();
6105
    age("d/c.txt");
6106
    let snap = repo.snapshot_status("status").unwrap();
6107
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
6108
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
6109
    lock("d/c.txt", 0o000);
6110
    let snap = repo.snapshot_status("status").unwrap();
6111
    assert!(snap.statuses.is_empty());
6112
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
6113
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6114
        lock(p, 0o644);
6115
    }
6116
}
6117
6118
/// Attributes decide how a file compares with the base, so a changed
6119
/// `.oxyattributes` makes every text file be compared again.
6120
#[cfg(unix)]
6121
#[test]
6122
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
6123
    hermetic();
6124
    let dir = tempfile::tempdir().unwrap();
6125
    let root = dir.path();
6126
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6127
    write(root, "a.txt", b"crlf\r\n");
6128
    repo.commit("base", &[]).unwrap();
6129
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6130
    fs::File::options()
6131
        .write(true)
6132
        .open(root.join("a.txt"))
6133
        .unwrap()
6134
        .set_modified(old)
6135
        .unwrap();
6136
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6137
    assert!(repo
6138
        .snapshot_status("status")
6139
        .unwrap()
6140
        .base_snapshot
6141
        .unrendered
6142
        .contains("a.txt"));
6143
    // With eol=lf, a.txt as stored no longer equals the base.
6144
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
6145
    let snap = repo.snapshot_status("status").unwrap();
6146
    assert_eq!(
6147
        statuses(&snap),
6148
        vec![
6149
            (".oxyattributes".to_string(), ChangeStatus::Added),
6150
            ("a.txt".to_string(), ChangeStatus::Modified)
6151
        ]
6152
    );
6153
}
54cd08a1 Andy McCall ↶ 6154
6155
/// Bookmarks with `/` in their names: pushing records their
6156
/// attestations, and checkpoints are kept for them, beside `feature`
6157
/// itself.
6158
#[test]
6159
fn bookmarks_with_slashes_push_and_checkpoint() {
6160
    hermetic();
6161
    let dir = tempfile::tempdir().unwrap();
6162
    let root = dir.path();
6163
    let origin = Repo::init(&root.join("origin")).unwrap();
6164
    let url = root.join("origin").to_string_lossy().to_string();
6165
    let mut repo = Repo::clone(&url, &root.join("r"))
6166
        .unwrap()
6167
        .with_home(root.join("home"));
6168
    // With an identity, pushes carry reference attestations: the case
6169
    // that failed, since the attestation is a file named after the bookmark.
6170
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6171
        .unwrap();
6172
    let r = root.join("r");
6173
    write(&r, "a.txt", b"a\n");
6174
    let h_a = repo.commit("a", &[]).unwrap();
6175
    assert!(repo.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 6176
    origin.refresh().unwrap();
54cd08a1 Andy McCall ↶ 6177
    repo.bookmark_create("feature", None).unwrap();
6178
    repo.bookmark_create("feature/x", None).unwrap();
6179
    repo.bookmark_switch("feature/x", false).unwrap();
6180
    write(&r, "b.txt", b"b\n");
6181
    let h_b = repo.commit("b", &[]).unwrap();
6182
    for name in ["feature", "feature/x"] {
6183
        let res = repo.push_bookmark("origin", name, false).unwrap();
767ac6cd Andy McCall 6184
        origin.refresh().unwrap();
54cd08a1 Andy McCall ↶ 6185
        assert!(res[0].ok, "{name}: {res:?}");
6186
    }
6187
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
6188
    assert_eq!(
6189
        origin.resolve_heads("feature/x").unwrap(),
6190
        repo.resolve_heads("feature/x").unwrap()
6191
    );
6192
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
6193
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
6194
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
6195
6196
    // A checkpoint of feature/x is found again when loading its state.
6197
    let (cp, _, _) = repo.checkpoint().unwrap();
6198
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
6199
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
6200
    let heads = repo.resolve_heads("feature/x").unwrap();
6201
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
f8c69576 Andy McCall ↶ 6202
}
6203
6204
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
6205
/// never the remote's own bookmark, and a bookmark created again later is
6206
/// accepted although the deletion's attestation stays the latest.
6207
#[test]
6208
fn bookmarks_are_deleted_on_a_remote() {
6209
    hermetic();
6210
    let dir = tempfile::tempdir().unwrap();
6211
    let root = dir.path();
6212
    let origin = Repo::init(&root.join("origin")).unwrap();
6213
    let url = root.join("origin").to_string_lossy().to_string();
6214
    let mut repo = Repo::clone(&url, &root.join("r"))
6215
        .unwrap()
6216
        .with_home(root.join("home"));
6217
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6218
        .unwrap();
6219
    let r = root.join("r");
6220
    write(&r, "a.txt", b"a\n");
6221
    repo.commit("a", &[]).unwrap();
6222
    assert!(repo.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 6223
    origin.refresh().unwrap();
f8c69576 Andy McCall ↶ 6224
    repo.bookmark_create("feature/x", None).unwrap();
6225
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
767ac6cd Andy McCall 6226
    origin.refresh().unwrap();
f8c69576 Andy McCall ↶ 6227
    assert!(origin.resolve_heads("feature/x").is_ok());
6228
6229
    let res = repo.push_delete("origin", "feature/x").unwrap();
767ac6cd Andy McCall 6230
    origin.refresh().unwrap();
f8c69576 Andy McCall ↶ 6231
    assert!(res[0].ok, "{res:?}");
6232
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
6233
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
6234
    assert!(
6235
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
6236
        "the deletion is attested"
6237
    );
6238
    assert!(
6239
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
6240
        "the local bookmark stays"
6241
    );
6242
    assert!(!repo
6243
        .view()
6244
        .unwrap()
6245
        .remotes
6246
        .get("origin")
6247
        .is_some_and(|m| m.contains_key("feature/x")));
6248
6249
    // Pushing it again creates it again, past the deletion's serial.
6250
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
767ac6cd Andy McCall 6251
    origin.refresh().unwrap();
f8c69576 Andy McCall ↶ 6252
    assert!(res[0].ok, "{res:?}");
6253
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
6254
6255
    // Nothing to delete, and never the remote's own bookmark.
6256
    assert!(repo.push_delete("origin", "nope").is_err());
6257
    let res = repo.push_delete("origin", "main").unwrap();
767ac6cd Andy McCall 6258
    origin.refresh().unwrap();
f8c69576 Andy McCall ↶ 6259
    assert!(
6260
        !res[0].ok && res[0].reason.contains("default bookmark"),
6261
        "{res:?}"
6262
    );
6263
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
54cd08a1 Andy McCall ↶ 6264
}
61e3bce7 Andy McCall ↶ 6265
6266
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
6267
/// when the target has the same versions of the files it touches, and is
6268
/// refused, untouched, when it has others.
6269
#[test]
6270
fn switching_bookmarks_carries_uncommitted_work() {
6271
    hermetic();
6272
    let dir = tempfile::tempdir().unwrap();
6273
    let root = dir.path();
6274
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6275
    write(root, "a.txt", b"a\n");
6276
    write(root, "b.txt", b"b\n");
6277
    write(root, "gone.txt", b"gone\n");
6278
    repo.commit("base", &[]).unwrap();
6279
    repo.bookmark_create("feature", None).unwrap();
6280
    // Started on main, belongs on feature: edit, add, remove.
6281
    write(root, "a.txt", b"a\nmore\n");
6282
    write(root, "new.txt", b"new\n");
6283
    fs::remove_file(root.join("gone.txt")).unwrap();
6284
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
6285
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
6286
    assert_eq!(repo.config.bookmark, "feature");
6287
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
6288
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
6289
    assert!(!root.join("gone.txt").exists());
6290
    let snap = repo.snapshot("status").unwrap();
6291
    assert_eq!(
6292
        statuses(&snap),
6293
        vec![
6294
            ("a.txt".to_string(), ChangeStatus::Modified),
6295
            ("gone.txt".to_string(), ChangeStatus::Removed),
6296
            ("new.txt".to_string(), ChangeStatus::Added)
6297
        ]
6298
    );
6299
    repo.commit("the work", &[]).unwrap();
6300
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
6301
6302
    // main moves b.txt on; work on feature touching b.txt cannot follow.
6303
    repo.bookmark_switch("main", false).unwrap();
6304
    write(root, "b.txt", b"b on main\n");
6305
    repo.commit("b on main", &[]).unwrap();
6306
    repo.bookmark_switch("feature", false).unwrap();
6307
    write(root, "b.txt", b"b edited\n");
6308
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
6309
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
6310
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
6311
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
6312
}
1c2bd9ab Andy McCall ↶ 6313
6314
/// Merging and checking out (feedback 3): a working copy without changes
6315
/// follows a merge whichever state it sat on; a refused checkout names
6316
/// what is in the way; `checkout --carry` takes the work along.
6317
#[test]
6318
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
6319
    hermetic();
6320
    let dir = tempfile::tempdir().unwrap();
6321
    let root = dir.path();
6322
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6323
    write(root, "a.txt", b"a\n");
6324
    let h1 = repo.commit("a", &[]).unwrap();
6325
    write(root, "b.txt", b"b\n");
6326
    repo.commit("b", &[]).unwrap();
6327
    repo.bookmark_create("feature", None).unwrap();
6328
    repo.bookmark_switch("feature", false).unwrap();
6329
    write(root, "c.txt", b"c\n");
6330
    repo.commit("c on feature", &[]).unwrap();
6331
    repo.bookmark_switch("main", false).unwrap();
6332
    // The working copy sits on an older state than main's heads.
6333
    repo.checkout(&[h1], false, "checkout").unwrap();
6334
    assert!(!root.join("b.txt").exists());
6335
    let m = repo.merge("feature").unwrap();
6336
    assert!(m.checked_out, "a clean working copy follows the merge");
6337
    for f in ["a.txt", "b.txt", "c.txt"] {
6338
        assert!(root.join(f).exists(), "{f}");
6339
    }
6340
6341
    // A refusal says which paths are in the way and what to do.
6342
    fs::remove_file(root.join("b.txt")).unwrap();
6343
    write(root, "a.txt", b"a edited\n");
6344
    let err = repo
6345
        .checkout(&[h1], false, "checkout")
6346
        .unwrap_err()
6347
        .to_string();
6348
    assert!(
6349
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
6350
        "{err}"
6351
    );
fe9586d9 Andy McCall ↶ 6352
    // --carry takes them along: h1 has a.txt as the base has it, and the
6353
    // removed b.txt is already as h1 has it (none), so that is no conflict
6354
    // either (oxygen#100).
1c2bd9ab Andy McCall ↶ 6355
    let (_, carried) = repo
6356
        .checkout_carry(&[h1], "the first change", "checkout")
6357
        .unwrap();
6358
    assert_eq!(carried, vec!["a.txt"]);
6359
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
6360
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
6361
}
e7ac6c2e Andy McCall ↶ 6362
6363
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
6364
/// user identity not stored in a new repository yet is fine while its
6365
/// secret key is there; an added subrepo is listed as not committed yet.
6366
#[test]
6367
fn a_new_repository_is_healthy_before_its_first_commit() {
6368
    hermetic();
6369
    let dir = tempfile::tempdir().unwrap();
6370
    let root = dir.path();
6371
    let home = root.join("home");
6372
    let mut first = Repo::init(&root.join("first"))
6373
        .unwrap()
6374
        .with_home(home.clone());
6375
    let (key, _) = first
6376
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6377
        .unwrap();
6378
    let repo = Repo::init(&root.join("second"))
6379
        .unwrap()
6380
        .with_home(home.clone());
6381
    // Only the secret key: no identity object anywhere this repository sees.
6382
    let keys = repo.keys_dir.clone();
6383
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
6384
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
6385
    let r = repo.doctor(true);
6386
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
6387
    assert_eq!(id.health, Health::Ok, "{}", id.message);
6388
    assert!(id.message.contains("first signed change"), "{}", id.message);
6389
6390
    // A subrepo added and not committed yet is listed, pinned where it is.
6391
    let lib = root.join("lib");
6392
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
6393
    write(&lib, "x.txt", b"x\n");
6394
    l.commit("x", &[]).unwrap();
6395
    let second = root.join("second");
6396
    write(&second, "a.txt", b"a\n");
6397
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
6398
        .unwrap();
6399
    let subs = repo.subrepos().unwrap();
6400
    assert_eq!(subs.len(), 1);
6401
    assert_eq!(
6402
        (subs[0].path.as_str(), subs[0].committed),
6403
        ("deps/lib", false)
6404
    );
6405
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
6406
    repo.commit("add lib", &[]).unwrap();
6407
    let subs = repo.subrepos().unwrap();
6408
    assert!(subs[0].committed, "committed now");
6409
}
8ab265dc Andy McCall ↶ 6410
6411
/// Commit, diff, hunks and discard use the partial snapshot: a file
6412
/// unchanged since the manifest is neither read nor rendered, and showing
6413
/// a change renders only what it edits, the same as from a full base.
6414
#[cfg(unix)]
6415
#[test]
6416
fn commits_and_diffs_leave_unchanged_files_alone() {
6417
    use std::os::unix::fs::PermissionsExt;
6418
    hermetic();
6419
    let dir = tempfile::tempdir().unwrap();
6420
    let root = dir.path();
6421
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6422
    write(root, "big.txt", b"lots\nof\nlines\n");
6423
    write(root, "a.txt", b"one\ntwo\n");
6424
    repo.commit("base", &[]).unwrap();
6425
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6426
    for f in ["big.txt", "a.txt"] {
6427
        fs::File::options()
6428
            .write(true)
6429
            .open(root.join(f))
6430
            .unwrap()
6431
            .set_modified(old)
6432
            .unwrap();
6433
    }
6434
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6435
    // big.txt cannot be read at all from here on.
6436
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6437
6438
    write(root, "a.txt", b"one\nTWO\nthree\n");
6439
    let diff = repo.diff_files(None).unwrap();
6440
    assert_eq!(
6441
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
6442
        ["a.txt"]
6443
    );
6444
    let (_, hunks) = repo.hunks().unwrap();
6445
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
6446
    let h = repo.commit("edit a", &[]).unwrap();
6447
6448
    // Showing the change needs only a.txt's graph, and renders as a full base does.
6449
    let c = repo.store().get_change(&h).unwrap();
6450
    let full = repo.load_state(&c.deps).unwrap();
6451
    let want = render_change(&c, &full, &full.materialize());
6452
    assert_eq!(repo.describe_change(&h).unwrap(), want);
6453
    let (base, snap) = repo.change_base(&c).unwrap();
6454
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
6455
6456
    // Discarding works the same way.
6457
    write(root, "a.txt", b"scratch\n");
6458
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
6459
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
6460
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6461
}
f7510b63 Andy McCall ↶ 6462
6463
/// A replace conflict (spec §9.3) is settled by a change that writes one
6464
/// candidate, or new bytes, at the path when the caller names it; a plain
6465
/// snapshot of a checkout never settles it on its own.
6466
#[test]
6467
fn replace_conflicts_are_settled_when_asked() {
6468
    hermetic();
6469
    let dir = tempfile::tempdir().unwrap();
6470
    let root = dir.path();
6471
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6472
    let blob = |n: u8| {
6473
        let mut v = vec![0u8; 64];
6474
        v[1] = n;
6475
        v
6476
    };
6477
    write(root, "img.bin", &blob(1));
6478
    repo.commit("add img", &[]).unwrap();
6479
    repo.bookmark_create("other", None).unwrap();
6480
    write(root, "img.bin", &blob(2));
6481
    repo.commit("img two", &[]).unwrap();
6482
    repo.bookmark_switch("other", false).unwrap();
6483
    write(root, "img.bin", &blob(3));
6484
    repo.commit("img three", &[]).unwrap();
6485
    repo.bookmark_switch("main", false).unwrap();
6486
    repo.merge("other").unwrap();
6487
    let heads = repo.bookmark_heads().unwrap();
6488
    let merged = repo.load_state(&heads).unwrap().materialize();
6489
    assert!(
6490
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
6491
        "a replace conflict"
6492
    );
6493
    // A snapshot of the checkout records nothing.
6494
    assert!(repo
6495
        .snapshot("status")
6496
        .unwrap()
6497
        .statuses
6498
        .iter()
6499
        .all(|s| s.path != "img.bin"));
6500
6501
    // Keeping candidate 3 settles it.
6502
    let author = repo.author();
6503
    let edits = [FileEdit {
6504
        path: "img.bin".into(),
6505
        content: Some(blob(3)),
6506
    }];
6507
    let c = repo
6508
        .build_change(&heads, &edits, "keep three", author)
6509
        .unwrap();
6510
    assert_eq!(c.kind, ChangeKind::Resolution);
6511
    let mut st = repo.load_state(&heads).unwrap();
6512
    for d in &c.deps {
6513
        assert!(st.contains(d));
6514
    }
6515
    assert!(
6516
        heads.iter().all(|h| c.deps.contains(h)),
6517
        "depends on both contributors"
6518
    );
6519
    st.add(c).unwrap();
6520
    let after = st.materialize();
6521
    assert!(!after.is_conflicted());
6522
    assert_eq!(
6523
        after.files["img.bin"].content,
6524
        FileContent::Opaque {
6525
            blobs: vec![Repo::blob_ref(&blob(3))]
6526
        }
6527
    );
6528
6529
    // New bytes settle it too.
6530
    let edits = [FileEdit {
6531
        path: "img.bin".into(),
6532
        content: Some(blob(9)),
6533
    }];
6534
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
6535
    let mut st = repo.load_state(&heads).unwrap();
6536
    st.add(c).unwrap();
6537
    assert_eq!(
6538
        st.materialize().files["img.bin"].content,
6539
        FileContent::Opaque {
6540
            blobs: vec![Repo::blob_ref(&blob(9))]
6541
        }
6542
    );
6543
}
83d61e80 Andy McCall ↶ 6544
6545
/// The history of a range of lines (spec §27): the changes that wrote
6546
/// or deleted its atoms, or deleted atoms from between them; edits outside
6547
/// the range and changes the range's lines survived are not in it.
6548
#[test]
6549
fn line_ranges_have_exact_histories() {
6550
    hermetic();
6551
    let dir = tempfile::tempdir().unwrap();
6552
    let root = dir.path();
6553
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6554
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
6555
    let base = repo.commit("add f", &[]).unwrap();
6556
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
6557
    let outside = repo.commit("change the import", &[]).unwrap();
6558
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
6559
    let inside = repo.commit("edit a line of a", &[]).unwrap();
6560
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
6561
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
6562
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
6563
    let after = repo.commit("add b after a", &[]).unwrap();
6564
    let heads = repo.bookmark_heads().unwrap();
6565
6566
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
6567
    let hist: Vec<ChangeHash> = repo
6568
        .line_history(&heads, "f.rs", 2, 4)
6569
        .unwrap()
6570
        .iter()
6571
        .map(|e| e.hash)
6572
        .collect();
6573
    for (h, what) in [
6574
        (base, "wrote it"),
6575
        (inside, "edited a line"),
6576
        (deleted, "deleted a line from inside"),
6577
    ] {
6578
        assert!(hist.contains(&h), "{what}");
6579
    }
6580
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
6581
        assert!(!hist.contains(&h), "{what}");
6582
    }
6583
    assert_eq!(hist[0], deleted, "newest first");
6584
    // One line: only what touched it.
6585
    let one: Vec<ChangeHash> = repo
6586
        .line_history(&heads, "f.rs", 1, 1)
6587
        .unwrap()
6588
        .iter()
6589
        .map(|e| e.hash)
6590
        .collect();
6591
    assert!(one.contains(&outside) && !one.contains(&inside));
6592
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
6593
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
6594
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
6595
}
fc1a466a Andy McCall ↶ 6596
6597
#[test]
6598
fn receipts_are_kept_with_their_state_and_verified() {
6599
    use crate::receipt::{Receipt, SignedReceipt};
6600
    hermetic();
6601
    let dir = tempfile::tempdir().unwrap();
6602
    let root = dir.path();
6603
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6604
    write(root, "a.txt", b"1\n");
6605
    repo.commit("A", &[]).unwrap();
6606
    let heads = repo.bookmark_heads().unwrap();
6607
    let state = repo
6608
        .store()
6609
        .put_state(&StateObject::new(heads.clone()))
6610
        .unwrap();
6611
    let out = repo.store_blob(b"built\n").unwrap();
6612
    let receipt = Receipt {
6613
        job_name: "build".into(),
6614
        pipeline_hash: ObjectRef([1; 32]),
6615
        scope_tree_hash: ObjectRef([2; 32]),
6616
        inputs: vec![],
6617
        environment: ObjectRef([3; 32]),
6618
        outputs: vec![out],
6619
        exit_code: 0,
6620
        duration_ms: 42,
6621
    };
6622
    let sk = SecretKey::generate();
6623
    let runner = sk.identity("earth-1", "runner@earth", 1);
6624
    let sr = SignedReceipt::sign(
6625
        receipt.clone(),
6626
        repo.id().unwrap(),
6627
        state,
6628
        "demo#1",
6629
        &runner,
6630
        &sk,
6631
    );
6632
6633
    let r = repo.add_receipt(&sr).unwrap();
6634
    let found = repo.receipts(&heads).unwrap();
6635
    assert_eq!(found.len(), 1);
6636
    assert_eq!(found[0].attest, r);
6637
    assert_eq!(found[0].signed, sr);
6638
    assert!(found[0].problem.is_none() && !found[0].revoked);
6639
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
6640
6641
    // Another repository's receipt, or a forged one, is refused.
6642
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
6643
    assert!(repo
6644
        .add_receipt(&elsewhere)
6645
        .unwrap_err()
6646
        .to_string()
6647
        .contains("another repository"));
6648
    let mut forged = sr.clone();
6649
    forged.receipt.exit_code = 1;
6650
    assert!(repo
6651
        .add_receipt(&forged)
6652
        .unwrap_err()
6653
        .to_string()
6654
        .contains("does not verify"));
6655
c63fed2e Andy McCall ↶ 6656
    // A receipt signed by a short-lived key keeps its certificate and the
6657
    // issuer's identity, and reads back with them (oxygenhub#241).
6658
    let hub_sk = SecretKey::generate();
6659
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
6660
    let job_sk = SecretKey::generate();
6661
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
6662
    let mut test_receipt = receipt.clone();
6663
    test_receipt.job_name = "test".into();
6664
    let plain = SignedReceipt::sign(
6665
        test_receipt,
6666
        repo.id().unwrap(),
6667
        state,
6668
        "demo#2",
6669
        &job,
6670
        &job_sk,
6671
    );
6672
    let now = plain.attest.hlc.wall_ms;
6673
    let cert = crate::cert::SignedCertificate::sign(
6674
        crate::cert::Certificate {
6675
            key: job.clone(),
6676
            issuer: hub.hash(),
6677
            subject: "repo:andy/demo:bookmark:main".into(),
6678
            claims: vec![],
6679
            scope: crate::identity::Scope::SEAL,
6680
            not_before: now - 1_000,
6681
            expires: now + 600_000,
a2387d54 Andy McCall ↶ 6682
            grant: None,
c63fed2e Andy McCall ↶ 6683
        },
6684
        &hub,
6685
        &hub_sk,
6686
    );
6687
    let certified = plain.with_certificate(cert, hub.clone());
6688
    repo.add_receipt(&certified).unwrap();
6689
    let found = repo.receipts(&heads).unwrap();
6690
    let got = found
6691
        .iter()
6692
        .find(|i| i.signed.receipt.job_name == "test")
6693
        .unwrap();
6694
    assert_eq!(got.signed, certified);
6695
    assert!(got.problem.is_none(), "{:?}", got.problem);
6696
6697
    // gc keeps the receipts, their runners, the certificate and its issuer,
6698
    // and the output while the state lives.
fc1a466a Andy McCall ↶ 6699
    repo.gc(true).unwrap();
c63fed2e Andy McCall ↶ 6700
    let found = repo.receipts(&heads).unwrap();
6701
    assert_eq!(found.len(), 2);
6702
    let got = found
6703
        .iter()
6704
        .find(|i| i.signed.receipt.job_name == "test")
6705
        .unwrap();
6706
    assert_eq!(got.signed, certified, "the certificate survives gc");
6707
    assert!(got.problem.is_none());
fc1a466a Andy McCall ↶ 6708
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
6709
    assert!(repo.fsck().unwrap().problems.is_empty());
dfb23a3a Andy McCall ↶ 6710
}
6711
6712
#[test]
3a4b3e01 Andy McCall ↶ 6713
fn approvals_are_kept_with_their_state_and_survive_gc() {
6714
    hermetic();
6715
    let dir = tempfile::tempdir().unwrap();
6716
    let root = dir.path();
6717
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6718
    write(root, "a.txt", b"1\n");
6719
    repo.commit("A", &[]).unwrap();
6720
    let heads = repo.bookmark_heads().unwrap();
6721
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
6722
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
6723
    let sk = SecretKey::generate();
6724
    let andy = sk.identity("Andy", "[email protected]", 1);
6725
    let statement = crate::approval::Statement {
6726
        repo: repo.id().unwrap(),
6727
        run: "https://hub.example/andy/infra/flow/8".into(),
6728
        job: "apply".into(),
6729
        job_hash: ObjectRef([1; 32]),
6730
        state,
6731
        inputs: vec![plan],
6732
        environment: "prod".into(),
6733
        approve: true,
6734
    };
6735
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
6736
    let r = repo.add_approval(&sa).unwrap();
6737
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6738
    // Another repository's approval, or a changed one, is refused.
6739
    let elsewhere = crate::approval::SignedApproval::sign(
6740
        &crate::approval::Statement {
6741
            repo: [0; 16],
6742
            ..statement.clone()
6743
        },
6744
        &andy,
6745
        &sk,
6746
    );
6747
    assert!(repo
6748
        .add_approval(&elsewhere)
6749
        .unwrap_err()
6750
        .to_string()
6751
        .contains("another repository"));
6752
    let mut forged = sa.clone();
6753
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
6754
        *environment = "dev".into();
6755
    }
6756
    assert!(repo
6757
        .add_approval(&forged)
6758
        .unwrap_err()
6759
        .to_string()
6760
        .contains("does not verify"));
6761
    // gc keeps it, its signature and its signer while the state lives.
6762
    repo.gc(true).unwrap();
6763
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
6764
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
6765
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
6766
    assert!(repo.fsck().unwrap().problems.is_empty());
6767
}
6768
6769
#[test]
dfb23a3a Andy McCall ↶ 6770
fn status_leaves_an_unchanged_manifest_alone() {
6771
    hermetic();
6772
    let dir = tempfile::tempdir().unwrap();
6773
    let root = dir.path();
6774
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6775
    write(root, "a.txt", b"1\n");
6776
    write(root, "b.txt", b"2\n");
6777
    repo.commit("A", &[]).unwrap();
6778
    // Files last touched well outside the racy window.
6779
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6780
    for f in ["a.txt", "b.txt"] {
6781
        fs::File::options()
6782
            .write(true)
6783
            .open(root.join(f))
6784
            .unwrap()
6785
            .set_modified(old)
6786
            .unwrap();
6787
    }
6788
    repo.snapshot_status("status").unwrap();
6789
    let path = repo.manifest_path();
6790
    let first = fs::read(&path).unwrap();
6791
    repo.snapshot_status("status").unwrap();
6792
    assert_eq!(
6793
        fs::read(&path).unwrap(),
6794
        first,
6795
        "an unchanged tree does not rewrite the manifest"
6796
    );
6797
    // A change rewrites it.
6798
    write(root, "a.txt", b"1\n2\n");
6799
    repo.snapshot_status("status").unwrap();
6800
    assert_ne!(fs::read(&path).unwrap(), first);
fc1a466a Andy McCall ↶ 6801
}
6f8aeb99 Andy McCall ↶ 6802
6803
#[test]
6804
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6805
    hermetic();
6806
    let dir = tempfile::tempdir().unwrap();
6807
    let root = dir.path();
6808
    let origin_path = root.join("origin");
6809
    Repo::init(&origin_path).unwrap();
6810
    let origin_url = origin_path.to_string_lossy().to_string();
6811
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6812
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6813
    write(&root.join("a"), "big.txt", big.as_bytes());
6814
    write(&root.join("a"), "small.txt", b"small\n");
6815
    let h1 = a.commit("large", &[]).unwrap();
6816
    let (_, body) = a.store().get(&h1).unwrap();
6817
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6818
    assert!(a.push("origin", false).unwrap()[0].ok);
6819
6820
    // A clone reads the text from the blobs that came with the change.
6821
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6822
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6823
    // An edit in the middle of the stored insert is an ordinary change.
6824
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6825
    write(&root.join("b"), "big.txt", edited.as_bytes());
6826
    let h2 = b.commit("edit", &[]).unwrap();
6827
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6828
    assert!(b.push("origin", false).unwrap()[0].ok);
6829
    assert!(a.pull("origin").unwrap().checked_out);
6830
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6831
    assert_eq!(
6832
        a.fsck().unwrap().errors(),
6833
        0,
6834
        "{:?}",
6835
        a.fsck().unwrap().problems
6836
    );
6837
6838
    // With zero retention gc keeps the text blobs of every kept change.
6839
    let mut a = Repo::open(&root.join("a")).unwrap();
6840
    a.config.set("core.op-retention", "0").unwrap();
6841
    a.save_config().unwrap();
6842
    let a = Repo::open(&root.join("a")).unwrap();
6843
    a.gc(true).unwrap();
6844
    let a = Repo::open(&root.join("a")).unwrap();
6845
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6846
    assert_eq!(
6847
        a.fsck().unwrap().errors(),
6848
        0,
6849
        "{:?}",
6850
        a.fsck().unwrap().problems
6851
    );
6852
    // And a clone of the packed repository reads them from its packs.
6853
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6854
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6855
    drop(c);
6caacfff Andy McCall ↶ 6856
}
6857
6858
#[test]
6859
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6860
    hermetic();
6861
    let dir = tempfile::tempdir().unwrap();
6862
    let root = dir.path();
6863
    let repo = Repo::init(root).unwrap();
6864
    write(root, "a.txt", b"a\n");
6865
    let a = repo.commit("a", &[]).unwrap();
6866
    write(root, "b.txt", b"b\n");
6867
    repo.commit("b", &[]).unwrap();
6868
    let (x, op) = repo.head_op().unwrap();
6869
    let ws = *op.view.workspaces.keys().next().unwrap();
6870
    let mut one = op.view.clone();
6871
    one.workspaces.insert(ws, a);
6872
    let mut two = op.view.clone();
6873
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6874
    let first = repo.record_op(&[x], "one", one).unwrap();
6875
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6876
    assert!(
6877
        e.to_string()
6878
            .contains("changed this working copy at the same time"),
6879
        "{e}"
6880
    );
6881
    assert_eq!(
6882
        repo.head_op().unwrap().0,
6883
        first,
6884
        "the second is not recorded"
6885
    );
6886
}
6887
6888
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6889
/// rewrote the working copy recorded the half-written files as edits, and
6890
/// its view replaced the switch's.
6891
#[test]
6892
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6893
    hermetic();
6894
    let dir = tempfile::tempdir().unwrap();
6895
    let root = dir.path().to_path_buf();
6896
    let mut repo = Repo::init(&root).unwrap();
6897
    write(&root, "keep.txt", b"keep\n");
6898
    repo.commit("base", &[]).unwrap();
6899
    repo.bookmark_create("small", None).unwrap();
6900
    for i in 0..300 {
6901
        write(
6902
            &root,
6903
            &format!("many/f{i}.txt"),
6904
            format!("file {i}\n").as_bytes(),
6905
        );
6906
    }
6907
    repo.commit("many", &[]).unwrap();
6908
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6909
    let watcher = {
6910
        let (root, stop) = (root.clone(), stop.clone());
6911
        std::thread::spawn(move || {
6912
            let r = Repo::open(&root).unwrap();
6913
            let mut ran = 0;
6914
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6915
                if r.snapshot_status("oxy status").is_ok() {
6916
                    ran += 1;
6917
                }
6918
            }
6919
            ran
6920
        })
6921
    };
6922
    for i in 0..20 {
6923
        let to = if i % 2 == 0 { "small" } else { "main" };
6924
        repo.bookmark_switch(to, false).unwrap();
6925
    }
6926
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6927
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6928
    // Back on main, clean, with every file where main has it.
6929
    let repo = Repo::open(&root).unwrap();
6930
    let s = repo.snapshot_status("oxy status").unwrap();
6931
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6932
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6933
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6934
    assert!(root.join("many/f299.txt").exists());
1a3b6203 Andy McCall ↶ 6935
}
6936
6937
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6938
/// put a subrepo that was ahead of its pin back at the pin and moved the
6939
/// subrepo's own bookmark backwards.
6940
#[test]
6941
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6942
    hermetic();
6943
    let dir = tempfile::tempdir().unwrap();
6944
    let root = dir.path();
6945
    Repo::init(&root.join("lib-origin")).unwrap();
6946
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6947
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6948
    write(&root.join("lib"), "lib.txt", b"v1\n");
6949
    lib.commit("lib v1", &[]).unwrap();
6950
    assert!(lib.push("origin", false).unwrap()[0].ok);
6951
6952
    let app_dir = root.join("app");
6953
    let mut app = Repo::init(&app_dir).unwrap();
6954
    write(&app_dir, "main.txt", b"app\n");
6955
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6956
    app.commit("app with lib", &[]).unwrap();
6957
    app.bookmark_create("feature", None).unwrap();
6958
6959
    // New work in the subrepo, not yet pinned by the parent.
6960
    let nested_dir = app_dir.join("libs/lib");
6961
    let nested = Repo::open(&nested_dir).unwrap();
6962
    write(&nested_dir, "new.txt", b"new\n");
6963
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6964
    drop(nested);
6965
6966
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6967
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6968
    let nested = Repo::open(&nested_dir).unwrap();
6969
    assert!(
6970
        nested.bookmark_heads().unwrap().contains(&l2),
6971
        "its bookmark kept its work"
6972
    );
6973
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6974
    let s = app.snapshot("status").unwrap();
6975
    assert_eq!(
6976
        statuses(&s),
6977
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6978
    );
6f8aeb99 Andy McCall ↶ 6979
}
7d9dab13 Andy McCall ↶ 6980
6981
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6982
/// moving `main` to a change this clone had pushed on another bookmark,
6983
/// the first `pull` said "Already up to date" while `main` was behind.
6984
#[test]
6985
fn pull_takes_a_remote_move_to_changes_already_here() {
6986
    hermetic();
6987
    let dir = tempfile::tempdir().unwrap();
6988
    let root = dir.path();
6989
    let origin_path = root.join("origin");
6990
    let origin = Repo::init(&origin_path).unwrap();
6991
    let url = origin_path.to_string_lossy().to_string();
6992
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6993
    write(&root.join("b"), "base.txt", b"base\n");
6994
    b.commit("base", &[]).unwrap();
6995
    assert!(b.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 6996
    origin.refresh().unwrap();
7d9dab13 Andy McCall ↶ 6997
6998
    // A feature bookmark with one change, pushed.
6999
    b.bookmark_create("feat", None).unwrap();
7000
    b.bookmark_switch("feat", false).unwrap();
7001
    write(&root.join("b"), "x.txt", b"x\n");
7002
    let x = b.commit("x", &[]).unwrap();
7003
    assert!(b.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 7004
    origin.refresh().unwrap();
7d9dab13 Andy McCall ↶ 7005
    b.bookmark_switch("main", false).unwrap();
7006
7007
    // The remote lands it: its main moves to the feature's state.
7008
    let feat = origin
7009
        .store()
7010
        .get_state(&origin.view().unwrap().bookmarks["feat"])
7011
        .unwrap()
7012
        .heads;
7013
    origin.bookmark_set("main", &feat).unwrap();
7014
7015
    let r = b.pull("origin").unwrap();
7016
    assert!(r.changed, "{r:?}");
7017
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
7018
    let main = b
7019
        .bookmarks()
7020
        .unwrap()
7021
        .into_iter()
7022
        .find(|m| m.name == "main")
7023
        .unwrap();
7024
    assert_eq!(main.behind, Some(0), "{main:?}");
7025
}
86e1824f Andy McCall ↶ 7026
14edbaaf Andy McCall ↶ 7027
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
7028
/// to one only the remote has makes a local bookmark from it; a pull moves
7029
/// every local bookmark the remote has too; a clone checks out the remote's
7030
/// default bookmark.
7031
#[test]
7032
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
7033
    hermetic();
7034
    let dir = tempfile::tempdir().unwrap();
7035
    let root = dir.path();
7036
    let origin_path = root.join("origin");
7037
    let mut origin = Repo::init(&origin_path).unwrap();
7038
    let url = origin_path.to_string_lossy().to_string();
7039
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
7040
    write(&root.join("a"), "base.txt", b"base\n");
7041
    a.commit("base", &[]).unwrap();
7042
    assert!(a.push("origin", false).unwrap()[0].ok);
7043
    a.bookmark_create("develop", None).unwrap();
7044
    a.bookmark_switch("develop", false).unwrap();
7045
    write(&root.join("a"), "base.txt", b"base\nd1\n");
7046
    let d1 = a.commit("d1", &[]).unwrap();
7047
    assert!(a.push("origin", false).unwrap()[0].ok);
7048
7049
    // A clone has main only; origin/develop is a name all the same.
7050
    let c_root = root.join("c");
7051
    let mut c = Repo::clone(&url, &c_root).unwrap();
7052
    assert_eq!(c.config.bookmark, "main");
7053
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
7054
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
7055
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
7056
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
7057
7058
    // Switching makes the local bookmark from origin's.
7059
    c.bookmark_switch("develop", false).unwrap();
7060
    assert_eq!(c.config.bookmark, "develop");
7061
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
7062
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
7063
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
7064
    assert!(c.bookmark_switch("nowhere", false).is_err());
7065
7066
    // Both bookmarks move on the remote; one pull takes both.
7067
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
7068
    let d2 = a.commit("d2", &[]).unwrap();
7069
    assert!(a.push("origin", false).unwrap()[0].ok);
7070
    a.bookmark_switch("main", false).unwrap();
7071
    write(&root.join("a"), "m.txt", b"m\n");
7072
    let m = a.commit("m", &[]).unwrap();
7073
    assert!(a.push("origin", false).unwrap()[0].ok);
7074
    let r = c.pull("origin").unwrap();
7075
    assert!(r.changed && r.checked_out, "{r:?}");
7076
    assert_eq!(r.heads, vec![d2]);
7077
    assert_eq!(r.others, vec!["main".to_string()]);
7078
    assert!(c.resolve_heads("main").unwrap().contains(&m));
7079
    assert_eq!(
7080
        fs::read(c_root.join("base.txt")).unwrap(),
7081
        b"base\nd1\nd2\n"
7082
    );
7083
    let again = c.pull("origin").unwrap();
7084
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
7085
7086
    // A clone checks out the remote's default bookmark.
7087
    origin.config.set("workspace.bookmark", "develop").unwrap();
7088
    origin.save_config().unwrap();
7089
    let e = Repo::clone(&url, &root.join("e")).unwrap();
7090
    assert_eq!(e.config.bookmark, "develop");
7091
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
7092
    let reopened = Repo::open(&root.join("e")).unwrap();
7093
    assert_eq!(reopened.config.bookmark, "develop");
7094
    // REMOTE/NAME names the remote's bookmark to switch to.
7095
    let mut e = reopened;
7096
    e.bookmark_switch("origin/main", false).unwrap();
7097
    assert_eq!(e.config.bookmark, "main");
7098
    assert!(e.bookmark_heads().unwrap().contains(&m));
7099
}
7100
98a1620a Andy McCall ↶ 7101
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
7102
/// op restore goes back to an operation, files included, and undo takes
7103
/// the restore back whole; op revert undoes one operation alone; each
7104
/// operation's changes are described from the views.
7105
#[test]
7106
fn operations_can_be_read_restored_and_reverted() {
7107
    hermetic();
7108
    let dir = tempfile::tempdir().unwrap();
7109
    let root = dir.path();
7110
    let repo = Repo::init(root).unwrap();
7111
    write(root, "a.txt", b"a\n");
7112
    let first = repo.commit("first", &[]).unwrap();
7113
    write(root, "a.txt", b"a\nb\n");
7114
    let second = repo.commit("second", &[]).unwrap();
7115
    let at_second = repo.head_op().unwrap().0.to_hex();
7116
    repo.bookmark_create("keep", None).unwrap();
7117
    let created = repo.head_op().unwrap().0.to_hex();
7118
    write(root, "n.txt", b"n\n");
7119
    let third = repo.commit("third", &[]).unwrap();
7120
7121
    // What each operation changed.
7122
    let ops = repo.op_log().unwrap();
7123
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
7124
    assert!(
7125
        changes
7126
            .iter()
7127
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
7128
        "{changes:?}"
7129
    );
7130
    assert!(changes
7131
        .iter()
7132
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
7133
7134
    // Reading at an earlier operation.
7135
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
7136
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
7137
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
7138
    write(root, "z.txt", b"z\n");
7139
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
7140
    fs::remove_file(root.join("z.txt")).unwrap();
7141
    assert!(repo.resolve_op("zz").is_err());
7142
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
7143
7144
    // Restore goes back, files and all; undo takes it back whole.
7145
    repo.op_restore(&at_second, false).unwrap();
7146
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
7147
    assert!(!root.join("n.txt").exists());
7148
    repo.undo().unwrap();
7149
    let mut heads = repo.bookmark_heads().unwrap();
7150
    heads.sort();
7151
    let mut want = vec![second, third];
7152
    want.sort();
7153
    assert_eq!(heads, want);
7154
    assert!(
7155
        root.join("n.txt").exists(),
7156
        "the files came back with the undo"
7157
    );
7158
7159
    // Revert the bookmark's creation alone: the commit after it stays.
7160
    let r = repo.op_revert(&created).unwrap();
7161
    assert_eq!(r.reverted, vec!["keep".to_string()]);
7162
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
7163
    assert!(repo
7164
        .load_state(&repo.bookmark_heads().unwrap())
7165
        .unwrap()
7166
        .contains(&third));
7167
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
7168
    let _ = first;
7169
}
7170
36041796 Andy McCall ↶ 7171
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
7172
/// from the status cache while every file is as the snapshot left it, and
7173
/// from a snapshot again as soon as one is not.
7174
#[test]
7175
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
7176
    hermetic();
7177
    let dir = tempfile::tempdir().unwrap();
7178
    let root = dir.path();
7179
    let repo = Repo::init(root).unwrap();
7180
    write(root, "a.txt", b"a\n");
7181
    write(root, "b.txt", b"b\n");
7182
    repo.commit("base", &[]).unwrap();
7183
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
7184
7185
    write(root, "a.txt", b"a\nmore\n");
7186
    assert_eq!(
7187
        repo.status_by_manifest().unwrap(),
7188
        None,
7189
        "no snapshot of the edit yet"
7190
    );
7191
    let snap = repo.snapshot_status("oxy status").unwrap();
7192
    assert_eq!(snap.statuses.len(), 1);
7193
    let cached = repo
7194
        .status_by_manifest()
7195
        .unwrap()
7196
        .expect("answered from the cache");
7197
    assert_eq!(cached.len(), 1);
7198
    assert_eq!(
7199
        (cached[0].path.as_str(), cached[0].status),
7200
        ("a.txt", ChangeStatus::Modified)
7201
    );
7202
7203
    // Any further change sends status back to a snapshot.
7204
    write(root, "a.txt", b"a\nmore\nand more\n");
7205
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
7206
    repo.snapshot_status("oxy status").unwrap();
7207
    assert!(repo.status_by_manifest().unwrap().is_some());
7208
    write(root, "new.txt", b"n\n");
7209
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
7210
    fs::remove_file(root.join("new.txt")).unwrap();
7211
    assert!(
7212
        repo.status_by_manifest().unwrap().is_some(),
7213
        "back as it was"
7214
    );
7215
    fs::remove_file(root.join("b.txt")).unwrap();
7216
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
7217
    write(root, "b.txt", b"b\n");
7218
7219
    // A commit leaves nothing uncommitted: clean again, no cache needed.
7220
    repo.snapshot_status("oxy status").unwrap();
7221
    repo.commit("more", &[]).unwrap();
7222
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7223
}
7224
77445673 Andy McCall ↶ 7225
/// oxygen#41: while the status cache holds, the working copy's diff is
7226
/// rendered from the stored working-copy change, and says exactly what a
7227
/// snapshot's diff says.
7228
#[test]
7229
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
7230
    hermetic();
7231
    let dir = tempfile::tempdir().unwrap();
7232
    let root = dir.path();
7233
    let repo = Repo::init(root).unwrap();
7234
    write(root, "a.txt", b"one\ntwo\nthree\n");
7235
    write(root, "gone.txt", b"bye\n");
7236
    repo.commit("base", &[]).unwrap();
7237
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
7238
    write(root, "new.txt", b"hello\n");
7239
    fs::remove_file(root.join("gone.txt")).unwrap();
7240
    let snap = repo.snapshot_status("oxy status").unwrap();
7241
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
7242
    assert!(
7243
        repo.status_by_manifest().unwrap().is_some(),
7244
        "the cache holds"
7245
    );
7246
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
7247
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
7248
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
7249
}
7250
1ec3f008 Andy McCall ↶ 7251
/// oxygen#41: a manifest written from a walk keeps every directory's time;
7252
/// while none has moved, the check stats the tracked files without listing
7253
/// the tree, and a file added or removed anywhere moves its directory's
7254
/// time, so the tree is listed again.
7255
#[test]
7256
fn the_manifest_check_skips_listing_while_no_directory_changed() {
7257
    hermetic();
7258
    let dir = tempfile::tempdir().unwrap();
7259
    let root = dir.path();
7260
    let repo = Repo::init(root).unwrap();
7261
    write(root, "a.txt", b"a\n");
7262
    write(root, "sub/deep/b.txt", b"b\n");
7263
    repo.commit("base", &[]).unwrap();
7264
    // Out of the racy window: every file and directory a minute old.
7265
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7266
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
7267
        fs::File::open(root.join(p))
7268
            .unwrap()
7269
            .set_modified(old)
7270
            .unwrap();
7271
    }
7272
    repo.snapshot_status("oxy status").unwrap();
7273
    repo.write_manifest(false, false).unwrap();
7274
    let m = repo.read_manifest().unwrap().unwrap().2;
7275
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
7276
    assert_eq!(
7277
        repo.disk_differs_by_dirs(&m),
7278
        Some(false),
7279
        "no listing needed"
7280
    );
7281
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7282
7283
    // A same-size edit with a new time: found by its stat.
7284
    write(root, "sub/deep/b.txt", b"c\n");
7285
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
7286
    write(root, "sub/deep/b.txt", b"b\n");
7287
    fs::File::open(root.join("sub/deep/b.txt"))
7288
        .unwrap()
7289
        .set_modified(old)
7290
        .unwrap();
7291
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
7292
7293
    // A new file moves its directory's time: the tree must be listed.
7294
    write(root, "sub/deep/new.txt", b"n\n");
7295
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7296
    assert_eq!(repo.status_by_manifest().unwrap(), None);
7297
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
7298
    // A removed one too.
7299
    fs::remove_file(root.join("a.txt")).unwrap();
7300
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7301
}
7302
e226a6cc Andy McCall ↶ 7303
/// oxygen#41: a commit right after a status takes the snapshot the status
7304
/// left (the status cache holds) rather than walking again, and commits
7305
/// exactly what a snapshot would have.
7306
#[test]
7307
fn a_commit_after_a_status_uses_the_cached_snapshot() {
7308
    hermetic();
7309
    let dir = tempfile::tempdir().unwrap();
7310
    let root = dir.path();
7311
    let repo = Repo::init(root).unwrap();
7312
    write(root, "a.txt", b"a\nb\n");
7313
    write(root, ".oxyattributes", b"*.bin binary\n");
7314
    repo.commit("base", &[]).unwrap();
7315
    write(root, "a.txt", b"a\nB\n");
7316
    write(root, "new.txt", b"new\n");
7317
    let snap = repo.snapshot_status("oxy status").unwrap();
7318
    let cached = repo
7319
        .snapshot_from_cache()
7320
        .unwrap()
7321
        .expect("the cache holds");
7322
    assert_eq!(cached.wc_hash, snap.wc_hash);
7323
    assert_eq!(cached.statuses, snap.statuses);
7324
    assert!(
7325
        !cached.attributes.is_empty(),
7326
        "the .oxyattributes file was read"
7327
    );
7328
    let h = repo.commit("edit", &[]).unwrap();
7329
    let c = repo.store().get_change(&h).unwrap();
7330
    assert_eq!(
7331
        c.tree_ops.len() + c.edits.len(),
7332
        snap.wc.tree_ops.len() + snap.wc.edits.len()
7333
    );
7334
    assert_eq!(
7335
        repo.status_by_manifest().unwrap(),
7336
        Some(vec![]),
7337
        "clean after the commit"
7338
    );
7339
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
7340
}
7341
0389c3e8 Andy McCall ↶ 7342
/// oxygen#41: a clean check that verified racy entries restamps the
7343
/// manifest, so later checks can trust them, and a same-size rewrite
7344
/// straight afterwards is still found: entries within two seconds of the
7345
/// new time stay racy.
7346
#[test]
7347
fn a_verified_clean_check_restamps_the_manifest_safely() {
7348
    hermetic();
7349
    let dir = tempfile::tempdir().unwrap();
7350
    let root = dir.path();
7351
    let repo = Repo::init(root).unwrap();
7352
    write(root, "a.txt", b"one\n");
7353
    repo.commit("one", &[]).unwrap();
7354
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
7355
    assert!(repo.clean_by_manifest().unwrap());
7356
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
7357
    assert!(after > before, "restamped");
7358
    write(root, "a.txt", b"two\n");
7359
    assert!(
7360
        !repo.clean_by_manifest().unwrap(),
7361
        "a same-size rewrite is still seen"
7362
    );
7363
}
7364
86e1824f Andy McCall ↶ 7365
/// oxygen#35: a history-only state keeps no inserted text. It reads a
7366
/// stored insert's text blob only when it builds that file's graph, and
7367
/// builds the same graph a full load does.
7368
#[test]
7369
fn history_only_states_read_text_only_for_the_graphs_they_build() {
7370
    hermetic();
7371
    let dir = tempfile::tempdir().unwrap();
7372
    let root = dir.path();
7373
    let repo = Repo::init(root).unwrap();
7374
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
7375
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
7376
    write(root, "big.txt", big.as_bytes());
7377
    write(root, "other.txt", other.as_bytes());
7378
    let h = repo.commit("two large files", &[]).unwrap();
7379
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
7380
    let h2 = repo.commit("append", &[]).unwrap();
7381
7382
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
7383
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
7384
        FileContent::Text { bytes, .. } => bytes.clone(),
7385
        other => panic!("{other:?}"),
7386
    };
7387
    // Built on demand, every graph renders as the full load's.
7388
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7389
    let big_node = full.files["big.txt"].node;
7390
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
7391
    repo.load_all_graphs(&mut hist).unwrap();
7392
    let rendered = hist.materialize();
7393
    for p in ["big.txt", "other.txt"] {
7394
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
7395
    }
7396
7397
    // Without other.txt's text blob, history still loads and big.txt still
7398
    // builds: nothing read the other text.
7399
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7400
    assert_eq!(texts.len(), 2);
7401
    let content = |r: &ObjectRef| -> Vec<u8> {
7402
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
7403
        blob.chunks
7404
            .iter()
7405
            .flat_map(|c| repo.store().get(c).unwrap().1)
7406
            .collect()
7407
    };
7408
    let other_text = texts
7409
        .iter()
a4fad5b0 Andy McCall ↶ 7410
        .filter_map(|t| match t {
0f93f49c Andy McCall ↶ 7411
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
a4fad5b0 Andy McCall ↶ 7412
            _ => None,
7413
        })
86e1824f Andy McCall ↶ 7414
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
7415
        .unwrap();
64818938 Andy McCall ↶ 7416
    repo.store().remove_loose_for_test(&other_text).unwrap();
86e1824f Andy McCall ↶ 7417
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7418
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
7419
    assert!(repo
7420
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
7421
        .is_err());
7422
}
7423
7424
/// oxygen#35: the first status after a commit read and rendered every
7425
/// file (79 s and more than 14 GB on the Linux tree), because the
7426
/// manifest had no graph keys for files the commit added.
7427
#[test]
7428
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
7429
    use std::os::unix::fs::PermissionsExt;
7430
    hermetic();
7431
    let dir = tempfile::tempdir().unwrap();
7432
    let root = dir.path();
7433
    let repo = Repo::init(root).unwrap();
7434
    let files = ["a.txt", "b.txt", "d/c.txt"];
7435
    for p in files {
7436
        write(root, p, format!("{p}\n").as_bytes());
7437
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7438
        fs::File::options()
7439
            .write(true)
7440
            .open(root.join(p))
7441
            .unwrap()
7442
            .set_modified(old)
7443
            .unwrap();
7444
    }
7445
    repo.commit("added", &[]).unwrap();
7446
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
7447
    assert!(
7448
        m.entries.values().all(|e| e.graph.is_some()),
7449
        "keys recorded at commit"
7450
    );
7451
    // Unreadable files prove the next status reads none of them.
7452
    for p in files {
7453
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
7454
    }
7455
    let snap = repo.snapshot_status("status").unwrap();
7456
    for p in files {
7457
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
7458
    }
7459
    assert!(!snap.changed && snap.statuses.is_empty());
7460
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
7461
}
c5ce0367 Andy McCall ↶ 7462
7463
/// oxygen#35: a checkout reads, renders and writes only the files whose
7464
/// graphs differ, and renders the rest a batch at a time.
7465
#[test]
7466
fn checkout_touches_only_what_differs_and_renders_in_batches() {
7467
    use std::os::unix::fs::PermissionsExt;
7468
    hermetic();
7469
    let dir = tempfile::tempdir().unwrap();
7470
    let root = dir.path();
7471
    let origin = root.join("origin");
7472
    let mut repo = Repo::init(&origin).unwrap();
7473
    // More files than one batch holds.
7474
    let n = 2100;
7475
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7476
    for i in 0..n {
7477
        let p = format!("f/{i:04}.txt");
7478
        write(&origin, &p, format!("file {i}\n").as_bytes());
7479
        fs::File::options()
7480
            .write(true)
7481
            .open(origin.join(&p))
7482
            .unwrap()
7483
            .set_modified(old)
7484
            .unwrap();
7485
    }
7486
    repo.commit("many", &[]).unwrap();
7487
    repo.bookmark_create("feature", None).unwrap();
7488
    repo.bookmark_switch("feature", false).unwrap();
7489
    write(&origin, "f/0007.txt", b"changed\n");
7490
    repo.commit("one change", &[]).unwrap();
7491
7492
    // Switching back to main must not read the unchanged files.
7493
    for i in 0..n {
7494
        if i != 7 {
7495
            let p = origin.join(format!("f/{i:04}.txt"));
7496
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
7497
        }
7498
    }
7499
    let r = repo.bookmark_switch("main", false).unwrap();
7500
    for i in 0..n {
7501
        let p = origin.join(format!("f/{i:04}.txt"));
7502
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
7503
    }
7504
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
7505
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
7506
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7507
7508
    // A clone renders every file, across batches.
7509
    let c = root.join("clone");
7510
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
7511
    for i in [0, 2047, 2048, n - 1] {
7512
        assert_eq!(
7513
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
7514
            format!("file {i}\n").as_bytes()
7515
        );
7516
    }
7517
    let cloned = Repo::open(&c).unwrap();
7518
    assert!(cloned
7519
        .snapshot_status("status")
7520
        .unwrap()
7521
        .statuses
7522
        .is_empty());
d3cd7ef9 Andy McCall ↶ 7523
}
7524
7525
/// A file written just before the manifest (inside the racy window) is
7526
/// checked by its hash: trusted when equal, caught when edited in place
7527
/// with the same size and time.
7528
#[test]
7529
fn a_racy_manifest_entry_is_checked_by_hash() {
7530
    hermetic();
7531
    let dir = tempfile::tempdir().unwrap();
7532
    let root = dir.path();
7533
    let repo = Repo::init(root).unwrap();
7534
    write(root, "a.txt", b"one\n");
7535
    repo.commit("fresh", &[]).unwrap();
7536
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
7537
    let t = fs::metadata(root.join("a.txt"))
7538
        .unwrap()
7539
        .modified()
7540
        .unwrap();
7541
    write(root, "a.txt", b"two\n");
7542
    fs::File::options()
7543
        .write(true)
7544
        .open(root.join("a.txt"))
7545
        .unwrap()
7546
        .set_modified(t)
7547
        .unwrap();
7548
    assert!(
7549
        !repo.clean_by_manifest().unwrap(),
7550
        "same size and time, other bytes"
7551
    );
7552
    assert_eq!(
7553
        statuses(&repo.snapshot_status("status").unwrap()),
7554
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
7555
    );
c5ce0367 Andy McCall ↶ 7556
}
2c75672f Andy McCall ↶ 7557
7558
/// A fetch on one machine moves changes as stored, text blobs among the
7559
/// objects; a change whose text blob did not come is refused, not stored.
7560
#[test]
7561
fn a_raw_bundle_without_a_changes_text_is_refused() {
7562
    hermetic();
7563
    let dir = tempfile::tempdir().unwrap();
7564
    let root = dir.path();
7565
    let a = Repo::init(&root.join("a")).unwrap();
7566
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7567
    write(&root.join("a"), "big.txt", big.as_bytes());
7568
    let h = a.commit("big", &[]).unwrap();
7569
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
7570
    assert_eq!(bundle.raw_changes.len(), 1);
7571
    assert!(bundle.changes.is_empty());
7572
    let b = Repo::init(&root.join("b")).unwrap();
7573
    let mut without = bundle.clone();
7574
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
7575
    let e = b.import_bundle(&without, false).unwrap_err();
7576
    assert!(e.to_string().contains("came without its text blob"), "{e}");
7577
    assert!(!b.store().has(&h));
7578
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
7579
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
7580
}
a87c7b9d Andy McCall ↶ 7581
7582
/// oxygen#30 (vscode): a directory deleted in one line of history and made
7583
/// again was a second node for one Git path, so a file moved into it on
7584
/// another line, where the first node still stood, ended up in two places.
7585
/// An import now brings the directory back rather than make a new one.
7586
#[test]
7587
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
7588
    hermetic();
7589
    if std::process::Command::new("git")
7590
        .arg("--version")
7591
        .output()
7592
        .is_err()
7593
    {
7594
        eprintln!("git not installed; skipping");
7595
        return;
7596
    }
7597
    let dir = tempfile::tempdir().unwrap();
7598
    let root = dir.path();
7599
    let g = root.join("src.git");
7600
    fs::create_dir_all(&g).unwrap();
7601
    let git = |args: &[&str]| -> String {
7602
        let out = std::process::Command::new("git")
7603
            .arg("-C")
7604
            .arg(&g)
7605
            .args([
7606
                "-c",
7607
                "user.name=Grace",
7608
                "-c",
7609
                "[email protected]",
7610
                "-c",
7611
                "commit.gpgsign=false",
7612
            ])
7613
            .args(args)
7614
            .output()
7615
            .unwrap();
7616
        assert!(
7617
            out.status.success(),
7618
            "git {args:?}: {}",
7619
            String::from_utf8_lossy(&out.stderr)
7620
        );
7621
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7622
    };
7623
    git(&["init", "-q", "-b", "main"]);
7624
    write(&g, "d/a.txt", b"a\n");
7625
    write(&g, "c/x.txt", b"x\n");
7626
    git(&["add", "."]);
7627
    git(&["commit", "-qm", "base"]);
7628
    // One line: move x into d while d still stands.
7629
    git(&["checkout", "-qb", "side"]);
7630
    git(&["mv", "c/x.txt", "d/x.txt"]);
7631
    git(&["commit", "-qm", "x into d"]);
7632
    // The other: d goes, comes back, and x moves into it too.
7633
    git(&["checkout", "-q", "main"]);
7634
    git(&["rm", "-q", "d/a.txt"]);
7635
    git(&["commit", "-qm", "d goes"]);
7636
    write(&g, "d/b.txt", b"b\n");
7637
    git(&["add", "."]);
7638
    git(&["commit", "-qm", "d comes back"]);
7639
    git(&["mv", "c/x.txt", "d/x.txt"]);
7640
    git(&["commit", "-qm", "x into d again"]);
7641
    git(&["merge", "-q", "--no-edit", "side"]);
7642
7643
    let repo = Repo::init(&root.join("o")).unwrap();
7644
    repo.import_git(&g, "main").unwrap();
7645
    let v = repo.verify_git_import(&g, "main").unwrap();
7646
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7647
    let st = repo
7648
        .load_state_history(&repo.bookmark_heads().unwrap())
7649
        .unwrap();
7650
    let view = st.tree().view();
7651
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7652
    // The directory is the one the first commit made.
7653
    // Commits made in one second tie on time: find the first by its message.
7654
    let first = repo
7655
        .log()
7656
        .unwrap()
7657
        .into_iter()
7658
        .find(|e| e.change.message.starts_with("base"))
7659
        .unwrap();
7660
    let base = repo
7661
        .load_state_history(&[first.hash])
7662
        .unwrap()
7663
        .tree()
7664
        .view();
7665
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
7666
}
7667
7668
/// oxygen#30, the rest: a placement left under a directory another line
7669
/// removed is out of sight, so no diff reaches it; the merge that settles
7670
/// where the file is retires it.
7671
#[test]
7672
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
7673
    hermetic();
7674
    if std::process::Command::new("git")
7675
        .arg("--version")
7676
        .output()
7677
        .is_err()
7678
    {
7679
        eprintln!("git not installed; skipping");
7680
        return;
7681
    }
7682
    let dir = tempfile::tempdir().unwrap();
7683
    let root = dir.path();
7684
    let g = root.join("src.git");
7685
    fs::create_dir_all(&g).unwrap();
7686
    let run = |args: &[&str]| {
7687
        std::process::Command::new("git")
7688
            .arg("-C")
7689
            .arg(&g)
7690
            .args([
7691
                "-c",
7692
                "user.name=Grace",
7693
                "-c",
7694
                "[email protected]",
7695
                "-c",
7696
                "commit.gpgsign=false",
7697
            ])
7698
            .args(args)
7699
            .output()
7700
            .unwrap()
7701
    };
7702
    let git = |args: &[&str]| {
7703
        let out = run(args);
7704
        assert!(
7705
            out.status.success(),
7706
            "git {args:?}: {}",
7707
            String::from_utf8_lossy(&out.stderr)
7708
        );
7709
    };
7710
    git(&["init", "-q", "-b", "main"]);
7711
    write(&g, "c/x.txt", b"x\n");
7712
    write(&g, "keep.txt", b"k\n");
7713
    git(&["add", "."]);
7714
    git(&["commit", "-qm", "base"]);
7715
    // One line renames the file within c; the other moves it out of c,
7716
    // which goes.
7717
    git(&["checkout", "-qb", "side"]);
7718
    git(&["mv", "c/x.txt", "c/y.txt"]);
7719
    git(&["commit", "-qm", "rename within c"]);
7720
    git(&["checkout", "-q", "main"]);
7721
    fs::create_dir_all(g.join("n")).unwrap();
7722
    git(&["mv", "c/x.txt", "n/x.txt"]);
7723
    git(&["commit", "-qm", "move out of c"]);
7724
    // Git cannot merge the two renames; the merge keeps n/x.txt.
7725
    let _ = run(&["merge", "-q", "side"]);
7726
    let _ = run(&[
7727
        "rm",
7728
        "-q",
7729
        "--cached",
7730
        "--ignore-unmatch",
7731
        "c/y.txt",
7732
        "c/x.txt",
7733
    ]);
7734
    let _ = std::fs::remove_dir_all(g.join("c"));
7735
    write(&g, "n/x.txt", b"x\n");
7736
    git(&["add", "-A"]);
7737
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
7738
7739
    let repo = Repo::init(&root.join("o")).unwrap();
7740
    repo.import_git(&g, "main").unwrap();
7741
    let v = repo.verify_git_import(&g, "main").unwrap();
7742
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7743
    let st = repo
7744
        .load_state_history(&repo.bookmark_heads().unwrap())
7745
        .unwrap();
7746
    let view = st.tree().view();
7747
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7748
    assert!(view.entries.contains_key("n/x.txt"));
7749
}
7750
7751
/// oxygen#30, orphans: a file added on one line into a directory the other
7752
/// line removed is placed where the tree cannot show it; Git's merge keeps
7753
/// the file, and the import's merge leaves exactly one of it.
7754
#[test]
7755
fn git_import_merge_leaves_no_orphan_behind() {
7756
    hermetic();
7757
    if std::process::Command::new("git")
7758
        .arg("--version")
7759
        .output()
7760
        .is_err()
7761
    {
7762
        eprintln!("git not installed; skipping");
7763
        return;
7764
    }
7765
    let dir = tempfile::tempdir().unwrap();
7766
    let root = dir.path();
7767
    let g = root.join("src.git");
7768
    fs::create_dir_all(&g).unwrap();
7769
    let git = |args: &[&str]| {
7770
        let out = std::process::Command::new("git")
7771
            .arg("-C")
7772
            .arg(&g)
7773
            .args([
7774
                "-c",
7775
                "user.name=Grace",
7776
                "-c",
7777
                "[email protected]",
7778
                "-c",
7779
                "commit.gpgsign=false",
7780
            ])
7781
            .args(args)
7782
            .output()
7783
            .unwrap();
7784
        assert!(
7785
            out.status.success(),
7786
            "git {args:?}: {}",
7787
            String::from_utf8_lossy(&out.stderr)
7788
        );
7789
    };
7790
    git(&["init", "-q", "-b", "main"]);
7791
    write(&g, "d/f.txt", b"f\n");
7792
    write(&g, "keep.txt", b"k\n");
7793
    git(&["add", "."]);
7794
    git(&["commit", "-qm", "base"]);
7795
    git(&["checkout", "-qb", "side"]);
7796
    write(&g, "d/new.txt", b"new\n");
7797
    git(&["add", "."]);
7798
    git(&["commit", "-qm", "add into d"]);
7799
    git(&["checkout", "-q", "main"]);
7800
    git(&["rm", "-q", "d/f.txt"]);
7801
    git(&["commit", "-qm", "d goes"]);
7802
    git(&["merge", "-q", "--no-edit", "side"]);
7803
7804
    let repo = Repo::init(&root.join("o")).unwrap();
7805
    repo.import_git(&g, "main").unwrap();
7806
    let v = repo.verify_git_import(&g, "main").unwrap();
7807
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7808
    let st = repo
7809
        .load_state_history(&repo.bookmark_heads().unwrap())
7810
        .unwrap();
7811
    let view = st.tree().view();
7812
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7813
    assert!(view.entries.contains_key("d/new.txt"));
7814
}
d77e1702 Andy McCall ↶ 7815
7816
/// fsck checks a change's text as the blobs it is stored in, without
7817
/// decoding it: a missing text blob is an error named for the change.
7818
#[test]
7819
fn fsck_names_a_missing_text_blob() {
7820
    hermetic();
7821
    let dir = tempfile::tempdir().unwrap();
7822
    let root = dir.path();
7823
    let repo = Repo::init(root).unwrap();
7824
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7825
    write(root, "big.txt", big.as_bytes());
7826
    let h = repo.commit("big", &[]).unwrap();
7827
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7828
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7829
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7830
        panic!("a stored text")
7831
    };
64818938 Andy McCall ↶ 7832
    repo.store().remove_loose_for_test(&b).unwrap();
d77e1702 Andy McCall ↶ 7833
    let rep = repo.fsck().unwrap();
7834
    assert!(rep.errors() > 0);
7835
    assert!(
7836
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7837
        "{:?}",
7838
        rep.problems
7839
    );
7840
}
a07f60a3 Andy McCall ↶ 7841
7842
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7843
/// reached with that remote's token and CA (a private subrepo then clones
7844
/// for anyone who can read the parent); another hub gets none of them.
7845
#[test]
7846
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7847
    hermetic();
7848
    let dir = tempfile::tempdir().unwrap();
7849
    let mut repo = Repo::init(dir.path()).unwrap();
7850
    repo.config
7851
        .set(
7852
            "remote.origin.url",
7853
            "https://Hub.example:7343/doomsdayone/metalgear",
7854
        )
7855
        .unwrap();
7856
    repo.config.set("remote.origin.token", "secret").unwrap();
7857
    repo.config
7858
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7859
        .unwrap();
7860
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7861
    assert_eq!(same.token.as_deref(), Some("secret"));
7862
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7863
    for other in [
7864
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7865
        "https://hub.example/doomsdayone/rstar-api",
7866
        "http://hub.example:7343/doomsdayone/rstar-api",
7867
    ] {
7868
        let o = repo.credentials_for(other);
7869
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7870
    }
7871
}
ce14f0d6 Andy McCall ↶ 7872
ff1f62fe Andy McCall ↶ 7873
/// oxygen#47: a remote with no token of its own uses the user's credential
7874
/// store for its hub, and a nested checkout finds its parent's remote
7875
/// token there instead of keeping a copy.
ce14f0d6 Andy McCall ↶ 7876
#[test]
ff1f62fe Andy McCall ↶ 7877
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7878
    hermetic();
7879
    let home = tempfile::tempdir().unwrap();
7880
    let dir = tempfile::tempdir().unwrap();
7881
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7882
    parent
7883
        .config
7884
        .set("remote.origin.url", "https://hub.example/o/parent")
7885
        .unwrap();
7886
    parent.save_config().unwrap();
7887
    assert_eq!(parent.remote_options("origin").token, None);
7888
    crate::credentials::Credentials::at(home.path())
7889
        .save("https://hub.example", "stored", Some("andy"), None)
7890
        .unwrap();
7891
    assert_eq!(
7892
        parent.remote_options("origin").token.as_deref(),
7893
        Some("stored")
7894
    );
7895
7896
    let empty_home = tempfile::tempdir().unwrap();
7897
    let nested = dir.path().join("deps").join("child");
7898
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7899
    child
7900
        .config
7901
        .set("remote.origin.url", "https://hub.example/o/child")
7902
        .unwrap();
7903
    child.save_config().unwrap();
7904
    assert_eq!(child.remote_options("origin").token, None);
7905
    parent
7906
        .config
7907
        .set("remote.origin.token", "checkout")
7908
        .unwrap();
7909
    parent.save_config().unwrap();
7910
    assert_eq!(
7911
        child.remote_options("origin").token.as_deref(),
7912
        Some("checkout")
7913
    );
7914
    // Another hub's checkout token is not borrowed.
7915
    child
7916
        .config
7917
        .set("remote.origin.url", "https://other.example/o/child")
7918
        .unwrap();
7919
    assert_eq!(child.remote_options("origin").token, None);
7920
}
7921
7922
#[test]
ce14f0d6 Andy McCall ↶ 7923
fn the_metadata_cache_survives_a_torn_tail() {
7924
    hermetic();
7925
    let dir = tempfile::tempdir().unwrap();
7926
    let root = dir.path();
7927
    let repo = Repo::init(root).unwrap();
7928
    write(root, "a.txt", b"1\n");
7929
    let h = repo.commit("first", &[]).unwrap();
7930
    let meta = repo.store().get_change_meta(&h).unwrap();
7931
    let cache = repo.store().dir().join("metas");
7932
    let len = fs::metadata(&cache).unwrap().len();
7933
    assert!(len > 0, "a change read is cached");
7934
    // A torn record at the end: the cache reads up to it and cuts it off.
7935
    fs::OpenOptions::new()
7936
        .append(true)
7937
        .open(&cache)
7938
        .unwrap()
7939
        .write_all(&[7; 20])
7940
        .unwrap();
7941
    let again = Repo::open(root).unwrap();
7942
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7943
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7944
}
f9466021 Andy McCall ↶ 7945
7946
#[test]
7947
fn a_manifest_that_does_not_check_reads_as_none() {
7948
    hermetic();
7949
    let dir = tempfile::tempdir().unwrap();
7950
    let root = dir.path();
7951
    let repo = Repo::init(root).unwrap();
7952
    write(root, "a.txt", b"1\n");
7953
    repo.commit("first", &[]).unwrap();
7954
    let path = repo.manifest_path();
7955
    let mut bytes = fs::read(&path).unwrap();
7956
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7957
    let last = bytes.len() - 1;
7958
    bytes[last] ^= 1;
7959
    fs::write(&path, &bytes).unwrap();
7960
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7961
    // The next status reads the files and writes it again.
7962
    let again = Repo::open(root).unwrap();
7963
    assert!(!again.snapshot("status").unwrap().changed);
7964
    assert!(again.read_manifest().unwrap().is_some());
7965
}
7966
7967
#[test]
7968
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7969
    hermetic();
7970
    let dir = tempfile::tempdir().unwrap();
7971
    let root = dir.path();
7972
    let repo = Repo::init(root).unwrap();
7973
    write(root, "a.txt", b"1\n");
7974
    write(root, "b.txt", b"2\n");
7975
    // b.txt outside the racy window, so snapshots take it as unchanged.
7976
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7977
    fs::File::options()
7978
        .write(true)
7979
        .open(root.join("b.txt"))
7980
        .unwrap()
7981
        .set_modified(old)
7982
        .unwrap();
7983
    repo.commit("first", &[]).unwrap();
7984
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7985
    repo.snapshot_status("status").unwrap();
7986
    write(root, "a.txt", b"1\n2\n");
7987
    repo.commit("second", &[]).unwrap();
7988
    assert!(
7989
        repo.clean_by_manifest().unwrap(),
7990
        "after a commit of one file"
7991
    );
7992
    // Edited, seen by a status, edited again, then committed: the status
7993
    // left the first edit's stat, which the commit must not keep.
7994
    write(root, "a.txt", b"1\n2\n3\n");
7995
    repo.snapshot_status("status").unwrap();
7996
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7997
    repo.commit("third", &[]).unwrap();
7998
    assert!(
7999
        repo.clean_by_manifest().unwrap(),
8000
        "after an edit a status saw"
8001
    );
8002
}
e266b7d4 Andy McCall ↶ 8003
8004
#[test]
8005
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
8006
    hermetic();
8007
    let dir = tempfile::tempdir().unwrap();
8008
    let root = dir.path();
8009
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8010
    write(root, "a.txt", b"1\n2\n");
8011
    let a = repo.commit("A", &[]).unwrap();
8012
    repo.bookmark_create("develop", Some(&[a])).unwrap();
8013
    write(root, "a.txt", b"1\nX\n");
8014
    let c = repo.commit("C: 2 to X", &[]).unwrap();
8015
    repo.bookmark_switch("develop", false).unwrap();
8016
    write(root, "a.txt", b"1\nY\n");
8017
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
8018
    repo.bookmark_switch("main", false).unwrap();
8019
8020
    let err = repo.rebase(&c, &[d]).unwrap_err();
8021
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
8022
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
8023
    assert!(r.changed && r.checked_out);
8024
    let snap = repo.snapshot_status("status").unwrap();
8025
    assert!(
8026
        snap.base_snapshot.is_conflicted(),
8027
        "the conflict is in the working copy"
8028
    );
8029
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
8030
    assert!(text.contains('X') && text.contains('Y'), "{text}");
8031
8032
    write(root, "a.txt", b"1\nXY\n");
8033
    repo.commit("Resolve", &[]).unwrap();
8034
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
8035
    assert!(st.contains(&c) && st.contains(&d));
8036
    let files = st.materialize().files;
8037
    assert!(!files["a.txt"].is_conflicted());
8038
    assert!(
8039
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
8040
    );
8041
8042
    // A change the current bookmark does not hold is refused.
8043
    repo.bookmark_switch("develop", false).unwrap();
8044
    write(root, "b.txt", b"b\n");
8045
    let e = repo.commit("E", &[]).unwrap();
8046
    repo.bookmark_switch("main", false).unwrap();
8047
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
8048
    assert!(
8049
        err.to_string().contains("not on the current bookmark"),
8050
        "{err}"
8051
    );
8052
}
d4dbab97 Andy McCall ↶ 8053
8054
#[test]
8055
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
8056
    hermetic();
8057
    let dir = tempfile::tempdir().unwrap();
8058
    let root = dir.path();
8059
    let repo = Repo::init(root).unwrap();
8060
    write(root, "a.txt", b"a\n");
8061
    write(root, "kept.log", b"tracked\n");
8062
    repo.commit("first", &[]).unwrap();
8063
    write(root, "build.log", b"made\n");
8064
    let snap = repo.snapshot_status("status").unwrap();
8065
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
8066
    // A rule written afterwards leaves the added file out again, while the
8067
    // committed one stays tracked.
8068
    write(root, ".gitignore", b"*.log\n");
8069
    let snap = repo.snapshot_status("status").unwrap();
8070
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
8071
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
8072
    write(root, "kept.log", b"tracked, edited\n");
8073
    let snap = repo.snapshot_status("status").unwrap();
8074
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
8075
}
fd280228 Andy McCall ↶ 8076
8077
#[test]
8078
fn shed_graphs_come_back_the_same() {
8079
    hermetic();
8080
    let dir = tempfile::tempdir().unwrap();
8081
    let root = dir.path();
8082
    let repo = Repo::init(root).unwrap();
8083
    write(root, "a.txt", b"1\n2\n3\n");
8084
    write(root, "b.txt", b"x\n");
8085
    repo.commit("first", &[]).unwrap();
8086
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
8087
    repo.commit("second", &[]).unwrap();
8088
    let heads = repo.bookmark_heads().unwrap();
8089
    let mut st = repo.load_state_history(&heads).unwrap();
8090
    let view = st.tree().view();
8091
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
8092
        .iter()
8093
        .map(|p| view.entries[*p].node)
8094
        .collect();
8095
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8096
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8097
    assert_eq!(st.built_count(), 2);
8098
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
8099
    assert_eq!((shed, st.built_count()), (2, 0));
8100
    // A later change applies on top of the shed history.
8101
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
8102
    let h3 = repo.commit("third", &[]).unwrap();
8103
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
8104
    st.add_known(h3, skeleton, texts);
8105
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8106
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8107
    assert_eq!(after[1], before[1]);
8108
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
8109
}
360aa74a Andy McCall ↶ 8110
8111
#[test]
8112
fn many_edited_files_diff_in_parallel() {
8113
    // Enough edited files that the builder diffs them in parallel; the
8114
    // commit must hold exactly what is on disk, and a second snapshot
8115
    // must find nothing left to commit.
8116
    hermetic();
8117
    let dir = tempfile::tempdir().unwrap();
8118
    let root = dir.path();
8119
    let repo = Repo::init(root).unwrap();
8120
    let text = |i: usize, round: usize| {
8121
        let mut s = String::new();
8122
        for line in 0..50 {
8123
            if round > 0 && line % 7 == i % 7 {
8124
                s.push_str(&format!("edited {round} {i} {line}\n"));
8125
            } else {
8126
                s.push_str(&format!("file {i} line {line}\n"));
8127
            }
8128
        }
8129
        if round > 0 && i.is_multiple_of(3) {
8130
            s.push_str("appended\n");
8131
        }
8132
        s
8133
    };
8134
    for i in 0..40 {
8135
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
8136
    }
8137
    repo.commit("first", &[]).unwrap();
8138
    for i in 0..40 {
8139
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
8140
    }
8141
    let h = repo.commit("edit every file", &[]).unwrap();
8142
    let snap = repo.load_state(&[h]).unwrap().materialize();
8143
    for i in 0..40 {
8144
        let want = text(i, 1);
8145
        assert!(
8146
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
8147
            "d/f{i}.txt as committed"
8148
        );
8149
    }
8150
    assert!(
8151
        repo.commit("nothing", &[]).is_err(),
8152
        "nothing left to commit"
8153
    );
8154
}
b35df36b Andy McCall ↶ 8155
8156
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
8157
/// is known (fetch printed "up to date" while main was behind), a change
8158
/// only fetched resolves and says where it is, and a checkout whose only
8159
/// remote is not `origin` uses that one.
8160
#[test]
8161
fn a_fetched_change_shows_as_behind_and_resolves() {
8162
    hermetic();
8163
    let dir = tempfile::tempdir().unwrap();
8164
    let root = dir.path();
8165
    let origin = Repo::init(&root.join("origin")).unwrap();
8166
    drop(origin);
8167
    let url = root.join("origin").to_string_lossy().to_string();
8168
    let a = Repo::clone(&url, &root.join("a"))
8169
        .unwrap()
8170
        .with_home(root.join("home-a"));
8171
    write(&root.join("a"), "f.txt", b"one\n");
8172
    a.commit("one", &[]).unwrap();
8173
    a.push("origin", false).unwrap();
8174
    let b = Repo::clone(&url, &root.join("b"))
8175
        .unwrap()
8176
        .with_home(root.join("home-b"));
8177
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8178
8179
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
8180
    let h2 = a.commit("two", &[]).unwrap();
8181
    a.push("origin", false).unwrap();
8182
    b.fetch("origin").unwrap();
8183
    // Fetched, not pulled: one behind, the change found and placed.
8184
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8185
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
8186
    assert_eq!(
8187
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
8188
            .unwrap(),
8189
        h2
8190
    );
8191
    assert_eq!(
8192
        b.remote_only_location(&h2).unwrap().as_deref(),
8193
        Some("origin/main")
8194
    );
8195
    // Fetching again changes nothing: still behind, which is what the
8196
    // CLI now says rather than "up to date".
8197
    b.fetch("origin").unwrap();
8198
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8199
    b.pull("origin").unwrap();
8200
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8201
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
8202
8203
    // One remote, not called origin: it is the default.
8204
    let mut c = Repo::init(&root.join("c")).unwrap();
8205
    assert_eq!(c.default_remote(), "origin");
8206
    c.config.set("remote.earth.url", &url).unwrap();
8207
    assert_eq!(c.default_remote(), "earth");
8208
    c.config.set("remote.origin.url", &url).unwrap();
8209
    assert_eq!(c.default_remote(), "origin");
8210
}
827281ee Andy McCall ↶ 8211
8212
/// oxygen#57: a clone from a relative local path records the remote as an
8213
/// absolute path, so fetch still finds it from inside the clone.
8214
#[test]
8215
fn a_clone_from_a_relative_path_records_it_absolute() {
8216
    hermetic();
8217
    let dir = tempfile::tempdir().unwrap();
8218
    let root = dir.path();
8219
    Repo::init(&root.join("origin")).unwrap();
8220
    let rel = crate::protocol::stored_url("relative/repo");
8221
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
8222
    assert_eq!(
8223
        crate::protocol::stored_url("https://hub.example/o/n"),
8224
        "https://hub.example/o/n"
8225
    );
8226
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8d803563 Andy McCall ↶ 8227
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
8228
    // A bucket is kept as written: it is not a path.
8229
    assert_eq!(
8230
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
8231
        "s3://bucket/prefix?profile=p"
8232
    );
827281ee Andy McCall ↶ 8233
    let url = root.join("origin").to_string_lossy().to_string();
8234
    let b = Repo::clone(&url, &root.join("b")).unwrap();
8235
    assert_eq!(b.config.remotes["origin"], url);
8236
    b.fetch("origin").unwrap();
8237
}
a46f3e4f Andy McCall ↶ 8238
8239
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
8240
/// and gets its subrepos at their pins from this workspace's copies, with
8241
/// their remotes pointing where the subrepos come from.
8242
#[test]
8243
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
8244
    hermetic();
8245
    let dir = tempfile::tempdir().unwrap();
8246
    let root = dir.path();
8247
    Repo::init(&root.join("lib-origin")).unwrap();
8248
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8249
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8250
        .unwrap()
8251
        .with_home(root.join("home"));
8252
    write(&root.join("lib"), "lib.txt", b"v1\n");
8253
    let l1 = lib.commit("lib v1", &[]).unwrap();
8254
    assert!(lib.push("origin", false).unwrap()[0].ok);
8255
8256
    let app_dir = root.join("app");
8257
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8258
    write(&app_dir, "main.txt", b"app\n");
8259
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8260
    app.commit("app with lib", &[]).unwrap();
8261
    // A second bookmark, and the main workspace on another.
8262
    app.bookmark_create("develop", None).unwrap();
8263
    app.bookmark_create("feature", None).unwrap();
8264
    let mut app = app;
8265
    app.bookmark_switch("feature", false).unwrap();
8266
    assert_eq!(app.config.bookmark, "feature");
8267
8268
    // The library's origin goes away: the subrepo must come from here.
8269
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
8270
    let heads = app.resolve_heads("develop").unwrap();
8271
    let ws = app
8272
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
8273
        .unwrap();
8274
    assert_eq!(
8275
        ws.config.bookmark, "develop",
8276
        "the new workspace is on develop"
8277
    );
8278
    assert_eq!(
8279
        app.config.bookmark, "feature",
8280
        "and this one stays on its own"
8281
    );
8282
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
8283
    assert_eq!(
8284
        sub.config.remotes["origin"], lib_url,
8285
        "its origin is the subrepo's URL"
8286
    );
8287
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
8288
    assert_eq!(
8289
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
8290
        b"v1\n"
8291
    );
8292
}
47ce8b8e Andy McCall ↶ 8293
8294
/// Revsets (docs/revset_query_language.md): symbols, relations, set
8295
/// operators and the predicates, over a small graph with two heads and
8296
/// a rename.
8297
#[test]
8298
fn revsets_select_changes_by_relation_author_text_date_and_path() {
8299
    hermetic();
8300
    let dir = tempfile::tempdir().unwrap();
8301
    let root = dir.path();
8302
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8303
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
8304
        .unwrap();
8305
    write(root, "src/a.rs", b"one\n");
8306
    let a = repo.commit("first: add a", &[]).unwrap();
8307
    write(root, "src/a.rs", b"one\ntwo\n");
8308
    let b = repo.commit("second: grow a", &[]).unwrap();
8309
    // A second head, independent of b: a new file on top of a.
8310
    repo.checkout(&[a], false, "checkout a").unwrap();
8311
    write(root, "docs/notes.md", b"notes\n");
8312
    let c = repo.commit("third: notes", &[]).unwrap();
8313
    // Back to both heads, then rename a.rs: the node keeps its identity.
8314
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
8315
        .unwrap();
8316
    fs::remove_file(root.join("src/a.rs")).unwrap();
8317
    write(root, "src/z.rs", b"one\ntwo\n");
8318
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
8319
    let wc = repo.working_copy().unwrap().0;
8320
    // A saved revset is checked when set.
8321
    repo.set_user_config("revset.mine", "author(me) & ::main")
8322
        .unwrap();
8323
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
8324
    let set = |src: &str| -> Vec<ChangeHash> {
8325
        let mut v = repo.revset(src).unwrap().hashes;
8326
        v.sort();
8327
        v
8328
    };
8329
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
8330
        let mut v = hs.to_vec();
8331
        v.sort();
8332
        v
8333
    };
8334
8335
    // Changes commute: a new file depends on nothing and the rename on the
8336
    // file's creation, so the graph is a, b->a, d->a, c, and the working
8337
    // copy on the three heads b, c, d.
8338
    let heads = sorted(&repo.bookmark_heads().unwrap());
8339
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
8340
    assert!(heads.contains(&d) && heads.contains(&c));
8341
    // Symbols and closures.
8342
    assert_eq!(set("main"), heads);
8343
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
8344
    assert_eq!(set("@"), vec![wc]);
8345
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
8346
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
8347
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
8348
    assert_eq!(
8349
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
8350
        sorted(&[a, b])
8351
    );
8352
    // Ranges: what main has beyond b, and `..` forms.
8353
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
8354
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
8355
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
8356
    // Operators and precedence: ~ binds tighter than &, & than |.
8357
    assert_eq!(
8358
        set(&format!("::main ~ #{}", d.short(12))),
8359
        sorted(&[a, b, c])
8360
    );
8361
    assert_eq!(
8362
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
8363
        sorted(&[b, c])
8364
    );
8365
    assert_eq!(set("all() ~ ::main"), vec![wc]);
8366
    // Relations.
8367
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
8368
    head_deps.sort();
8369
    head_deps.dedup();
8370
    assert_eq!(set("deps(main)"), head_deps);
8371
    let on_a: Vec<ChangeHash> = [b, c, d]
8372
        .into_iter()
8373
        .filter(|h| meta(h).deps.contains(&a))
8374
        .collect();
8375
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
8376
    assert_eq!(set("heads(::main)"), heads);
8377
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
8378
    assert_eq!(
8379
        set(&format!(
8380
            "heads(#{} | #{} | #{})",
8381
            a.short(12),
8382
            b.short(12),
8383
            c.short(12)
8384
        )),
8385
        sorted(&[b, c])
8386
    );
8387
    assert_eq!(set("latest(::main, 1)"), vec![d]);
8388
    assert_eq!(set("kind(working-copy)"), vec![wc]);
8389
    assert_eq!(set("none()"), vec![]);
8390
    // Predicates: author by name, email, key prefix and `me`.
8391
    let key = repo.config.author_key.unwrap();
8392
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
8393
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
8394
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
8395
    assert_eq!(set("author(me) & ::main").len(), 4);
8396
    assert_eq!(set("author(nobody)"), vec![]);
8397
    assert_eq!(set("description(notes)"), vec![c]);
8398
    assert_eq!(set("description(\"rename a\")"), vec![d]);
8399
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
8400
    assert_eq!(set("date(..2000-01-01)"), vec![]);
8401
    // touches follows the node through the rename, in the current state.
8402
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
8403
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
8404
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
8405
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
8406
    // Newest first in the result order.
8407
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
8408
    // The saved revset, and errors that say what is wrong.
8409
    assert_eq!(set("mine()").len(), 4);
8410
    let e = repo.revset("nosuch()").unwrap_err().to_string();
8411
    assert!(e.contains("unknown function nosuch()"), "{e}");
8412
    let e = repo.revset("main &").unwrap_err().to_string();
8413
    assert!(e.contains("at character"), "{e}");
8414
    let e = repo.revset("zzzz").unwrap_err().to_string();
8415
    assert!(e.contains("no change matches"), "{e}");
8416
    let e = repo
8417
        .revset_with_budget("::main", std::time::Duration::ZERO)
8418
        .unwrap_err()
8419
        .to_string();
8420
    assert!(e.contains("budget"), "{e}");
8421
    // The log entries carry the bookmark's heads and the working copy.
8422
    let entries = repo.log_revset("::@").unwrap();
8423
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
2c9ddac3 Andy McCall ↶ 8424
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
8425
    // push); then a signed change, a tag, and a revocation.
8426
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
8427
    assert_eq!(set("signed_by(me)"), vec![]);
8428
    repo.sign_change(&d).unwrap();
8429
    assert_eq!(set("signed_by(me)"), vec![d]);
8430
    assert_eq!(set("signed_by([email protected])"), vec![d]);
8431
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
8432
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
8433
    assert_eq!(set("delegated()"), vec![]);
8434
    assert_eq!(set("revoked()"), vec![]);
8435
    assert_eq!(set("attested(tag)"), vec![]);
8436
    repo.tag_create("v1", &[b], "first").unwrap();
8437
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
8438
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
8439
    assert_eq!(set("attested(receipt)"), vec![]);
8440
    assert_eq!(set("built(test)"), vec![]);
8441
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
8442
    assert!(e.contains("tag, receipt or ref"), "{e}");
8443
    repo.revoke_identity(&key, "test").unwrap();
8444
    assert_eq!(set("revoked()"), vec![d]);
8445
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
47ce8b8e Andy McCall ↶ 8446
}
614f55e1 Andy McCall ↶ 8447
8448
#[test]
8449
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
8450
    let dir = tempfile::tempdir().unwrap();
8451
    let root = dir.path();
8452
    let home = root.join("home");
8453
    // Ada's identity lives in the user file; repository `a` pins the same
8454
    // key in its own file, repository `b` names none.
8455
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
8456
    let (key, _) = a
8457
        .create_identity("Ada", "[email protected]", IdentityScope::User)
8458
        .unwrap();
8459
    a.config.set("author.key", &key.to_hex()).unwrap();
8460
    a.save_config().unwrap();
8461
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
8462
    let r = a
8463
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
8464
        .unwrap();
8465
    assert_eq!(
8466
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
8467
        r.new.to_hex(),
8468
        "the user file follows"
8469
    );
8470
    assert_eq!(
8471
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
8472
        r.new.to_hex(),
8473
        "the pinning repository follows"
8474
    );
8475
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
8476
    assert_eq!(
8477
        b.config.author_key,
8478
        Some(r.new),
8479
        "a checkout without a pin follows the user file"
8480
    );
8481
    // A repository-scoped identity leaves the user file alone.
8482
    let other_home = root.join("home2");
8483
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
8484
    let (ck, _) = c
8485
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
8486
        .unwrap();
8487
    assert!(!other_home.join("config.toml").exists());
8488
    let r2 = c.rotate_identity().unwrap();
8489
    assert_ne!(r2.new, ck);
8490
    assert_eq!(
8491
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
8492
        r2.new.to_hex()
8493
    );
8494
    assert!(
8495
        !other_home.join("config.toml").exists(),
8496
        "a repository-scoped identity stays repository-scoped"
8497
    );
8498
    // Several delegates in one rotation; a repeat is refused.
8499
    let (d1, d2) = (
8500
        SecretKey::generate().identity("D1", "d1@x", 1),
8501
        SecretKey::generate().identity("D2", "d2@x", 1),
8502
    );
8503
    let r3 = c
8504
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
8505
        .unwrap();
8506
    assert_eq!(r3.identity.delegates.len(), 2);
8507
    assert!(c
8508
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
8509
        .is_err());
8510
}
33be2409 Andy McCall ↶ 8511
8512
/// Two unrelated histories that both add the same file, joined by two
8513
/// independent merges on two branches, then those branches merged: Git
8514
/// merges identical additions cleanly, and the import must too (#71,
8515
/// found in VS Code's history).
8516
#[test]
8517
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
8518
    // Batches of one: every merge renders apart from the state, where a
8519
    // file whose graph the state had built came out empty (#71).
8520
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8521
    hermetic();
8522
    if std::process::Command::new("git")
8523
        .arg("--version")
8524
        .output()
8525
        .is_err()
8526
    {
8527
        eprintln!("git not installed; skipping");
8528
        return;
8529
    }
8530
    let dir = tempfile::tempdir().unwrap();
8531
    let root = dir.path();
8532
    let g = root.join("src.git");
8533
    fs::create_dir_all(&g).unwrap();
8534
    let git = |args: &[&str]| -> String {
8535
        let out = std::process::Command::new("git")
8536
            .arg("-C")
8537
            .arg(&g)
8538
            .args([
8539
                "-c",
8540
                "user.name=Grace",
8541
                "-c",
8542
                "[email protected]",
8543
                "-c",
8544
                "commit.gpgsign=false",
8545
            ])
8546
            .args(args)
8547
            .output()
8548
            .unwrap();
8549
        assert!(
8550
            out.status.success(),
8551
            "git {args:?}: {}",
8552
            String::from_utf8_lossy(&out.stderr)
8553
        );
8554
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8555
    };
8556
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
8557
    // History A: main.
8558
    git(&["init", "-q", "-b", "main"]);
8559
    write(&g, "gulpfile.js", text);
8560
    write(&g, "a.txt", b"a\n");
8561
    git(&["add", "."]);
8562
    git(&["commit", "-q", "-m", "A root"]);
8563
    // History B: an unrelated root adding the same file, identical.
8564
    git(&["checkout", "-q", "--orphan", "fork"]);
8565
    git(&["rm", "-q", "-r", "--cached", "."]);
8566
    for f in ["gulpfile.js", "a.txt"] {
8567
        let _ = fs::remove_file(g.join(f));
8568
    }
8569
    write(&g, "gulpfile.js", text);
8570
    write(&g, "b.txt", b"b\n");
8571
    git(&["add", "."]);
8572
    git(&["commit", "-q", "-m", "B root"]);
8573
    // Two branches from main, each joining B on its own.
8574
    git(&["checkout", "-q", "-b", "one", "main"]);
8575
    git(&[
8576
        "merge",
8577
        "-q",
8578
        "--no-ff",
8579
        "--allow-unrelated-histories",
8580
        "-m",
8581
        "join on one",
8582
        "fork",
8583
    ]);
8584
    git(&["checkout", "-q", "-b", "two", "main"]);
8585
    write(&g, "a.txt", b"a\ntwo\n");
8586
    git(&["commit", "-q", "-am", "work on two"]);
8587
    git(&[
8588
        "merge",
8589
        "-q",
8590
        "--no-ff",
8591
        "--allow-unrelated-histories",
8592
        "-m",
8593
        "join on two",
8594
        "fork",
8595
    ]);
8596
    // Then the two joins meet, and the file is reformatted after.
8597
    git(&["checkout", "-q", "main"]);
8598
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
8599
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8600
    write(
8601
        &g,
8602
        "gulpfile.js",
8603
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
8604
    );
8605
    git(&["commit", "-q", "-am", "after"]);
8606
8607
    let dest = root.join("dest");
8608
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8609
    repo.import_git(&g, "main").unwrap();
8610
    let v = repo.verify_git_import(&g, "main").unwrap();
8611
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8612
    assert_eq!(
8613
        fs::read(dest.join("gulpfile.js")).unwrap(),
8614
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
8615
    );
8616
}
8617
8618
/// As above, but the two joins keep different copies (each branch had a
8619
/// different version when it joined), and later work edits each copy:
8620
/// the shape of VS Code's c67ef57cda90 (#71).
8621
#[test]
8622
fn git_import_joins_where_each_join_kept_a_different_copy() {
8623
    // Batches of one: every merge renders apart from the state, where a
8624
    // file whose graph the state had built came out empty (#71).
8625
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8626
    hermetic();
8627
    if std::process::Command::new("git")
8628
        .arg("--version")
8629
        .output()
8630
        .is_err()
8631
    {
8632
        eprintln!("git not installed; skipping");
8633
        return;
8634
    }
8635
    let dir = tempfile::tempdir().unwrap();
8636
    let root = dir.path();
8637
    let g = root.join("src.git");
8638
    fs::create_dir_all(&g).unwrap();
8639
    let run = |args: &[&str]| {
8640
        std::process::Command::new("git")
8641
            .arg("-C")
8642
            .arg(&g)
8643
            .args([
8644
                "-c",
8645
                "user.name=Grace",
8646
                "-c",
8647
                "[email protected]",
8648
                "-c",
8649
                "commit.gpgsign=false",
8650
            ])
8651
            .args(args)
8652
            .output()
8653
            .unwrap()
8654
    };
8655
    let git = |args: &[&str]| -> String {
8656
        let out = run(args);
8657
        assert!(
8658
            out.status.success(),
8659
            "git {args:?}: {}",
8660
            String::from_utf8_lossy(&out.stderr)
8661
        );
8662
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8663
    };
8664
    git(&["init", "-q", "-b", "main"]);
8665
    write(
8666
        &g,
8667
        "gulpfile.js",
8668
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
8669
    );
8670
    git(&["add", "."]);
8671
    git(&["commit", "-q", "-m", "A root"]);
8672
    write(
8673
        &g,
8674
        "gulpfile.js",
8675
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
8676
    );
8677
    git(&["commit", "-q", "-am", "whitespace"]);
8678
    git(&["checkout", "-q", "--orphan", "fork"]);
8679
    git(&["rm", "-q", "-r", "--cached", "."]);
8680
    let _ = fs::remove_file(g.join("gulpfile.js"));
8681
    write(
8682
        &g,
8683
        "gulpfile.js",
8684
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
8685
    );
8686
    git(&["add", "."]);
8687
    git(&["commit", "-q", "-m", "B root"]);
8688
    // Branch one joins B keeping main's copy; branch two keeps B's.
8689
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
8690
        git(&["checkout", "-q", "-b", branch, "main"]);
8691
        let _ = run(&[
8692
            "merge",
8693
            "-q",
8694
            "--no-ff",
8695
            "--allow-unrelated-histories",
8696
            "-m",
8697
            "join",
8698
            "fork",
8699
        ]);
8700
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
8701
        git(&["add", "gulpfile.js"]);
8702
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
8703
    }
8704
    // Each branch then edits its copy.
8705
    git(&["checkout", "-q", "one"]);
8706
    write(
8707
        &g,
8708
        "gulpfile.js",
8709
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
8710
    );
8711
    git(&["commit", "-q", "-am", "tslint on one"]);
8712
    git(&["checkout", "-q", "two"]);
8713
    write(
8714
        &g,
8715
        "gulpfile.js",
8716
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
8717
    );
8718
    write(&g, "extra.txt", b"x\n");
8719
    write(&g, "more.txt", b"m\n");
8720
    git(&["add", "."]);
8721
    git(&["commit", "-q", "-am", "fmt on two"]);
8722
    // They meet: resolved by hand.
8723
    git(&["checkout", "-q", "one"]);
8724
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8725
    write(
8726
        &g,
8727
        "gulpfile.js",
8728
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
8729
    );
8730
    git(&["add", "gulpfile.js"]);
8731
    git(&["commit", "-q", "-m", "merge two into one"]);
8732
8733
    let dest = root.join("dest");
8734
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8735
    repo.import_git(&g, "one").unwrap();
8736
    let v = repo.verify_git_import(&g, "one").unwrap();
8737
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8738
}
dd21fd82 Andy McCall ↶ 8739
8740
/// oxygen#68: on a store that is not this disk's directory, the operation
8741
/// head is the store's reference record, moved by compare-and-swap. Two
8742
/// handles recording from the same head both get through, merged; a swap
8743
/// from a stale version is refused; a second repository cannot start on a
8744
/// store that already holds one.
8745
#[test]
8746
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8747
    use crate::strata::{MemoryStore, Store as _};
8748
    let backend = std::sync::Arc::new(MemoryStore::new());
8749
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8750
    let dir = tempfile::tempdir().unwrap();
8751
    let a = Repo::init(dir.path()).unwrap();
8752
    assert!(
8753
        !dir.path().join(".oxy/ops/head").exists(),
8754
        "the head is not a file"
8755
    );
8756
    let (h0, op0) = a.head_op().unwrap();
8757
    let record = backend
8758
        .read_ref(HEAD_RECORD)
8759
        .unwrap()
8760
        .expect("the head is the store's record");
8761
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8762
8763
    let b = Repo::open(dir.path()).unwrap();
8764
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8765
    let mut va = op0.view.clone();
8766
    va.bookmarks.insert("from-a".into(), state);
8767
    let mut vb = op0.view.clone();
8768
    vb.bookmarks.insert("from-b".into(), state);
8769
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8770
    assert_eq!(b.head_ref().unwrap(), rb);
8771
    // a recorded from h0 too: the head moved, so the two are merged.
8772
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8773
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8774
    assert_eq!(head, ra);
8775
    assert!(
8776
        op.command.ends_with("(merged with a concurrent operation)"),
8777
        "{}",
8778
        op.command
8779
    );
8780
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8781
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8782
8783
    // A swap from a version that is no longer current moves nothing.
8784
    let (h, v) = a.read_head().unwrap();
8785
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8786
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
767ac6cd Andy McCall 8787
    a.refresh().unwrap();
dd21fd82 Andy McCall ↶ 8788
    assert_eq!(a.head_ref().unwrap(), rb);
8789
8790
    let other = tempfile::tempdir().unwrap();
8791
    let err = Repo::init(other.path())
8792
        .err()
8793
        .expect("the store already holds a log")
8794
        .to_string();
8795
    assert!(
8796
        err.contains("already holds a repository's operation log"),
8797
        "{err}"
8798
    );
8799
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8800
}
d069701a Andy McCall ↶ 8801
8802
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8803
/// objects and operation head there, with `.oxy/cache` in front: it works
8804
/// as one on disk does, reopens, and survives losing its cache.
8805
#[test]
8806
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8807
    hermetic();
8808
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8809
        return;
8810
    }
8811
    let dir = tempfile::tempdir().unwrap();
8812
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8813
    let url = format!("dir://{}", bucket.display());
8814
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8815
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8816
    write(&root, "a.txt", b"one\n");
8817
    let h1 = repo.commit("First", &[]).unwrap();
8818
    write(&root, "a.txt", b"one\ntwo\n");
8819
    let h2 = repo.commit("Second", &[]).unwrap();
8820
    assert!(
8821
        !root.join(".oxy/ops/head").exists(),
8822
        "the head is in the store"
8823
    );
8824
    assert!(bucket.join("ops/head").is_file());
8825
    assert!(root.join(".oxy/cache").is_dir());
8826
    drop(repo);
8827
8828
    // Reopened, and again with no cache at all: everything comes from the store.
8829
    for drop_cache in [false, true] {
8830
        if drop_cache {
8831
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8832
        }
8833
        let repo = Repo::open(&root).unwrap();
8834
        let log: Vec<String> = repo
8835
            .op_log()
8836
            .unwrap()
8837
            .into_iter()
8838
            .map(|(_, op)| op.command)
8839
            .collect();
8840
        assert!(log.len() >= 3, "{log:?}");
8841
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8842
        let heads = repo
8843
            .store()
8844
            .get_state(&repo.view().unwrap().bookmarks["main"])
8845
            .unwrap()
8846
            .heads;
8847
        assert_eq!(heads, vec![h2]);
8848
        assert_eq!(
8849
            repo.load_state(&heads).unwrap().materialize().files.len(),
8850
            1
8851
        );
8852
    }
8853
8854
    // A second repository cannot start on the same store.
8855
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8856
        .err()
8857
        .unwrap()
8858
        .to_string();
8859
    assert!(
8860
        err.contains("already holds a repository's operation log"),
8861
        "{err}"
8862
    );
8863
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8864
        .err()
8865
        .unwrap()
8866
        .to_string();
8867
    assert!(err.contains("cannot open that kind of store"), "{err}");
8868
}
80677b7a Andy McCall ↶ 8869
8870
/// oxygen#75: the prompt's quick check agrees with status in a repository
8871
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8872
/// another state, clean again once that pin is committed. (It compared the
8873
/// subrepo's directory as if it were a file, so it was always dirty.)
8874
#[test]
8875
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8876
    hermetic();
8877
    let dir = tempfile::tempdir().unwrap();
8878
    let root = dir.path();
8879
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8880
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8881
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8882
        .unwrap()
8883
        .with_home(root.join("home"));
8884
    write(&root.join("lib"), "lib.txt", b"v1\n");
8885
    lib.commit("lib v1", &[]).unwrap();
8886
    assert!(lib.push("origin", false).unwrap()[0].ok);
8887
    let app_dir = root.join("app");
8888
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8889
    write(&app_dir, "main.txt", b"app\n");
8890
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8891
    app.commit("app with lib", &[]).unwrap();
8892
    // Out of the racy window, so the stat-only path decides.
8893
    std::thread::sleep(std::time::Duration::from_millis(2100));
8894
    let reopen = || Repo::open(&app_dir).unwrap();
8895
    assert_eq!(
8896
        reopen().quick_dirty().unwrap(),
8897
        Some(false),
8898
        "clean, as status says"
8899
    );
8900
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8901
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8902
    nested.commit("lib v2", &[]).unwrap();
8903
    assert_eq!(
8904
        reopen().quick_dirty().unwrap(),
8905
        Some(true),
8906
        "the subrepo moved"
8907
    );
8908
    reopen().commit("pin lib v2", &[]).unwrap();
8909
    std::thread::sleep(std::time::Duration::from_millis(2100));
8910
    assert_eq!(
8911
        reopen().quick_dirty().unwrap(),
8912
        Some(false),
8913
        "the new pin is committed"
8914
    );
8915
}
7993d465 Andy McCall ↶ 8916
8917
#[test]
8918
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8919
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8920
    hermetic();
8921
    let dir = tempfile::tempdir().unwrap();
8922
    let root = dir.path();
8923
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8924
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8925
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8926
        .unwrap()
8927
        .with_home(root.join("home"));
8928
    write(&root.join("lib"), "lib.txt", b"v1\n");
8929
    lib.commit("lib v1", &[]).unwrap();
8930
    assert!(lib.push("origin", false).unwrap()[0].ok);
8931
    let app_dir = root.join("app");
8932
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8933
    write(
8934
        &app_dir,
8935
        ".oxymodules",
8936
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8937
    );
8938
    let unpinned = app.unpinned_modules().unwrap();
8939
    assert_eq!(unpinned.len(), 1);
8940
    assert_eq!(unpinned[0].0, "libs/lib");
8941
    assert_eq!(unpinned[0].1.url, lib_url);
8942
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8943
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8944
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8945
}
bf3a6781 Andy McCall ↶ 8946
8947
#[test]
8948
fn the_bookmark_revset_function_names_only_bookmarks() {
8949
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8950
    hermetic();
8951
    let dir = tempfile::tempdir().unwrap();
8952
    let repo = Repo::init(dir.path()).unwrap();
8953
    write(dir.path(), "a.txt", b"a\n");
8954
    let a = repo.commit("A", &[]).unwrap();
8955
    write(dir.path(), "b.txt", b"b\n");
8956
    let b = repo.commit("B", &[]).unwrap();
8957
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8958
    heads.sort();
8959
    let mut want = repo.bookmark_heads().unwrap();
8960
    want.sort();
8961
    assert_eq!(heads, want);
8962
    assert!(heads.contains(&b));
8963
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8964
    // A change prefix is a symbol, not a bookmark.
8965
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8966
    assert!(repo.revset(&prefix).is_ok());
8967
    let e = repo
8968
        .revset(&format!("bookmark({prefix})"))
8969
        .unwrap_err()
8970
        .to_string();
8971
    assert!(e.contains("no such bookmark"), "{e}");
8972
}
72484195 Andy McCall ↶ 8973
8974
#[test]
8975
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8976
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8977
    // pinning the subrepo, and the nested repository on disk at that pin.
8978
    hermetic();
8979
    let dir = tempfile::tempdir().unwrap();
8980
    let root = dir.path();
8981
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8982
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8983
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8984
        .unwrap()
8985
        .with_home(root.join("home"));
8986
    write(&root.join("lib"), "lib.txt", b"v1\n");
8987
    lib.commit("lib v1", &[]).unwrap();
8988
    assert!(lib.push("origin", false).unwrap()[0].ok);
8989
    let app_dir = root.join("app");
8990
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8991
    write(&app_dir, "main.txt", b"app\n");
8992
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8993
    // The stale state: registered in .oxymodules, never pinned.
8994
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8995
    app.commit("initial", &[]).unwrap();
8996
    let stale = app.bookmark_heads().unwrap();
8997
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8998
    app.commit("pin lib", &[]).unwrap();
8999
    let newer = app.bookmark_heads().unwrap();
9000
    app.checkout(&stale, false, "test").unwrap();
9001
    write(&app_dir, "notes.txt", b"mine\n");
9002
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
9003
    assert_eq!(carried, vec!["notes.txt".to_string()]);
9004
    assert!(app_dir.join("notes.txt").exists());
9005
}
9006
9007
#[test]
9008
fn a_bookmark_only_behind_its_remote_catches_up() {
9009
    // oxygen#74: switch takes the remote's state rather than a stale one.
9010
    hermetic();
9011
    let dir = tempfile::tempdir().unwrap();
9012
    let root = dir.path();
9013
    let _origin = Repo::init(&root.join("origin")).unwrap();
9014
    let url = root.join("origin").to_string_lossy().to_string();
9015
    let one = Repo::clone(&url, &root.join("one"))
9016
        .unwrap()
9017
        .with_home(root.join("home"));
9018
    write(&root.join("one"), "a.txt", b"a\n");
9019
    one.commit("A", &[]).unwrap();
9020
    assert!(one.push("origin", false).unwrap()[0].ok);
9021
    let two = Repo::clone(&url, &root.join("two"))
9022
        .unwrap()
9023
        .with_home(root.join("home"));
9024
    write(&root.join("two"), "b.txt", b"b\n");
9025
    two.commit("B", &[]).unwrap();
9026
    assert!(two.push("origin", false).unwrap()[0].ok);
9027
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
9028
    one.fetch("origin").unwrap();
9029
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
9030
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
9031
    // Local work the remote lacks: left alone.
9032
    write(&root.join("one"), "c.txt", b"c\n");
9033
    one.commit("C", &[]).unwrap();
9034
    write(&root.join("two"), "d.txt", b"d\n");
9035
    two.commit("D", &[]).unwrap();
9036
    assert!(two.push("origin", false).unwrap()[0].ok);
9037
    one.fetch("origin").unwrap();
9038
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
9039
}
42ccf504 Andy McCall ↶ 9040
9041
#[test]
9042
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
9043
    // oxygen#83: remotes earth and gcs, origin removed.
9044
    hermetic();
9045
    let dir = tempfile::tempdir().unwrap();
9046
    let root = dir.path();
9047
    let _up = Repo::init(&root.join("up")).unwrap();
9048
    let url = root.join("up").to_string_lossy().to_string();
9049
    let other = Repo::clone(&url, &root.join("other"))
9050
        .unwrap()
9051
        .with_home(root.join("home"));
9052
    write(&root.join("other"), "a.txt", b"a\n");
9053
    other.commit("a", &[]).unwrap();
9054
    assert!(other.push("origin", false).unwrap()[0].ok);
9055
    let mut one = Repo::clone(&url, &root.join("one"))
9056
        .unwrap()
9057
        .with_home(root.join("home"));
9058
    one.config.set("remote.earth.url", &url).unwrap();
9059
    one.config.set("remote.gcs.url", &url).unwrap();
9060
    one.config.set("remote.origin.url", "").unwrap();
9061
    one.save_config().unwrap();
9062
    write(&root.join("other"), "b.txt", b"b\n");
9063
    other.commit("b", &[]).unwrap();
9064
    assert!(other.push("origin", false).unwrap()[0].ok);
9065
    one.fetch("earth").unwrap();
9066
    let b = one
9067
        .bookmarks()
9068
        .unwrap()
9069
        .into_iter()
9070
        .find(|b| b.name == "main")
9071
        .unwrap();
9072
    assert_eq!(
9073
        (b.remote.as_deref(), b.behind),
9074
        (Some("earth"), Some(1)),
9075
        "a stale origin copy is not used"
9076
    );
9077
    assert_eq!(
9078
        one.default_remote(),
9079
        "origin",
9080
        "no default chosen among several"
9081
    );
9082
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
9083
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
9084
    one.config.set("core.remote", "earth").unwrap();
9085
    assert_eq!(one.default_remote(), "earth");
9086
}
cbe8499a Andy McCall ↶ 9087
9088
#[test]
9089
fn a_missing_author_identity_says_how_to_fix_it() {
9090
    // oxygen#82: an agent home's author.key naming an identity the
9091
    // repository does not hold.
9092
    hermetic();
9093
    let dir = tempfile::tempdir().unwrap();
9094
    let mut repo = Repo::init(dir.path()).unwrap();
9095
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
9096
    repo.config.set("author.key", &missing.to_hex()).unwrap();
9097
    let e = repo.identity(&missing).unwrap_err().to_string();
9098
    assert!(
9099
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
9100
        "{e}"
9101
    );
9102
    assert!(e.contains("this repository's config"), "{e}");
9103
}
f6dccc45 Andy McCall ↶ 9104
9105
#[test]
9106
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
9107
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
9108
    // the working copy, a pull with nothing new left it there, and status
9109
    // said "clean".
9110
    hermetic();
9111
    let dir = tempfile::tempdir().unwrap();
9112
    let root = dir.path();
9113
    let _up = Repo::init(&root.join("up")).unwrap();
9114
    let url = root.join("up").to_string_lossy().to_string();
9115
    let other = Repo::clone(&url, &root.join("other"))
9116
        .unwrap()
9117
        .with_home(root.join("home"));
9118
    write(&root.join("other"), "a.txt", b"a\n");
9119
    other.commit("a", &[]).unwrap();
9120
    assert!(other.push("origin", false).unwrap()[0].ok);
9121
    let one = Repo::clone(&url, &root.join("one"))
9122
        .unwrap()
9123
        .with_home(root.join("home"));
9124
    write(&root.join("other"), "b.txt", b"b\n");
9125
    other.commit("b", &[]).unwrap();
9126
    assert!(other.push("origin", false).unwrap()[0].ok);
9127
    one.fetch("origin").unwrap();
9128
    // The bookmark moves; the working copy does not.
9129
    let theirs = one.resolve_heads("origin/main").unwrap();
9130
    one.bookmark_set("main", &theirs).unwrap();
9131
    assert!(!root.join("one/b.txt").exists());
9132
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
9133
    let r = one.pull("origin").unwrap();
9134
    assert!(
9135
        !r.changed && r.checked_out,
9136
        "nothing new, but the working copy caught up"
9137
    );
9138
    assert!(root.join("one/b.txt").exists());
9139
    assert_eq!(one.working_copy_behind().unwrap(), None);
9140
}
170bb436 Andy McCall ↶ 9141
9142
#[test]
9143
fn touched_nodes_cache_answers_as_the_changes_do() {
9144
    hermetic();
9145
    let dir = tempfile::tempdir().unwrap();
9146
    let repo = Repo::init(dir.path()).unwrap();
9147
    write(dir.path(), "a.txt", b"one\n");
9148
    write(dir.path(), "b.txt", b"x\n");
9149
    repo.snapshot("t").unwrap();
9150
    let c1 = repo.commit("first", &[]).unwrap();
9151
    write(dir.path(), "b.txt", b"y\n");
9152
    repo.snapshot("t").unwrap();
9153
    repo.commit("b only", &[]).unwrap();
9154
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
9155
    write(dir.path(), "c.txt", b"one\ntwo\n");
9156
    repo.snapshot("t").unwrap();
9157
    let c3 = repo.commit("rename and edit", &[]).unwrap();
9158
    // Uncommitted work, so the working copy touches a file too.
9159
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
9160
    repo.snapshot("t").unwrap();
9161
9162
    let path = dir.path().join(".oxy/index/touched");
9163
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
9164
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
9165
    assert!(path.exists(), "the first query writes the cache");
9166
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
9167
    assert_eq!(cold, warm, "the cache answers as the changes do");
9168
    let (wc, _) = repo.working_copy().unwrap();
9169
    assert_eq!(
9170
        cold,
9171
        vec![wc, c3, c1],
9172
        "renames followed, the working copy included"
9173
    );
9174
9175
    // Working-copy changes are not kept: they are replaced by every snapshot.
9176
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
9177
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
9178
    assert!(cached.contains(&c1) && cached.contains(&c3));
9179
9180
    // A damaged cache is ignored, not trusted.
9181
    let mut bytes = fs::read(&path).unwrap();
9182
    let last = bytes.len() - 40;
9183
    bytes[last] ^= 1;
9184
    fs::write(&path, &bytes).unwrap();
9185
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
9186
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
9187
    assert_eq!(hashes(touches), vec![c3, c1]);
9188
}
e8e6e0ca Andy McCall ↶ 9189
9190
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
9191
/// file back where it was leave two placements at one place, which the
9192
/// tree shows as one file. Removing it, and then its directory, retires
9193
/// both, so no copy is left under a directory that is gone.
9194
#[test]
9195
fn git_import_removes_every_copy_of_a_file_at_one_place() {
9196
    hermetic();
9197
    if std::process::Command::new("git")
9198
        .arg("--version")
9199
        .output()
9200
        .is_err()
9201
    {
9202
        eprintln!("git not installed; skipping");
9203
        return;
9204
    }
9205
    let dir = tempfile::tempdir().unwrap();
9206
    let root = dir.path();
9207
    let g = root.join("src.git");
9208
    fs::create_dir_all(&g).unwrap();
9209
    let git = |args: &[&str]| {
9210
        let out = std::process::Command::new("git")
9211
            .arg("-C")
9212
            .arg(&g)
9213
            .args([
9214
                "-c",
9215
                "user.name=Grace",
9216
                "-c",
9217
                "[email protected]",
9218
                "-c",
9219
                "commit.gpgsign=false",
9220
            ])
9221
            .args(args)
9222
            .output()
9223
            .unwrap();
9224
        assert!(
9225
            out.status.success(),
9226
            "git {args:?}: {}",
9227
            String::from_utf8_lossy(&out.stderr)
9228
        );
9229
    };
9230
    git(&["init", "-q", "-b", "main"]);
9231
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
9232
    write(&g, "keep.txt", b"k\n");
9233
    git(&["add", "."]);
9234
    git(&["commit", "-qm", "base"]);
9235
    fs::create_dir_all(g.join("d/sub")).unwrap();
9236
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
9237
    git(&["commit", "-qm", "into sub"]);
9238
    git(&["checkout", "-qb", "side"]);
9239
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9240
    git(&["commit", "-qm", "back, on side"]);
9241
    git(&["checkout", "-q", "main"]);
9242
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9243
    git(&["commit", "-qm", "back, on main"]);
9244
    git(&["merge", "-q", "--no-edit", "side"]);
9245
    git(&["rm", "-rq", "d"]);
9246
    git(&["commit", "-qm", "d goes"]);
9247
9248
    let repo = Repo::init(&root.join("o")).unwrap();
9249
    repo.import_git(&g, "main").unwrap();
9250
    let v = repo.verify_git_import(&g, "main").unwrap();
9251
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9252
    let st = repo
9253
        .load_state_history(&repo.bookmark_heads().unwrap())
9254
        .unwrap();
9255
    let view = st.tree().view();
9256
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
9257
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
9258
}
5552e69c Andy McCall ↶ 9259
9260
/// oxygen#94: a state index's file histories are read, and checked by
9261
/// their own hashes, only when a file is built. One found damaged is an
9262
/// error that says so, the index is removed, and the next read rebuilds it.
9263
#[test]
9264
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
9265
    hermetic();
9266
    let dir = tempfile::tempdir().unwrap();
9267
    let repo = Repo::init(dir.path()).unwrap();
9268
    for i in 0..6 {
9269
        write(
9270
            dir.path(),
9271
            &format!("f{i}.txt"),
9272
            format!("one {i}\n").as_bytes(),
9273
        );
9274
    }
9275
    repo.snapshot("t").unwrap();
9276
    repo.commit("first", &[]).unwrap();
9277
    for i in 0..6 {
9278
        write(
9279
            dir.path(),
9280
            &format!("f{i}.txt"),
9281
            format!("one {i}\ntwo\n").as_bytes(),
9282
        );
9283
    }
9284
    repo.snapshot("t").unwrap();
9285
    repo.commit("second", &[]).unwrap();
9286
    let want: Vec<Vec<u8>> = (0..6)
9287
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
9288
        .collect();
9289
    // The index of the working copy's base, holding every file's history
9290
    // (a few changes behind, an index is replayed onto, not rewritten).
9291
    let (_, wc) = repo.working_copy().unwrap();
9292
    let base = repo.load_state_history(&wc.deps).unwrap();
9293
    repo.write_state_index(&wc.deps, &base);
9294
    for (i, w) in want.iter().enumerate() {
9295
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9296
    }
9297
    let index = repo.state_indexes();
9298
    assert!(!index.is_empty(), "a state index was written");
9299
    // The histories are last in the file: damage the last of them.
9300
    let mut bytes = fs::read(&index[0]).unwrap();
9301
    let last = bytes.len() - 1;
9302
    bytes[last] ^= 0x40;
9303
    fs::write(&index[0], &bytes).unwrap();
9304
9305
    let reads: Vec<_> = (0..6)
9306
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
9307
        .collect();
9308
    let damaged: Vec<String> = reads
9309
        .iter()
9310
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
9311
        .collect();
9312
    assert_eq!(damaged.len(), 1, "{damaged:?}");
9313
    assert!(
9314
        damaged[0].contains("state index was damaged")
9315
            && damaged[0].contains("run the command again"),
9316
        "{}",
9317
        damaged[0]
9318
    );
9319
    // Every file reads right again, from an index rebuilt from history.
9320
    for (i, w) in want.iter().enumerate() {
9321
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9322
    }
9323
}
cb8b8082 Andy McCall ↶ 9324
9325
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
9326
/// objects alone and in dependency order, and the last moves the bookmark.
9327
/// The remote ends with every change and the same state, and says how each
9328
/// part went.
9329
#[test]
9330
fn a_long_push_goes_in_parts() {
9331
    hermetic();
9332
    let dir = tempfile::tempdir().unwrap();
9333
    let root = dir.path();
9334
    let origin = root.join("origin");
9335
    Repo::init_bare_unbound(&origin).unwrap();
9336
    let main = root.join("main");
9337
    let mut repo = Repo::init(&main).unwrap();
9338
    repo.config
9339
        .set("remote.origin.url", &origin.to_string_lossy())
9340
        .unwrap();
9341
    // One byte: every change is a part of its own.
9342
    repo.config.set("push.batch-bytes", "1").unwrap();
9343
    repo.save_config().unwrap();
9344
    for i in 0..6 {
9345
        write(
9346
            &main,
9347
            &format!("f{i}.txt"),
9348
            format!("file {i}\n").as_bytes(),
9349
        );
9350
        repo.commit(&format!("c{i}"), &[]).unwrap();
9351
    }
9352
    let mut parts = Vec::new();
9353
    let results = repo
9354
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9355
        .unwrap();
9356
    assert!(
9357
        results.iter().any(|r| r.ok && r.name == "main"),
9358
        "{results:?}"
9359
    );
9360
    assert_eq!(parts.len(), 6, "{parts:?}");
9361
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
9362
9363
    let remote = Repo::open(&origin).unwrap();
9364
    let heads = repo.bookmark_heads().unwrap();
9365
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
9366
    assert_eq!(
9367
        remote.log_state(&heads).unwrap().len(),
9368
        repo.log_state(&heads).unwrap().len()
9369
    );
9370
    // A push of objects alone reports how it went, as `objects`.
9371
    let got = remote
9372
        .receive_push(Bundle::default(), vec![], None, vec![])
9373
        .unwrap();
9374
    assert_eq!(got.len(), 1);
9375
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
9376
}
d6e0d5b8 Andy McCall ↶ 9377
d3b27090 Andy McCall ↶ 9378
/// oxygen#133: one change whose blobs pass `push.batch-bytes` sends them
9379
/// first, in parts of objects alone, so no request is larger than about
9380
/// that (a proxy in front of a hub refuses one past 100 MB); the change
9381
/// and the bookmark follow, and a clone has every file.
9382
#[test]
9383
fn a_heavy_change_sends_its_blobs_in_parts() {
9384
    hermetic();
9385
    let dir = tempfile::tempdir().unwrap();
9386
    let root = dir.path();
9387
    let origin = root.join("origin");
9388
    Repo::init_bare_unbound(&origin).unwrap();
9389
    let main = root.join("main");
9390
    let mut repo = Repo::init(&main).unwrap();
9391
    repo.config
9392
        .set("remote.origin.url", &origin.to_string_lossy())
9393
        .unwrap();
9394
    repo.config.set("push.batch-bytes", "50000").unwrap();
9395
    repo.save_config().unwrap();
9396
    let mut x: u64 = 0x9e3779b97f4a7c15;
9397
    let mut noise = |n: usize| -> Vec<u8> {
9398
        (0..n)
9399
            .map(|_| {
9400
                x ^= x << 13;
9401
                x ^= x >> 7;
9402
                x ^= x << 17;
9403
                (x >> 24) as u8
9404
            })
9405
            .collect()
9406
    };
9407
    let files: Vec<Vec<u8>> = (0..4).map(|_| noise(40_000)).collect();
9408
    for (i, f) in files.iter().enumerate() {
9409
        write(&main, &format!("bin{i}.dat"), f);
9410
    }
9411
    repo.commit("four blobs", &[]).unwrap();
9412
    let mut parts = Vec::new();
9413
    let results = repo
9414
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9415
        .unwrap();
9416
    assert!(
9417
        results.iter().any(|r| r.ok && r.name == "main"),
9418
        "{results:?}"
9419
    );
9420
    assert!(
9421
        parts.len() >= 3 && parts[0].starts_with("objects 1 of"),
9422
        "{parts:?}"
9423
    );
9424
    let back = Repo::clone(&origin.to_string_lossy(), &root.join("back")).unwrap();
9425
    for (i, f) in files.iter().enumerate() {
9426
        assert_eq!(&fs::read(root.join(format!("back/bin{i}.dat"))).unwrap(), f);
9427
    }
9428
    drop(back);
9429
}
9430
570e3531 Andy McCall ↶ 9431
/// oxygen#136: a bundle carries a replaced binary file's new content
9432
/// only. Its old content came with the change that added it, so removing
9433
/// or replacing a file sends no old blob again; the remote and a clone of
9434
/// it are whole.
9435
#[test]
9436
fn a_replacement_does_not_send_the_old_content_again() {
9437
    hermetic();
9438
    let dir = tempfile::tempdir().unwrap();
9439
    let root = dir.path();
9440
    let origin = root.join("origin");
9441
    Repo::init_bare_unbound(&origin).unwrap();
9442
    let main = root.join("main");
9443
    let mut repo = Repo::init(&main).unwrap();
9444
    repo.config
9445
        .set("remote.origin.url", &origin.to_string_lossy())
9446
        .unwrap();
9447
    repo.save_config().unwrap();
9448
    let blobs = |b: &Bundle| {
9449
        b.objects
9450
            .iter()
9451
            .filter(|(ty, _)| *ty == ObjectType::Blob)
9452
            .count()
9453
    };
9454
    write(&main, "bin.dat", b"\0\x01first binary");
9455
    write(&main, "gone.dat", b"\0\x02to be removed");
9456
    let added = repo.commit("add", &[]).unwrap();
9457
    assert!(repo.push("origin", false).unwrap()[0].ok);
9458
    write(&main, "bin.dat", b"\0\x01second binary");
9459
    fs::remove_file(main.join("gone.dat")).unwrap();
9460
    let changed = repo.commit("replace and remove", &[]).unwrap();
9461
    assert_eq!(blobs(&repo.bundle_for(&[changed]).unwrap()), 1);
9462
    assert_eq!(blobs(&repo.bundle_for(&[added, changed]).unwrap()), 3);
9463
    assert!(repo.push("origin", false).unwrap()[0].ok);
9464
    let origin = Repo::open(&origin).unwrap();
9465
    assert_eq!(origin.fsck().unwrap().problems, vec![]);
9466
    let back = Repo::clone(&origin.root().to_string_lossy(), &root.join("back")).unwrap();
9467
    assert_eq!(back.fsck().unwrap().problems, vec![]);
9468
    assert_eq!(
9469
        fs::read(root.join("back/bin.dat")).unwrap(),
9470
        b"\0\x01second binary"
9471
    );
9472
    assert!(!root.join("back/gone.dat").exists());
9473
}
9474
d6e0d5b8 Andy McCall ↶ 9475
/// oxygen#97: with `git.claim`, an import authors the importing identity's
9476
/// own commits (Git author email = its email, any case) with its key, and
9477
/// leaves anyone else's with the zero key; the history verifies as before.
9478
#[test]
9479
fn git_import_claims_your_own_commits() {
9480
    hermetic();
9481
    if std::process::Command::new("git")
9482
        .arg("--version")
9483
        .output()
9484
        .is_err()
9485
    {
9486
        eprintln!("git not installed; skipping");
9487
        return;
9488
    }
9489
    let dir = tempfile::tempdir().unwrap();
9490
    let root = dir.path();
9491
    let g = root.join("src.git");
9492
    fs::create_dir_all(&g).unwrap();
9493
    let git = |who: &str, args: &[&str]| {
9494
        let (name, email) = who.split_once(' ').unwrap();
9495
        let out = std::process::Command::new("git")
9496
            .arg("-C")
9497
            .arg(&g)
9498
            .args([
9499
                "-c",
9500
                &format!("user.name={name}"),
9501
                "-c",
9502
                &format!("user.email={email}"),
9503
                "-c",
9504
                "commit.gpgsign=false",
9505
            ])
9506
            .args(args)
9507
            .output()
9508
            .unwrap();
9509
        assert!(
9510
            out.status.success(),
9511
            "git {args:?}: {}",
9512
            String::from_utf8_lossy(&out.stderr)
9513
        );
9514
    };
9515
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
9516
    write(&g, "a.txt", b"a\n");
9517
    git("Grace [email protected]", &["add", "."]);
9518
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
9519
    write(&g, "b.txt", b"b\n");
9520
    git("Ada [email protected]", &["add", "."]);
9521
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
9522
9523
    let mut repo = Repo::init(&root.join("o")).unwrap();
9524
    let (key, _) = repo
9525
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
9526
        .unwrap();
9527
    repo.config.set("git.claim", "true").unwrap();
9528
    repo.save_config().unwrap();
9529
    let repo = Repo::open(&root.join("o")).unwrap();
9530
    repo.import_git(&g, "main").unwrap();
9531
    let v = repo.verify_git_import(&g, "main").unwrap();
9532
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9533
    let heads = repo.bookmark_heads().unwrap();
9534
    let by_message: std::collections::HashMap<String, KeyId> = repo
9535
        .log_state(&heads)
9536
        .unwrap()
9537
        .into_iter()
9538
        .map(|e| {
9539
            (
9540
                e.change.message.lines().next().unwrap_or("").to_string(),
9541
                e.change.author,
9542
            )
9543
        })
9544
        .collect();
9545
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
9546
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
9547
}
34fad4a9 Andy McCall ↶ 9548
9549
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
9550
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
9551
#[test]
9552
fn removing_a_remote_leaves_nothing_of_it() {
9553
    hermetic();
9554
    let dir = tempfile::tempdir().unwrap();
9555
    let origin = dir.path().join("origin");
9556
    Repo::init_bare_unbound(&origin).unwrap();
9557
    let main = dir.path().join("main");
9558
    let mut repo = Repo::init(&main).unwrap();
9559
    repo.config
9560
        .set("remote.origin.url", &origin.to_string_lossy())
9561
        .unwrap();
9562
    repo.config
9563
        .set("remote.origin.token", "secret-ish")
9564
        .unwrap();
9565
    repo.config
9566
        .set("remote.keep.url", &origin.to_string_lossy())
9567
        .unwrap();
9568
    repo.save_config().unwrap();
9569
    write(&main, "a.txt", b"a\n");
9570
    repo.commit("a", &[]).unwrap();
9571
    assert!(repo.push("origin", false).unwrap()[0].ok);
9572
    assert!(
9573
        repo.view().unwrap().remotes.contains_key("origin"),
9574
        "a tracking bookmark"
9575
    );
9576
9577
    repo.remove_remote("origin").unwrap();
9578
    let again = Repo::open(&main).unwrap();
9579
    assert!(
9580
        !again
9581
            .config
9582
            .repo_layer()
9583
            .keys()
9584
            .any(|k| k.starts_with("remote.origin.")),
9585
        "{:?}",
9586
        again.config.repo_layer()
9587
    );
9588
    assert!(!again.config.remotes.contains_key("origin"));
9589
    assert!(
9590
        !again.view().unwrap().remotes.contains_key("origin"),
9591
        "its tracking bookmarks go"
9592
    );
9593
    assert!(
9594
        again.config.remotes.contains_key("keep"),
9595
        "another remote stays"
9596
    );
9597
    let mut again = again;
9598
    assert!(
9599
        again.remove_remote("origin").is_err(),
9600
        "a second removal is refused"
9601
    );
9602
}
9d580f21 Andy McCall ↶ 9603
9604
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
9605
/// unreachable from history, so gc prunes it, unless the host names it:
9606
/// then it and its chunks stay, and it reads back whole.
9607
#[test]
9608
fn gc_keeps_the_blobs_a_host_names() {
9609
    hermetic();
9610
    let dir = tempfile::tempdir().unwrap();
9611
    let repo = Repo::init(dir.path()).unwrap();
9612
    write(dir.path(), "a.txt", b"a\n");
9613
    repo.commit("a", &[]).unwrap();
9614
    // Large enough to be several chunks.
9615
    let body: Vec<u8> = (0..400_000u32)
9616
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
9617
        .collect();
9618
    let kept = repo.store_blob(&body).unwrap();
9619
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
9620
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
9621
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
9622
    assert!(!repo.store().has(&lost), "not named: pruned");
9623
    repo.gc(true).unwrap();
9624
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
9625
}
530a0fc6 Andy McCall ↶ 9626
9627
/// oxygen#99: undo in one workspace undoes that workspace's last command,
9628
/// never another workspace's, says what it undid, and goes further back
9629
/// when run again.
9630
#[test]
9631
fn undo_is_scoped_to_its_workspace() {
9632
    hermetic();
9633
    let dir = tempfile::tempdir().unwrap();
9634
    let root = dir.path().join("main");
9635
    let a = Repo::init(&root).unwrap();
9636
    write(&root, "base.txt", b"base\n");
9637
    let base = a.commit("base", &[]).unwrap();
9638
    a.bookmark_create("feature", None).unwrap();
9639
    let ws_dir = dir.path().join("ws");
9640
    let heads = a.resolve_heads("feature").unwrap();
9641
    let b = a
9642
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
9643
        .unwrap();
9644
9645
    // A commits on main, then B commits on feature: B's is the newest.
9646
    write(&root, "a.txt", b"a\n");
9647
    let ca = a.commit("from a", &[]).unwrap();
9648
    write(&ws_dir, "b.txt", b"b\n");
9649
    let cb = b.commit("from b", &[]).unwrap();
9650
9651
    // A's undo undoes A's commit and leaves B's.
9652
    let u = a.undo().unwrap();
9653
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9654
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
9655
    assert!(!u.changes.is_empty());
9656
    let view = a.view().unwrap();
9657
    // (Independent changes commute, so a bookmark's heads may hold base too.)
9658
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
9659
    assert!(
9660
        a.heads_of(&view, "feature").unwrap().contains(&cb),
9661
        "B's commit stands"
9662
    );
9663
    assert!(
9664
        a.store().get_change(&ca).is_ok(),
9665
        "the change itself is still in the store"
9666
    );
9667
    // A's working copy was clean, so its files followed; B's are untouched.
9668
    assert!(!root.join("a.txt").exists());
9669
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
9670
    assert!(ws_dir.join("b.txt").exists());
9671
9672
    // B's undo still finds B's own commit, under A's undo.
9673
    let u = b.undo().unwrap();
9674
    assert_eq!(u.command, "oxy commit -m \"from b\"");
9675
    assert!(!b
9676
        .heads_of(&b.view().unwrap(), "feature")
9677
        .unwrap()
9678
        .contains(&cb));
9679
    assert_eq!(
9680
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
9681
        vec![base],
9682
        "A's undo stands"
9683
    );
9684
9685
    // A's next undo goes past the commit it already undid, to adding B's
9686
    // workspace: refused, since B has worked there since.
9687
    let e = a.undo().unwrap_err().to_string();
9688
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
9689
}
9690
9691
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
9692
/// own commit's head, and the other workspace's head stays.
9693
#[test]
9694
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
9695
    hermetic();
9696
    let dir = tempfile::tempdir().unwrap();
9697
    let root = dir.path().join("main");
9698
    let a = Repo::init(&root).unwrap();
9699
    write(&root, "base.txt", b"base\n");
9700
    a.commit("base", &[]).unwrap();
9701
    let ws_dir = dir.path().join("ws");
9702
    let b = a.workspace_add(&ws_dir, None).unwrap();
9703
    write(&root, "a.txt", b"a\n");
9704
    let ca = a.commit("from a", &[]).unwrap();
9705
    write(&ws_dir, "b.txt", b"b\n");
9706
    let cb = b.commit("from b", &[]).unwrap();
9707
    let u = a.undo().unwrap();
9708
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9709
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
9710
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
9711
}
9712
9713
/// oxygen#99: an undo that would also take back what another workspace
9714
/// did since to the same bookmark is refused, naming it.
9715
#[test]
9716
fn undo_refuses_to_take_back_another_workspaces_work() {
9717
    hermetic();
9718
    let dir = tempfile::tempdir().unwrap();
9719
    let root = dir.path().join("main");
9720
    let a = Repo::init(&root).unwrap();
9721
    write(&root, "base.txt", b"base\n");
9722
    a.commit("base", &[]).unwrap();
9723
    let ws_dir = dir.path().join("ws");
9724
    let b = a.workspace_add(&ws_dir, None).unwrap();
9725
    // Both on main: A commits, then B builds on it, editing A's file.
9726
    write(&root, "a.txt", b"a\n");
9727
    a.commit("from a", &[]).unwrap();
767ac6cd Andy McCall 9728
    b.refresh().unwrap();
530a0fc6 Andy McCall ↶ 9729
    let heads = b.resolve_heads("main").unwrap();
9730
    b.checkout(&heads, false, "oxy checkout").unwrap();
9731
    write(&ws_dir, "a.txt", b"a, then b\n");
9732
    b.commit("from b", &[]).unwrap();
9733
    let e = a.undo().unwrap_err().to_string();
9734
    assert!(
9735
        e.contains("bookmark main") && e.contains("builds on"),
9736
        "{e}"
9737
    );
9738
    assert!(e.contains("oxy op restore"), "{e}");
9739
}
9740
9741
/// oxygen#99: undoing a commit that was already pushed says so: the remote
9742
/// still has it.
9743
#[test]
9744
fn undo_says_when_the_commit_was_pushed() {
9745
    hermetic();
9746
    let dir = tempfile::tempdir().unwrap();
9747
    let root = dir.path();
9748
    Repo::init(&root.join("origin")).unwrap();
9749
    let url = root.join("origin").to_string_lossy().to_string();
9750
    let repo = Repo::clone(&url, &root.join("work"))
9751
        .unwrap()
9752
        .with_home(root.join("home"));
9753
    write(&root.join("work"), "a.txt", b"a\n");
9754
    repo.commit("a", &[]).unwrap();
9755
    assert!(repo.push("origin", false).unwrap()[0].ok);
9756
    // The push itself is passed over: the remote keeps what it was sent.
9757
    let u = repo.undo().unwrap();
9758
    assert_eq!(u.command, "oxy commit -m \"a\"");
9759
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
9760
}
b689779e Andy McCall ↶ 9761
9762
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
9763
/// out of the snapshot and named; tracked files and files already in the
9764
/// working copy are not.
9765
#[test]
9766
fn large_new_files_are_left_out_of_snapshots() {
9767
    hermetic();
9768
    let dir = tempfile::tempdir().unwrap();
9769
    let root = dir.path();
9770
    let mut repo = Repo::init(root).unwrap();
9771
    repo.config.max_new_file = 1024;
9772
    write(root, "small.txt", b"small\n");
9773
    write(root, "big.bin", &vec![0u8; 4096]);
9774
    let s = repo.snapshot("oxy status").unwrap();
9775
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9776
    assert_eq!(paths, ["small.txt"]);
9777
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
9778
    repo.commit("small", &[]).unwrap();
9779
9780
    // A tracked file may grow past the limit.
9781
    write(root, "small.txt", &vec![b'x'; 4096]);
9782
    let s = repo.snapshot("oxy status").unwrap();
9783
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
9784
    // With no limit the big file is taken in, and stays once it is.
9785
    repo.config.max_new_file = 0;
9786
    let s = repo.snapshot("oxy status").unwrap();
9787
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
9788
    repo.config.max_new_file = 1024;
9789
    let s = repo.snapshot("oxy status").unwrap();
9790
    assert!(
9791
        s.statuses.iter().any(|p| p.path == "big.bin"),
9792
        "already in the working copy"
9793
    );
9794
    assert!(repo.skipped_large().is_empty());
9795
}
9796
9797
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
9798
/// snapshots expire, and kept while they have not.
9799
#[test]
9800
fn gc_prunes_what_only_expired_snapshots_held() {
9801
    hermetic();
9802
    let dir = tempfile::tempdir().unwrap();
9803
    let root = dir.path();
9804
    let mut repo = Repo::init(root).unwrap();
9805
    repo.config.gc_grace_days = 0;
9806
    write(root, "a.txt", b"a\n");
9807
    repo.commit("a", &[]).unwrap();
9808
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
9809
    write(root, "image.tar", &image);
9810
    repo.snapshot("oxy status").unwrap();
9811
    std::fs::remove_file(root.join("image.tar")).unwrap();
9812
    repo.snapshot("oxy status").unwrap();
9813
    let blob = Repo::blob_ref(&image);
9814
    assert!(repo.store().has(&blob));
9815
    repo.gc(true).unwrap();
9816
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
9817
    repo.config.snapshot_retention_days = 0;
9818
    repo.gc(true).unwrap();
9819
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
9820
    assert_eq!(
9821
        repo.file_at("a.txt", None).unwrap(),
9822
        b"a\n",
9823
        "committed files stay"
9824
    );
fe9586d9 Andy McCall ↶ 9825
}
9826
9827
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
9828
/// already has is no conflict: the switch goes through, nothing is lost,
9829
/// and other carried work still comes along.
9830
#[test]
9831
fn carrying_work_the_target_already_has_is_no_conflict() {
9832
    hermetic();
9833
    let dir = tempfile::tempdir().unwrap();
9834
    let root = dir.path();
9835
    let mut repo = Repo::init(root).unwrap();
9836
    write(root, "a.txt", b"one\n");
9837
    write(root, "b.txt", b"b\n");
9838
    repo.commit("one", &[]).unwrap();
9839
    repo.bookmark_create("landed", None).unwrap();
9840
    // On landed, a.txt becomes "two" (as a proposal landing would).
9841
    repo.bookmark_switch("landed", false).unwrap();
9842
    write(root, "a.txt", b"two\n");
9843
    repo.commit("two", &[]).unwrap();
9844
    repo.bookmark_switch("main", false).unwrap();
9845
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
9846
    // The same edit, uncommitted, on main; and another edit besides.
9847
    write(root, "a.txt", b"two\n");
9848
    write(root, "b.txt", b"b, edited\n");
9849
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
9850
    assert_eq!(
9851
        carried,
9852
        vec!["b.txt".to_string()],
9853
        "only the work landed lacks is carried"
9854
    );
9855
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
9856
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
9857
    let s = repo.snapshot("oxy status").unwrap();
9858
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9859
    assert_eq!(paths, ["b.txt"]);
9860
9861
    // A real difference is still refused.
9862
    repo.bookmark_switch("main", true).unwrap();
9863
    write(root, "a.txt", b"three\n");
9864
    let e = repo
9865
        .bookmark_switch_carry("landed")
9866
        .unwrap_err()
9867
        .to_string();
9868
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
b689779e Andy McCall ↶ 9869
}
aa4939e0 Andy McCall ↶ 9870
9871
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
9872
/// resolves, so JSON output feeds back into commands.
9873
#[test]
9874
fn a_full_hash_resolves_without_its_hash_sign() {
9875
    hermetic();
9876
    let dir = tempfile::tempdir().unwrap();
9877
    let root = dir.path();
9878
    let repo = Repo::init(root).unwrap();
9879
    write(root, "a.txt", b"a\n");
9880
    let h = repo.commit("a", &[]).unwrap();
9881
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
9882
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
9883
    assert!(repo
9884
        .resolve_change(&"0".repeat(64))
9885
        .unwrap_err()
9886
        .to_string()
9887
        .contains("no change matches"));
9888
}
f2f91ceb Andy McCall ↶ 9889
9890
#[test]
9891
fn a_pin_change_moves_only_the_pin() {
9892
    hermetic();
9893
    let dir = tempfile::tempdir().unwrap();
9894
    let root = dir.path();
9895
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9896
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9897
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9898
        .unwrap()
9899
        .with_home(root.join("home"));
9900
    write(&root.join("lib"), "lib.txt", b"v1\n");
9901
    lib.commit("lib v1", &[]).unwrap();
9902
    assert!(lib.push("origin", false).unwrap()[0].ok);
9903
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
9904
    let app_dir = root.join("app");
9905
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
9906
        .unwrap()
9907
        .with_home(root.join("home"));
9908
    write(&app_dir, "main.txt", b"app\n");
9909
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9910
    let a1 = app.commit("app with lib", &[]).unwrap();
9911
    // The library moves on.
9912
    write(&root.join("lib"), "more.txt", b"v2\n");
9913
    let l2 = lib.commit("lib v2", &[]).unwrap();
9914
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
9915
        panic!("an Oxygen pin")
9916
    };
9917
    let pin2 = crate::subrepo::Pin::Oxy {
9918
        repo,
9919
        heads: vec![l2],
9920
        bookmark,
9921
    };
9922
    let author = app.store().get_change(&a1).unwrap().author;
9923
    let change = app
9924
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
9925
        .unwrap();
9926
    let mut state = app.load_state(&[a1]).unwrap();
9927
    state.add(change).unwrap();
9928
    let files = state.materialize().files;
9929
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
9930
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
9931
        panic!("a pin is opaque")
9932
    };
9933
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
9934
    assert_eq!(read, pin2, "the new pin");
9935
    assert!(
9936
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
9937
        "nothing else changes"
9938
    );
9939
    // Only a subrepo's pin can be moved this way.
9940
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
9941
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
9942
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
9943
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
9944
}
767ac6cd Andy McCall 9945
9946
/// oxygenhub#249: a handle reads the operation head once and keeps it,
9947
/// so one command or request never mixes two heads; another handle's
9948
/// operation shows only after `refresh`. Its own operations move it, and
9949
/// one recorded from the head it kept merges with what landed since, as
9950
/// any concurrent operation does.
9951
#[test]
9952
fn one_handle_keeps_one_head_until_it_refreshes() {
9953
    hermetic();
9954
    let dir = tempfile::tempdir().unwrap();
9955
    let root = dir.path();
9956
    let writer = Repo::init(root).unwrap();
9957
    write(root, "a.txt", b"one\n");
9958
    let h1 = writer.commit("one", &[]).unwrap();
9959
    let reader = Repo::open(root).unwrap();
9960
    let before = reader.view().unwrap();
9961
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9962
    write(root, "a.txt", b"two\n");
9963
    let h2 = writer.commit("two", &[]).unwrap();
9964
    assert_eq!(
9965
        writer.bookmark_heads().unwrap(),
9966
        vec![h2],
9967
        "its own operation"
9968
    );
9969
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
9970
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
9971
    reader.refresh().unwrap();
9972
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
9973
9974
    // A handle recording from an older head merges with the newer one.
9975
    let stale = Repo::open(root).unwrap();
9976
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
9977
    write(root, "a.txt", b"three\n");
9978
    let h3 = writer.commit("three", &[]).unwrap();
9979
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
9980
    let view = stale.view().unwrap();
9981
    assert!(view.bookmarks.contains_key("feature"));
9982
    assert_eq!(
9983
        stale.bookmark_heads().unwrap(),
9984
        vec![h3],
9985
        "merged, not lost"
9986
    );
9987
    let fresh = Repo::open(root).unwrap();
9988
    assert_eq!(fresh.view().unwrap(), view);
9989
}
9990
9991
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
9992
#[test]
9993
fn over_a_store_one_handle_keeps_one_head() {
9994
    hermetic();
9995
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
9996
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9997
    let dir = tempfile::tempdir().unwrap();
9998
    let a = Repo::init(dir.path()).unwrap();
9999
    let (h0, _) = a.head_op().unwrap();
10000
    let b = Repo::open(dir.path()).unwrap();
10001
    assert_eq!(b.head_op().unwrap().0, h0);
10002
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
10003
    let mut view = a.view().unwrap();
10004
    view.bookmarks.insert("x".into(), state);
10005
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
10006
    assert_eq!(a.head_op().unwrap().0, r);
10007
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
10008
    b.refresh().unwrap();
10009
    assert_eq!(b.head_op().unwrap().0, r);
10010
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
10011
}
10012
10013
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
10014
/// reader opened before reads on, then and after the next gc deletes the
10015
/// retired files once their hour is up. Younger ones are kept.
10016
#[test]
10017
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
10018
    hermetic();
10019
    let dir = tempfile::tempdir().unwrap();
10020
    let root = dir.path();
10021
    let repo = Repo::init(root).unwrap();
10022
    let mut heads = Vec::new();
10023
    for i in 0..4 {
10024
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
10025
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
10026
    }
10027
    let reader = Repo::open(root).unwrap();
10028
    assert_eq!(reader.log().unwrap().len(), 5);
10029
    let r = repo.gc(true).unwrap();
10030
    assert_eq!(r.retired, crate::store::RetiredReport::default());
10031
    assert_eq!(repo.store().loose_count().unwrap(), 0);
10032
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
10033
    // Nothing is an hour old yet: a gc keeps it all.
10034
    let r = repo.gc(true).unwrap();
10035
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
10036
    assert!(r.retired.kept > 0, "{r:?}");
10037
    write(root, "f9.txt", b"9\n");
10038
    heads.push(repo.commit("c9", &[]).unwrap());
10039
    crate::store::reader_tests::age_retired(
10040
        repo.store(),
10041
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
10042
    );
10043
    let r = repo.gc(true).unwrap();
10044
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
10045
    assert_eq!(r.retired.kept, 0, "{r:?}");
10046
    let r = repo.gc(true).unwrap();
10047
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
10048
    assert!(r.retired.kept > 0, "what the last gc retired is young");
10049
    // The reader opened before all of it still reads everything, from
10050
    // the packs it finds when what it loaded is gone.
10051
    assert_eq!(reader.log().unwrap().len(), 5);
10052
    for h in &heads[..4] {
10053
        reader.store().get_change(h).unwrap();
10054
    }
10055
    reader.refresh().unwrap();
10056
    assert_eq!(reader.log().unwrap().len(), 6);
10057
    let fresh = Repo::open(root).unwrap();
10058
    assert_eq!(
10059
        fresh.store().pack_count(),
10060
        1,
10061
        "retired packs are not loaded"
10062
    );
10063
}
10064
10065
/// oxygenhub#249: a repository opens when its store's pack listing names
10066
/// an index that is not there (deleted between the listing and the read).
10067
#[test]
10068
fn a_repository_opens_when_a_listed_index_is_gone() {
10069
    hermetic();
10070
    let backend = crate::store::reader_tests::racing(true);
10071
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
10072
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
10073
    let dir = tempfile::tempdir().unwrap();
10074
    let repo = Repo::init(dir.path()).unwrap();
10075
    write(dir.path(), "a.txt", b"a\n");
10076
    let h = repo.commit("a", &[]).unwrap();
10077
    repo.gc(true).unwrap();
10078
    let again = Repo::open(dir.path()).unwrap();
10079
    assert_eq!(again.store().pack_count(), 1);
10080
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
10081
    // And when one is deleted between the listing and the read: a copy of
10082
    // the live pack, whose index goes as the store opens.
10083
    use crate::strata::Store as _;
10084
    let idx = backend
10085
        .list("pack-")
10086
        .unwrap()
10087
        .into_iter()
10088
        .map(|e| e.key)
10089
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
10090
        .unwrap();
10091
    let stem = idx.trim_end_matches(".idx");
10092
    for ext in ["pack", "idx"] {
10093
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
10094
        backend
10095
            .put_new(&format!("pack-copy.{ext}"), &bytes)
10096
            .unwrap();
10097
    }
10098
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
10099
    let again = Repo::open(dir.path()).unwrap();
10100
    assert_eq!(again.store().pack_count(), 1);
10101
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
10102
    assert!(!backend.has("pack-copy.idx").unwrap());
10103
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
10104
}