OXYGENHUB
# 028545dfa7a4 oxygen / crates / oxy-core / src / repo / tests.rs
335.0 KiB · Rust · last changed Trusted time: judge a fetched attestation at its integrated time 19 days ago source blame history raw
98286406 Andy McCall ↶ 1
//! Tests for the repository layer.
2
3
use super::*;
75167672 Andy McCall 4
use crate::protocol::SignedPolicy;
957fee30 Andy McCall ↶ 5
use crate::repo::{BisectStep, Selection};
98286406 Andy McCall ↶ 6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
75167672 Andy McCall 26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
98286406 Andy McCall ↶ 30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
75167672 Andy McCall 80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
98286406 Andy McCall ↶ 85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
75167672 Andy McCall 103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
98286406 Andy McCall ↶ 108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
75167672 Andy McCall 114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
98286406 Andy McCall ↶ 121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
137
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
138
    assert!(d.contains("-fn main() {}"), "{d}");
139
140
    // Resolution by prefix.
141
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
75167672 Andy McCall 142
    assert_eq!(
143
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
144
        h1
145
    );
98286406 Andy McCall ↶ 146
    assert!(repo.resolve_change("zzzz").is_err());
147
148
    // Undo the commit: bookmark and working copy go back.
149
    repo.undo().unwrap();
150
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
151
    let s = repo.snapshot("oxy status").unwrap();
75167672 Andy McCall 152
    assert!(
153
        !s.changed,
154
        "files on disk still match the pre-commit working copy"
155
    );
98286406 Andy McCall ↶ 156
    assert_eq!(s.statuses.len(), 3);
157
}
158
159
/// Make `main` conflicted: two commits on the same base that edit the same line.
160
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
161
    let dir = tempfile::tempdir().unwrap();
162
    let root = dir.path();
163
    let repo = Repo::init(root).unwrap();
164
    write(root, "f.txt", b"a\nb\nc\n");
165
    let h1 = repo.commit("base", &[]).unwrap();
166
    write(root, "f.txt", b"a\nB\nc\n");
167
    let h2 = repo.commit("upper", &[]).unwrap();
168
    repo.checkout(&[h1], false, "checkout").unwrap();
169
    write(root, "f.txt", b"a\nX\nc\n");
170
    let h3 = repo.commit("ex", &[]).unwrap();
171
    (dir, repo, h1, h2, h3)
172
}
173
174
#[test]
175
fn concurrent_edits_conflict_and_can_be_resolved() {
176
    hermetic();
177
    let (dir, repo, h1, h2, h3) = conflicted_repo();
178
    let root = dir.path();
179
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
180
    assert_eq!(heads, [h2, h3].into_iter().collect());
181
    let st = repo.load_state(&[h2, h3]).unwrap();
182
    assert!(st.materialize().is_conflicted());
183
184
    // Checking out main writes markers.
75167672 Andy McCall 185
    let r = repo
186
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
187
        .unwrap();
98286406 Andy McCall ↶ 188
    assert!(r.conflicted);
189
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 190
    assert!(
191
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
192
        "{marked}"
193
    );
194
    assert!(
195
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
196
        "{marked}"
197
    );
98286406 Andy McCall ↶ 198
    assert!(has_conflict_markers(marked.as_bytes()));
199
    // Untouched markers: clean working copy; commit has nothing to do.
200
    let s = repo.snapshot("status").unwrap();
201
    assert!(s.statuses.is_empty());
202
    assert!(!s.resolves);
203
204
    // Partially edited file that still has markers cannot be committed.
205
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
206
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 207
    assert_eq!(
208
        statuses(&s),
209
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
210
    );
98286406 Andy McCall ↶ 211
    assert!(repo.commit("no", &[]).is_err());
212
213
    // Resolve by keeping one side and adding a line elsewhere.
214
    write(root, "f.txt", b"a\nX\nc\nd\n");
215
    let s = repo.snapshot("status").unwrap();
216
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
217
    assert!(s.resolves);
218
    let h4 = repo.commit("resolve", &[]).unwrap();
219
    let c4 = repo.store().get_change(&h4).unwrap();
220
    assert_eq!(c4.kind, ChangeKind::Resolution);
221
    let mut want = vec![h1, h2, h3];
222
    want.sort();
75167672 Andy McCall 223
    assert_eq!(
224
        c4.deps, want,
225
        "a resolution depends on exactly the contributors and what it references"
226
    );
98286406 Andy McCall ↶ 227
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
228
    let snap = repo.load_state(&[h4]).unwrap().materialize();
229
    assert!(!snap.is_conflicted());
75167672 Andy McCall 230
    assert!(
231
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
232
    );
98286406 Andy McCall ↶ 233
    assert!(!repo.snapshot("status").unwrap().changed);
234
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
235
    // whatever order the changes arrive in.
236
    let mut st = State::new();
237
    for h in [h4, h3, h1, h2] {
238
        st.add_unchecked(repo.store().get_change(&h).unwrap());
239
    }
240
    st.validate().unwrap();
75167672 Andy McCall 241
    assert!(
242
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
243
    );
98286406 Andy McCall ↶ 244
}
245
246
#[test]
247
fn resolution_may_keep_both_sides_or_neither() {
248
    hermetic();
249
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
250
    let root = dir.path();
75167672 Andy McCall 251
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
252
        .unwrap();
98286406 Andy McCall ↶ 253
    // Keep both sides in a chosen order.
254
    write(root, "f.txt", b"a\nX\nB\nc\n");
255
    let h = repo.commit("both", &[]).unwrap();
256
    let snap = repo.load_state(&[h]).unwrap().materialize();
257
    assert!(!snap.is_conflicted());
75167672 Andy McCall 258
    assert!(
259
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
260
    );
98286406 Andy McCall ↶ 261
    // Undo and instead drop the whole region.
262
    repo.undo().unwrap();
263
    write(root, "f.txt", b"a\nc\n");
264
    let h = repo.commit("neither", &[]).unwrap();
265
    let snap = repo.load_state(&[h]).unwrap().materialize();
266
    assert!(!snap.is_conflicted());
75167672 Andy McCall 267
    assert!(
268
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
269
    );
98286406 Andy McCall ↶ 270
}
271
272
#[test]
273
fn name_conflict_resolved_by_removing_a_candidate() {
274
    hermetic();
275
    let dir = tempfile::tempdir().unwrap();
276
    let root = dir.path();
277
    let repo = Repo::init(root).unwrap();
278
    write(root, "keep.txt", b"k\n");
279
    let h1 = repo.commit("base", &[]).unwrap();
280
    write(root, "new.txt", b"one\n");
281
    repo.commit("one", &[]).unwrap();
282
    repo.checkout(&[h1], false, "checkout").unwrap();
283
    write(root, "new.txt", b"two\n");
284
    repo.commit("two", &[]).unwrap();
75167672 Andy McCall 285
    let r = repo
286
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
287
        .unwrap();
98286406 Andy McCall ↶ 288
    assert!(r.conflicted);
75167672 Andy McCall 289
    assert!(
290
        root.join("new.txt.oxy-conflict-1").exists()
291
            && root.join("new.txt.oxy-conflict-2").exists()
292
    );
98286406 Andy McCall ↶ 293
    assert!(!root.join("new.txt").exists());
294
    // Candidate numbering follows change-hash order, so pick by content:
295
    // keep the "two" candidate under the real name and drop the other.
75167672 Andy McCall 296
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
297
        (1, 2)
298
    } else {
299
        (2, 1)
300
    };
98286406 Andy McCall ↶ 301
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
75167672 Andy McCall 302
    fs::rename(
303
        root.join(format!("new.txt.oxy-conflict-{keep}")),
304
        root.join("new.txt"),
305
    )
306
    .unwrap();
98286406 Andy McCall ↶ 307
    let h = repo.commit("pick two", &[]).unwrap();
75167672 Andy McCall 308
    assert_eq!(
309
        repo.store().get_change(&h).unwrap().kind,
310
        ChangeKind::Resolution
311
    );
98286406 Andy McCall ↶ 312
    // The resolution does not touch keep.txt, so it does not depend on h1;
313
    // the bookmark keeps both as heads and their union is the state.
314
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
315
    assert_eq!(heads, [h1, h].into_iter().collect());
75167672 Andy McCall 316
    let snap = repo
317
        .load_state(&repo.bookmark_heads().unwrap())
318
        .unwrap()
319
        .materialize();
98286406 Andy McCall ↶ 320
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
75167672 Andy McCall 321
    assert_eq!(
322
        snap.files.keys().cloned().collect::<Vec<_>>(),
323
        ["keep.txt", "new.txt"]
324
    );
325
    assert!(
326
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
327
    );
98286406 Andy McCall ↶ 328
}
329
330
#[test]
331
fn identities_and_signed_commits() {
332
    hermetic();
333
    let dir = tempfile::tempdir().unwrap();
334
    let root = dir.path();
335
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
336
    write(root, "a.txt", b"a\n");
337
    let h0 = repo.commit("unsigned", &[]).unwrap();
338
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
75167672 Andy McCall 339
    assert_eq!(
340
        repo.store().get_change(&h0).unwrap().author,
341
        ObjectRef::ZERO
342
    );
98286406 Andy McCall ↶ 343
75167672 Andy McCall 344
    let (key, id) = repo
345
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
346
        .unwrap();
98286406 Andy McCall ↶ 347
    assert_eq!(id.hash(), key);
348
    assert_eq!(repo.config.author_key, Some(key));
349
    // Config survives reopen; the secret key is found again.
350
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
351
    assert_eq!(reopened.config.author_key, Some(key));
352
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
353
354
    // Default core.sign = seal: commits carry the author but no signature.
355
    write(root, "a.txt", b"a\nb\n");
356
    let h1 = repo.commit("authored", &[]).unwrap();
357
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
358
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
359
    // Signing later works too.
360
    repo.sign_change(&h1).unwrap();
75167672 Andy McCall 361
    assert!(
362
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
363
    );
98286406 Andy McCall ↶ 364
365
    repo.config.set("core.sign", "change").unwrap();
366
    repo.save_config().unwrap();
367
    write(root, "a.txt", b"a\nb\nc\n");
368
    let h2 = repo.commit("signed", &[]).unwrap();
75167672 Andy McCall 369
    assert_eq!(
370
        repo.verify_change(&h2).unwrap(),
371
        SignatureStatus::Valid {
372
            key,
373
            name: "Ada".into(),
374
            email: "[email protected]".into(),
375
            sealed: false,
376
            revoked: false
377
        }
378
    );
98286406 Andy McCall ↶ 379
05e71ed6 Andy McCall ↶ 380
    // A signature by a key that is not the author or a delegate is rejected
381
    // when the change names an author; an anonymous change (made before any
382
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
98286406 Andy McCall ↶ 383
    let other = SecretKey::generate();
384
    let other_id = other.identity("Mallory", "[email protected]", 0);
385
    let other_key = repo.store().put_identity(&other_id).unwrap();
05e71ed6 Andy McCall ↶ 386
    write(root, "a.txt", b"a\nb\nc\nd\n");
387
    repo.config.set("core.sign", "seal").unwrap();
388
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
389
    let forged = other.sign(Domain::Change, &other_key, &h3);
390
    repo.store().put_signature(&h3, &forged).unwrap();
75167672 Andy McCall 391
    assert!(
05e71ed6 Andy McCall ↶ 392
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
75167672 Andy McCall 393
    );
05e71ed6 Andy McCall ↶ 394
    let adopted = other.sign(Domain::Change, &other_key, &h0);
395
    repo.store().put_signature(&h0, &adopted).unwrap();
396
    assert!(
397
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
398
    );
98286406 Andy McCall ↶ 399
400
    // Tampering with the stored signature invalidates it.
401
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
402
    sig.ed[0] ^= 1;
403
    repo.store().put_signature(&h2, &sig).unwrap();
75167672 Andy McCall 404
    assert!(matches!(
405
        repo.verify_change(&h2).unwrap(),
406
        SignatureStatus::Invalid(_)
407
    ));
98286406 Andy McCall ↶ 408
409
    // Without the secret key, signing at commit fails cleanly.
410
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
411
    write(root, "a.txt", b"z\n");
412
    assert!(no_keys.commit("cannot sign", &[]).is_err());
413
}
414
415
#[test]
416
fn checkout_moves_the_working_copy() {
417
    hermetic();
418
    let dir = tempfile::tempdir().unwrap();
419
    let root = dir.path();
420
    let repo = Repo::init(root).unwrap();
421
    write(root, "a.txt", b"one\n");
422
    write(root, "sub/deep/b.txt", b"b\n");
423
    let h1 = repo.commit("first", &[]).unwrap();
424
    write(root, "a.txt", b"two\n");
425
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
426
    write(root, "bin.dat", &[0, 1, 2, 3]);
427
    let h2 = repo.commit("second", &[]).unwrap();
428
429
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
75167672 Andy McCall 430
    assert_eq!(
431
        r,
432
        CheckoutReport {
433
            written: 2,
434
            removed: 1,
435
            conflicted: false,
d3cd7ef9 Andy McCall ↶ 436
            notes: vec![],
437
            lacks: 1,
75167672 Andy McCall 438
        }
439
    );
98286406 Andy McCall ↶ 440
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
441
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
442
    assert!(!root.join("bin.dat").exists());
443
    let (_, wc) = repo.working_copy().unwrap();
444
    assert_eq!(wc.deps, vec![h1]);
75167672 Andy McCall 445
    assert!(
446
        !repo.snapshot("status").unwrap().changed,
447
        "checkout leaves a clean working copy"
448
    );
98286406 Andy McCall ↶ 449
    // The bookmark still points at h2.
450
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
451
452
    // Dirty working copy refuses without --discard.
453
    write(root, "a.txt", b"dirty\n");
454
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
75167672 Andy McCall 455
    let r = repo
456
        .checkout(&[h2], true, "oxy checkout --discard")
457
        .unwrap();
98286406 Andy McCall ↶ 458
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
459
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
460
    assert!(!root.join("sub").exists(), "empty directories are pruned");
461
    assert_eq!(r.removed, 1);
462
    assert!(!repo.snapshot("status").unwrap().changed);
463
464
    // Refuses to write through a symlinked directory.
465
    #[cfg(unix)]
466
    {
467
        fs::remove_dir_all(root.join("sub")).ok();
468
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
469
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
470
    }
471
}
472
473
#[test]
474
fn large_files_are_chunked_and_read_back() {
475
    hermetic();
476
    let dir = tempfile::tempdir().unwrap();
477
    let repo = Repo::init(dir.path()).unwrap();
478
    let mut big = vec![0u8; 700 * 1024];
479
    for (i, b) in big.iter_mut().enumerate() {
480
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
481
    }
482
    let r = repo.store_blob(&big).unwrap();
483
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
484
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
485
    assert_eq!(repo.read_blob(&r).unwrap(), big);
486
    assert_eq!(Repo::blob_ref(&big), r);
487
}
488
489
#[test]
490
fn clone_push_pull_with_seals_and_attestations() {
491
    hermetic();
492
    let dir = tempfile::tempdir().unwrap();
493
    let root = dir.path();
494
    let origin_path = root.join("origin");
495
    let origin = Repo::init(&origin_path).unwrap();
496
    let origin_url = origin_path.to_string_lossy().to_string();
497
498
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
75167672 Andy McCall 499
    let mut a = Repo::clone(&origin_url, &root.join("a"))
500
        .unwrap()
501
        .with_home(root.join("home-a"));
98286406 Andy McCall ↶ 502
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
75167672 Andy McCall 503
    let (key_a, _) = a
504
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
505
        .unwrap();
98286406 Andy McCall ↶ 506
    write(&root.join("a"), "f.txt", b"a\n");
507
    let h1 = a.commit("first", &[]).unwrap();
508
    let results = a.push("origin", false).unwrap();
509
    assert!(results[0].ok, "{}", results[0].reason);
510
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
511
    // The change was sealed at push and the reference attested.
75167672 Andy McCall 512
    assert!(
513
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
514
    );
515
    assert_eq!(
516
        origin.verify_change(&h1).unwrap(),
517
        SignatureStatus::Unsigned
518
    );
f8c69576 Andy McCall ↶ 519
    let serial_of = |att: &SignedAttest| match att.attest.body {
520
        AttestBody::Ref { serial, .. } => serial,
521
        _ => unreachable!(),
522
    };
98286406 Andy McCall ↶ 523
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 524
    // A bookmark new to the remote starts at the clock (past any deleted
525
    // namesake's serial); later updates count up from there.
526
    let first = serial_of(&att);
527
    assert!(first > 1_000_000_000_000, "{first}");
98286406 Andy McCall ↶ 528
    let again = a.push("origin", false).unwrap();
529
    assert!(again[0].ok && again[0].reason.contains("up to date"));
530
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 531
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
98286406 Andy McCall ↶ 532
533
    // B clones and sees the file and the seal.
534
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
535
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
536
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
75167672 Andy McCall 537
    assert!(matches!(
538
        b.authenticate_change(&h1).unwrap(),
539
        SignatureStatus::Valid { sealed: true, .. }
540
    ));
98286406 Andy McCall ↶ 541
542
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
543
    write(&root.join("b"), "f.txt", b"a\nb\n");
544
    let h2 = b.commit("second", &[]).unwrap();
545
    assert!(b.push("origin", false).unwrap()[0].ok);
546
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
547
548
    // A commits an independent change; push is refused until A pulls.
549
    write(&root.join("a"), "g.txt", b"g\n");
550
    let h3 = a.commit("third", &[]).unwrap();
551
    assert!(a.push("origin", false).is_err());
552
    let pr = a.pull("origin").unwrap();
553
    assert!(pr.changed && pr.checked_out);
554
    let mut want = vec![h2, h3];
555
    want.sort();
556
    assert_eq!(pr.heads, want);
557
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
558
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
559
    let results = a.push("origin", false).unwrap();
560
    assert!(results[0].ok, "{}", results[0].reason);
561
    let mut origin_heads = origin.bookmark_heads().unwrap();
562
    origin_heads.sort();
563
    assert_eq!(origin_heads, want);
564
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 565
    assert_eq!(serial_of(&att), first + 1);
98286406 Andy McCall ↶ 566
567
    // B pulls and ends up identical.
568
    let pr = b.pull("origin").unwrap();
569
    assert_eq!(pr.heads, want);
570
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
571
    assert!(!b.snapshot("status").unwrap().changed);
572
573
    // Concurrent edits of the same line: the union is a reified conflict.
574
    write(&root.join("a"), "f.txt", b"a\nA\n");
575
    a.commit("a-edit", &[]).unwrap();
576
    a.push("origin", false).unwrap();
577
    write(&root.join("b"), "f.txt", b"a\nB\n");
578
    b.commit("b-edit", &[]).unwrap();
579
    let pr = b.pull("origin").unwrap();
580
    assert!(pr.changed && pr.checked_out);
581
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
582
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
583
    write(&root.join("b"), "f.txt", b"a\nAB\n");
584
    let hr = b.commit("resolve", &[]).unwrap();
75167672 Andy McCall 585
    assert_eq!(
586
        b.store().get_change(&hr).unwrap().kind,
587
        ChangeKind::Resolution
588
    );
98286406 Andy McCall ↶ 589
    assert!(b.push("origin", false).unwrap()[0].ok);
590
    a.pull("origin").unwrap();
591
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
592
    // The resolution depends on the conflicting edits, but nothing depends
593
    // on "third" (it only added g.txt), so it stays a head beside it.
594
    let mut want = vec![hr, h3];
595
    want.sort();
596
    assert_eq!(a.bookmark_heads().unwrap(), want);
597
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
598
}
599
600
#[test]
601
fn receive_push_rejects_bad_updates() {
602
    hermetic();
603
    let dir = tempfile::tempdir().unwrap();
604
    let root = dir.path();
605
    let origin = Repo::init(&root.join("origin")).unwrap();
606
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 607
    let mut a = Repo::clone(&url, &root.join("a"))
608
        .unwrap()
609
        .with_home(root.join("home"));
610
    let (key, _) = a
611
        .create_identity("Ada", "a@b", IdentityScope::Repo)
612
        .unwrap();
98286406 Andy McCall ↶ 613
    write(&root.join("a"), "f.txt", b"x\n");
614
    let h1 = a.commit("one", &[]).unwrap();
615
    assert!(a.push("origin", false).unwrap()[0].ok);
616
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
75167672 Andy McCall 617
    let s1 = origin
618
        .store()
619
        .put_state(&StateObject::new(vec![h1]))
620
        .unwrap();
98286406 Andy McCall ↶ 621
622
    // Missing head.
75167672 Andy McCall 623
    let ghost = origin
624
        .store()
625
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
626
        .unwrap();
627
    let r = origin
628
        .receive_push(
629
            Bundle::default(),
630
            vec![RefUpdate {
631
                name: "main".into(),
632
                old_state: s1,
633
                new_state: ghost,
634
                force: false,
635
                attestation: None,
636
            }],
637
            None,
638
            vec![],
639
        )
640
        .unwrap();
641
    assert!(
642
        !r[0].ok && r[0].reason.contains("missing"),
643
        "{}",
644
        r[0].reason
645
    );
98286406 Andy McCall ↶ 646
647
    // Stale old_state.
75167672 Andy McCall 648
    let r = origin
649
        .receive_push(
650
            Bundle::default(),
651
            vec![RefUpdate {
652
                name: "main".into(),
653
                old_state: empty,
654
                new_state: s1,
655
                force: false,
656
                attestation: None,
657
            }],
658
            None,
659
            vec![],
660
        )
661
        .unwrap();
98286406 Andy McCall ↶ 662
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
663
664
    // Non-fast-forward without force is refused; with force it passes.
75167672 Andy McCall 665
    let r = origin
666
        .receive_push(
667
            Bundle::default(),
668
            vec![RefUpdate {
669
                name: "main".into(),
670
                old_state: s1,
671
                new_state: empty,
672
                force: false,
673
                attestation: None,
674
            }],
675
            None,
676
            vec![],
677
        )
678
        .unwrap();
679
    assert!(
680
        !r[0].ok && r[0].reason.contains("fast-forward"),
681
        "{}",
682
        r[0].reason
683
    );
684
    let r = origin
685
        .receive_push(
686
            Bundle::default(),
687
            vec![RefUpdate {
688
                name: "main".into(),
689
                old_state: s1,
690
                new_state: empty,
691
                force: true,
692
                attestation: None,
693
            }],
694
            None,
695
            vec![],
696
        )
697
        .unwrap();
98286406 Andy McCall ↶ 698
    assert!(r[0].ok);
699
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
700
701
    // Attestation with a stale serial is a rollback and is refused.
75167672 Andy McCall 702
    let sa = a
703
        .sign_attest(&Attest {
704
            repo: a.id().unwrap(),
705
            hlc: Hlc::now(),
706
            body: AttestBody::Ref {
707
                name: "main".into(),
708
                old_state: empty,
709
                new_state: s1,
710
                serial: 1,
711
            },
712
        })
713
        .unwrap();
714
    let r = origin
715
        .receive_push(
716
            Bundle::default(),
717
            vec![RefUpdate {
718
                name: "main".into(),
719
                old_state: empty,
720
                new_state: s1,
721
                force: false,
722
                attestation: Some(sa.clone()),
723
            }],
724
            None,
725
            vec![],
726
        )
727
        .unwrap();
728
    assert!(
729
        !r[0].ok && r[0].reason.contains("serial"),
730
        "{}",
731
        r[0].reason
732
    );
98286406 Andy McCall ↶ 733
    // An attestation for a different update is refused too.
75167672 Andy McCall 734
    let sa2 = a
735
        .sign_attest(&Attest {
736
            repo: a.id().unwrap(),
737
            hlc: Hlc::now(),
738
            body: AttestBody::Ref {
739
                name: "main".into(),
740
                old_state: s1,
741
                new_state: empty,
742
                serial: 5,
743
            },
744
        })
745
        .unwrap();
746
    let r = origin
747
        .receive_push(
748
            Bundle::default(),
749
            vec![RefUpdate {
750
                name: "main".into(),
751
                old_state: empty,
752
                new_state: s1,
753
                force: false,
754
                attestation: Some(sa2),
755
            }],
756
            None,
757
            vec![],
758
        )
759
        .unwrap();
760
    assert!(
761
        !r[0].ok && r[0].reason.contains("describe"),
762
        "{}",
763
        r[0].reason
764
    );
98286406 Andy McCall ↶ 765
    let _ = key;
766
}
767
768
#[test]
769
fn user_config_supplies_defaults_and_clones_sign() {
770
    hermetic();
771
    let dir = tempfile::tempdir().unwrap();
772
    let root = dir.path();
773
    let home = root.join("home");
774
    let origin = Repo::init(&root.join("origin")).unwrap();
775
    let url = root.join("origin").to_string_lossy().to_string();
776
777
    // Identity at user scope: the repository file stays free of author keys.
778
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
75167672 Andy McCall 779
    let (key, _) = a
780
        .create_identity("Ada", "[email protected]", IdentityScope::User)
781
        .unwrap();
98286406 Andy McCall ↶ 782
    assert!(!a.config.repo_layer().contains_key("author.key"));
783
    assert_eq!(a.config.author_key, Some(key));
784
    assert!(home.join("config.toml").exists());
785
    a.set_user_config("core.sign", "change").unwrap();
786
    assert!(a.config.sign_changes);
787
788
    // Repository settings override user settings and are the only ones saved.
789
    a.config.set("core.sign", "seal").unwrap();
790
    a.save_config().unwrap();
791
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
792
    assert!(!again.config.sign_changes);
793
    assert_eq!(again.config.author_key, Some(key));
75167672 Andy McCall 794
    assert_eq!(
795
        read_config_file(&root.join("a/.oxy/config"))
796
            .unwrap()
797
            .get("core.sign")
798
            .map(String::as_str),
799
        Some("seal")
800
    );
98286406 Andy McCall ↶ 801
802
    // A fresh clone made by this user signs with the user-level identity,
803
    // even though the clone's store has never seen the identity object.
804
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
805
    assert!(b.config.sign_changes);
806
    write(&root.join("b"), "f.txt", b"f\n");
807
    let h = b.commit("signed from a clone", &[]).unwrap();
75167672 Andy McCall 808
    assert!(
809
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
810
    );
98286406 Andy McCall ↶ 811
    assert!(b.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 812
    assert!(matches!(
813
        origin.verify_change(&h).unwrap(),
814
        SignatureStatus::Valid { .. }
815
    ));
98286406 Andy McCall ↶ 816
}
817
818
#[test]
819
fn format1_repositories_are_migrated_on_open() {
820
    hermetic();
821
    use crate::oplog::{Format1Op, Format1View};
822
    let dir = tempfile::tempdir().unwrap();
823
    let root = dir.path();
824
    let repo = Repo::init(root).unwrap();
825
    write(root, "a.txt", b"a\n");
826
    let h1 = repo.commit("one", &[]).unwrap();
827
    let (wc_hash, _) = repo.working_copy().unwrap();
828
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
829
    let mut v1 = Format1View::default();
830
    v1.bookmarks.insert("main".into(), vec![]);
831
    v1.workspaces.insert(repo.workspace(), wc_hash);
75167672 Andy McCall 832
    let init = Format1Op {
833
        parents: vec![],
834
        hlc: Hlc::default(),
835
        command: "oxy init".into(),
836
        view: v1.clone(),
837
    };
98286406 Andy McCall ↶ 838
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
839
    v1.bookmarks.insert("main".into(), vec![h1]);
75167672 Andy McCall 840
    let commit = Format1Op {
841
        parents: vec![init_ref],
842
        hlc: Hlc::default(),
843
        command: "oxy commit".into(),
844
        view: v1,
845
    };
98286406 Andy McCall ↶ 846
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
847
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
848
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
849
    drop(repo);
850
851
    let repo = Repo::open(root).unwrap();
75167672 Andy McCall 852
    assert_eq!(
853
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
854
        FORMAT_LINE
855
    );
98286406 Andy McCall ↶ 856
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
857
    let ops = repo.op_log().unwrap();
75167672 Andy McCall 858
    assert_eq!(
859
        ops.iter()
860
            .map(|(_, o)| o.command.as_str())
861
            .collect::<Vec<_>>(),
862
        ["oxy commit", "oxy init"]
863
    );
98286406 Andy McCall ↶ 864
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
865
    assert!(!repo.snapshot("status").unwrap().changed);
866
    // Reopening again is a no-op.
867
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
868
}
869
870
#[test]
871
fn undo_skips_snapshot_operations() {
872
    hermetic();
873
    let dir = tempfile::tempdir().unwrap();
874
    let root = dir.path();
875
    let repo = Repo::init(root).unwrap();
876
    write(root, "a.txt", b"a\n");
877
    let h1 = repo.commit("a", &[]).unwrap();
878
    // A later command snapshots new edits on top of the commit.
879
    write(root, "b.txt", b"b\n");
880
    let s = repo.snapshot("oxy status").unwrap();
881
    assert!(s.changed);
882
    assert!(repo.head_op().unwrap().1.is_snapshot());
883
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
884
    // Undo must undo the commit, not the snapshot.
885
    repo.undo().unwrap();
886
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
887
    let s = repo.snapshot("oxy status").unwrap();
888
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
75167672 Andy McCall 889
    assert_eq!(
890
        paths,
891
        ["a.txt", "b.txt"],
892
        "both files are back in the working copy"
893
    );
98286406 Andy McCall ↶ 894
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
895
    // Only snapshots remain above `init`, so there is nothing left to undo.
896
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
897
    assert!(repo.undo().is_err());
898
}
899
900
#[test]
901
fn independent_changes_commute_and_make_multiple_heads() {
902
    hermetic();
903
    let dir = tempfile::tempdir().unwrap();
904
    let root = dir.path();
905
    let repo = Repo::init(root).unwrap();
906
    write(root, "a.txt", b"a\n");
907
    let h1 = repo.commit("a", &[]).unwrap();
908
    write(root, "b.txt", b"b\n");
909
    let h2 = repo.commit("b", &[]).unwrap();
910
    let c2 = repo.store().get_change(&h2).unwrap();
911
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
912
    let mut heads = repo.bookmark_heads().unwrap();
913
    heads.sort();
914
    let mut want = vec![h1, h2];
915
    want.sort();
916
    assert_eq!(heads, want);
917
    // Editing a.txt depends on h1 only.
918
    write(root, "a.txt", b"a\na2\n");
919
    let h3 = repo.commit("a2", &[]).unwrap();
920
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
921
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
922
    assert_eq!(heads, [h2, h3].into_iter().collect());
923
    // Explicit dependency.
924
    write(root, "c.txt", b"c\n");
925
    let h4 = repo.commit("c", &[h2]).unwrap();
926
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
927
}
928
929
#[test]
930
fn mode_change_and_text_binary_switch() {
931
    hermetic();
932
    let dir = tempfile::tempdir().unwrap();
933
    let root = dir.path();
934
    let repo = Repo::init(root).unwrap();
935
    write(root, "run.sh", b"#!/bin/sh\n");
936
    repo.commit("add script", &[]).unwrap();
937
    #[cfg(unix)]
938
    {
939
        use std::os::unix::fs::PermissionsExt;
940
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
941
        let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 942
        assert_eq!(
943
            statuses(&s),
944
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
945
        );
98286406 Andy McCall ↶ 946
        let h = repo.commit("exec", &[]).unwrap();
947
        let snap = repo.load_state(&[h]).unwrap().materialize();
948
        assert!(snap.files["run.sh"].mode.exec);
949
    }
950
    // Text → binary → text.
951
    write(root, "run.sh", b"\0binary");
952
    let h = repo.commit("binary", &[]).unwrap();
953
    let snap = repo.load_state(&[h]).unwrap().materialize();
954
    assert!(snap.files["run.sh"].mode.opaque);
955
    write(root, "run.sh", b"text again\n");
956
    let h = repo.commit("text", &[]).unwrap();
957
    let snap = repo.load_state(&[h]).unwrap().materialize();
958
    assert!(!snap.files["run.sh"].mode.opaque);
75167672 Andy McCall 959
    assert!(
960
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
961
    );
98286406 Andy McCall ↶ 962
    assert!(!snap.is_conflicted());
963
}
83e0677b Andy McCall ↶ 964
6eae06b6 Andy McCall ↶ 965
/// oxygen#87: a binary file given new contents and the executable bit in
966
/// one commit kept the contents and lost the bit.
967
#[cfg(unix)]
968
#[test]
969
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
970
    use std::os::unix::fs::PermissionsExt;
971
    hermetic();
972
    let dir = tempfile::tempdir().unwrap();
973
    let root = dir.path();
974
    let repo = Repo::init(root).unwrap();
975
    write(root, "tool.exe", b"MZ\0one");
976
    repo.commit("add", &[]).unwrap();
977
    write(root, "tool.exe", b"MZ\0two");
978
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
979
    let h = repo.commit("update and +x", &[]).unwrap();
980
    let snap = repo.load_state(&[h]).unwrap().materialize();
981
    let f = &snap.files["tool.exe"];
982
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
983
    assert!(
984
        repo.snapshot("status").unwrap().statuses.is_empty(),
985
        "nothing left to commit"
986
    );
987
}
988
f0a517d2 Andy McCall ↶ 989
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
990
/// key whose certificate an issuer gave pushes when the policy grants its
991
/// subject, and a fetch accepts what it attested; an expired certificate,
992
/// or a subject the policy does not grant, may not move the bookmark.
83e0677b Andy McCall ↶ 993
#[test]
f0a517d2 Andy McCall ↶ 994
fn a_certified_key_pushes_under_a_subject_grant() {
995
    use crate::cert::{Certificate, SignedCertificate};
996
    use crate::identity::Scope;
997
    hermetic();
998
    let dir = tempfile::tempdir().unwrap();
999
    let root = dir.path();
1000
    let _origin = Repo::init(&root.join("origin")).unwrap();
1001
    let url = root.join("origin").to_string_lossy().to_string();
1002
    let mut a = Repo::clone(&url, &root.join("a"))
1003
        .unwrap()
1004
        .with_home(root.join("home-a"));
1005
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1006
        .unwrap();
1007
    write(&root.join("a"), "a.txt", b"a\n");
1008
    a.commit("a", &[]).unwrap();
1009
    a.policy_init().unwrap();
1010
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1011
    let hub_sk = SecretKey::generate();
1012
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1013
    a.policy_grant_subject(
1014
        "agent:claude@ada",
1015
        hub.clone(),
1016
        Scope::CHANGES | Scope::REFS,
1017
        None,
1018
    )
1019
    .unwrap();
1020
    assert!(a
1021
        .push("origin", false)
1022
        .unwrap()
1023
        .iter()
1024
        .any(|r| r.name == "policy" && r.ok));
1025
1026
    let now = Hlc::now().wall_ms;
1027
    // An agent repository whose key the hub certified for `subject`, from
1028
    // `from` to `to`.
1029
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1030
        let mut r = Repo::clone(&url, &root.join(name))
1031
            .unwrap()
1032
            .with_home(root.join(format!("home-{name}")));
1033
        let (_, id) = r
1034
            .create_identity(name, "[email protected]", IdentityScope::User)
1035
            .unwrap();
1036
        let cert = SignedCertificate::sign(
1037
            Certificate {
1038
                key: id,
1039
                issuer: hub.hash(),
1040
                subject: subject.into(),
1041
                claims: vec![],
1042
                scope: Scope::CHANGES | Scope::REFS,
1043
                not_before: from,
1044
                expires: to,
a2387d54 Andy McCall ↶ 1045
                grant: None,
f0a517d2 Andy McCall ↶ 1046
            },
1047
            &hub,
1048
            &hub_sk,
1049
        );
1050
        r.store().put_identity(&hub).unwrap();
1051
        r.store().put_certificate(&cert).unwrap();
1052
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1053
        r.commit("work", &[]).unwrap();
1054
        r
1055
    };
1056
1057
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1058
    let r = claude.push("origin", false).unwrap();
1059
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1060
    // Ada's fetch accepts the bookmark the certified key attested.
1061
    a.pull("origin").unwrap();
1062
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1063
        .store()
1064
        .get_change(h)
1065
        .map(|c| c.message == "work")
1066
        .unwrap_or(false)));
1067
f53cbe7a Andy McCall ↶ 1068
    // Step 4c: a host with an acceptor key records when it accepted the
1069
    // certified update and serves it; a fetch checks the certificate at
1070
    // that time only when the certificate's issuer signed it for exactly
1071
    // this attestation, else at the attestation's own time.
1072
    let host = Repo::open(&root.join("origin"))
1073
        .unwrap()
1074
        .with_acceptor(hub.clone(), hub_sk.clone());
1075
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1076
    host.record_acceptance(&attest_ref).unwrap();
1077
    let served = host.remote_refs().unwrap();
1078
    let acc = served
1079
        .refs
1080
        .iter()
1081
        .find(|r| r.name == "main")
1082
        .unwrap()
1083
        .accepted
1084
        .clone()
1085
        .expect("served with the refs");
1086
    let signer = sa.sigs[0].key;
1087
    assert_eq!(
1088
        a.certified_time(&signer, &sa, Some(&acc)),
1089
        acc.attest.hlc.wall_ms
1090
    );
1091
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1092
    let stranger_sk = SecretKey::generate();
1093
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1094
    let mut forged = acc.clone();
1095
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1096
    assert_eq!(
1097
        a.certified_time(&signer, &sa, Some(&forged)),
1098
        sa.attest.hlc.wall_ms,
1099
        "not the issuer's"
1100
    );
1101
    let mut elsewhere = acc.clone();
1102
    elsewhere.attest.body = AttestBody::Accepted {
1103
        attest: ObjectRef([7; 32]),
1104
    };
1105
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1106
    assert_eq!(
1107
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1108
        sa.attest.hlc.wall_ms,
1109
        "another attestation's"
1110
    );
1111
    a.pull("origin").unwrap();
1112
    // gc keeps the acceptance with the attestation.
1113
    host.gc(true).unwrap();
1114
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1115
f0a517d2 Andy McCall ↶ 1116
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1117
    let r = late.push("origin", false).unwrap();
1118
    assert!(
1119
        !r[0].ok && r[0].reason.contains("may not update"),
1120
        "an expired certificate: {r:?}"
1121
    );
1122
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1123
    let r = other.push("origin", false).unwrap();
1124
    assert!(
1125
        !r[0].ok && r[0].reason.contains("may not update"),
1126
        "a subject not granted: {r:?}"
1127
    );
1128
}
1129
028545df Andy McCall ↶ 1130
/// Trusted time (oxygenhub#240, spec §14.8): a fetched attestation by a
1131
/// short-lived key is judged at its integrated time, the earliest time a
1132
/// pinned witness cosigned a checkpoint holding it. A certificate valid
1133
/// then but expired now passes; a witness this user does not trust gives
1134
/// no time (the earlier rule, said so); a backdated attestation is noted;
1135
/// an answer without the new fields is judged as before.
1136
#[test]
1137
fn a_fetched_attestation_is_judged_at_its_integrated_time() {
1138
    use super::transparency::LogCheck;
1139
    use crate::cert::{Certificate, SignedCertificate};
1140
    use crate::identity::Scope;
1141
    use crate::protocol::{Integration, Logged, RefsResponse, RemoteRef};
1142
    use crate::tlog::{self, Checkpoint, Entry, Hash, Integrated, Note};
1143
    hermetic();
1144
    let dir = tempfile::tempdir().unwrap();
1145
    let root = dir.path();
1146
    let mut a = Repo::init(&root.join("a"))
1147
        .unwrap()
1148
        .with_home(root.join("home-a"));
1149
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1150
        .unwrap();
1151
    write(&root.join("a"), "a.txt", b"a\n");
1152
    a.commit("a", &[]).unwrap();
1153
    a.policy_init().unwrap();
1154
    let issuer_sk = SecretKey::generate();
1155
    let issuer = issuer_sk.identity("hub", "[email protected]", 1);
1156
    a.policy_grant_subject(
1157
        "agent:claude@ada",
1158
        issuer.clone(),
1159
        Scope::CHANGES | Scope::REFS,
1160
        None,
1161
    )
1162
    .unwrap();
1163
    let p = a.current_policy().unwrap().unwrap().1.policy;
1164
1165
    // An agent key the issuer certified for ten minutes two hours ago.
1166
    let now = Hlc::now().wall_ms;
1167
    let t0 = now - 2 * 3_600_000;
1168
    let agent_sk = SecretKey::generate();
1169
    let agent = agent_sk.identity("claude", "[email protected]", t0);
1170
    let cert = SignedCertificate::sign(
1171
        Certificate {
1172
            key: agent.clone(),
1173
            issuer: issuer.hash(),
1174
            subject: "agent:claude@ada".into(),
1175
            claims: vec![],
1176
            scope: Scope::CHANGES | Scope::REFS,
1177
            not_before: t0,
1178
            expires: t0 + 600_000,
1179
            grant: None,
1180
        },
1181
        &issuer,
1182
        &issuer_sk,
1183
    );
1184
    a.store().put_identity(&agent).unwrap();
1185
    a.store().put_certificate(&cert).unwrap();
1186
    let signer = agent.hash();
1187
    let attested = |claimed: u64| {
1188
        let attest = Attest {
1189
            repo: a.id().unwrap(),
1190
            hlc: Hlc {
1191
                wall_ms: claimed,
1192
                logical: 0,
1193
            },
1194
            body: AttestBody::Ref {
1195
                name: "main".into(),
1196
                old_state: ObjectRef([1; 32]),
1197
                new_state: ObjectRef([2; 32]),
1198
                serial: 1,
1199
            },
1200
        };
1201
        let sig = agent_sk.sign(Domain::Attest, &signer, &attest.hash());
1202
        SignedAttest {
1203
            attest,
1204
            sigs: vec![sig],
1205
        }
1206
    };
1207
1208
    // The hub's log: eight entries, the attestation's at 3, the latest
1209
    // checkpoint of 8, and one of 4 that witnesses cosigned.
1210
    let log_sk = SecretKey::generate();
1211
    let log_key = log_sk.identity("hub.example", "[email protected]", 1);
1212
    let origin = "hub.example/log";
1213
    let hub = "https://hub.example";
1214
    let url = "https://hub.example/ada/a";
1215
    let w_sk = SecretKey::generate();
1216
    let w = w_sk.identity("w", "[email protected]", 1);
1217
    let stranger_sk = SecretKey::generate();
1218
    let stranger = stranger_sk.identity("s", "[email protected]", 1);
1219
    let sa = attested(t0 + 300_000);
1220
    let entry_of = |i: u64| {
1221
        let (kind, object) = if i == 3 {
1222
            ("ref", sa.attest.hash())
1223
        } else {
1224
            ("seal", ObjectRef([i as u8; 32]))
1225
        };
1226
        Entry {
1227
            kind: kind.into(),
1228
            repo: sa.attest.repo,
1229
            object,
1230
            signers: vec![signer],
1231
            received: t0 + 300_000,
1232
        }
1233
        .encode()
1234
    };
1235
    let mut stored: Vec<Hash> = Vec::new();
1236
    for i in 0..8 {
1237
        let add = tlog::stored_hashes_for_leaf(i, tlog::leaf_hash(&entry_of(i)), &stored).unwrap();
1238
        stored.extend(add);
1239
    }
1240
    let note_of = |n: u64, cosigners: &[(&str, &Identity, &SecretKey, u64)]| {
1241
        let mut note = Checkpoint {
1242
            origin: origin.into(),
1243
            size: n,
1244
            root: tlog::tree_hash(n, &stored).unwrap(),
1245
            extensions: vec![],
1246
        }
1247
        .sign(&log_key, &log_sk)
1248
        .unwrap();
1249
        for (name, id, sk, t) in cosigners {
1250
            note.sigs
1251
                .extend(tlog::cosign(&note.text, name, id, sk, *t).unwrap());
1252
        }
1253
        note.encode()
1254
    };
1255
    let latest = note_of(8, &[]);
1256
    let witnessed_at = (t0 + 360_000) / 1000;
1257
    let cosigned = note_of(
1258
        4,
1259
        &[
1260
            ("w.example", &w, &w_sk, witnessed_at),
1261
            ("s.example", &stranger, &stranger_sk, 1),
1262
        ],
1263
    );
1264
    let answer = |integration: Vec<Integration>, witnesses: Vec<(String, Vec<u8>)>| RefsResponse {
1265
        refs: vec![RemoteRef {
1266
            name: "main".into(),
1267
            state: ObjectRef([2; 32]),
1268
            heads: vec![],
1269
            attestation: Some(sa.clone()),
1270
            last_serial: None,
1271
            accepted: None,
1272
            logged: Some(Logged {
1273
                index: 3,
1274
                entry: entry_of(3),
1275
                proof: tlog::prove_inclusion(8, 3, &stored).unwrap(),
1276
            }),
1277
            integration,
1278
        }],
1279
        log: Some(latest.clone()),
1280
        witnesses,
1281
        ..RefsResponse::default()
1282
    };
1283
    let proof4 = tlog::prove_inclusion(4, 3, &stored).unwrap();
1284
    let served = vec![Integration {
1285
        note: cosigned.clone(),
1286
        proof: proof4.clone(),
1287
    }];
1288
    let listed = vec![("w.example".to_string(), w.encode())];
1289
    // This user saw the hub's log before (pinned, so nothing is fetched).
1290
    a.remember_log(hub, &log_key, &Note::parse(&latest).unwrap())
1291
        .unwrap();
1292
1293
    // The witness is pinned on first sight, silently; the stranger's
1294
    // earlier cosignature counts for nothing.
1295
    let resp = answer(served.clone(), listed.clone());
1296
    let lc = a.check_log(url, None, &resp).unwrap();
1297
    assert!(lc.notes.is_empty(), "{:?}", lc.notes);
1298
    let t = lc.time_of("main").unwrap();
1299
    assert_eq!((t.time, t.witness.as_str()), (witnessed_at, "w.example"));
1300
    // The certificate expired an hour and fifty minutes ago, but covered
1301
    // the integrated time: accepted, and nothing to say.
1302
    assert!(cert.cert.expires < now);
1303
    let mut notes = Vec::new();
1304
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1305
        .unwrap();
1306
    assert!(notes.is_empty(), "{notes:?}");
1307
1308
    // Only the stranger cosigned: no witnessed time, so the earlier rule
1309
    // (the attestation's own time, inside the window), said so.
1310
    let lonely = vec![Integration {
1311
        note: note_of(4, &[("s.example", &stranger, &stranger_sk, 1)]),
1312
        proof: proof4.clone(),
1313
    }];
1314
    let resp = answer(lonely, vec![]);
1315
    let lc = a.check_log(url, None, &resp).unwrap();
1316
    assert!(lc
1317
        .time_of("main")
1318
        .unwrap_err()
1319
        .contains("no witness this user trusts"));
1320
    let mut notes = Vec::new();
1321
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
1322
        .unwrap();
1323
    assert!(
1324
        notes.len() == 1 && notes[0].contains("not at a witnessed time"),
1325
        "{notes:?}"
1326
    );
1327
1328
    // A witness listed later under the pinned name with another key is
1329
    // pinned with a note, as a new log key is.
1330
    let resp = answer(
1331
        served.clone(),
1332
        vec![("w.example".into(), stranger.encode())],
1333
    );
1334
    let lc = a.check_log(url, None, &resp).unwrap();
1335
    assert!(
1336
        lc.notes.iter().any(|n| n.contains("another key")),
1337
        "{:?}",
1338
        lc.notes
1339
    );
1340
    assert!(
1341
        lc.time_of("main").is_err(),
1342
        "w's cosignature is by its old key"
1343
    );
1344
    a.check_log(url, None, &answer(served.clone(), listed.clone()))
1345
        .unwrap();
1346
1347
    // An old peer's answer: no log, no witnesses, no integration. Judged
1348
    // as before, silently.
1349
    let mut old = answer(vec![], vec![]);
1350
    old.log = None;
1351
    old.refs[0].logged = None;
1352
    let lc = a.check_log(url, None, &old).unwrap();
1353
    assert!(!lc.kept && lc.notes.is_empty());
1354
    let mut notes = Vec::new();
1355
    a.authorize_in_time(&p, "origin", &old.refs[0], &sa, &signer, &lc, &mut notes)
1356
        .unwrap();
1357
    assert!(notes.is_empty(), "{notes:?}");
1358
1359
    // Judged at given integrated times.
1360
    let at = |secs_after_t0: u64| {
1361
        let mut times = std::collections::HashMap::new();
1362
        times.insert(
1363
            "main".to_string(),
1364
            Ok(Integrated {
1365
                time: (t0 + secs_after_t0 * 1000) / 1000,
1366
                witness: "w.example".into(),
1367
                size: 4,
1368
            }),
1369
        );
1370
        LogCheck {
1371
            kept: true,
1372
            times,
1373
            ..LogCheck::default()
1374
        }
1375
    };
1376
    let judged = |sa: &SignedAttest, lc: &LogCheck| {
1377
        let mut notes = Vec::new();
1378
        a.authorize_in_time(&p, "origin", &old.refs[0], sa, &signer, lc, &mut notes)
1379
            .map(|_| notes)
1380
    };
1381
    // Claimed inside the window, first witnessed an hour later, after
1382
    // the certificate expired: backdated, or held back. Accepted by the
1383
    // earlier rule while logs are new, with both said.
1384
    let notes = judged(&sa, &at(3600)).unwrap();
1385
    assert!(
1386
        notes
1387
            .iter()
1388
            .any(|n| n.contains("had lapsed when witness w.example"))
1389
            && notes
1390
                .iter()
1391
                .any(|n| n.contains("55 minutes before witness")),
1392
        "{notes:?}"
1393
    );
1394
    // Claimed after the certificate expired, but witnessed inside its
1395
    // window: the clock the signer did not choose decides. The gap is
1396
    // still noted.
1397
    let fast = attested(now);
1398
    let notes = judged(&fast, &at(400)).unwrap();
1399
    assert!(
1400
        notes.len() == 1 && notes[0].contains("after witness w.example saw it"),
1401
        "{notes:?}"
1402
    );
1403
    // Claimed and witnessed after it expired: refused, as before.
1404
    assert!(judged(&fast, &at(3600)).is_err());
1405
    // A gap within ten minutes is nothing to note.
1406
    assert!(judged(&sa, &at(500)).unwrap().is_empty());
1407
}
1408
a2387d54 Andy McCall ↶ 1409
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1410
/// subject the author granted, seals changes in the author's name; with
1411
/// no grant, a stranger's, or one that had ended, it is neither the
1412
/// author nor a delegate.
f0a517d2 Andy McCall ↶ 1413
#[test]
a2387d54 Andy McCall ↶ 1414
fn a_certified_key_acts_for_its_author_under_a_grant() {
1415
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1416
    use crate::identity::{Identity, Scope};
1417
    hermetic();
1418
    let dir = tempfile::tempdir().unwrap();
1419
    let root = dir.path();
1420
    let _origin = Repo::init(&root.join("origin")).unwrap();
1421
    let url = root.join("origin").to_string_lossy().to_string();
1422
    let mut a = Repo::clone(&url, &root.join("a"))
1423
        .unwrap()
1424
        .with_home(root.join("home-a"));
1425
    let (ada, _) = a
1426
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1427
        .unwrap();
1428
    write(&root.join("a"), "a.txt", b"a\n");
1429
    a.commit("a", &[]).unwrap();
1430
    a.policy_init().unwrap();
1431
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1432
    let hub_sk = SecretKey::generate();
1433
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1434
    a.policy_grant_subject(
1435
        "agent:claude@ada",
1436
        hub.clone(),
1437
        Scope::CHANGES | Scope::REFS,
1438
        None,
1439
    )
1440
    .unwrap();
1441
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1442
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1443
    let ada_id = a.identity(&ada).unwrap();
1444
1445
    let now = Hlc::now().wall_ms;
1446
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1447
        SignedGrant::sign(
1448
            Grant {
1449
                grantor: by.hash(),
1450
                subject: "agent:claude@ada".into(),
1451
                issuer: hub.hash(),
1452
                scope: Scope::CHANGES | Scope::SEAL,
1453
                not_before: from,
1454
                expires: to,
1455
            },
1456
            by,
1457
            sk,
1458
        )
1459
    };
1460
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1461
    // certified (with `g` inside) the signer.
1462
    let agent = |name: &str, g: Option<SignedGrant>| {
1463
        let mut r = Repo::clone(&url, &root.join(name))
1464
            .unwrap()
1465
            .with_home(root.join(format!("home-{name}")));
1466
        let (key, id) = r
1467
            .create_identity(name, "[email protected]", IdentityScope::User)
1468
            .unwrap();
1469
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1470
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1471
        let cert = SignedCertificate::sign(
1472
            Certificate {
1473
                key: id,
1474
                issuer: hub.hash(),
1475
                subject: "agent:claude@ada".into(),
1476
                claims: vec![],
1477
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1478
                not_before: now - 60_000,
1479
                expires: now + 600_000,
1480
                grant: g,
1481
            },
1482
            &hub,
1483
            &hub_sk,
1484
        );
1485
        r.store().put_identity(&hub).unwrap();
1486
        r.store().put_certificate(&cert).unwrap();
1487
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1488
        let h = r.commit("work", &[]).unwrap();
1489
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1490
        (r, key, h)
1491
    };
1492
1493
    let (claude, key, h) = agent(
1494
        "claude",
1495
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1496
    );
1497
    let r = claude.push("origin", false).unwrap();
1498
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1499
    let host = Repo::open(&root.join("origin")).unwrap();
1500
    assert!(matches!(
1501
        host.authenticate_change(&h).unwrap(),
1502
        SignatureStatus::Valid { key: k, sealed: true, .. } if k == key
1503
    ));
1504
    a.pull("origin").unwrap();
1505
    assert!(matches!(
1506
        a.authenticate_change(&h).unwrap(),
1507
        SignatureStatus::Valid { key: k, .. } if k == key
1508
    ));
1509
1510
    let (none, _, _) = agent("none", None);
1511
    let r = none.push("origin", false).unwrap();
1512
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1513
    let mallory_sk = SecretKey::generate();
1514
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1515
    let (stranger, _, _) = agent(
1516
        "stranger",
1517
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1518
    );
1519
    let r = stranger.push("origin", false).unwrap();
1520
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1521
    let (ended, _, eh) = agent(
1522
        "ended",
1523
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1524
    );
1525
    let r = ended.push("origin", false).unwrap();
1526
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1527
    assert!(matches!(
1528
        ended.authenticate_change(&eh).unwrap(),
1529
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1530
    ));
1531
}
1532
1533
#[test]
83e0677b Andy McCall ↶ 1534
fn trust_policy_governs_pushes_and_fetches() {
1535
    hermetic();
1536
    let dir = tempfile::tempdir().unwrap();
1537
    let root = dir.path();
1538
    let origin = Repo::init(&root.join("origin")).unwrap();
1539
    let url = root.join("origin").to_string_lossy().to_string();
1540
1541
    // A is the root. Before the policy, an unsigned push from B is fine.
75167672 Andy McCall 1542
    let mut a = Repo::clone(&url, &root.join("a"))
1543
        .unwrap()
1544
        .with_home(root.join("home-a"));
1545
    let (key_a, _) = a
1546
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1547
        .unwrap();
1548
    let mut b = Repo::clone(&url, &root.join("b"))
1549
        .unwrap()
1550
        .with_home(root.join("home-b"));
83e0677b Andy McCall ↶ 1551
    write(&root.join("b"), "b.txt", b"b\n");
1552
    b.commit("unsigned before policy", &[]).unwrap();
1553
    assert!(b.push("origin", false).unwrap()[0].ok);
1554
1555
    // A creates the policy and pushes it; origin now enforces it.
1556
    write(&root.join("a"), "a.txt", b"a\n");
1557
    a.commit("a", &[]).unwrap();
1558
    let sp = a.policy_init().unwrap();
1559
    assert_eq!(sp.policy.serial, 1);
1560
    a.pull("origin").unwrap();
1561
    let results = a.push("origin", false).unwrap();
1562
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1563
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1564
1565
    // B pulls the policy. Without an identity B cannot push at all.
1566
    b.pull("origin").unwrap();
75167672 Andy McCall 1567
    assert!(
1568
        b.current_policy().unwrap().is_some(),
1569
        "the policy arrived with the fetch"
1570
    );
83e0677b Andy McCall ↶ 1571
    assert!(b.push("origin", false).is_err());
1572
    // With an identity the policy does not list, the push is rejected by origin.
75167672 Andy McCall 1573
    let (key_b, id_b) = b
1574
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1575
        .unwrap();
83e0677b Andy McCall ↶ 1576
    write(&root.join("b"), "b.txt", b"b2\n");
1577
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1578
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1579
    let r = b.push("origin", false).unwrap();
75167672 Andy McCall 1580
    assert!(
1581
        !r[0].ok && r[0].reason.contains("may not update"),
1582
        "{:?}",
1583
        r
1584
    );
83e0677b Andy McCall ↶ 1585
1586
    // A grants B (identity handed over as a file) and publishes the policy.
1587
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1588
    assert_eq!(sp.policy.serial, 2);
1589
    let r = a.push("origin", false).unwrap();
1590
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1591
    // B must fetch the new policy before pushing.
75167672 Andy McCall 1592
    assert!(b
1593
        .push("origin", false)
1594
        .unwrap_or_else(|e| vec![RefResult {
1595
            name: "main".into(),
1596
            ok: false,
1597
            reason: e.to_string()
1598
        }])
1599
        .iter()
1600
        .all(|x| !x.ok));
83e0677b Andy McCall ↶ 1601
    b.pull("origin").unwrap();
1602
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1603
    let r = b.push("origin", false).unwrap();
1604
    assert!(r[0].ok, "{:?}", r);
1605
    // Origin verified B's change under the policy.
1606
    let heads = origin.bookmark_heads().unwrap();
1607
    for h in &heads {
1608
        let c = origin.store().get_change(h).unwrap();
1609
        if c.author == key_b {
75167672 Andy McCall 1610
            origin
1611
                .change_allowed(
1612
                    h,
1613
                    &origin.current_policy().unwrap().unwrap().1.policy,
1614
                    "main",
1615
                )
1616
                .unwrap();
83e0677b Andy McCall ↶ 1617
        }
1618
    }
1619
1620
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1621
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1622
    forged.serial = 3;
1623
    forged.roots = vec![key_b];
1624
    let fh = forged.hash();
1625
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 1626
    let forged = SignedPolicy {
1627
        policy: forged,
1628
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1629
    };
1630
    let r = origin
1631
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1632
        .unwrap();
83e0677b Andy McCall ↶ 1633
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1634
    let stale = a.current_policy().unwrap().unwrap().1;
1635
    let mut old = stale.clone();
1636
    old.policy.serial = 1;
75167672 Andy McCall 1637
    let r = origin
1638
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1639
        .unwrap();
83e0677b Andy McCall ↶ 1640
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1641
1642
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1643
    a.pull("origin").unwrap();
1644
    a.policy_revoke(&key_b).unwrap();
1645
    let r = a.push("origin", false).unwrap();
1646
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1647
    b.pull("origin").unwrap();
1648
    write(&root.join("b"), "b.txt", b"b3\n");
1649
    b.commit("b3", &[]).unwrap();
1650
    let r = b.push("origin", false).unwrap();
1651
    assert!(!r[0].ok, "{:?}", r);
1652
1653
    // A clone by a third party receives and verifies everything.
75167672 Andy McCall 1654
    let c = Repo::clone(&url, &root.join("c"))
1655
        .unwrap()
1656
        .with_home(root.join("home-c"));
83e0677b Andy McCall ↶ 1657
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
75167672 Andy McCall 1658
    assert!(c
1659
        .current_policy()
1660
        .unwrap()
1661
        .unwrap()
1662
        .1
1663
        .policy
1664
        .roots
1665
        .contains(&key_a));
83e0677b Andy McCall ↶ 1666
    assert!(!c.snapshot("status").unwrap().changed);
1667
}
d02e545d Andy McCall ↶ 1668
9ae4d15a Andy McCall ↶ 1669
/// oxygen#66: a gc says what it is doing, phase by phase.
d02e545d Andy McCall ↶ 1670
#[test]
9ae4d15a Andy McCall ↶ 1671
fn gc_reports_its_phases() {
1672
    hermetic();
1673
    let dir = tempfile::tempdir().unwrap();
1674
    let repo = Repo::init(dir.path()).unwrap();
1675
    for i in 0..3 {
1676
        write(
1677
            dir.path(),
1678
            &format!("f{i}.txt"),
1679
            format!("{i}\n").as_bytes(),
1680
        );
1681
        repo.commit(&format!("c{i}"), &[]).unwrap();
1682
    }
1683
    let mut phases = Vec::new();
1684
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1685
        .unwrap();
1686
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1687
    assert!(
1688
        phases.iter().any(|p| p.starts_with("pruning")),
1689
        "{phases:?}"
1690
    );
1691
    assert!(
1692
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1693
        "{phases:?}"
1694
    );
1695
    assert!(
1696
        phases
1697
            .iter()
1698
            .any(|p| p.starts_with("writing the index of ")),
1699
        "{phases:?}"
1700
    );
1701
}
1702
1703
#[test]
d02e545d Andy McCall ↶ 1704
fn gc_packs_objects_and_history_still_works() {
1705
    hermetic();
1706
    let dir = tempfile::tempdir().unwrap();
1707
    let root = dir.path();
1708
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1709
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1710
        .unwrap();
d02e545d Andy McCall ↶ 1711
    repo.set_user_config("core.sign", "change").unwrap();
1712
    write(root, "a.txt", b"one\n");
1713
    let h1 = repo.commit("one", &[]).unwrap();
1714
    write(root, "a.txt", b"two\n");
1715
    write(root, "big.bin", &vec![0u8; 100_000]);
1716
    let h2 = repo.commit("two", &[]).unwrap();
ba160f60 Andy McCall ↶ 1717
    // Several snapshots leave superseded working-copy versions behind.
1718
    for i in 0..5 {
1719
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1720
        repo.snapshot("status").unwrap();
1721
    }
1722
    write(root, "a.txt", b"two\n");
1723
    repo.snapshot("status").unwrap();
d02e545d Andy McCall ↶ 1724
    let before = repo.store().list().unwrap();
1725
    assert!(repo.store().loose_count().unwrap() > 0);
ba160f60 Andy McCall ↶ 1726
1727
    // With the default retention every operation's view is a root: nothing prunes.
1728
    let r = repo.gc(true).unwrap();
1729
    assert_eq!(r.packed.objects, before.len());
1730
    assert_eq!(r.pruned.objects, 0);
d02e545d Andy McCall ↶ 1731
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1732
    assert_eq!(repo.store().list().unwrap(), before);
ba160f60 Andy McCall ↶ 1733
1734
    // With zero retention only the current view is a root: superseded
1735
    // working copies go, everything reachable stays.
1736
    repo.config.set("core.op-retention", "0").unwrap();
1737
    repo.save_config().unwrap();
21b2aec2 Andy McCall ↶ 1738
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
ba160f60 Andy McCall ↶ 1739
    let r = repo.gc(true).unwrap();
1740
    assert!(r.pruned.objects >= 5, "{r:?}");
1741
    let after = repo.store().list().unwrap();
1742
    assert!(after.len() < before.len());
1743
    assert!(after.contains(&h1) && after.contains(&h2));
1744
    for (_, op) in repo.op_log().unwrap() {
1745
        assert!(!op.command.is_empty(), "operation objects are all kept");
1746
    }
1747
    // Everything still works from the pruned, packed store.
d02e545d Andy McCall ↶ 1748
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
75167672 Andy McCall 1749
    assert!(matches!(
1750
        repo.verify_change(&h2).unwrap(),
1751
        SignatureStatus::Valid { .. }
1752
    ));
d02e545d Andy McCall ↶ 1753
    assert_eq!(repo.log().unwrap().len(), 3);
1754
    repo.checkout(&[h1], false, "checkout").unwrap();
1755
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1756
    repo.checkout(&[h2], false, "checkout").unwrap();
1757
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1758
    assert!(!repo.snapshot("status").unwrap().changed);
ba160f60 Andy McCall ↶ 1759
    // Grace period defers pruning of young garbage.
d02e545d Andy McCall ↶ 1760
    write(root, "a.txt", b"three\n");
1761
    repo.commit("three", &[]).unwrap();
ba160f60 Andy McCall ↶ 1762
    let r = repo.gc(false).unwrap();
1763
    assert_eq!(r.pruned.objects, 0);
1764
    assert!(r.pruned.deferred > 0);
1765
    let r = repo.gc(true).unwrap();
1766
    assert!(r.pruned.objects > 0);
1767
    assert_eq!(repo.log().unwrap().len(), 4);
21b2aec2 Andy McCall ↶ 1768
    // Restoring the default retention makes the old views roots again; the
1769
    // working copies they name were pruned, which gc tolerates.
1770
    repo.config.set("core.op-retention", "90").unwrap();
1771
    repo.save_config().unwrap();
1772
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1773
    let r = repo.gc(false).unwrap();
1774
    assert_eq!(r.pruned.objects, 0);
1775
    assert_eq!(repo.log().unwrap().len(), 4);
d02e545d Andy McCall ↶ 1776
}
614541c3 Andy McCall ↶ 1777
1778
#[test]
1779
fn describe_amend_abandon_heads() {
1780
    hermetic();
1781
    let dir = tempfile::tempdir().unwrap();
1782
    let root = dir.path();
1783
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1784
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1785
        .unwrap();
614541c3 Andy McCall ↶ 1786
    repo.set_user_config("core.sign", "change").unwrap();
1787
    write(root, "a.txt", b"one\n");
1788
    let h1 = repo.commit("first", &[]).unwrap();
1789
    write(root, "a.txt", b"one\ntwo\n");
1790
    let h2 = repo.commit("secnod", &[]).unwrap();
1791
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1792
1793
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1794
    let h2b = repo.describe(&h2, "second").unwrap();
1795
    assert_ne!(h2b, h2);
1796
    let c = repo.store().get_change(&h2b).unwrap();
75167672 Andy McCall 1797
    assert_eq!(
1798
        (c.change_id, c.message.as_str(), c.deps.clone()),
1799
        (id2, "second", vec![h1])
1800
    );
614541c3 Andy McCall ↶ 1801
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
75167672 Andy McCall 1802
    assert!(matches!(
1803
        repo.verify_change(&h2b).unwrap(),
1804
        SignatureStatus::Valid { .. }
1805
    ));
614541c3 Andy McCall ↶ 1806
    let s = repo.snapshot("status").unwrap();
1807
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
75167672 Andy McCall 1808
    assert_eq!(
1809
        repo.resolve_change(&id2.short(8)).unwrap(),
1810
        h2b,
1811
        "the old object is no longer reachable from the log"
1812
    );
c07e0e7d Andy McCall ↶ 1813
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1814
    let h1b = repo.describe(&h1, "first, described").unwrap();
1815
    assert_ne!(h1b, h1);
1816
    let heads = repo.bookmark_heads().unwrap();
1817
    assert_eq!(heads.len(), 1);
1818
    let top = repo.store().get_change(&heads[0]).unwrap();
1819
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
75167672 Andy McCall 1820
    assert!(
1821
        matches!(
1822
            repo.verify_change(&heads[0]).unwrap(),
1823
            SignatureStatus::Valid { .. }
1824
        ),
1825
        "rewritten own change is re-signed"
1826
    );
c07e0e7d Andy McCall ↶ 1827
    let (_, wc) = repo.working_copy().unwrap();
75167672 Andy McCall 1828
    assert_eq!(
1829
        wc.deps,
1830
        vec![heads[0]],
1831
        "the working copy follows the rewrite"
1832
    );
c07e0e7d Andy McCall ↶ 1833
    assert!(!repo.snapshot("status").unwrap().changed);
1834
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 1835
    assert!(
1836
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1837
    );
614541c3 Andy McCall ↶ 1838
1839
    // amend: fold an edit into the head; the result is one change from h1.
1840
    write(root, "a.txt", b"one\ntwo\nthree\n");
1841
    write(root, "b.txt", b"b\n");
1842
    let h2c = repo.amend(None).unwrap();
1843
    let c = repo.store().get_change(&h2c).unwrap();
1844
    assert_eq!(c.change_id, id2);
1845
    assert_eq!(c.message, "second");
1846
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
75167672 Andy McCall 1847
    assert_eq!(
1848
        repo.log().unwrap().len(),
1849
        3,
1850
        "working copy, amended head, first"
1851
    );
614541c3 Andy McCall ↶ 1852
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
75167672 Andy McCall 1853
    assert!(
1854
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1855
    );
614541c3 Andy McCall ↶ 1856
    assert!(snap.files.contains_key("b.txt"));
1857
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 1858
    assert!(
1859
        repo.amend(None).is_err(),
1860
        "clean working copy and no message"
1861
    );
614541c3 Andy McCall ↶ 1862
    let h2d = repo.amend(Some("second, amended")).unwrap();
75167672 Andy McCall 1863
    assert_eq!(
1864
        repo.store().get_change(&h2d).unwrap().message,
1865
        "second, amended"
1866
    );
614541c3 Andy McCall ↶ 1867
1868
    // abandon: the head goes, its content stays as uncommitted work.
1869
    repo.abandon(&h2d).unwrap();
75167672 Andy McCall 1870
    assert_eq!(
1871
        repo.bookmark_heads().unwrap(),
1872
        vec![h1b],
1873
        "the described first change is the head again"
1874
    );
614541c3 Andy McCall ↶ 1875
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 1876
    let paths: Vec<_> = s
1877
        .statuses
1878
        .iter()
1879
        .map(|p| (p.path.as_str(), p.status))
1880
        .collect();
1881
    assert_eq!(
1882
        paths,
1883
        vec![
1884
            ("a.txt", ChangeStatus::Modified),
1885
            ("b.txt", ChangeStatus::Added)
1886
        ]
1887
    );
614541c3 Andy McCall ↶ 1888
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1889
    let h3 = repo.commit("recommitted", &[]).unwrap();
1890
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1891
    // undo brings the abandoned head back.
1892
    repo.undo().unwrap();
1893
    repo.undo().unwrap();
1894
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
c07e0e7d Andy McCall ↶ 1895
6706bdcf Andy McCall ↶ 1896
    // Abandoning a non-head whose dependent references its atoms reifies
1897
    // the references (here: a.txt vanishes with it, so the dependent's edit
1898
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
c07e0e7d Andy McCall ↶ 1899
    let base = repo.bookmark_heads().unwrap()[0];
1900
    let base_change = repo.store().get_change(&base).unwrap();
1901
    let h1_now = base_change.deps[0];
6706bdcf Andy McCall ↶ 1902
    let notes = repo.abandon(&h1_now).unwrap();
75167672 Andy McCall 1903
    assert!(
1904
        !notes.is_empty(),
1905
        "the dependent's edit of a.txt was reified"
1906
    );
6706bdcf Andy McCall ↶ 1907
    let heads = repo.bookmark_heads().unwrap();
1908
    let after = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 1909
    assert!(
1910
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1911
        "{:?}",
1912
        after.files.keys()
1913
    );
6706bdcf Andy McCall ↶ 1914
    repo.undo().unwrap();
1915
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
c07e0e7d Andy McCall ↶ 1916
    write(root, "c.txt", b"c\n");
1917
    let hc = repo.commit("c", &[]).unwrap();
1918
    write(root, "d.txt", b"d\n");
1919
    let hd = repo.commit("d", &[hc]).unwrap();
1920
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1921
    repo.abandon(&hc).unwrap();
1922
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1923
    assert!(!heads.contains(&hc));
75167672 Andy McCall 1924
    let d_now = heads
1925
        .iter()
1926
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1927
        .copied()
1928
        .unwrap();
1929
    assert!(
1930
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1931
        "d inherited c's (empty) dependencies"
1932
    );
c07e0e7d Andy McCall ↶ 1933
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 1934
    assert_eq!(
1935
        s.statuses
1936
            .iter()
1937
            .map(|p| p.path.as_str())
1938
            .collect::<Vec<_>>(),
1939
        vec!["c.txt"],
1940
        "c's content is now uncommitted work"
1941
    );
614541c3 Andy McCall ↶ 1942
}
79ab8528 Andy McCall ↶ 1943
1944
#[test]
1945
fn git_export_mirrors_history() {
1946
    hermetic();
75167672 Andy McCall 1947
    if std::process::Command::new("git")
1948
        .arg("--version")
1949
        .output()
1950
        .is_err()
1951
    {
79ab8528 Andy McCall ↶ 1952
        eprintln!("git not installed; skipping");
1953
        return;
1954
    }
1955
    let dir = tempfile::tempdir().unwrap();
1956
    let root = dir.path();
75167672 Andy McCall 1957
    let mut repo = Repo::init(&root.join("r"))
1958
        .unwrap()
1959
        .with_home(root.join("home"));
1960
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1961
        .unwrap();
79ab8528 Andy McCall ↶ 1962
    let r = root.join("r");
1963
    write(&r, "README.md", b"hello\n");
1964
    write(&r, "src/main.rs", b"fn main() {}\n");
1965
    let h1 = repo.commit("first", &[]).unwrap();
1966
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1967
    write(&r, "logo.png", b"\x89PNG\0\0");
1968
    let h2 = repo.commit("second", &[]).unwrap();
1969
1970
    let git_dir = root.join("mirror.git");
1971
    let rep = repo.git_export(&git_dir).unwrap();
1972
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1973
    let git = |args: &[&str]| -> String {
75167672 Andy McCall 1974
        let out = std::process::Command::new("git")
1975
            .arg("-C")
1976
            .arg(&git_dir)
1977
            .args(args)
1978
            .output()
1979
            .unwrap();
1980
        assert!(
1981
            out.status.success(),
1982
            "{}",
1983
            String::from_utf8_lossy(&out.stderr)
1984
        );
79ab8528 Andy McCall ↶ 1985
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1986
    };
1987
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1988
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1989
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1990
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 1991
    assert!(
1992
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1993
        "{body}"
1994
    );
79ab8528 Andy McCall ↶ 1995
    assert!(body.contains("Change-Id: "), "{body}");
75167672 Andy McCall 1996
    assert_eq!(
1997
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1998
        "Ada Lovelace <[email protected]>"
1999
    );
2000
    assert_eq!(
2001
        git(&["ls-tree", "--name-only", "main"]),
2002
        "README.md\nlogo.png\nsrc"
2003
    );
79ab8528 Andy McCall ↶ 2004
2005
    // Re-export is incremental.
2006
    let rep = repo.git_export(&git_dir).unwrap();
2007
    assert_eq!((rep.exported, rep.skipped), (0, 2));
2008
2009
    // An independent change makes two heads; the next state is one more
2010
    // commit on the linear branch whose tree is the union.
2011
    repo.checkout(&[h1], false, "checkout").unwrap();
2012
    write(&r, "other.txt", b"o\n");
2013
    let h3 = repo.commit("third", &[]).unwrap();
2014
    let rep = repo.git_export(&git_dir).unwrap();
2015
    assert_eq!((rep.exported, rep.heads), (1, 2));
2016
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
2017
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
2018
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
2019
    assert_eq!(git(&["show", "main:other.txt"]), "o");
2020
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
75167672 Andy McCall 2021
    assert_eq!(
2022
        git(&["ls-tree", "--name-only", "main"]),
2023
        "README.md\nlogo.png\nother.txt\nsrc"
2024
    );
79ab8528 Andy McCall ↶ 2025
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 2026
    assert!(
2027
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
2028
        "{body}"
2029
    );
79ab8528 Andy McCall ↶ 2030
    // A rewrite is a new state whose one new change is the rewritten one.
2031
    repo.describe(&h3, "third, described").unwrap();
2032
    let rep = repo.git_export(&git_dir).unwrap();
2033
    assert_eq!(rep.exported, 1);
75167672 Andy McCall 2034
    assert_eq!(
2035
        git(&["log", "-1", "--format=%s", "main"]),
2036
        "third, described"
2037
    );
79ab8528 Andy McCall ↶ 2038
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
2039
    let _ = h2;
2040
}
c3069537 Andy McCall ↶ 2041
2042
#[test]
2043
fn git_import_reproduces_trees() {
c3d2ef61 Andy McCall ↶ 2044
    git_import_reproduces_trees_with(None);
2045
}
2046
2047
/// The same import with every merge rendered in batches of one file
2048
/// (oxygen#25): what a merge onto a base of thousands of files takes.
2049
#[test]
2050
fn git_import_reproduces_trees_in_batches() {
2051
    git_import_reproduces_trees_with(Some(1));
2052
}
2053
2054
fn git_import_reproduces_trees_with(batch: Option<usize>) {
2055
    crate::repo::git::set_merge_batch_for_tests(batch);
c3069537 Andy McCall ↶ 2056
    hermetic();
75167672 Andy McCall 2057
    if std::process::Command::new("git")
2058
        .arg("--version")
2059
        .output()
2060
        .is_err()
2061
    {
c3069537 Andy McCall ↶ 2062
        eprintln!("git not installed; skipping");
2063
        return;
2064
    }
2065
    let dir = tempfile::tempdir().unwrap();
2066
    let root = dir.path();
2067
    let g = root.join("src.git");
2068
    fs::create_dir_all(&g).unwrap();
2069
    let git = |args: &[&str]| -> String {
2070
        let out = std::process::Command::new("git")
2071
            .arg("-C")
2072
            .arg(&g)
75167672 Andy McCall 2073
            .args([
2074
                "-c",
2075
                "user.name=Grace",
2076
                "-c",
2077
                "[email protected]",
2078
                "-c",
2079
                "commit.gpgsign=false",
2080
            ])
c3069537 Andy McCall ↶ 2081
            .args(args)
2082
            .output()
2083
            .unwrap();
75167672 Andy McCall 2084
        assert!(
2085
            out.status.success(),
2086
            "git {args:?}: {}",
2087
            String::from_utf8_lossy(&out.stderr)
2088
        );
c3069537 Andy McCall ↶ 2089
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2090
    };
2091
    git(&["init", "-q", "-b", "main"]);
2092
    write(&g, "README.md", b"# Hi\n");
2093
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
2094
    git(&["add", "."]);
2095
    git(&["commit", "-q", "-m", "initial"]);
2096
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2097
    write(&g, "run.sh", b"#!/bin/sh\n");
2098
    #[cfg(unix)]
2099
    {
2100
        use std::os::unix::fs::PermissionsExt;
2101
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
2102
    }
2103
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
2104
    git(&["add", "."]);
75167672 Andy McCall 2105
    git(&[
2106
        "commit",
2107
        "-q",
2108
        "-m",
2109
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
2110
    ]);
c3069537 Andy McCall ↶ 2111
    // A branch that edits README, merged back with a conflict-free merge.
2112
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
2113
    write(&g, "README.md", b"# Hi\n\nMore.\n");
2114
    git(&["commit", "-q", "-am", "readme"]);
2115
    git(&["checkout", "-q", "main"]);
2116
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
2117
    // A branch from the initial commit inserting at the same place as
2118
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
2119
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
2120
    git(&["checkout", "-q", "-b", "clash", &initial]);
2121
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
2122
    git(&["commit", "-q", "-am", "clash"]);
2123
    git(&["checkout", "-q", "main"]);
75167672 Andy McCall 2124
    let _ = std::process::Command::new("git")
2125
        .arg("-C")
2126
        .arg(&g)
2127
        .args(["merge", "-q", "clash"])
2128
        .output();
2129
    write(
2130
        &g,
2131
        "src/lib.rs",
2132
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2133
    );
c3069537 Andy McCall ↶ 2134
    git(&["add", "."]);
2135
    git(&["commit", "-q", "-m", "resolve clash"]);
2136
    git(&["rm", "-q", "logo.png"]);
2137
    git(&["commit", "-q", "-m", "drop logo"]);
6e723b81 Andy McCall ↶ 2138
    // A rename with a small edit is imported as a move of the same node.
2139
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
75167672 Andy McCall 2140
    write(
2141
        &g,
2142
        "src/lib2.rs",
2143
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
2144
    );
6e723b81 Andy McCall ↶ 2145
    git(&["add", "."]);
2146
    git(&["commit", "-q", "-m", "rename lib"]);
958fb27d Andy McCall ↶ 2147
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
2148
    // run.sh is the same as in the first parent's tree, but the merged
2149
    // change touched it, so the importer must compare it, not skip it.
2150
    git(&["checkout", "-q", "-b", "discarded"]);
2151
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
2152
    git(&["commit", "-q", "-am", "discarded edit"]);
2153
    git(&["checkout", "-q", "main"]);
314db9b4 Andy McCall ↶ 2154
    git(&[
2155
        "merge",
2156
        "-q",
2157
        "-s",
2158
        "ours",
2159
        "-m",
2160
        "merge discarded, keeping ours",
2161
        "discarded",
2162
    ]);
c3069537 Andy McCall ↶ 2163
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
2164
2165
    let dest = root.join("oxy");
2166
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
2167
    let rep = repo.import_git(&g, "main").unwrap();
2168
    assert_eq!(rep.commits, expected_count);
958fb27d Andy McCall ↶ 2169
    assert_eq!(rep.merges, 3);
314db9b4 Andy McCall ↶ 2170
    assert_eq!(
2171
        fs::read(dest.join("run.sh")).unwrap(),
2172
        b"#!/bin/sh\n",
2173
        "the ours merge kept main's run.sh"
2174
    );
958fb27d Andy McCall ↶ 2175
    let v = repo.verify_git_import(&g, "main").unwrap();
2176
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
2177
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
c3069537 Andy McCall ↶ 2178
    // The working copy equals the Git tree at main.
75167672 Andy McCall 2179
    assert_eq!(
2180
        fs::read(dest.join("src/lib2.rs")).unwrap(),
2181
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2182
    );
6e723b81 Andy McCall ↶ 2183
    assert!(!dest.join("src/lib.rs").exists());
75167672 Andy McCall 2184
    assert_eq!(
2185
        fs::read(dest.join("README.md")).unwrap(),
2186
        b"# Hi\n\nMore.\n"
2187
    );
c3069537 Andy McCall ↶ 2188
    assert!(!dest.join("logo.png").exists());
2189
    #[cfg(unix)]
2190
    {
2191
        use std::os::unix::fs::PermissionsExt;
75167672 Andy McCall 2192
        assert!(
2193
            fs::metadata(dest.join("run.sh"))
2194
                .unwrap()
2195
                .permissions()
2196
                .mode()
2197
                & 0o111
2198
                != 0
2199
        );
c3069537 Andy McCall ↶ 2200
    }
75167672 Andy McCall 2201
    assert!(
2202
        !repo.snapshot("status").unwrap().changed,
2203
        "clean after import"
2204
    );
c3069537 Andy McCall ↶ 2205
    let heads = repo.bookmark_heads().unwrap();
2206
    let st = repo.load_state(&heads).unwrap();
2207
    assert!(!st.materialize().is_conflicted());
2208
    assert_eq!(st.len(), expected_count);
75167672 Andy McCall 2209
    let tip = repo
2210
        .log()
2211
        .unwrap()
2212
        .into_iter()
2213
        .find(|e| e.change.message.starts_with("rename lib"))
2214
        .unwrap();
6e723b81 Andy McCall ↶ 2215
    let c = repo.store().get_change(&tip.hash).unwrap();
75167672 Andy McCall 2216
    assert!(
2217
        c.tree_ops
2218
            .iter()
2219
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
2220
        "{:?}",
2221
        c.tree_ops
2222
    );
2223
    assert!(!c
2224
        .tree_ops
2225
        .iter()
2226
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
c3069537 Andy McCall ↶ 2227
    // Messages carry Git trailers; the Change-Id trailer was honoured.
2228
    let log = repo.log().unwrap();
75167672 Andy McCall 2229
    let second = log
2230
        .iter()
2231
        .find(|e| e.change.message.starts_with("second"))
2232
        .unwrap();
2233
    assert_eq!(
2234
        second.change.change_id,
2235
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
2236
    );
2237
    assert!(second
2238
        .change
2239
        .message
2240
        .contains("Git-Author: Grace <[email protected]>"));
2241
    let resolve = log
2242
        .iter()
2243
        .find(|e| e.change.message.starts_with("resolve clash"))
2244
        .unwrap();
2245
    assert_eq!(
2246
        resolve.change.kind,
2247
        ChangeKind::Resolution,
2248
        "a conflicting Git merge becomes a resolution"
2249
    );
c3069537 Andy McCall ↶ 2250
    // Re-importing into another fresh repository gives the same ChangeIds.
75167672 Andy McCall 2251
    let repo2 = Repo::init(&root.join("oxy2"))
2252
        .unwrap()
2253
        .with_home(root.join("home"));
c3069537 Andy McCall ↶ 2254
    repo2.import_git(&g, "main").unwrap();
dfb23a3a Andy McCall ↶ 2255
    // New nodes' identifiers derive from the commit (spec §23), so the
2256
    // re-import is not just the same ChangeIds but the same changes.
2257
    assert_eq!(
2258
        repo2.bookmark_heads().unwrap(),
2259
        repo.bookmark_heads().unwrap()
2260
    );
75167672 Andy McCall 2261
    let ids: BTreeSet<ChangeId> = repo
2262
        .log()
2263
        .unwrap()
2264
        .iter()
2265
        .filter(|e| !e.is_working_copy)
2266
        .map(|e| e.change.change_id)
2267
        .collect();
2268
    let ids2: BTreeSet<ChangeId> = repo2
2269
        .log()
2270
        .unwrap()
2271
        .iter()
2272
        .filter(|e| !e.is_working_copy)
2273
        .map(|e| e.change.change_id)
2274
        .collect();
c3069537 Andy McCall ↶ 2275
    assert_eq!(ids, ids2);
2276
    // Round trip back out to Git reproduces the tip tree.
2277
    let mirror = root.join("mirror.git");
2278
    repo.git_export(&mirror).unwrap();
75167672 Andy McCall 2279
    let out = std::process::Command::new("git")
2280
        .arg("-C")
2281
        .arg(&mirror)
2282
        .args(["show", "main:src/lib2.rs"])
2283
        .output()
2284
        .unwrap();
2285
    assert_eq!(
2286
        String::from_utf8_lossy(&out.stdout),
2287
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2288
    );
2289
    let out = std::process::Command::new("git")
2290
        .arg("-C")
2291
        .arg(&mirror)
2292
        .args(["show", "main:src/lib.rs"])
2293
        .output()
2294
        .unwrap();
2295
    assert!(
2296
        !out.status.success(),
2297
        "the old path is gone from the export"
2298
    );
c3069537 Andy McCall ↶ 2299
}
252e8cb2 Andy McCall ↶ 2300
2301
#[test]
2302
fn checkpoints_accelerate_loading_and_stay_correct() {
2303
    hermetic();
2304
    let dir = tempfile::tempdir().unwrap();
2305
    let root = dir.path();
2306
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2307
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2308
    repo.save_config().unwrap();
2309
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2310
    let mut hashes = Vec::new();
2311
    for i in 0..12 {
75167672 Andy McCall 2312
        write(
2313
            root,
2314
            "a.txt",
2315
            format!(
2316
                "{}\n",
2317
                (0..=i)
2318
                    .map(|k| k.to_string())
2319
                    .collect::<Vec<_>>()
2320
                    .join("\n")
2321
            )
2322
            .as_bytes(),
2323
        );
252e8cb2 Andy McCall ↶ 2324
        write(root, &format!("f{i}.txt"), b"x\n");
2325
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2326
    }
75167672 Andy McCall 2327
    let (_, cp) = repo
2328
        .latest_checkpoint("main")
2329
        .unwrap()
2330
        .expect("automatic checkpoint");
252e8cb2 Andy McCall ↶ 2331
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2332
    // Loading through the checkpoint equals loading everything.
2333
    let heads = repo.bookmark_heads().unwrap();
2334
    let fast = repo.load_state(&heads).unwrap();
2335
    let full = repo.load_state_full(&heads).unwrap();
2336
    assert_eq!(fast.len(), full.len());
2337
    assert_eq!(fast.heads(), full.heads());
2338
    let (a, b) = (fast.materialize(), full.materialize());
75167672 Andy McCall 2339
    assert_eq!(
2340
        a.files.keys().collect::<Vec<_>>(),
2341
        b.files.keys().collect::<Vec<_>>()
2342
    );
252e8cb2 Andy McCall ↶ 2343
    for (p, f) in &a.files {
2344
        assert_eq!(f.content, b.files[p].content, "{p}");
2345
    }
2346
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2347
    // A head set that does not contain the checkpoint's heads falls back.
75167672 Andy McCall 2348
    assert!(repo
2349
        .load_state_checkpointed(&[hashes[0]])
2350
        .unwrap()
2351
        .is_none());
252e8cb2 Andy McCall ↶ 2352
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2353
    // Everything else keeps working on top of the checkpoint.
2354
    assert!(!repo.snapshot("status").unwrap().changed);
2355
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2356
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2357
    let (r, n, bytes) = repo.checkpoint().unwrap();
2358
    assert!(n >= 12 && bytes > 0);
2359
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2360
    write(root, "a.txt", b"after\n");
2361
    let h_after = repo.commit("after", &[]).unwrap();
2362
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2363
    assert!(st.contains(&h_after));
75167672 Andy McCall 2364
    assert!(
2365
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2366
    );
252e8cb2 Andy McCall ↶ 2367
    assert_eq!(repo.log().unwrap().len(), 14);
2368
    // Checkpoints survive gc.
2369
    repo.gc(true).unwrap();
2370
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
75167672 Andy McCall 2371
    assert!(repo
2372
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2373
        .unwrap()
2374
        .is_some());
252e8cb2 Andy McCall ↶ 2375
}
135212de Andy McCall ↶ 2376
2377
#[test]
2378
fn quick_status_for_prompts() {
2379
    hermetic();
2380
    let dir = tempfile::tempdir().unwrap();
2381
    let root = dir.path();
2382
    let origin = Repo::init(&root.join("origin")).unwrap();
2383
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2384
    let a = Repo::clone(&url, &root.join("a"))
2385
        .unwrap()
2386
        .with_home(root.join("home"));
135212de Andy McCall ↶ 2387
    let ops_before = a.op_log().unwrap().len();
2388
    let info = a.quick_status().unwrap();
75167672 Andy McCall 2389
    assert_eq!(
2390
        (
2391
            info.bookmark.as_str(),
2392
            info.heads,
2393
            info.dirty,
2394
            info.conflicted,
2395
            info.ahead,
2396
            info.behind
2397
        ),
2398
        ("main", 0, false, false, Some(0), Some(0))
2399
    );
135212de Andy McCall ↶ 2400
    write(&root.join("a"), "f.txt", b"f\n");
2401
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
75167672 Andy McCall 2402
    assert_eq!(
2403
        a.op_log().unwrap().len(),
2404
        ops_before,
2405
        "quick_status records nothing"
2406
    );
135212de Andy McCall ↶ 2407
    // A snapshotted but uncommitted change is still dirty.
2408
    a.snapshot("status").unwrap();
2409
    assert!(a.quick_status().unwrap().dirty);
2410
    a.commit("f", &[]).unwrap();
2411
    let info = a.quick_status().unwrap();
2412
    assert!(!info.dirty, "clean right after a commit");
2413
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
75167672 Andy McCall 2414
    assert_eq!(
2415
        info.format("%b %c%d%x%A%D"),
2416
        format!("main {}+1", info.change_id)
2417
    );
135212de Andy McCall ↶ 2418
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2419
    // Touching a file without changing it is not dirty; changing content of
2420
    // the same size is.
2421
    let p = root.join("a/f.txt");
2422
    let content = fs::read(&p).unwrap();
2423
    fs::write(&p, &content).unwrap();
2424
    assert!(!a.quick_status().unwrap().dirty);
2425
    fs::write(&p, b"g\n").unwrap();
2426
    assert!(a.quick_status().unwrap().dirty);
2427
    fs::write(&p, b"f\n").unwrap();
2428
    // Push, then a second clone commits and pushes: we are behind.
2429
    assert!(a.push("origin", false).unwrap()[0].ok);
2430
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
75167672 Andy McCall 2431
    let b = Repo::clone(&url, &root.join("b"))
2432
        .unwrap()
2433
        .with_home(root.join("home-b"));
135212de Andy McCall ↶ 2434
    write(&root.join("b"), "g.txt", b"g\n");
2435
    b.commit("g", &[]).unwrap();
2436
    b.push("origin", false).unwrap();
2437
    a.fetch("origin").unwrap();
2438
    let info = a.quick_status().unwrap();
2439
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2440
    assert_eq!(info.format("%A%D"), "-1");
2441
    let _ = origin;
2442
}
b3c5a59a Andy McCall ↶ 2443
2444
#[test]
2445
fn lazy_blobs_are_fetched_on_first_read() {
2446
    hermetic();
2447
    let dir = tempfile::tempdir().unwrap();
2448
    let root = dir.path();
2449
    let origin_dir = root.join("origin");
75167672 Andy McCall 2450
    let origin = Repo::init(&origin_dir)
2451
        .unwrap()
2452
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 2453
    let url = origin_dir.to_string_lossy().to_string();
2454
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2455
    write(&origin_dir, "big.bin", &big);
2456
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2457
    write(&origin_dir, "t.txt", b"t\n");
2458
    let h = origin.commit("blobs", &[]).unwrap();
2459
    let big_ref = Repo::blob_ref(&big);
2460
2461
    // Fetch only (no checkout) with a filter: the big blob stays absent.
75167672 Andy McCall 2462
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2463
        .unwrap()
2464
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 2465
    let a = {
2466
        let mut a = a;
2467
        a.config.set("remote.origin.url", &url).unwrap();
2468
        a.config.set("filter.max-blob", "100K").unwrap();
2469
        a.save_config().unwrap();
2470
        a
2471
    };
2472
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2473
    a.fetch("origin").unwrap();
2474
    assert!(a.store().has(&h));
2475
    assert!(!a.store().has(&big_ref), "withheld");
75167672 Andy McCall 2476
    assert!(
2477
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2478
        "small blob came along"
2479
    );
b3c5a59a Andy McCall ↶ 2480
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2481
2482
    // status and commit do not need it: adopt the state, edit a text file, commit.
2483
    let (op_ref, op) = a.head_op().unwrap();
2484
    let mut view = op.view.clone();
75167672 Andy McCall 2485
    view.bookmarks.insert(
2486
        "main".into(),
2487
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2488
    );
b3c5a59a Andy McCall ↶ 2489
    a.record_op(&[op_ref], "adopt", view).unwrap();
2490
    // Checkout reads the blob lazily, which fetches it.
2491
    a.checkout(&[h], true, "checkout").unwrap();
2492
    assert!(a.store().has(&big_ref), "fetched on first read");
2493
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2494
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2495
    write(&root.join("a"), "t.txt", b"t2\n");
2496
    a.commit("text edit", &[]).unwrap();
2497
2498
    // clone --max-blob records the filter; the checkout fetches lazily.
7421309f Andy McCall ↶ 2499
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
b3c5a59a Andy McCall ↶ 2500
    assert_eq!(b.config.max_blob, Some(1024));
2501
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2502
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2503
    assert!(parse_size("lots").is_err());
2504
}
7421309f Andy McCall ↶ 2505
2506
#[test]
2507
fn sparse_checkout_materializes_only_chosen_paths() {
2508
    hermetic();
2509
    let dir = tempfile::tempdir().unwrap();
2510
    let root = dir.path();
2511
    let origin_dir = root.join("origin");
75167672 Andy McCall 2512
    let origin = Repo::init(&origin_dir)
2513
        .unwrap()
2514
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 2515
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2516
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2517
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2518
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2519
    write(&origin_dir, "docs/logo.png", &logo);
2520
    write(&origin_dir, "README.md", b"# top\n");
2521
    let h1 = origin.commit("tree", &[]).unwrap();
2522
    let url = origin_dir.to_string_lossy().to_string();
2523
75167672 Andy McCall 2524
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2525
        .unwrap()
2526
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 2527
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2528
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2529
    assert!(root.join("a/src/main.rs").exists());
2530
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
75167672 Andy McCall 2531
    assert!(
2532
        !a.store().has(&Repo::blob_ref(&logo)),
2533
        "out-of-scope blob never fetched"
2534
    );
2535
    assert!(
2536
        !a.snapshot("status").unwrap().changed,
2537
        "out-of-scope files are not removals"
2538
    );
05e71ed6 Andy McCall ↶ 2539
    assert!(!a.quick_status().unwrap().dirty);
7421309f Andy McCall ↶ 2540
2541
    // Edits in scope commit normally and keep the rest of the tree intact.
75167672 Andy McCall 2542
    write(
2543
        &root.join("a"),
2544
        "src/lib.rs",
2545
        b"pub fn a() {}\npub fn b() {}\n",
2546
    );
7421309f Andy McCall ↶ 2547
    let h2 = a.commit("edit lib", &[]).unwrap();
2548
    let st = a.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 2549
    assert!(
2550
        st.files.contains_key("docs/guide.md"),
2551
        "the state still has everything"
2552
    );
7421309f Andy McCall ↶ 2553
    assert!(a.push("origin", false).unwrap()[0].ok);
2554
    // Files created outside the scope are ignored by status.
2555
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2556
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2557
2558
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2559
    let mut a = a;
2560
    a.config.set("filter.paths", "src,docs").unwrap();
2561
    a.save_config().unwrap();
75167672 Andy McCall 2562
    let r = a
2563
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2564
        .unwrap();
7421309f Andy McCall ↶ 2565
    assert!(r.written >= 2);
75167672 Andy McCall 2566
    assert_eq!(
2567
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2568
        logo,
2569
        "now fetched lazily"
2570
    );
7421309f Andy McCall ↶ 2571
    assert!(!root.join("a/README.md").exists());
2572
    // Origin sees the change made under a sparse checkout with the full tree intact.
2573
    origin.pull("origin").err();
75167672 Andy McCall 2574
    let full = origin
2575
        .load_state(&origin.bookmark_heads().unwrap())
2576
        .unwrap()
2577
        .materialize();
2578
    assert!(
2579
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2580
    );
7421309f Andy McCall ↶ 2581
    assert!(full.files.contains_key("README.md"));
2582
    let _ = h1;
2583
}
2863456a Andy McCall ↶ 2584
2585
#[test]
2586
fn shallow_clone_and_deepen() {
2587
    hermetic();
2588
    let dir = tempfile::tempdir().unwrap();
2589
    let root = dir.path();
2590
    let origin_dir = root.join("origin");
75167672 Andy McCall 2591
    let origin = Repo::init(&origin_dir)
2592
        .unwrap()
2593
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2594
    let mut hashes = Vec::new();
2595
    for i in 0..8 {
75167672 Andy McCall 2596
        write(
2597
            &origin_dir,
2598
            "a.txt",
2599
            format!(
2600
                "{}\n",
2601
                (0..=i)
2602
                    .map(|k| k.to_string())
2603
                    .collect::<Vec<_>>()
2604
                    .join("\n")
2605
            )
2606
            .as_bytes(),
2607
        );
2863456a Andy McCall ↶ 2608
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2609
    }
2610
    let url = origin_dir.to_string_lossy().to_string();
75167672 Andy McCall 2611
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2612
        .unwrap()
2613
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2614
    assert!(a.is_shallow());
75167672 Andy McCall 2615
    assert_eq!(
2616
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2617
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2618
    );
2619
    assert!(
2620
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2621
        "three levels present"
2622
    );
2863456a Andy McCall ↶ 2623
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2624
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
75167672 Andy McCall 2625
    assert_eq!(
2626
        a.log().unwrap().len(),
2627
        9,
2628
        "the log shows every change from the checkpoint's metadata"
2629
    );
2863456a Andy McCall ↶ 2630
    assert!(!a.snapshot("status").unwrap().changed);
2631
    assert_eq!(a.quick_status().unwrap().heads, 1);
2632
2633
    // Work continues on top of the shallow history and pushes back.
2634
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2635
    let h_new = a.commit("c8", &[]).unwrap();
2636
    assert!(a.push("origin", false).unwrap()[0].ok);
2637
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2638
    // Fetching new work from origin into the shallow clone works too.
2639
    write(&origin_dir, "b.txt", b"b\n");
2640
    origin.pull("origin").err();
2641
    let (_, wc) = origin.working_copy().unwrap();
2642
    let _ = wc;
75167672 Andy McCall 2643
    origin
2644
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2645
        .unwrap();
2863456a Andy McCall ↶ 2646
    write(&origin_dir, "b.txt", b"b\n");
2647
    let h_b = origin.commit("b", &[]).unwrap();
2648
    let pr = a.pull("origin").unwrap();
2649
    assert!(pr.changed);
2650
    assert!(a.store().has(&h_b));
2651
    assert!(root.join("a/b.txt").exists());
2652
2653
    // Deepening fetches older history until the boundary is gone.
2654
    // Every commit also depends on the change that created the file, so two
2655
    // levels below the boundary hold h4, h3, and the root.
2656
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2657
    assert!(a.store().has(&hashes[3]));
2658
    assert!(a.is_shallow());
2659
    a.deepen("origin", 100).unwrap();
2660
    assert!(!a.is_shallow(), "boundary reached the root");
2661
    assert!(a.store().has(&hashes[0]));
75167672 Andy McCall 2662
    assert_eq!(
2663
        a.load_state_full(&a.bookmark_heads().unwrap())
2664
            .unwrap()
2665
            .len(),
2666
        10
2667
    );
2863456a Andy McCall ↶ 2668
}
132b884b Andy McCall ↶ 2669
2670
#[test]
2671
fn tags_are_immutable_named_states_and_travel() {
2672
    hermetic();
2673
    let dir = tempfile::tempdir().unwrap();
2674
    let root = dir.path();
2675
    let origin = Repo::init(&root.join("origin")).unwrap();
2676
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2677
    let mut a = Repo::clone(&url, &root.join("a"))
2678
        .unwrap()
2679
        .with_home(root.join("home-a"));
2680
    let (key_a, _) = a
2681
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2682
        .unwrap();
132b884b Andy McCall ↶ 2683
    write(&root.join("a"), "f.txt", b"1\n");
2684
    let h1 = a.commit("one", &[]).unwrap();
2685
    write(&root.join("a"), "f.txt", b"1\n2\n");
2686
    let h2 = a.commit("two", &[]).unwrap();
2687
2688
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
75167672 Andy McCall 2689
    assert_eq!(
2690
        (t.heads.clone(), t.signer.as_deref()),
2691
        (vec![h1], Some("Ada"))
2692
    );
132b884b Andy McCall ↶ 2693
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2694
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2695
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2696
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2697
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2698
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2699
    assert_eq!(sa.sigs[0].key, key_a);
2700
    // Checkout by tag.
75167672 Andy McCall 2701
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2702
        .unwrap();
132b884b Andy McCall ↶ 2703
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
75167672 Andy McCall 2704
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2705
        .unwrap();
132b884b Andy McCall ↶ 2706
2707
    // Push carries the tag; a second attestation for the name is refused.
2708
    let r = a.push("origin", false).unwrap();
2709
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2710
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
75167672 Andy McCall 2711
    let mut forged = a
2712
        .tag_refs()
2713
        .unwrap()
2714
        .into_iter()
2715
        .find(|t| t.name == "v1")
2716
        .unwrap();
2717
    forged.state = origin
2718
        .store()
2719
        .put_state(&StateObject::new(vec![h2]))
2720
        .unwrap();
132b884b Andy McCall ↶ 2721
    forged.heads = vec![h2];
2722
    forged.attestation = None;
75167672 Andy McCall 2723
    let r = origin
2724
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2725
        .unwrap();
132b884b Andy McCall ↶ 2726
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2727
2728
    // A clone gets the tag; a later tag arrives on fetch.
75167672 Andy McCall 2729
    let b = Repo::clone(&url, &root.join("b"))
2730
        .unwrap()
2731
        .with_home(root.join("home-b"));
132b884b Andy McCall ↶ 2732
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2733
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2734
    a.tag_create("v2", &[h2], "second").unwrap();
2735
    a.push("origin", false).unwrap();
2736
    let rep = b.fetch("origin").unwrap();
2737
    assert_eq!(rep.new_tags, 1);
2738
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2739
2740
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2741
    a.policy_init().unwrap();
2742
    a.push("origin", false).unwrap();
75167672 Andy McCall 2743
    let unattested = crate::protocol::TagRef {
2744
        name: "v3".into(),
2745
        state: origin
2746
            .store()
2747
            .put_state(&StateObject::new(vec![h2]))
2748
            .unwrap(),
2749
        heads: vec![h2],
2750
        attestation: None,
2751
    };
2752
    let r = origin
2753
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2754
        .unwrap();
132b884b Andy McCall ↶ 2755
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2756
    a.tag_create("v3", &[h2], "").unwrap();
2757
    let r = a.push("origin", false).unwrap();
2758
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2759
    assert!(a.gc(true).is_ok());
2760
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2761
}
4e88e774 Andy McCall ↶ 2762
2763
#[test]
2764
fn multiple_workspaces_share_a_repository() {
2765
    hermetic();
2766
    let dir = tempfile::tempdir().unwrap();
2767
    let root = dir.path();
2768
    let main_dir = root.join("main");
2769
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2770
    write(&main_dir, "a.txt", b"a\n");
2771
    let h1 = repo.commit("a", &[]).unwrap();
2772
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2773
2774
    // A second workspace elsewhere, checked out on the bookmark.
2775
    let ws_dir = root.join("ws2");
2776
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2777
    assert!(ws_dir.join(".oxy").is_file());
2778
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2779
    assert_ne!(ws.workspace(), repo.workspace());
2780
    let list = repo.workspaces().unwrap();
2781
    assert_eq!(list.len(), 2);
75167672 Andy McCall 2782
    assert!(list
2783
        .iter()
2784
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
4e88e774 Andy McCall ↶ 2785
    assert!(!ws.snapshot("status").unwrap().changed);
2786
2787
    // Work in the second workspace: its own working copy, shared bookmark.
2788
    write(&ws_dir, "b.txt", b"b\n");
2789
    let s = ws.snapshot("status").unwrap();
2790
    assert_eq!(s.statuses.len(), 1);
75167672 Andy McCall 2791
    assert!(
2792
        !repo.snapshot("status").unwrap().changed,
2793
        "the first workspace is untouched"
2794
    );
4e88e774 Andy McCall ↶ 2795
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2796
    let mut heads = repo.bookmark_heads().unwrap();
2797
    heads.sort();
2798
    let mut want = vec![h1, h2];
2799
    want.sort();
2800
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2801
    assert!(!main_dir.join("b.txt").exists());
75167672 Andy McCall 2802
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2803
        .unwrap();
4e88e774 Andy McCall ↶ 2804
    assert!(main_dir.join("b.txt").exists());
2805
2806
    // Reopening from inside the second workspace finds the shared repository.
2807
    let reopened = Repo::open(&ws_dir).unwrap();
2808
    assert_eq!(reopened.workspace(), ws.workspace());
2809
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2810
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2811
2812
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2813
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2814
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2815
    repo.workspace_forget(&ws.workspace()).unwrap();
2816
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2817
    assert!(ws_dir.join("b.txt").exists());
75167672 Andy McCall 2818
    assert!(
2819
        ws.snapshot("status").is_err(),
2820
        "a forgotten workspace is no longer in the view"
2821
    );
4e88e774 Andy McCall ↶ 2822
6caacfff Andy McCall ↶ 2823
    // The working-copy lock: re-entrant in a thread; a lock whose process
2824
    // is gone is taken over, and a live process's is not, however old.
4e88e774 Andy McCall ↶ 2825
    let lock = repo.lock_snapshot().unwrap();
6caacfff Andy McCall ↶ 2826
    let again = repo.lock_working_copy().unwrap();
2827
    drop(again);
4e88e774 Andy McCall ↶ 2828
    drop(lock);
75167672 Andy McCall 2829
    let lock_path = main_dir
2830
        .join(".oxy/workspaces")
2831
        .join(repo.workspace().to_hex())
2832
        .join("lock");
4e88e774 Andy McCall ↶ 2833
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
6caacfff Andy McCall ↶ 2834
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2835
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2836
    age(&lock_path);
2837
    assert!(
2838
        !super::workspace::lock_is_stale(&lock_path),
2839
        "a live process keeps its lock"
2840
    );
2841
    fs::write(&lock_path, "4294967295").unwrap();
2842
    age(&lock_path);
4e88e774 Andy McCall ↶ 2843
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2844
}
cdb5beba Andy McCall ↶ 2845
2846
#[test]
2847
fn attributes_binary_eol_nocompress_lockable() {
2848
    hermetic();
2849
    let dir = tempfile::tempdir().unwrap();
2850
    let root = dir.path();
2851
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2852
    write(
2853
        root,
2854
        ".oxyattributes",
2855
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2856
    );
cdb5beba Andy McCall ↶ 2857
    write(root, "plain.dat", b"no nul bytes here\n");
2858
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2859
    write(root, "assets/model.bin", b"\0model");
2860
    let h = repo.commit("attrs", &[]).unwrap();
2861
    let snap = repo.load_state(&[h]).unwrap().materialize();
75167672 Andy McCall 2862
    assert!(
2863
        snap.files["plain.dat"].mode.opaque,
2864
        "binary attribute forces opaque without NUL bytes"
2865
    );
2866
    assert!(
2867
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2868
        "stored with LF"
2869
    );
2870
    assert!(
2871
        !repo.snapshot("status").unwrap().changed,
2872
        "CRLF on disk equals LF in the state"
2873
    );
cdb5beba Andy McCall ↶ 2874
    // nocompress chunks pack raw.
2875
    let r = repo.gc(true).unwrap();
2876
    assert!(r.packed.objects > 0);
2877
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2878
    fs::remove_file(root.join("notes.txt")).unwrap();
2879
    repo.checkout(&[h], true, "co").unwrap();
2880
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
75167672 Andy McCall 2881
    assert!(fs::metadata(root.join("assets/model.bin"))
2882
        .unwrap()
2883
        .permissions()
2884
        .readonly());
cdb5beba Andy McCall ↶ 2885
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2886
    repo.lock_path("assets/model.bin").unwrap();
75167672 Andy McCall 2887
    assert!(!fs::metadata(root.join("assets/model.bin"))
2888
        .unwrap()
2889
        .permissions()
2890
        .readonly());
cdb5beba Andy McCall ↶ 2891
    assert!(repo.is_locked("assets/model.bin"));
2892
    write(root, "assets/model.bin", b"\0model2");
2893
    repo.commit("edit model", &[]).unwrap();
2894
    repo.unlock_path("assets/model.bin").unwrap();
75167672 Andy McCall 2895
    assert!(fs::metadata(root.join("assets/model.bin"))
2896
        .unwrap()
2897
        .permissions()
2898
        .readonly());
cdb5beba Andy McCall ↶ 2899
    // A later checkout can still overwrite a read-only lockable file.
2900
    repo.checkout(&[h], true, "co").unwrap();
2901
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2902
}
6d3eefbc Andy McCall ↶ 2903
2904
#[cfg(unix)]
2905
#[test]
2906
fn hooks_can_veto_observe_and_add_dependencies() {
2907
    use std::os::unix::fs::PermissionsExt;
2908
    hermetic();
2909
    let dir = tempfile::tempdir().unwrap();
2910
    let root = dir.path();
2911
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2912
    let hooks = root.join(".oxy/hooks");
2913
    fs::create_dir_all(&hooks).unwrap();
2914
    let hook = |name: &str, body: &str| {
2915
        let p = hooks.join(name);
2916
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2917
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2918
    };
2919
    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");
2920
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2921
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2922
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2923
    write(root, ".oxyignore", b".last-*\n");
2924
    write(root, "a.txt", b"a\n");
2925
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2926
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2927
    let h1 = repo.commit("first", &[]).unwrap();
2928
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
75167672 Andy McCall 2929
    assert!(
2930
        pre.contains("\"event\":\"pre-commit\"")
2931
            && pre.contains("\"path\":\"a.txt\"")
2932
            && pre.contains("\"message\":\"first\""),
2933
        "{pre}"
2934
    );
6d3eefbc Andy McCall ↶ 2935
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2936
    assert!(post.contains(&h1.to_hex()), "{post}");
2937
    repo.checkout(&[h1], false, "co").unwrap();
75167672 Andy McCall 2938
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2939
        .unwrap()
2940
        .contains("post-checkout"));
6d3eefbc Andy McCall ↶ 2941
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2942
    repo.save_config().unwrap();
2943
    let err = repo.push("origin", false).unwrap_err().to_string();
2944
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2945
2946
    // semantic-deps: only when enabled; adds an explicit dependency.
2947
    write(root, "b.txt", b"b\n");
75167672 Andy McCall 2948
    hook(
2949
        "semantic-deps",
2950
        &format!(
2951
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2952
            h1.to_hex()
2953
        ),
2954
    );
6d3eefbc Andy McCall ↶ 2955
    let h2 = repo.commit("b without hook", &[]).unwrap();
75167672 Andy McCall 2956
    assert!(
2957
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2958
        "hook disabled by default"
2959
    );
6d3eefbc Andy McCall ↶ 2960
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2961
    repo.save_config().unwrap();
2962
    write(root, "c.txt", b"c\n");
2963
    let h3 = repo.commit("c with hook", &[]).unwrap();
2964
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2965
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
75167672 Andy McCall 2966
    assert!(
2967
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2968
        "{sem}"
2969
    );
6d3eefbc Andy McCall ↶ 2970
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2971
}
23b217d7 Andy McCall ↶ 2972
2973
#[test]
2974
fn amend_into_older_change_and_split() {
2975
    hermetic();
2976
    let dir = tempfile::tempdir().unwrap();
2977
    let root = dir.path();
2978
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2979
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2980
        .unwrap();
23b217d7 Andy McCall ↶ 2981
    repo.set_user_config("core.sign", "change").unwrap();
2982
    write(root, "a.txt", b"one\ntwo\n");
2983
    let h0 = repo.commit("base", &[]).unwrap();
2984
    write(root, "a.txt", b"one\nTWO\n");
2985
    let h1 = repo.commit("edit two", &[]).unwrap();
2986
    write(root, "a.txt", b"one\nTWO\nthree\n");
2987
    let h2 = repo.commit("add three", &[]).unwrap();
2988
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2989
2990
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2991
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2992
    let h1b = repo.amend_into(&h1, None).unwrap();
2993
    assert_ne!(h1b, h1);
2994
    let c1b = repo.store().get_change(&h1b).unwrap();
2995
    assert_eq!(c1b.change_id, id1);
2996
    assert_eq!(c1b.deps, vec![h0]);
75167672 Andy McCall 2997
    assert!(matches!(
2998
        repo.verify_change(&h1b).unwrap(),
2999
        SignatureStatus::Valid { .. }
3000
    ));
23b217d7 Andy McCall ↶ 3001
    let heads = repo.bookmark_heads().unwrap();
3002
    assert_eq!(heads.len(), 1);
3003
    let top = repo.store().get_change(&heads[0]).unwrap();
3004
    assert_eq!(top.message, "add three");
75167672 Andy McCall 3005
    assert_eq!(
3006
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
3007
        [h0, h1b].into_iter().collect(),
3008
        "depends on the file's creator and the rewritten line"
3009
    );
23b217d7 Andy McCall ↶ 3010
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 3011
    assert!(
3012
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
3013
    );
3014
    assert!(
3015
        !repo.snapshot("status").unwrap().changed,
3016
        "the working copy is clean after folding"
3017
    );
23b217d7 Andy McCall ↶ 3018
    // Only h1b's own state shows the fix without "three".
3019
    let only = repo.load_state(&[h1b]).unwrap().materialize();
75167672 Andy McCall 3020
    assert!(
3021
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
3022
    );
23b217d7 Andy McCall ↶ 3023
    assert_eq!(repo.log().unwrap().len(), 4);
3024
3025
    // An edit to a line introduced by h2 cannot fold into h1.
3026
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
3027
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
3028
    assert!(err.contains("introduced after"), "{err}");
75167672 Andy McCall 3029
    assert!(
3030
        repo.snapshot("status").unwrap().statuses.len() == 1,
3031
        "nothing was changed by the refusal"
3032
    );
23b217d7 Andy McCall ↶ 3033
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3034
3035
    // Split the head that touches two files.
3036
    write(root, "b.txt", b"b\n");
3037
    write(root, "c.txt", b"c\n");
3038
    let h3 = repo.commit("b and c", &[]).unwrap();
3039
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
3040
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
3041
    let c_1 = repo.store().get_change(&p1).unwrap();
3042
    let c_2 = repo.store().get_change(&p2).unwrap();
3043
    assert!(c_1.message.contains("part 1: b.txt"));
3044
    assert_eq!(c_2.change_id, id3);
3045
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
75167672 Andy McCall 3046
    assert!(
3047
        heads.contains(&p1) && heads.contains(&p2),
3048
        "independent parts are both heads"
3049
    );
3050
    let snap = repo
3051
        .load_state(&repo.bookmark_heads().unwrap())
3052
        .unwrap()
3053
        .materialize();
23b217d7 Andy McCall ↶ 3054
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
3055
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
3056
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
3057
    assert!(!repo.snapshot("status").unwrap().changed);
3058
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
3059
    let _ = h2;
3060
}
28fc23d7 Andy McCall ↶ 3061
3062
#[test]
3063
fn identity_lifecycle() {
3064
    hermetic();
3065
    let dir = tempfile::tempdir().unwrap();
3066
    let root = dir.path();
3067
    let origin = Repo::init(&root.join("origin")).unwrap();
3068
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3069
    let mut a = Repo::clone(&url, &root.join("a"))
3070
        .unwrap()
3071
        .with_home(root.join("home-a"));
28fc23d7 Andy McCall ↶ 3072
    a.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 3073
    let (key_a, _) = a
3074
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3075
        .unwrap();
28fc23d7 Andy McCall ↶ 3076
    write(&root.join("a"), "a.txt", b"a\n");
3077
    let h1 = a.commit("one", &[]).unwrap();
3078
    assert!(a.policy_init().unwrap().applied);
3079
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3080
3081
    // Expiry: an identity that had expired when the change was made does not authenticate it.
75167672 Andy McCall 3082
    let mut e = Repo::init(&root.join("e"))
3083
        .unwrap()
3084
        .with_home(root.join("home-e"));
28fc23d7 Andy McCall ↶ 3085
    e.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 3086
    e.create_identity_with(
3087
        "Eve",
3088
        "[email protected]",
3089
        IdentityScope::User,
3090
        Some(Hlc::now().wall_ms - 1),
3091
    )
3092
    .unwrap();
28fc23d7 Andy McCall ↶ 3093
    write(&root.join("e"), "e.txt", b"e\n");
3094
    let he = e.commit("late", &[]).unwrap();
75167672 Andy McCall 3095
    assert!(
3096
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
3097
    );
28fc23d7 Andy McCall ↶ 3098
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
75167672 Andy McCall 3099
    let r = e
3100
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
3101
        .unwrap();
28fc23d7 Andy McCall ↶ 3102
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
3103
    write(&root.join("e"), "e.txt", b"e2\n");
3104
    let he2 = e.commit("in time", &[]).unwrap();
75167672 Andy McCall 3105
    assert!(
3106
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
3107
    );
28fc23d7 Andy McCall ↶ 3108
3109
    // Rotation: a fresh key; the old change still verifies; the policy follows.
3110
    let r = a.rotate_identity().unwrap();
3111
    assert_eq!(r.old, key_a);
3112
    assert_eq!(a.config.author_key, Some(r.new));
3113
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
3114
    assert!(r.policy.as_ref().unwrap().applied);
3115
    let (_, sp) = a.current_policy().unwrap().unwrap();
75167672 Andy McCall 3116
    assert_eq!(
3117
        (sp.policy.serial, sp.policy.roots.clone()),
3118
        (2, vec![r.new])
3119
    );
3120
    assert!(
3121
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
3122
        "superseded, not revoked"
3123
    );
28fc23d7 Andy McCall ↶ 3124
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
75167672 Andy McCall 3125
    assert!(
3126
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
3127
    );
28fc23d7 Andy McCall ↶ 3128
    write(&root.join("a"), "a.txt", b"a2\n");
3129
    let h2 = a.commit("two", &[]).unwrap();
75167672 Andy McCall 3130
    assert!(
3131
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
3132
    );
28fc23d7 Andy McCall ↶ 3133
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
3134
    let res = a.push("origin", false).unwrap();
3135
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3136
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
3137
    let key_a = r.new;
3138
3139
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
3140
    // identity object, so Ada's KeyId changes while her keys stay the same.
75167672 Andy McCall 3141
    let mut b = Repo::clone(&url, &root.join("b"))
3142
        .unwrap()
3143
        .with_home(root.join("home-b"));
3144
    let (key_b, id_b) = b
3145
        .create_identity("Bob", "[email protected]", IdentityScope::User)
3146
        .unwrap();
7ba155f2 Andy McCall ↶ 3147
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
28fc23d7 Andy McCall ↶ 3148
    assert_eq!(r.old, key_a);
3149
    let key_a2 = r.new;
75167672 Andy McCall 3150
    assert_eq!(
7ba155f2 Andy McCall ↶ 3151
        a.identity(&key_a2).unwrap().delegates,
3152
        vec![Delegate::full(key_b)]
3153
    );
3154
    assert_eq!(
75167672 Andy McCall 3155
        a.identity(&key_a2).unwrap().ed25519_pk,
3156
        a.identity(&key_a).unwrap().ed25519_pk
7ba155f2 Andy McCall ↶ 3157
    );
3158
    assert!(
3159
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
3160
        "already a delegate"
75167672 Andy McCall 3161
    );
28fc23d7 Andy McCall ↶ 3162
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3163
    write(&root.join("a"), "a.txt", b"a3\n");
3164
    let h3 = a.commit("three", &[]).unwrap();
75167672 Andy McCall 3165
    assert!(
3166
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
3167
        "the same secret signs under the new KeyId"
3168
    );
28fc23d7 Andy McCall ↶ 3169
    // A change authored by Ada but signed only by Bob verifies through the delegation.
3170
    a.set_user_config("core.sign", "seal").unwrap();
3171
    write(&root.join("a"), "a.txt", b"a4\n");
3172
    let h4 = a.commit("four", &[]).unwrap();
3173
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
3174
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 3175
    a.store()
3176
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
3177
        .unwrap();
3178
    assert!(
3179
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
3180
    );
28fc23d7 Andy McCall ↶ 3181
    a.set_user_config("core.sign", "change").unwrap();
3182
    // Withdrawing the delegation re-issues the identity again.
3183
    let r = a.delegate_remove(&key_b).unwrap();
3184
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
3185
    assert!(a.delegate_remove(&key_b).is_err());
3186
    let key_a3 = r.new;
3187
    let res = a.push("origin", false).unwrap();
3188
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3189
3190
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
3191
    // both applied under the old threshold of 1. A grant then needs Bob too.
3192
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
3193
    assert!(a.policy_root_add(id_b.clone()).is_err());
3194
    assert!(a.policy_set_threshold(3).is_err());
3195
    assert!(a.policy_set_threshold(2).unwrap().applied);
3196
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
3197
    b.pull("origin").unwrap();
75167672 Andy McCall 3198
    assert_eq!(
3199
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
3200
        2
3201
    );
3202
    let mut c = Repo::init(&root.join("c"))
3203
        .unwrap()
3204
        .with_home(root.join("home-c"));
3205
    let (key_c, id_c) = c
3206
        .create_identity("Cy", "[email protected]", IdentityScope::User)
3207
        .unwrap();
28fc23d7 Andy McCall ↶ 3208
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
3209
    let proposal = a.policy_grant(id_c, None).unwrap();
3210
    assert!(!proposal.applied && proposal.sigs.len() == 1);
3211
    assert_eq!(proposal.policy.serial, serial_before + 1);
75167672 Andy McCall 3212
    assert_eq!(
3213
        a.current_policy().unwrap().unwrap().1.policy.serial,
3214
        serial_before,
3215
        "a proposal changes nothing yet"
3216
    );
28fc23d7 Andy McCall ↶ 3217
    // Bob signs the proposal, handed over as a file, and it applies for him.
3218
    let bytes = proposal.signed().encode();
75167672 Andy McCall 3219
    let signed = b
3220
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
3221
        .unwrap();
28fc23d7 Andy McCall ↶ 3222
    assert!(signed.applied && signed.sigs.len() == 2);
75167672 Andy McCall 3223
    assert!(b
3224
        .current_policy()
3225
        .unwrap()
3226
        .unwrap()
3227
        .1
3228
        .policy
3229
        .authorizes(&key_c, "main"));
3230
    assert!(
3231
        b.policy_sign(signed.signed()).is_err(),
3232
        "a stale proposal is refused"
3233
    );
28fc23d7 Andy McCall ↶ 3234
    // Bob publishes it and Ada picks it up.
75167672 Andy McCall 3235
    assert!(b
3236
        .push("origin", false)
3237
        .unwrap()
3238
        .iter()
3239
        .any(|x| x.name == "policy" && x.ok));
28fc23d7 Andy McCall ↶ 3240
    a.pull("origin").unwrap();
75167672 Andy McCall 3241
    assert_eq!(
3242
        a.current_policy().unwrap().unwrap().1.policy.serial,
3243
        serial_before + 1
3244
    );
28fc23d7 Andy McCall ↶ 3245
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3246
    assert!(a.policy_revoke(&key_a3).is_err());
75167672 Andy McCall 3247
    let u = a
3248
        .revoke_identity(&key_c, "left the project")
3249
        .unwrap()
3250
        .unwrap();
28fc23d7 Andy McCall ↶ 3251
    assert!(!u.applied);
3252
    assert!(a.is_revoked(&key_c).unwrap());
3253
    assert!(!b.is_revoked(&key_c).unwrap());
3254
    let u = b.policy_sign(u.signed()).unwrap();
3255
    assert!(u.applied && u.policy.is_revoked(&key_c));
3256
    assert!(b.is_revoked(&key_c).unwrap());
3257
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
75167672 Andy McCall 3258
    assert!(
3259
        b.policy_revoke(&key_a3).is_err(),
3260
        "would leave one root for a threshold of 2"
3261
    );
28fc23d7 Andy McCall ↶ 3262
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3263
    let key_c_own = c.config.author_key.unwrap();
75167672 Andy McCall 3264
    assert!(c
3265
        .revoke_identity(&key_c_own, "lost laptop")
3266
        .unwrap()
3267
        .is_none());
28fc23d7 Andy McCall ↶ 3268
    assert!(c.is_revoked(&key_c_own).unwrap());
3269
    assert_eq!(key_c_own, key_c);
3270
}
3271
6e723b81 Andy McCall ↶ 3272
#[test]
3273
fn renames_are_detected_and_tracked_as_moves() {
3274
    hermetic();
3275
    let dir = tempfile::tempdir().unwrap();
3276
    let root = dir.path();
3277
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3278
    write(
3279
        root,
3280
        "src/old.rs",
3281
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3282
    );
6e723b81 Andy McCall ↶ 3283
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3284
    write(root, "tiny.txt", b"x\n");
3285
    let h1 = repo.commit("base", &[]).unwrap();
3286
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3287
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3288
3289
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3290
    // that shares nothing with the removed file.
3291
    fs::remove_file(root.join("src/old.rs")).unwrap();
75167672 Andy McCall 3292
    write(
3293
        root,
3294
        "lib/new.rs",
3295
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3296
    );
6e723b81 Andy McCall ↶ 3297
    fs::remove_file(root.join("img.bin")).unwrap();
3298
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3299
    fs::remove_file(root.join("tiny.txt")).unwrap();
3300
    write(root, "other.txt", b"completely different\n");
3301
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3302
    let statuses: Vec<(&str, ChangeStatus)> = snap
3303
        .statuses
3304
        .iter()
3305
        .map(|s| (s.path.as_str(), s.status))
3306
        .collect();
6e723b81 Andy McCall ↶ 3307
    assert_eq!(
3308
        statuses,
75167672 Andy McCall 3309
        vec![
3310
            ("assets/img.bin", ChangeStatus::Renamed),
3311
            ("lib/new.rs", ChangeStatus::Renamed),
3312
            ("other.txt", ChangeStatus::Added),
3313
            ("src", ChangeStatus::Removed),
3314
            ("tiny.txt", ChangeStatus::Removed)
3315
        ]
6e723b81 Andy McCall ↶ 3316
    );
3317
    let h2 = repo.commit("move things", &[]).unwrap();
3318
    let c = repo.store().get_change(&h2).unwrap();
75167672 Andy McCall 3319
    let moves: Vec<_> = c
3320
        .tree_ops
3321
        .iter()
3322
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3323
        .collect();
6e723b81 Andy McCall ↶ 3324
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
75167672 Andy McCall 3325
    assert!(c.tree_ops.iter().any(
3326
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3327
    ));
3328
    assert!(c.tree_ops.iter().any(
3329
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3330
    ));
6e723b81 Andy McCall ↶ 3331
    let snap = repo.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 3332
    assert_eq!(
3333
        snap.files["lib/new.rs"].node, node_old,
3334
        "the node survives the rename"
3335
    );
3336
    assert!(
3337
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3338
    );
6e723b81 Andy McCall ↶ 3339
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
75167672 Andy McCall 3340
    assert!(render_change(
3341
        &c,
3342
        &repo.load_state(&[h1]).unwrap(),
3343
        &repo.load_state(&[h1]).unwrap().materialize()
3344
    )
3345
    .contains("R "));
6e723b81 Andy McCall ↶ 3346
    // A fresh checkout reproduces the tree.
3347
    let other = tempfile::tempdir().unwrap();
3348
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
75167672 Andy McCall 3349
    assert_eq!(
3350
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3351
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3352
    );
6e723b81 Andy McCall ↶ 3353
    assert!(!other.path().join("src").exists());
3354
    assert!(!clone.snapshot("status").unwrap().changed);
3355
    // Similarity is line based, byte weighted.
3356
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3357
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3358
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3359
    assert_eq!(similarity(b"", b"x\n"), 0);
3360
}
3361
30ea9c1e Andy McCall ↶ 3362
#[test]
3363
fn git_fetch_and_push_round_trip() {
3364
    hermetic();
75167672 Andy McCall 3365
    if std::process::Command::new("git")
3366
        .arg("--version")
3367
        .output()
3368
        .is_err()
3369
    {
30ea9c1e Andy McCall ↶ 3370
        eprintln!("git not installed; skipping");
3371
        return;
3372
    }
3373
    let dir = tempfile::tempdir().unwrap();
3374
    let root = dir.path();
3375
    let git_in = |d: &Path, args: &[&str]| -> String {
3376
        let out = std::process::Command::new("git")
3377
            .arg("-C")
3378
            .arg(d)
75167672 Andy McCall 3379
            .args([
3380
                "-c",
3381
                "user.name=Grace",
3382
                "-c",
3383
                "[email protected]",
3384
                "-c",
3385
                "commit.gpgsign=false",
3386
            ])
30ea9c1e Andy McCall ↶ 3387
            .args(args)
3388
            .output()
3389
            .unwrap();
75167672 Andy McCall 3390
        assert!(
3391
            out.status.success(),
3392
            "git {args:?}: {}",
3393
            String::from_utf8_lossy(&out.stderr)
3394
        );
30ea9c1e Andy McCall ↶ 3395
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3396
    };
3397
    // A bare "remote" and a work tree that pushes to it.
3398
    let remote = root.join("remote.git");
3399
    fs::create_dir_all(&remote).unwrap();
3400
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3401
    let work = root.join("work");
75167672 Andy McCall 3402
    git_in(
3403
        root,
3404
        &[
3405
            "clone",
3406
            "-q",
3407
            remote.to_str().unwrap(),
3408
            work.to_str().unwrap(),
3409
        ],
3410
    );
30ea9c1e Andy McCall ↶ 3411
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3412
    write(&work, "README.md", b"# Project\n");
3413
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3414
    git_in(&work, &["add", "."]);
3415
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3416
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3417
    git_in(&work, &["commit", "-q", "-am", "second"]);
3418
    git_in(&work, &["push", "-q", "origin", "main"]);
3419
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3420
3421
    // Fetch into a fresh oxy repository.
3422
    let o = root.join("oxy");
3423
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3424
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3425
        .unwrap();
30ea9c1e Andy McCall ↶ 3426
    let url = remote.to_string_lossy().to_string();
3427
    let r = repo.git_fetch(&url, "main").unwrap();
3428
    assert_eq!((r.commits, r.heads), (2, 1));
75167672 Andy McCall 3429
    assert_eq!(
3430
        fs::read(o.join("src/lib.rs")).unwrap(),
3431
        b"pub fn a() {}\npub fn b() {}\n"
3432
    );
30ea9c1e Andy McCall ↶ 3433
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 3434
    assert_eq!(
3435
        repo.git_fetch(&url, "main").unwrap().commits,
3436
        0,
3437
        "nothing new"
3438
    );
30ea9c1e Andy McCall ↶ 3439
3440
    // An oxy change, pushed back: one commit on top of the Git tip.
75167672 Andy McCall 3441
    write(
3442
        &o,
3443
        "src/lib.rs",
3444
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3445
    );
30ea9c1e Andy McCall ↶ 3446
    write(&o, "NOTES.md", b"from oxy\n");
3447
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3448
    let r = repo.git_push(&url, "main").unwrap();
3449
    assert_eq!(r.exported, 1, "{r:?}");
3450
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
75167672 Andy McCall 3451
    assert_eq!(
3452
        git_in(&work, &["log", "--format=%s", "main"]),
3453
        "add c and notes\nsecond\ninitial"
3454
    );
30ea9c1e Andy McCall ↶ 3455
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3456
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3457
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
75167672 Andy McCall 3458
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3459
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3460
    assert_eq!(
3461
        repo.git_push(&url, "main").unwrap().exported,
3462
        0,
3463
        "already pushed"
3464
    );
30ea9c1e Andy McCall ↶ 3465
3466
    // Git moves on; pushing without fetching is refused, fetching brings
3467
    // the commit in and the working copy follows.
3468
    write(&work, "README.md", b"# Project\n\nMore.\n");
3469
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3470
    git_in(&work, &["push", "-q", "origin", "main"]);
3471
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
75167672 Andy McCall 3472
    assert!(repo
3473
        .git_push(&url, "main")
3474
        .unwrap_err()
3475
        .to_string()
3476
        .contains("fetch"));
30ea9c1e Andy McCall ↶ 3477
    let r = repo.git_fetch(&url, "main").unwrap();
75167672 Andy McCall 3478
    assert_eq!(
3479
        (r.commits, r.heads),
3480
        (1, 2),
3481
        "the Git change and the oxy change commute"
3482
    );
3483
    assert_eq!(
3484
        fs::read(o.join("README.md")).unwrap(),
3485
        b"# Project\n\nMore.\n"
3486
    );
30ea9c1e Andy McCall ↶ 3487
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3488
    assert!(!repo.snapshot("status").unwrap().changed);
3489
    // Another oxy change pushes on top of Git's newest commit.
3490
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3491
    repo.commit("notes again", &[]).unwrap();
3492
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3493
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3494
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
75167672 Andy McCall 3495
    assert_eq!(
3496
        fs::read(work.join("NOTES.md")).unwrap(),
3497
        b"from oxy\nagain\n"
3498
    );
3499
    assert_eq!(
3500
        git_in(&work, &["log", "--format=%s", "main"])
3501
            .lines()
3502
            .count(),
3503
        5
3504
    );
30ea9c1e Andy McCall ↶ 3505
}
3506
2b872d07 Andy McCall ↶ 3507
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3508
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3509
#[test]
3510
#[ignore]
3511
fn bench_one_gibibyte_file() {
3512
    hermetic();
3513
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3514
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3515
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3516
        None => tempfile::tempdir().unwrap(),
3517
    };
3518
    let root = dir.path();
75167672 Andy McCall 3519
    let repo = Repo::init(&root.join("r"))
3520
        .unwrap()
3521
        .with_home(root.join("home"));
2b872d07 Andy McCall ↶ 3522
    let size = 1usize << 30;
3523
    let mut data = vec![0u8; size];
3524
    let mut x = 0x9e3779b97f4a7c15u64;
3525
    for chunk in data.chunks_mut(8) {
3526
        x ^= x << 13;
3527
        x ^= x >> 7;
3528
        x ^= x << 17;
3529
        let b = x.to_le_bytes();
3530
        chunk.copy_from_slice(&b[..chunk.len()]);
3531
    }
3532
    let t = std::time::Instant::now();
3533
    write(&root.join("r"), "big.bin", &data);
3534
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3535
    let t = std::time::Instant::now();
3536
    let h = repo.commit("big", &[]).unwrap();
3537
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3538
    let t = std::time::Instant::now();
3539
    assert!(!repo.snapshot("status").unwrap().changed);
3540
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3541
    let t = std::time::Instant::now();
3542
    let objects = repo.store().list().unwrap().len();
3543
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3544
    let t = std::time::Instant::now();
3545
    let g = repo.gc(true).unwrap();
3546
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3547
    let t = std::time::Instant::now();
3548
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3549
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3550
    let t = std::time::Instant::now();
3551
    let back = fs::read(root.join("c/big.bin")).unwrap();
3552
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3553
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3554
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3555
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
75167672 Andy McCall 3556
    eprintln!(
3557
        "store size: {:.1} MiB for 1 GiB of data",
3558
        store_bytes as f64 / (1024.0 * 1024.0)
3559
    );
2b872d07 Andy McCall ↶ 3560
}
3561
3562
fn walkdir_size(p: &Path) -> u64 {
3563
    let mut total = 0;
3564
    if let Ok(rd) = fs::read_dir(p) {
3565
        for e in rd.flatten() {
3566
            let path = e.path();
3567
            if path.is_dir() {
3568
                total += walkdir_size(&path);
3569
            } else if let Ok(m) = fs::metadata(&path) {
3570
                total += m.len();
3571
            }
3572
        }
3573
    }
3574
    total
3575
}
3576
b7f102fc Andy McCall ↶ 3577
/// An opaque file whose size and mtime match the manifest is not read on
3578
/// the next snapshot: its blob comes from the manifest's stat cache.
3579
#[cfg(unix)]
3580
#[test]
3581
fn stat_cache_skips_reading_unchanged_opaque_files() {
3582
    use std::os::unix::fs::PermissionsExt;
3583
    hermetic();
3584
    let dir = tempfile::tempdir().unwrap();
3585
    let root = dir.path();
3586
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3587
    let mut big = vec![0u8; 300 * 1024];
3588
    for (i, b) in big.iter_mut().enumerate() {
3589
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3590
    }
3591
    big[0] = 0;
3592
    write(root, "big.bin", &big);
3593
    write(root, "a.txt", b"text\n");
3594
    let h1 = repo.commit("base", &[]).unwrap();
3595
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
75167672 Andy McCall 3596
    assert!(
3597
        m.entries["big.bin"].blob.is_some(),
3598
        "opaque files record their blob"
3599
    );
b7f102fc Andy McCall ↶ 3600
    assert!(m.entries["a.txt"].blob.is_none());
3601
    let blob = m.entries["big.bin"].blob.unwrap();
3602
    assert!(repo.store().has(&blob));
3603
3604
    // Files modified within two seconds of the manifest are racy and still
3605
    // read; age the file so the cache applies, then snapshot to record it.
3606
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
75167672 Andy McCall 3607
    fs::File::options()
3608
        .write(true)
3609
        .open(root.join("big.bin"))
3610
        .unwrap()
3611
        .set_modified(old)
3612
        .unwrap();
b7f102fc Andy McCall ↶ 3613
    assert!(!repo.snapshot("status").unwrap().changed);
3614
    // Now the file cannot be read at all; the snapshot succeeds without it.
3615
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3616
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3617
    assert!(
3618
        !snap.changed && snap.statuses.is_empty(),
3619
        "{:?}",
3620
        snap.statuses
3621
    );
b7f102fc Andy McCall ↶ 3622
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3623
    // A real change (new mtime, new content) is seen and committed correctly.
3624
    let mut big2 = big.clone();
3625
    big2[10] ^= 0xff;
3626
    write(root, "big.bin", &big2);
3627
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3628
    assert_eq!(
3629
        snap.statuses
3630
            .iter()
3631
            .map(|s| (s.path.as_str(), s.status))
3632
            .collect::<Vec<_>>(),
3633
        vec![("big.bin", ChangeStatus::Modified)]
3634
    );
b7f102fc Andy McCall ↶ 3635
    let h2 = repo.commit("edit", &[]).unwrap();
3636
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 3637
    assert_eq!(
3638
        files["big.bin"].content,
3639
        FileContent::Opaque {
3640
            blobs: vec![Repo::blob_ref(&big2)]
3641
        }
3642
    );
b7f102fc Andy McCall ↶ 3643
    // Checkout writes a manifest with blobs too, so the next status is cached.
3644
    repo.checkout(&[h1], false, "checkout").unwrap();
3645
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3646
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3647
    assert!(!repo.snapshot("status").unwrap().changed);
3648
}
3649
50a046e4 Andy McCall ↶ 3650
#[test]
3651
fn status_json_lists_conflicts_with_contributors() {
3652
    hermetic();
3653
    let dir = tempfile::tempdir().unwrap();
3654
    let root = dir.path();
3655
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3656
    write(root, "a.txt", b"one\n");
3657
    let h1 = repo.commit("base", &[]).unwrap();
3658
    write(root, "a.txt", b"one\nleft\n");
3659
    let ha = repo.commit("left", &[]).unwrap();
3660
    repo.checkout(&[h1], true, "checkout").unwrap();
3661
    write(root, "a.txt", b"one\nright\n");
3662
    let hb = repo.commit("right", &[]).unwrap();
3663
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3664
    let snap = repo.snapshot("status").unwrap();
3665
    assert!(snap.base_snapshot.is_conflicted());
3666
    let json = repo.status_json(&snap).unwrap();
3667
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3668
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3669
    assert!(json.contains("\"conflicted\":true"), "{json}");
75167672 Andy McCall 3670
    assert!(
3671
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3672
        "{json}"
3673
    );
50a046e4 Andy McCall ↶ 3674
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3675
    assert!(json.contains("\"resolved\":false"), "{json}");
3676
    assert!(json.starts_with('{') && json.ends_with('}'));
3677
    // Resolve and the report says so; a clean copy has no conflicts.
3678
    write(root, "a.txt", b"one\nleft\nright\n");
3679
    let snap = repo.snapshot("status").unwrap();
3680
    let json = repo.status_json(&snap).unwrap();
3681
    assert!(json.contains("\"resolved\":true"), "{json}");
3682
    repo.commit("resolve", &[]).unwrap();
3683
    let snap = repo.snapshot("status").unwrap();
3684
    let json = repo.status_json(&snap).unwrap();
75167672 Andy McCall 3685
    assert!(
3686
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3687
        "{json}"
3688
    );
50a046e4 Andy McCall ↶ 3689
}
3690
9ac1fbe2 Andy McCall ↶ 3691
#[test]
3692
fn ignore_rules_do_not_untrack_files() {
3693
    hermetic();
3694
    let dir = tempfile::tempdir().unwrap();
3695
    let root = dir.path();
3696
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3697
    write(root, "src.c", b"int x;\n");
3698
    write(root, "build/out.o", b"\0obj");
3699
    write(root, "sub/keep.log", b"keep\n");
3700
    write(root, "sub/junk.log", b"junk\n");
3701
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3702
    let snap = repo.snapshot("status").unwrap();
3703
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 3704
    assert_eq!(
3705
        added,
3706
        vec![".oxyignore", "src.c", "sub/keep.log"],
3707
        "anchored, glob, and negated rules"
3708
    );
9ac1fbe2 Andy McCall ↶ 3709
    let h1 = repo.commit("base", &[]).unwrap();
3710
    // Ignoring a tracked file changes nothing about it.
3711
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3712
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3713
    assert_eq!(
3714
        snap.statuses
3715
            .iter()
3716
            .map(|s| s.path.as_str())
3717
            .collect::<Vec<_>>(),
3718
        vec![".oxyignore"]
3719
    );
9ac1fbe2 Andy McCall ↶ 3720
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
75167672 Andy McCall 3721
    assert!(repo
3722
        .load_state(&[h2])
3723
        .unwrap()
3724
        .materialize()
3725
        .files
3726
        .contains_key("src.c"));
9ac1fbe2 Andy McCall ↶ 3727
    // Its edits are still seen, by status and by the prompt.
3728
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3729
    write(root, "src.c", b"int x, y;\n");
3730
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3731
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3732
    assert_eq!(
3733
        snap.statuses
3734
            .iter()
3735
            .map(|s| (s.path.as_str(), s.status))
3736
            .collect::<Vec<_>>(),
3737
        vec![("src.c", ChangeStatus::Modified)]
3738
    );
9ac1fbe2 Andy McCall ↶ 3739
    let h3 = repo.commit("edit src.c", &[]).unwrap();
75167672 Andy McCall 3740
    assert!(
3741
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3742
    );
9ac1fbe2 Andy McCall ↶ 3743
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3744
    fs::remove_file(root.join("src.c")).unwrap();
3745
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3746
    assert_eq!(
3747
        snap.statuses
3748
            .iter()
3749
            .map(|s| (s.path.as_str(), s.status))
3750
            .collect::<Vec<_>>(),
3751
        vec![("src.c", ChangeStatus::Removed)]
3752
    );
9ac1fbe2 Andy McCall ↶ 3753
    repo.checkout(&[h3], true, "checkout").unwrap();
3754
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3755
    assert!(!repo.snapshot("status").unwrap().changed);
3756
    let _ = h1;
3757
}
3758
b837d2b5 Andy McCall ↶ 3759
#[test]
3760
fn split_works_on_non_heads_by_node() {
3761
    hermetic();
3762
    let dir = tempfile::tempdir().unwrap();
3763
    let root = dir.path();
3764
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3765
    write(root, "a.txt", b"one\n");
3766
    write(root, "junk/x.lock", b"lock\n");
3767
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3768
    write(root, "a.txt", b"one\ntwo\n");
3769
    let h2 = repo.commit("more work", &[]).unwrap();
3770
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3771
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3772
    // h1 is not a head: split it by node.
3773
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3774
    assert_ne!(h1b, h1);
75167672 Andy McCall 3775
    assert_eq!(
3776
        repo.store().get_change(&h1b).unwrap().change_id,
3777
        id1,
3778
        "the rest keeps the ChangeId"
3779
    );
b837d2b5 Andy McCall ↶ 3780
    let junk = repo.store().get_change(&hj).unwrap();
75167672 Andy McCall 3781
    assert!(junk.tree_ops.iter().all(
3782
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3783
    ));
b837d2b5 Andy McCall ↶ 3784
    let heads = repo.bookmark_heads().unwrap();
75167672 Andy McCall 3785
    assert!(
3786
        heads.contains(&hj),
3787
        "the split-off part is a head of its own"
3788
    );
b837d2b5 Andy McCall ↶ 3789
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 3790
    assert!(
3791
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3792
        "the dependent was rewritten onto the new hash"
3793
    );
b837d2b5 Andy McCall ↶ 3794
    assert!(snap.files.contains_key("junk/x.lock"));
75167672 Andy McCall 3795
    let h2b = heads
3796
        .iter()
3797
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3798
        .copied()
3799
        .unwrap();
b837d2b5 Andy McCall ↶ 3800
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3801
    assert!(!repo.snapshot("status").unwrap().changed);
3802
    // Abandoning the split-off head removes the junk from history.
3803
    repo.abandon(&hj).unwrap();
3804
    let heads = repo.bookmark_heads().unwrap();
3805
    let snap = repo.load_state(&heads).unwrap().materialize();
3806
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3807
    assert!(snap.files.contains_key("a.txt"));
3808
    // A dependent that touches the split-off paths blocks the split.
3809
    write(root, "junk/y.lock", b"y\n");
3810
    let hb = repo.commit("junk base", &[]).unwrap();
3811
    write(root, "junk/y.lock", b"yy\n");
3812
    write(root, "b.txt", b"b\n");
3813
    repo.commit("touches junk", &[]).unwrap();
3814
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3815
    assert!(err.contains("depends on the split-off paths"), "{err}");
3816
}
3817
7b9809e6 Andy McCall ↶ 3818
#[test]
3819
fn bookmarks_switch_merge_and_push() {
3820
    hermetic();
3821
    let dir = tempfile::tempdir().unwrap();
3822
    let root = dir.path();
3823
    let origin = Repo::init(&root.join("origin")).unwrap();
3824
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3825
    let mut repo = Repo::clone(&url, &root.join("r"))
3826
        .unwrap()
3827
        .with_home(root.join("home"));
7b9809e6 Andy McCall ↶ 3828
    let r = root.join("r");
3829
    write(&r, "a.txt", b"a\n");
3830
    let h_a = repo.commit("a", &[]).unwrap();
3831
    assert!(repo.push("origin", false).unwrap()[0].ok);
3832
3833
    // A bookmark at the working copy's base, then work on it.
3834
    assert!(repo.bookmark_create("bad name..", None).is_err());
3835
    assert!(repo.bookmark_create("-x", None).is_err());
3836
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3837
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3838
    repo.bookmark_switch("feature", false).unwrap();
3839
    assert_eq!(repo.config.bookmark, "feature");
3840
    write(&r, "a.txt", b"a\nb\n");
3841
    write(&r, "b.txt", b"b\n");
3842
    let h_b = repo.commit("b on feature", &[]).unwrap();
75167672 Andy McCall 3843
    assert_eq!(
3844
        repo.bookmark_heads().unwrap(),
3845
        vec![h_b],
3846
        "b edits a.txt, so it depends on a"
3847
    );
3848
    assert_eq!(
3849
        repo.resolve_heads("main").unwrap(),
3850
        vec![h_a],
3851
        "main is untouched"
3852
    );
3853
    assert_eq!(
3854
        repo.resolve_change("feature").unwrap(),
3855
        h_b,
3856
        "a one-head bookmark names its change"
3857
    );
7b9809e6 Andy McCall ↶ 3858
    // Reopening keeps the workspace's bookmark.
3859
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3860
    assert_eq!(reopened.config.bookmark, "feature");
3861
    // Back to main: b.txt goes away; work there.
3862
    repo.bookmark_switch("main", false).unwrap();
3863
    assert!(!r.join("b.txt").exists());
3864
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3865
    write(&r, "c.txt", b"c\n");
3866
    let h_c = repo.commit("c on main", &[]).unwrap();
3867
    let list = repo.bookmarks().unwrap();
75167672 Andy McCall 3868
    assert_eq!(
3869
        list.iter()
3870
            .map(|b| (b.name.as_str(), b.current))
3871
            .collect::<Vec<_>>(),
3872
        vec![("feature", false), ("main", true)]
3873
    );
3874
    assert_eq!(
3875
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3876
        Some(1),
3877
        "c is not on origin yet"
3878
    );
7b9809e6 Andy McCall ↶ 3879
    // Merge feature into main: the union, both heads, no merge change.
3880
    let m = repo.merge("feature").unwrap();
3881
    assert!(m.changed && m.checked_out);
3882
    let mut want = vec![h_b, h_c];
3883
    want.sort();
3884
    assert_eq!(m.heads, want);
3885
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3886
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3887
    assert!(repo.merge("main").is_err());
3888
    // The other bookmark can be pushed by name and appears at origin.
3889
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3890
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3891
    assert!(repo.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 3892
    assert_eq!(
3893
        repo.bookmarks()
3894
            .unwrap()
3895
            .iter()
3896
            .find(|b| b.name == "main")
3897
            .unwrap()
3898
            .ahead,
3899
        Some(0)
3900
    );
7b9809e6 Andy McCall ↶ 3901
    // A second workspace inherits the current bookmark and can switch independently.
3902
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3903
    assert_eq!(ws.config.bookmark, "main");
3904
    let mut ws = ws;
3905
    ws.bookmark_switch("feature", false).unwrap();
75167672 Andy McCall 3906
    assert_eq!(
3907
        Repo::open(&r).unwrap().config.bookmark,
3908
        "main",
3909
        "the first workspace is unaffected"
3910
    );
3911
    assert!(
3912
        repo.bookmark_delete("feature").is_err(),
3913
        "current bookmark of another workspace"
3914
    );
7b9809e6 Andy McCall ↶ 3915
    ws.bookmark_switch("main", false).unwrap();
3916
    // Set and delete.
3917
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3918
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3919
    repo.bookmark_delete("feature").unwrap();
3920
    assert!(repo.resolve_heads("feature").is_err());
3921
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
75167672 Andy McCall 3922
    assert!(
3923
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3924
        "changes of a deleted bookmark remain"
3925
    );
7b9809e6 Andy McCall ↶ 3926
}
3927
4dee277c Andy McCall ↶ 3928
#[test]
3929
fn oxygen_subrepos_pin_follow_and_update() {
3930
    hermetic();
3931
    let dir = tempfile::tempdir().unwrap();
3932
    let root = dir.path();
3933
    // A library repository with two commits, and a bare-ish origin for it.
3934
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3935
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
75167672 Andy McCall 3936
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3937
        .unwrap()
3938
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3939
    write(&root.join("lib"), "lib.txt", b"v1\n");
3940
    let l1 = lib.commit("lib v1", &[]).unwrap();
3941
    assert!(lib.push("origin", false).unwrap()[0].ok);
3942
    let _ = lib_origin;
3943
3944
    // The application (a clone of its own origin) adds it as a subrepo.
3945
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3946
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3947
    let _ = app_origin;
3948
    let app_dir = root.join("app");
75167672 Andy McCall 3949
    let app = Repo::clone(&app_url, &app_dir)
3950
        .unwrap()
3951
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3952
    write(&app_dir, "main.txt", b"app\n");
3953
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3954
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3955
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3956
    let snap = app.snapshot("status").unwrap();
3957
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 3958
    assert_eq!(
3959
        paths,
3960
        vec![".oxymodules", "libs/lib", "main.txt"],
3961
        "the nested files are not walked"
3962
    );
4dee277c Andy McCall ↶ 3963
    let a1 = app.commit("app with lib", &[]).unwrap();
3964
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3965
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3966
    assert!(!files.contains_key("libs/lib/lib.txt"));
3967
    assert!(!app.snapshot("status").unwrap().changed);
3968
    let subs = app.subrepos().unwrap();
3969
    assert_eq!(subs.len(), 1);
3970
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3971
3972
    // Advance the nested repository: the parent sees a modified pin.
75167672 Andy McCall 3973
    let nested = Repo::open(&app_dir.join("libs/lib"))
3974
        .unwrap()
3975
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3976
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3977
    let l2 = nested.commit("lib v2", &[]).unwrap();
3978
    assert!(nested.push("origin", false).unwrap()[0].ok);
3979
    let snap = app.snapshot("status").unwrap();
75167672 Andy McCall 3980
    assert_eq!(
3981
        snap.statuses
3982
            .iter()
3983
            .map(|s| (s.path.as_str(), s.status))
3984
            .collect::<Vec<_>>(),
3985
        vec![("libs/lib", ChangeStatus::Modified)]
3986
    );
4dee277c Andy McCall ↶ 3987
    let a2 = app.commit("bump lib", &[]).unwrap();
1a3b6203 Andy McCall ↶ 3988
    // Checking out the older app state brings the nested working copy back
3989
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4dee277c Andy McCall ↶ 3990
    let r = app.checkout(&[a1], false, "checkout").unwrap();
1a3b6203 Andy McCall ↶ 3991
    assert!(
3992
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3993
        "{:?}",
3994
        r.notes
3995
    );
4dee277c Andy McCall ↶ 3996
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
1a3b6203 Andy McCall ↶ 3997
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3998
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3999
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4dee277c Andy McCall ↶ 4000
    assert!(!app.snapshot("status").unwrap().changed);
4001
    // A dirty nested repository is left alone and reported.
4002
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
4003
    let r = app.checkout(&[a2], false, "checkout").unwrap();
75167672 Andy McCall 4004
    assert!(
4005
        r.notes.iter().any(|n| n.contains("uncommitted")),
4006
        "{:?}",
4007
        r.notes
4008
    );
4dee277c Andy McCall ↶ 4009
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4010
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
4011
    let r = app.submodule_update(false, &[]).unwrap();
4012
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
4013
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
4014
    let _ = l2;
4015
4016
    // A fresh clone of the app has the pin but no nested repository until update --init.
4017
    assert!(app.push("origin", false).unwrap()[0].ok);
4018
    let clone_dir = root.join("app-clone");
75167672 Andy McCall 4019
    let clone = Repo::clone(&app_url, &clone_dir)
4020
        .unwrap()
4021
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 4022
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
75167672 Andy McCall 4023
    assert_eq!(
4024
        clone.submodule_update(false, &[]).unwrap(),
4025
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
4026
    );
4027
    assert_eq!(
4028
        clone.submodule_update(true, &[]).unwrap(),
4029
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
4030
    );
4031
    assert_eq!(
4032
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
4033
        b"v2\n"
4034
    );
4dee277c Andy McCall ↶ 4035
    assert!(!clone.snapshot("status").unwrap().changed);
4036
    // Removing the subrepo leaves the directory and drops the node.
4037
    clone.submodule_remove("libs/lib").unwrap();
4038
    let snap = clone.snapshot("status").unwrap();
75167672 Andy McCall 4039
    assert!(
4040
        snap.statuses
4041
            .iter()
4042
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
4043
        "{:?}",
4044
        snap.statuses
4045
    );
4dee277c Andy McCall ↶ 4046
    let c = clone.commit("drop lib", &[]).unwrap();
75167672 Andy McCall 4047
    assert!(!clone
4048
        .load_state(&[c])
4049
        .unwrap()
4050
        .materialize()
4051
        .files
4052
        .contains_key("libs/lib"));
4dee277c Andy McCall ↶ 4053
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
75167672 Andy McCall 4054
    assert!(
4055
        !clone.snapshot("status").unwrap().changed,
4056
        "an unregistered nested repository is ignored"
4057
    );
4dee277c Andy McCall ↶ 4058
}
4059
4060
#[test]
4061
fn git_submodules_import_and_export_as_gitlinks() {
4062
    hermetic();
75167672 Andy McCall 4063
    if std::process::Command::new("git")
4064
        .arg("--version")
4065
        .output()
4066
        .is_err()
4067
    {
4dee277c Andy McCall ↶ 4068
        eprintln!("git not installed; skipping");
4069
        return;
4070
    }
4071
    let dir = tempfile::tempdir().unwrap();
4072
    let root = dir.path();
4073
    let git_in = |d: &Path, args: &[&str]| -> String {
4074
        let out = std::process::Command::new("git")
4075
            .arg("-C")
4076
            .arg(d)
75167672 Andy McCall 4077
            .args([
4078
                "-c",
4079
                "user.name=Grace",
4080
                "-c",
4081
                "[email protected]",
4082
                "-c",
4083
                "commit.gpgsign=false",
4084
                "-c",
4085
                "protocol.file.allow=always",
4086
            ])
4dee277c Andy McCall ↶ 4087
            .args(args)
4088
            .output()
4089
            .unwrap();
75167672 Andy McCall 4090
        assert!(
4091
            out.status.success(),
4092
            "git {args:?}: {}",
4093
            String::from_utf8_lossy(&out.stderr)
4094
        );
4dee277c Andy McCall ↶ 4095
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4096
    };
4097
    let sub = root.join("sub");
4098
    fs::create_dir_all(&sub).unwrap();
4099
    git_in(&sub, &["init", "-q", "-b", "main"]);
4100
    write(&sub, "s.txt", b"sub\n");
4101
    git_in(&sub, &["add", "."]);
4102
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
4103
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
4104
    let g = root.join("main.git");
4105
    fs::create_dir_all(&g).unwrap();
4106
    git_in(&g, &["init", "-q", "-b", "main"]);
4107
    write(&g, "README.md", b"# app\n");
4108
    git_in(&g, &["add", "."]);
4109
    git_in(&g, &["commit", "-q", "-m", "initial"]);
75167672 Andy McCall 4110
    git_in(
4111
        &g,
4112
        &[
4113
            "submodule",
4114
            "add",
4115
            "-q",
4116
            sub.to_str().unwrap(),
4117
            "vendor/sub",
4118
        ],
4119
    );
4dee277c Andy McCall ↶ 4120
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
4121
4122
    let dest = root.join("oxy");
4123
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
4124
    let rep = repo.import_git(&g, "main").unwrap();
4125
    assert_eq!((rep.commits, rep.submodules), (2, 1));
75167672 Andy McCall 4126
    let files = repo
4127
        .load_state(&repo.bookmark_heads().unwrap())
4128
        .unwrap()
4129
        .materialize()
4130
        .files;
4dee277c Andy McCall ↶ 4131
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
75167672 Andy McCall 4132
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
4133
        panic!()
4134
    };
4135
    assert_eq!(
4136
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
4137
        crate::subrepo::Pin::Git {
4138
            sha: sub_sha.clone(),
4139
            branch: "HEAD".into()
4140
        }
4141
    );
4142
    let modules =
4143
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4dee277c Andy McCall ↶ 4144
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
4145
    assert!(modules.entries["vendor/sub"].git);
75167672 Andy McCall 4146
    assert!(
4147
        files.contains_key(".gitmodules"),
4148
        "the Git file is kept for round trips"
4149
    );
4150
    assert!(
4151
        !dest.join("vendor/sub/.git").exists(),
4152
        "not cloned until update --init"
4153
    );
4dee277c Andy McCall ↶ 4154
    assert!(!repo.snapshot("status").unwrap().changed);
4155
    // update --init clones it at the pinned commit; status is unchanged.
75167672 Andy McCall 4156
    assert_eq!(
4157
        repo.submodule_update(true, &[]).unwrap(),
4158
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
4159
    );
4160
    assert_eq!(
4161
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
4162
        sub_sha
4163
    );
4dee277c Andy McCall ↶ 4164
    assert!(!repo.snapshot("status").unwrap().changed);
4165
    // Export writes the gitlink and .gitmodules back.
4166
    let mirror = root.join("mirror.git");
4167
    let rep = repo.git_export(&mirror).unwrap();
4168
    assert_eq!(rep.skipped_subrepos, 0);
4169
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
75167672 Andy McCall 4170
    assert!(
4171
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
4172
        "{ls}"
4173
    );
4174
    assert_eq!(
4175
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
4176
        ".gitmodules\nREADME.md\nvendor"
4177
    );
4dee277c Andy McCall ↶ 4178
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
75167672 Andy McCall 4179
    assert_eq!(
4180
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
4181
        orig_tree,
4182
        "tree round trip"
4183
    );
4dee277c Andy McCall ↶ 4184
}
4185
957fee30 Andy McCall ↶ 4186
#[test]
4187
fn partial_commits_by_path_and_by_hunk() {
4188
    hermetic();
4189
    let dir = tempfile::tempdir().unwrap();
4190
    let root = dir.path();
4191
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4192
    write(root, "a.txt", b"1\n2\n3\n");
4193
    write(root, "b.txt", b"b\n");
4194
    let h0 = repo.commit("base", &[]).unwrap();
4195
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
4196
    write(root, "b.txt", b"b\nbb\n");
4197
    write(root, "c.txt", b"c\n");
4198
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
75167672 Andy McCall 4199
    let h1 = repo
4200
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
4201
        .unwrap();
957fee30 Andy McCall ↶ 4202
    let c1 = repo.store().get_change(&h1).unwrap();
75167672 Andy McCall 4203
    assert!(
4204
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
4205
        "{:?}",
4206
        c1.tree_ops
4207
    );
957fee30 Andy McCall ↶ 4208
    assert_eq!(c1.deps, vec![h0]);
4209
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
75167672 Andy McCall 4210
    assert!(
4211
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
4212
    );
957fee30 Andy McCall ↶ 4213
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
4214
    assert!(!files.contains_key("c.txt"));
4215
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4216
    assert_eq!(
4217
        snap.statuses
4218
            .iter()
4219
            .map(|s| (s.path.as_str(), s.status))
4220
            .collect::<Vec<_>>(),
4221
        vec![
4222
            ("b.txt", ChangeStatus::Modified),
4223
            ("c.txt", ChangeStatus::Added)
4224
        ]
4225
    );
4226
    assert_eq!(
4227
        fs::read(root.join("b.txt")).unwrap(),
4228
        b"b\nbb\n",
4229
        "disk untouched"
4230
    );
957fee30 Andy McCall ↶ 4231
    // By hunk: pick the b.txt insert; c.txt's addition is left.
4232
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 4233
    let b_hunk = hunks
4234
        .iter()
4235
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
4236
        .unwrap()
4237
        .index;
4238
    let h2 = repo
4239
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4240
        .unwrap();
957fee30 Andy McCall ↶ 4241
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 4242
    assert!(
4243
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4244
    );
957fee30 Andy McCall ↶ 4245
    assert!(!files.contains_key("c.txt"));
4246
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4247
    assert_eq!(
4248
        snap.statuses
4249
            .iter()
4250
            .map(|s| s.path.as_str())
4251
            .collect::<Vec<_>>(),
4252
        vec!["c.txt"]
4253
    );
957fee30 Andy McCall ↶ 4254
    // Choosing only the content hunk of a file in a new directory pulls in
4255
    // the directory and file additions it needs.
4256
    write(root, "d/e.txt", b"e\n");
4257
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 4258
    let e_insert = hunks
4259
        .iter()
4260
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4261
        .unwrap()
4262
        .index;
4263
    let h3 = repo
4264
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4265
        .unwrap();
957fee30 Andy McCall ↶ 4266
    let c3 = repo.store().get_change(&h3).unwrap();
4267
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4268
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4269
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
d8c086ca Andy McCall ↶ 4270
    // Choosing a new file's addition hunk brings its content along.
4271
    write(root, "f/g.txt", b"g\n");
4272
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 4273
    let g_add = hunks
4274
        .iter()
4275
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4276
        .unwrap()
4277
        .index;
4278
    let h4 = repo
4279
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4280
        .unwrap();
d8c086ca Andy McCall ↶ 4281
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
75167672 Andy McCall 4282
    assert!(
4283
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4284
    );
4285
    assert!(!repo
4286
        .snapshot("status")
4287
        .unwrap()
4288
        .statuses
4289
        .iter()
4290
        .any(|s| s.path == "f/g.txt"));
957fee30 Andy McCall ↶ 4291
    // Everything left commits normally; the working copy is then clean.
4292
    repo.commit("the rest", &[]).unwrap();
4293
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 4294
    let files = repo
4295
        .load_state(&repo.bookmark_heads().unwrap())
4296
        .unwrap()
4297
        .materialize()
4298
        .files;
957fee30 Andy McCall ↶ 4299
    assert!(files.contains_key("c.txt"));
4300
}
4301
4302
#[test]
4303
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4304
    hermetic();
4305
    let dir = tempfile::tempdir().unwrap();
4306
    let root = dir.path();
4307
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 4308
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4309
        .unwrap();
957fee30 Andy McCall ↶ 4310
    write(root, "a.txt", b"one\n");
4311
    let h1 = repo.commit("first", &[]).unwrap();
4312
    write(root, "a.txt", b"one\ntwo\n");
4313
    let h2 = repo.commit("second", &[]).unwrap();
4314
    let b = repo.blame("a.txt").unwrap();
75167672 Andy McCall 4315
    assert_eq!(
4316
        b.iter()
4317
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4318
            .collect::<Vec<_>>(),
4319
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4320
    );
957fee30 Andy McCall ↶ 4321
    assert!(b.iter().all(|l| l.author == "Ada"));
75167672 Andy McCall 4322
    assert_eq!(
4323
        b[0].change_id,
4324
        repo.store().get_change(&h1).unwrap().change_id
4325
    );
957fee30 Andy McCall ↶ 4326
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4327
    repo.commit("rename", &[]).unwrap();
4328
    let b = repo.blame("b.txt").unwrap();
75167672 Andy McCall 4329
    assert_eq!(
4330
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4331
        vec![h1, h2],
4332
        "the node survives the rename"
4333
    );
957fee30 Andy McCall ↶ 4334
    assert!(repo.blame("a.txt").is_err());
4335
}
4336
4337
#[test]
4338
fn bisect_finds_the_first_bad_change() {
4339
    hermetic();
4340
    let dir = tempfile::tempdir().unwrap();
4341
    let root = dir.path();
4342
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4343
    let mut content = String::new();
4344
    let mut hashes = Vec::new();
4345
    for i in 1..=8 {
4346
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4347
        write(root, "f.txt", content.as_bytes());
4348
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4349
    }
4350
    // Each step appends after the previous line, so the chain is linear.
4351
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4352
    repo.bisect_start().unwrap();
75167672 Andy McCall 4353
    assert!(matches!(
4354
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4355
        BisectStep::NeedMarks { good: 1, bad: 0 }
4356
    ));
957fee30 Andy McCall ↶ 4357
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
75167672 Andy McCall 4358
    assert!(
4359
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4360
        "{step:?}"
4361
    );
957fee30 Andy McCall ↶ 4362
    // Automated: bad when the bug line is present.
75167672 Andy McCall 4363
    let step = repo
4364
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4365
        .unwrap();
957fee30 Andy McCall ↶ 4366
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
75167672 Andy McCall 4367
    assert_eq!(
4368
        repo.bisect_status().unwrap(),
4369
        Some(BisectStep::Found { culprit: hashes[4] })
4370
    );
957fee30 Andy McCall ↶ 4371
    repo.bisect_reset().unwrap();
4372
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4373
    assert!(repo.bisect_status().unwrap().is_none());
4374
    assert!(!repo.snapshot("status").unwrap().changed);
4375
    // Manual marks and a skip.
4376
    repo.bisect_start().unwrap();
4377
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4378
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4379
    let mut skipped_once = false;
4380
    let mut guard = 0;
4381
    while let BisectStep::Testing { .. } = step {
4382
        guard += 1;
4383
        assert!(guard < 20);
4384
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4385
        if !skipped_once && text.contains("line 6") {
4386
            // An untestable state away from the boundary: the search routes around it.
4387
            skipped_once = true;
4388
            step = repo.bisect_mark(None, &[]).unwrap();
4389
            continue;
4390
        }
4391
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4392
    }
4393
    assert!(skipped_once);
4394
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4395
    repo.bisect_reset().unwrap();
4396
    // Skipping the culprit itself leaves it among the candidates reported.
4397
    repo.bisect_start().unwrap();
4398
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4399
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4400
    let mut guard = 0;
4401
    while let BisectStep::Testing { heads, .. } = &step {
4402
        guard += 1;
4403
        assert!(guard < 20);
4404
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 4405
        let is_culprit_state =
4406
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4407
        step = if is_culprit_state {
4408
            repo.bisect_mark(None, &[]).unwrap()
4409
        } else {
4410
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4411
        };
957fee30 Andy McCall ↶ 4412
    }
4413
    match step {
75167672 Andy McCall 4414
        BisectStep::Inconclusive { candidates } => assert!(
4415
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4416
            "{candidates:?}"
4417
        ),
957fee30 Andy McCall ↶ 4418
        other => panic!("{other:?}"),
4419
    }
4420
    repo.bisect_reset().unwrap();
4421
}
4422
728da0f9 Andy McCall ↶ 4423
#[test]
4424
fn squash_folds_a_change_into_its_dependency() {
4425
    hermetic();
4426
    let dir = tempfile::tempdir().unwrap();
4427
    let root = dir.path();
4428
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4429
    write(root, "a.txt", b"1\n");
4430
    let a = repo.commit("A", &[]).unwrap();
4431
    write(root, "a.txt", b"1\n2\n");
4432
    let c = repo.commit("C", &[]).unwrap();
4433
    write(root, "a.txt", b"1\n2\n3\n");
4434
    let e = repo.commit("E", &[]).unwrap();
4435
    write(root, "b.txt", b"b\n");
4436
    let b = repo.commit("B", &[]).unwrap();
4437
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4438
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4439
    // E depends on C which A lacks: refused, naming it.
4440
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4441
    assert!(err.contains(&c.short(12)), "{err}");
4442
    // C into A: A' has both, C is gone, E follows and still reads the same.
4443
    let a2 = repo.squash(&c, &a).unwrap();
4444
    let a2c = repo.store().get_change(&a2).unwrap();
4445
    assert_eq!(a2c.change_id, id_a);
4446
    assert!(a2c.deps.is_empty());
4447
    let heads = repo.bookmark_heads().unwrap();
4448
    let st = repo.load_state(&heads).unwrap();
4449
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
75167672 Andy McCall 4450
    let e2 = st
4451
        .changes()
4452
        .find(|(_, m)| m.change_id == id_e)
4453
        .map(|(h, _)| *h)
4454
        .unwrap();
4455
    assert_eq!(
4456
        repo.store().get_change(&e2).unwrap().deps,
4457
        vec![a2],
4458
        "E now depends on A' alone"
4459
    );
728da0f9 Andy McCall ↶ 4460
    let files = st.materialize().files;
75167672 Andy McCall 4461
    assert!(
4462
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4463
    );
728da0f9 Andy McCall ↶ 4464
    assert!(files.contains_key("b.txt"));
4465
    assert!(st.contains(&b));
4466
    assert!(!repo.snapshot("status").unwrap().changed);
4467
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4468
    // Undo restores the three original changes.
4469
    repo.undo().unwrap();
4470
    repo.undo().unwrap();
4471
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4472
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4473
}
4474
4475
#[test]
4476
fn rebase_re_expresses_a_change_against_another_base() {
4477
    hermetic();
4478
    let dir = tempfile::tempdir().unwrap();
4479
    let root = dir.path();
4480
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4481
    write(root, "a.txt", b"1\n2\n");
4482
    let a = repo.commit("A", &[]).unwrap();
4483
    write(root, "a.txt", b"1\n2\n3\n");
4484
    let c = repo.commit("C: append 3", &[]).unwrap();
4485
    write(root, "a.txt", b"1\n2\n3\n4\n");
4486
    let e = repo.commit("E: append 4", &[]).unwrap();
4487
    // A different base: A plus a change that prepends a line.
4488
    repo.checkout(&[a], true, "checkout").unwrap();
4489
    write(root, "a.txt", b"0\n1\n2\n");
4490
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4491
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4492
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4493
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4494
    let c2 = repo.rebase(&c, &[d]).unwrap();
4495
    let c2c = repo.store().get_change(&c2).unwrap();
4496
    assert_eq!(c2c.change_id, id_c);
4497
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4498
    let heads = repo.bookmark_heads().unwrap();
4499
    let st = repo.load_state(&heads).unwrap();
4500
    assert!(!st.contains(&c) && st.contains(&d));
75167672 Andy McCall 4501
    let e2 = st
4502
        .changes()
4503
        .find(|(_, m)| m.change_id == id_e)
4504
        .map(|(h, _)| *h)
4505
        .unwrap();
728da0f9 Andy McCall ↶ 4506
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
75167672 Andy McCall 4507
    assert!(
4508
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4509
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4510
    );
728da0f9 Andy McCall ↶ 4511
    let files = st.materialize().files;
75167672 Andy McCall 4512
    assert!(
4513
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4514
        "{:?}",
4515
        files["a.txt"].content
4516
    );
728da0f9 Andy McCall ↶ 4517
    assert!(!files["a.txt"].is_conflicted());
4518
    // Rebasing onto a state that already contains the change is refused.
4519
    assert!(repo.rebase(&c2, &[c2]).is_err());
4520
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
75167672 Andy McCall 4521
    assert!(
4522
        err.contains("lacks dependencies"),
4523
        "E needs C, which D's state does not have: {err}"
4524
    );
728da0f9 Andy McCall ↶ 4525
}
4526
c792033a Andy McCall ↶ 4527
#[test]
4528
fn unsigned_tags_keep_their_message() {
4529
    hermetic();
4530
    let dir = tempfile::tempdir().unwrap();
4531
    let root = dir.path();
4532
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4533
    write(root, "a.txt", b"a\n");
4534
    repo.commit("a", &[]).unwrap();
4535
    assert!(repo.secret_key().unwrap().is_none());
75167672 Andy McCall 4536
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4537
        .unwrap();
c792033a Andy McCall ↶ 4538
    let tags = repo.tags().unwrap();
75167672 Andy McCall 4539
    assert_eq!(
4540
        (
4541
            tags[0].name.as_str(),
4542
            tags[0].message.as_str(),
4543
            tags[0].signer.as_deref()
4544
        ),
4545
        ("v1", "first release", None)
4546
    );
4547
    assert!(
4548
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4549
        "an unsigned attestation is not advertised"
4550
    );
c792033a Andy McCall ↶ 4551
}
387335ff Andy McCall ↶ 4552
4553
#[test]
4554
fn fsck_passes_a_sound_repository_and_names_each_fault() {
64818938 Andy McCall ↶ 4555
    // Files on disk are what this tests: tampering with them, and the
4556
    // directory store's crash points.
4557
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4558
        return;
4559
    }
387335ff Andy McCall ↶ 4560
    hermetic();
4561
    let dir = tempfile::tempdir().unwrap();
4562
    let root = dir.path();
4563
    let origin_path = root.join("origin");
4564
    let origin = Repo::init(&origin_path).unwrap();
4565
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4566
        .unwrap()
4567
        .with_home(root.join("home-a"));
4568
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4569
        .unwrap();
4570
    write(&root.join("a"), "f.txt", b"one\n");
4571
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4572
    let h1 = a.commit("first", &[]).unwrap();
4573
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4574
    let h2 = a.commit("second", &[]).unwrap();
4575
    a.tag_create("v1", &[h2], "first release").unwrap();
4576
    a.checkpoint().unwrap();
4577
    assert!(a.push("origin", false).unwrap()[0].ok);
4578
4579
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4580
    for repo in [&a, &origin] {
4581
        let rep = repo.fsck().unwrap();
4582
        assert_eq!(rep.problems, vec![], "{rep:?}");
4583
        // The two commits, plus the working copy's change in `a`.
4584
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4585
        assert!(rep.ops > 1 && rep.objects > 5);
4586
    }
4587
    assert!(origin.fsck().unwrap().attestations >= 1);
4588
4589
    // A flipped byte in a stored object is corruption, named by hash.
4590
    let c1 = a.store().path_for(&h1);
4591
    let pristine = fs::read(&c1).unwrap();
4592
    let mut bytes = pristine.clone();
4593
    *bytes.last_mut().unwrap() ^= 1;
4594
    fs::write(&c1, &bytes).unwrap();
4595
    let rep = a.fsck().unwrap();
4596
    assert!(rep.errors() >= 1);
4597
    assert!(
4598
        rep.problems
4599
            .iter()
4600
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4601
        "{rep:?}"
4602
    );
4603
    fs::write(&c1, &pristine).unwrap();
4604
    assert_eq!(a.fsck().unwrap().errors(), 0);
4605
4606
    // A missing change is named with what needed it.
4607
    fs::remove_file(&c1).unwrap();
4608
    let rep = a.fsck().unwrap();
4609
    assert!(
4610
        rep.problems.iter().any(|p| p.severity == Severity::Error
4611
            && p.object == Some(h1)
4612
            && p.what.contains("change missing, needed by change")),
4613
        "{rep:?}"
4614
    );
4615
    fs::write(&c1, &pristine).unwrap();
4616
4617
    // A missing blob is an error in a full clone.
4618
    let c2 = a.store().get_change(&h1).unwrap();
4619
    let blob = c2
4620
        .edits
4621
        .iter()
4622
        .find_map(|e| match e {
4623
            Edit::Replace { new: Some(b), .. } => Some(*b),
4624
            _ => None,
4625
        })
4626
        .expect("the binary file is a blob");
4627
    let bp = a.store().path_for(&blob);
4628
    let blob_bytes = fs::read(&bp).unwrap();
4629
    fs::remove_file(&bp).unwrap();
4630
    let rep = a.fsck().unwrap();
4631
    assert!(
4632
        rep.problems
4633
            .iter()
4634
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4635
        "{rep:?}"
4636
    );
4637
    fs::write(&bp, &blob_bytes).unwrap();
4638
4639
    // A broken op log head is reported, not a crash.
4640
    let head = root.join("a/.oxy/ops/head");
4641
    let saved = fs::read(&head).unwrap();
4642
    fs::write(&head, b"not a hash").unwrap();
4643
    let rep = a.fsck().unwrap();
4644
    assert!(
4645
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4646
        "{rep:?}"
4647
    );
4648
    fs::write(&head, saved).unwrap();
4649
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4650
}
4dcb8c09 Andy McCall ↶ 4651
4652
/// Copy a directory tree (for restoring a pristine repository).
4653
fn copy_tree(from: &Path, to: &Path) {
4654
    fs::create_dir_all(to).unwrap();
4655
    for e in fs::read_dir(from).unwrap() {
4656
        let e = e.unwrap();
4657
        let target = to.join(e.file_name());
4658
        if e.file_type().unwrap().is_dir() {
4659
            copy_tree(&e.path(), &target);
4660
        } else {
4661
            fs::copy(e.path(), &target).unwrap();
4662
        }
4663
    }
4664
}
4665
4666
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4667
/// would, and check that both repositories still open, pass `fsck`, and
4668
/// accept the same operation again.
4669
#[test]
4670
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
64818938 Andy McCall ↶ 4671
    // Files on disk are what this tests: tampering with them, and the
4672
    // directory store's crash points.
4673
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4674
        return;
4675
    }
4dcb8c09 Andy McCall ↶ 4676
    use crate::durable::failpoint;
4677
    hermetic();
4678
    let dir = tempfile::tempdir().unwrap();
4679
    let pristine = dir.path().join("pristine");
4680
    let origin_path = pristine.join("origin");
4681
    Repo::init(&origin_path).unwrap();
4682
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4683
        .unwrap()
4684
        .with_home(dir.path().join("home"));
4685
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4686
        .unwrap();
4687
    write(&pristine.join("a"), "f.txt", b"one\n");
4688
    a.commit("first", &[]).unwrap();
4689
    assert!(a.push("origin", false).unwrap()[0].ok);
4690
    drop(a);
4691
4692
    type Op = fn(&Repo) -> Result<()>;
4693
    let edit_and_commit: Op = |r| {
4694
        write(r.root(), "f.txt", b"one\ntwo\n");
4695
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4696
        r.commit("second", &[]).map(|_| ())
4697
    };
4698
    let push: Op = |r| {
4699
        let res = r.push("origin", false)?;
4700
        if res.iter().all(|x| x.ok) {
4701
            Ok(())
4702
        } else {
4703
            Err(RepoError::Msg(format!("{res:?}")))
4704
        }
4705
    };
4706
4707
    for (name, prepare, op) in [
4708
        ("commit", None, edit_and_commit),
4709
        ("push", Some(edit_and_commit), push),
4710
    ] {
4711
        let mut steps = 0;
4712
        for n in 1.. {
4713
            let run = dir.path().join(format!("{name}-{n}"));
4714
            copy_tree(&pristine, &run);
4715
            // Clones record their remote by path; point it at this copy.
4716
            let open = |p: &Path| {
4717
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4718
                r.config
4719
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4720
                    .unwrap();
4721
                r.save_config().unwrap();
4722
                r
4723
            };
4724
            let a = open(&run.join("a"));
4725
            if let Some(prep) = prepare {
4726
                prep(&a).unwrap();
4727
            }
4728
            failpoint::crash_after(n);
4729
            let outcome = op(&a);
4730
            let crashed = failpoint::disarm();
4731
            drop(a);
4732
            if !crashed {
4733
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4734
                steps = n - 1;
4735
                break;
4736
            }
4737
            assert!(
4738
                outcome.is_err(),
4739
                "{name}: a crash at step {n} was swallowed"
4740
            );
4741
            for repo in ["a", "origin"] {
4742
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4743
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4744
                });
4745
                let rep = r.fsck().unwrap();
4746
                assert_eq!(
4747
                    rep.errors(),
4748
                    0,
4749
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4750
                    rep.problems
4751
                );
4752
            }
4753
            // The interrupted operation can simply be run again.
4754
            let a = open(&run.join("a"));
4755
            // A crash after the commit point leaves the commit done.
4756
            let landed = a
4757
                .bookmark_heads()
4758
                .unwrap()
4759
                .iter()
4760
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4761
            let again = match (name, landed) {
4762
                ("commit", true) => Ok(()),
4763
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4764
                _ => op(&a),
4765
            };
4766
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4767
            assert_eq!(a.fsck().unwrap().errors(), 0);
4768
            fs::remove_dir_all(&run).unwrap();
4769
        }
4770
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4771
    }
4772
}
19555025 Andy McCall ↶ 4773
4774
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4775
/// running at the same time lose nothing: every commit ends up on the
4776
/// bookmark, locally and on the remote, and the repository passes fsck.
4777
#[test]
4778
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4779
    hermetic();
4780
    let dir = tempfile::tempdir().unwrap();
4781
    let root = dir.path();
4782
    let origin = root.join("origin");
4783
    Repo::init_bare_unbound(&origin).unwrap();
4784
    let main = root.join("main");
4785
    let mut repo = Repo::init(&main).unwrap();
4786
    repo.config
4787
        .set("remote.origin.url", &origin.to_string_lossy())
4788
        .unwrap();
4789
    repo.save_config().unwrap();
4790
    write(&main, "seed.txt", b"seed\n");
4791
    repo.commit("seed", &[]).unwrap();
4792
    let second = root.join("second");
4793
    repo.workspace_add(&second, None).unwrap();
4794
    drop(repo);
4795
4796
    const EACH: usize = 15;
4797
    std::thread::scope(|s| {
4798
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4799
            s.spawn(move || {
4800
                let r = Repo::open(&dir).unwrap();
4801
                for i in 0..EACH {
4802
                    write(
4803
                        &dir,
4804
                        &format!("{tag}-{i}.txt"),
4805
                        format!("{tag} {i}\n").as_bytes(),
4806
                    );
4807
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4808
                    if push && i % 5 == 4 {
4809
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4810
                        let _ = r.push("origin", false);
4811
                    }
4812
                }
4813
            });
4814
        }
4815
    });
4816
4817
    let repo = Repo::open(&main).unwrap();
4818
    let heads = repo.bookmark_heads().unwrap();
4819
    let state = repo.load_state(&heads).unwrap();
4820
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4821
    for tag in ["a", "b"] {
4822
        for i in 0..EACH {
4823
            assert!(
4824
                messages.contains(&format!("{tag} {i}")),
4825
                "lost commit {tag} {i}; have {messages:?}"
4826
            );
4827
        }
4828
    }
4829
    let rep = repo.fsck().unwrap();
4830
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4831
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4832
    let hosted = Repo::open(&origin).unwrap();
4833
    let hosted_heads = hosted.bookmark_heads().unwrap();
4834
    assert_eq!(
4835
        hosted.load_state(&hosted_heads).unwrap().len(),
4836
        state.len(),
4837
        "the remote has every commit"
4838
    );
4839
}
4840
4841
/// Two operations recorded from the same parent (what two processes do
4842
/// when they race) are merged: both bookmarks' heads survive, and a
4843
/// change made on one side only is kept.
4844
#[test]
4845
fn operations_from_the_same_parent_are_merged() {
4846
    hermetic();
4847
    let dir = tempfile::tempdir().unwrap();
4848
    let root = dir.path();
4849
    let repo = Repo::init(root).unwrap();
4850
    write(root, "a.txt", b"a\n");
4851
    let a = repo.commit("a", &[]).unwrap();
4852
    write(root, "b.txt", b"b\n");
4853
    let b = repo.commit("b", &[]).unwrap();
4854
    let (x, op) = repo.head_op().unwrap();
4855
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4856
4857
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4858
    let mut one = op.view.clone();
4859
    one.bookmarks.insert("main".into(), state(vec![a]));
4860
    one.bookmarks.insert("topic".into(), state(vec![a]));
4861
    let mut two = op.view.clone();
4862
    two.bookmarks.insert("main".into(), state(vec![b]));
4863
    repo.record_op(&[x], "one", one).unwrap();
4864
    let merged = repo.record_op(&[x], "two", two).unwrap();
4865
4866
    let (head, op) = repo.head_op().unwrap();
4867
    assert_eq!(head, merged);
4868
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4869
    assert!(op.command.contains("merged with a concurrent operation"));
4870
    let mut main = repo
4871
        .store()
4872
        .get_state(&op.view.bookmarks["main"])
4873
        .unwrap()
4874
        .heads;
4875
    main.sort();
4876
    let mut want = vec![a, b];
4877
    want.sort();
4878
    assert_eq!(main, want, "both sides' heads are kept");
4879
    assert!(
4880
        op.view.bookmarks.contains_key("topic"),
4881
        "a one-sided change survives"
4882
    );
4883
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4884
}
3e5772cc Andy McCall ↶ 4885
4886
#[test]
4887
fn failed_requests_come_with_a_next_step() {
4888
    use crate::protocol::hint_for;
4889
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4890
        .unwrap()
4891
        .contains("token"));
4892
    assert!(hint_for("…: HTTP 403: forbidden")
4893
        .unwrap()
4894
        .contains("repo:write"));
4895
    assert!(hint_for("…: HTTP 404: no such repository")
4896
        .unwrap()
4897
        .contains("owner and repository name"));
4898
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4899
        .unwrap()
4900
        .contains("oxyhub-ca.pem"));
4901
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4902
        .unwrap()
4903
        .contains("running"));
4904
    assert!(hint_for("Dns Failed: failed to lookup address information")
4905
        .unwrap()
4906
        .contains("resolve"));
4907
    assert_eq!(hint_for("something else entirely"), None);
4908
}
4909
4910
#[test]
4911
fn doctor_names_problems_and_what_to_do() {
4912
    hermetic();
4913
    let dir = tempfile::tempdir().unwrap();
4914
    let root = dir.path();
4915
    let origin = root.join("origin");
4916
    Repo::init_bare_unbound(&origin).unwrap();
4917
    let mut repo = Repo::init(&root.join("r"))
4918
        .unwrap()
4919
        .with_home(root.join("home"));
4920
    let find = |r: &DoctorReport, area: &str, h: Health| {
4921
        r.checks
4922
            .iter()
4923
            .find(|c| c.area == area && c.health == h)
4924
            .cloned()
4925
    };
4926
4927
    let r = repo.doctor(true);
4928
    assert!(find(&r, "identity", Health::Warn)
4929
        .unwrap()
4930
        .hint
4931
        .unwrap()
4932
        .contains("oxy identity create"));
4933
    assert!(find(&r, "repository", Health::Ok).is_some());
4934
4935
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4936
        .unwrap();
4937
    repo.config.set("author.name", "Ada").unwrap();
4938
    repo.config.set("author.email", "[email protected]").unwrap();
4939
    repo.config
4940
        .set("remote.origin.url", &origin.to_string_lossy())
4941
        .unwrap();
4942
    repo.config
4943
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4944
        .unwrap();
4945
    repo.config.set("remote.down.token", "t").unwrap();
4946
    repo.config
4947
        .set("remote.badca.url", "https://example.invalid/a/b")
4948
        .unwrap();
4949
    repo.config
4950
        .set(
4951
            "remote.badca.ca",
4952
            &root.join("missing.pem").to_string_lossy(),
4953
        )
4954
        .unwrap();
4955
    repo.save_config().unwrap();
4956
4957
    let r = repo.doctor(true);
4958
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4959
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4960
    assert!(find(&r, "remote origin", Health::Ok)
4961
        .unwrap()
4962
        .message
4963
        .contains("first push binds it"));
4964
    let down = find(&r, "remote down", Health::Fail).unwrap();
4965
    assert!(
4966
        down.hint.as_deref().unwrap_or("").contains("running"),
4967
        "{down:?}"
4968
    );
4969
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4970
    assert!(
4971
        badca.hint.unwrap().contains("remote.badca.ca"),
4972
        "the remote's own name is in the hint"
4973
    );
4974
    assert_eq!(r.worst(), Health::Fail);
4975
4976
    // Offline, nothing is contacted.
4977
    let r = repo.doctor(false);
4978
    assert!(find(&r, "remote down", Health::Fail).is_none());
4979
    assert!(find(&r, "remote down", Health::Ok)
4980
        .unwrap()
4981
        .message
4982
        .contains("not contacted"));
4983
}
62794ecc Andy McCall ↶ 4984
4985
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4986
/// after it. Inserting after `b` and then deleting `b`, one commit after
4987
/// the other, must not leave a delete/insert conflict.
4988
#[test]
4989
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4990
    hermetic();
4991
    let dir = tempfile::tempdir().unwrap();
4992
    let root = dir.path();
4993
    let repo = Repo::init(root).unwrap();
4994
    write(root, "f", b"a\nb\nc\n");
4995
    repo.commit("base", &[]).unwrap();
4996
    write(root, "f", b"a\nb\nx\nc\n");
4997
    let insert = repo.commit("insert x after b", &[]).unwrap();
4998
    write(root, "f", b"a\nx\nc\n");
4999
    let delete = repo.commit("delete b", &[]).unwrap();
5000
    assert!(
5001
        repo.store()
5002
            .get_change(&delete)
5003
            .unwrap()
5004
            .deps
5005
            .contains(&insert),
5006
        "the deletion depends on the insertion below the deleted line"
5007
    );
5008
    let heads = repo.bookmark_heads().unwrap();
5009
    assert_eq!(heads, vec![delete]);
5010
    let snap = repo.load_state(&heads).unwrap().materialize();
5011
    assert!(!snap.is_conflicted());
5012
    assert!(
5013
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
5014
    );
5015
}
5016
5017
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
5018
/// replacement depends on the change that set the blob it replaces.
5019
#[test]
5020
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
5021
    hermetic();
5022
    let dir = tempfile::tempdir().unwrap();
5023
    let root = dir.path();
5024
    let repo = Repo::init(root).unwrap();
5025
    write(root, "bin", b"\0A");
5026
    let v1 = repo.commit("v1", &[]).unwrap();
5027
    write(root, "bin", b"\0B");
5028
    let v2 = repo.commit("v2", &[]).unwrap();
5029
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
5030
    write(root, "bin", b"\0A");
5031
    let v3 = repo.commit("back to A", &[]).unwrap();
5032
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
5033
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
5034
    let state = repo.load_state(&[v3]).unwrap();
5035
    let snap = state.materialize();
5036
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
5037
        panic!("opaque")
5038
    };
5039
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
5040
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
5041
}
5042
5043
/// Spec §23: a binary file changed on two branches and merged in Git to
5044
/// one side's version comes back as that version at the merge, and the
5045
/// import verifies commit by commit.
5046
#[test]
5047
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
5048
    hermetic();
5049
    if std::process::Command::new("git")
5050
        .arg("--version")
5051
        .output()
5052
        .is_err()
5053
    {
5054
        eprintln!("git not installed; skipping");
5055
        return;
5056
    }
5057
    let dir = tempfile::tempdir().unwrap();
5058
    let root = dir.path();
5059
    let g = root.join("src.git");
5060
    fs::create_dir_all(&g).unwrap();
5061
    let git = |args: &[&str]| -> String {
5062
        let out = std::process::Command::new("git")
5063
            .arg("-C")
5064
            .arg(&g)
5065
            .args([
5066
                "-c",
5067
                "user.name=Grace",
5068
                "-c",
5069
                "[email protected]",
5070
                "-c",
5071
                "commit.gpgsign=false",
5072
            ])
5073
            .args(args)
5074
            .output()
5075
            .unwrap();
5076
        assert!(
5077
            out.status.success(),
5078
            "git {args:?}: {}",
5079
            String::from_utf8_lossy(&out.stderr)
5080
        );
5081
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5082
    };
5083
    git(&["init", "-q", "-b", "main"]);
5084
    write(&g, "logo.bin", b"\0base");
5085
    write(&g, "notes.txt", b"a\nb\nc\n");
5086
    git(&["add", "."]);
5087
    git(&["commit", "-qm", "base"]);
5088
    git(&["checkout", "-qb", "side"]);
5089
    write(&g, "logo.bin", b"\0side");
5090
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
5091
    git(&["commit", "-qam", "side"]);
5092
    git(&["checkout", "-q", "main"]);
5093
    write(&g, "logo.bin", b"\0main");
5094
    git(&["commit", "-qam", "main"]);
5095
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
5096
    let _ = std::process::Command::new("git")
5097
        .arg("-C")
5098
        .arg(&g)
5099
        .args([
5100
            "-c",
5101
            "user.name=G",
5102
            "-c",
5103
            "user.email=g@e",
5104
            "merge",
5105
            "-q",
5106
            "side",
5107
        ])
5108
        .output();
5109
    write(&g, "logo.bin", b"\0main");
5110
    git(&["add", "."]);
5111
    git(&["commit", "-qm", "merge side"]);
5112
    // Then a revert of the binary to its first version.
5113
    write(&g, "logo.bin", b"\0base");
5114
    git(&["commit", "-qam", "back to base"]);
5115
5116
    let repo = Repo::init(&root.join("o")).unwrap();
5117
    let rep = repo.import_git(&g, "main").unwrap();
5118
    assert_eq!(rep.merges, 1);
5119
    let v = repo.verify_git_import(&g, "main").unwrap();
5120
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
5121
    assert_eq!(v.commits, 5);
5122
    let snap = repo
5123
        .load_state(&repo.bookmark_heads().unwrap())
5124
        .unwrap()
5125
        .materialize();
5126
    assert!(!snap.is_conflicted());
5127
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
5128
        panic!("opaque")
5129
    };
5130
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
5131
}
c863c7a7 Andy McCall ↶ 5132
5133
/// Spec §7.7 on a file system without executable bits or symlinks: the
5134
/// recorded bit is kept, and a symlink checked out as a plain file holding
5135
/// its target is still that symlink.
5136
#[cfg(unix)]
5137
#[test]
5138
fn windows_file_systems_keep_exec_bits_and_symlinks() {
5139
    use crate::portable::Platform;
5140
    use std::os::unix::fs::PermissionsExt;
5141
    hermetic();
5142
    let dir = tempfile::tempdir().unwrap();
5143
    let root = dir.path();
5144
    let repo = Repo::init(root).unwrap();
5145
    write(root, "run.sh", b"#!/bin/sh\n");
5146
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
5147
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
5148
    repo.commit("script and link", &[]).unwrap();
5149
    drop(repo);
5150
5151
    // What checking out on Windows leaves: no exec bit, the link as a file.
5152
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
5153
    fs::remove_file(root.join("link")).unwrap();
5154
    write(root, "link", b"run.sh");
5155
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
5156
    let s = win.snapshot("oxy status").unwrap();
5157
    assert!(
5158
        s.statuses.is_empty(),
5159
        "nothing changed on Windows: {:?}",
5160
        statuses(&s)
5161
    );
5162
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
5163
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
5164
    write(root, "link", b"other");
5165
    let h = win.commit("edit on Windows", &[]).unwrap();
5166
    let snap = win.load_state(&[h]).unwrap().materialize();
5167
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
5168
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
5169
    // The same working copy read as Linux sees the lost bit and the plain file.
5170
    let linux = Repo::open(root).unwrap();
5171
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
5172
}
5173
5174
/// Paths that collide on case-insensitive or Windows file systems are
5175
/// named at checkout there, and by doctor everywhere.
5176
#[test]
5177
fn paths_other_platforms_cannot_hold_are_reported() {
5178
    use crate::portable::Platform;
5179
    hermetic();
5180
    let dir = tempfile::tempdir().unwrap();
5181
    let root = dir.path();
5182
    let repo = Repo::init(root).unwrap();
5183
    write(root, "README.md", b"a\n");
5184
    write(root, "readme.md", b"b\n");
5185
    write(root, "src/aux.c", b"int x;\n");
5186
    let h = repo.commit("unportable", &[]).unwrap();
5187
    let r = repo.doctor(false);
5188
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
5189
    assert_eq!(port.health, Health::Warn);
5190
    assert!(
5191
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
5192
        "{}",
5193
        port.message
5194
    );
5195
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
5196
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
5197
    assert!(
5198
        rep.notes
5199
            .iter()
5200
            .any(|n| n.contains("README.md and readme.md")),
5201
        "{:?}",
5202
        rep.notes
5203
    );
5204
    assert!(
5205
        !rep.notes.iter().any(|n| n.contains("aux.c")),
5206
        "macOS allows aux.c"
5207
    );
5208
}
bc489b6c Andy McCall ↶ 5209
5210
#[test]
5211
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
5212
    hermetic();
5213
    let dir = tempfile::tempdir().unwrap();
5214
    let repo = Repo::init(dir.path()).unwrap();
5215
    write(dir.path(), "a.txt", b"one\n");
5216
    write(dir.path(), "other.txt", b"x\n");
5217
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
5218
    repo.snapshot("t").unwrap();
5219
    let c1 = repo.commit("first", &[]).unwrap();
5220
    write(dir.path(), "other.txt", b"y\n");
5221
    repo.snapshot("t").unwrap();
5222
    repo.commit("other only", &[]).unwrap();
5223
    write(dir.path(), "a.txt", b"one\ntwo\n");
5224
    repo.snapshot("t").unwrap();
5225
    let c3 = repo.commit("second line", &[]).unwrap();
5226
    write(dir.path(), "other.txt", b"z\n");
5227
    repo.snapshot("t").unwrap();
5228
    repo.commit("other again", &[]).unwrap();
5229
5230
    let heads = repo.bookmark_heads().unwrap();
5231
    let state = repo.load_state(&heads).unwrap();
5232
    let full: Vec<ChangeHash> = repo
5233
        .log_for_path_in("a.txt", &heads)
5234
        .unwrap()
5235
        .iter()
5236
        .map(|e| e.hash)
5237
        .collect();
5238
    assert_eq!(
5239
        full,
5240
        vec![c3, c1],
5241
        "newest first, only changes touching the path"
5242
    );
5243
    let newest: Vec<ChangeHash> = repo
5244
        .log_for_path_of(&state, "a.txt", Some(1))
5245
        .unwrap()
5246
        .iter()
5247
        .map(|e| e.hash)
5248
        .collect();
5249
    assert_eq!(newest, vec![c3], "stops at the first");
5250
    assert_eq!(
5251
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5252
        2
5253
    );
5254
    assert!(repo
5255
        .log_for_path_of(&state, "missing.txt", Some(1))
5256
        .is_err());
5257
    assert_eq!(
5258
        repo.log_state(&heads).unwrap().len(),
5259
        repo.log_of(&state).len()
5260
    );
5261
5262
    let tree = state.tree().view();
5263
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5264
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5265
    assert_eq!(
5266
        via_state
5267
            .iter()
5268
            .map(|l| (l.hash, l.text.clone()))
5269
            .collect::<Vec<_>>(),
5270
        via_heads
5271
            .iter()
5272
            .map(|l| (l.hash, l.text.clone()))
5273
            .collect::<Vec<_>>()
5274
    );
5275
    assert_eq!(
5276
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5277
        vec![c1, c3]
5278
    );
5279
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5280
}
696bbf29 Andy McCall ↶ 5281
5282
/// A text file whose stat matches the manifest and whose recorded hash is
5283
/// the base's content is taken from the base without reading it; anything
5284
/// else is read, so no edit is missed (spec §12.3).
5285
#[cfg(unix)]
5286
#[test]
5287
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5288
    use std::os::unix::fs::PermissionsExt;
5289
    hermetic();
5290
    let dir = tempfile::tempdir().unwrap();
5291
    let root = dir.path();
5292
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5293
    write(root, "a.txt", b"one\ntwo\n");
5294
    write(root, "b.txt", b"bee\n");
5295
    repo.commit("base", &[]).unwrap();
5296
    let age = |p: &str| {
5297
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5298
        fs::File::options()
5299
            .write(true)
5300
            .open(root.join(p))
5301
            .unwrap()
5302
            .set_modified(old)
5303
            .unwrap();
5304
    };
5305
    age("a.txt");
5306
    age("b.txt");
5307
    assert!(
5308
        !repo.snapshot("status").unwrap().changed,
5309
        "records the aged stat"
5310
    );
5311
5312
    // Clean and equal to the base: not read at all.
5313
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5314
    let snap = repo.snapshot("status").unwrap();
5315
    assert!(
5316
        !snap.changed && snap.statuses.is_empty(),
5317
        "{:?}",
5318
        snap.statuses
5319
    );
5320
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5321
5322
    // An uncommitted edit that is older than the manifest: stat-clean, but
5323
    // its hash is not the base's, so it is read and stays visible.
5324
    write(root, "b.txt", b"bee edited\n");
5325
    age("b.txt");
5326
    let first = repo.snapshot("status").unwrap();
5327
    assert_eq!(
5328
        statuses(&first),
5329
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5330
    );
5331
    let again = repo.snapshot("status").unwrap();
5332
    assert_eq!(
5333
        statuses(&again),
5334
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5335
        "still seen once stat-clean"
5336
    );
5337
    assert!(!again.changed, "and the working copy hashes the same");
5338
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5339
    assert!(
5340
        repo.snapshot("status").is_err(),
5341
        "an edited file must be read, never taken from the base"
5342
    );
5343
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5344
5345
    // A same-size edit made just now is racy and read.
5346
    write(root, "a.txt", b"one\nTWO\n");
5347
    assert_eq!(
5348
        statuses(&repo.snapshot("status").unwrap()),
5349
        vec![
5350
            ("a.txt".to_string(), ChangeStatus::Modified),
5351
            ("b.txt".to_string(), ChangeStatus::Modified)
5352
        ]
5353
    );
5354
    // Committing makes the edits the base: both are clean and served from it again.
5355
    repo.commit("edits", &[]).unwrap();
5356
    age("a.txt");
5357
    age("b.txt");
5358
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5359
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5360
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5361
    let snap = repo.snapshot("status").unwrap();
5362
    assert!(!snap.changed && snap.statuses.is_empty());
5363
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5364
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5365
}
afaba5f1 Andy McCall ↶ 5366
5367
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5368
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5369
/// file is unchanged, and loading through the checkpoint equals a full load.
5370
#[test]
5371
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5372
    hermetic();
5373
    let dir = tempfile::tempdir().unwrap();
5374
    let root = dir.path();
5375
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5376
    let long: String = (0..300)
5377
        .map(|i| format!("line {i} of a long file\n"))
5378
        .collect();
5379
    write(root, "long.txt", long.as_bytes());
5380
    write(root, "short.txt", b"short\n");
5381
    repo.commit("base", &[]).unwrap();
5382
    let (r1, _, _) = repo.checkpoint().unwrap();
5383
    let cp1 = crate::objects::Checkpoint::decode(
5384
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5385
    )
5386
    .unwrap();
5387
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5388
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5389
5390
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5391
    repo.gc(true).unwrap();
5392
    assert!(repo.store().has(&graphs1[0]));
5393
    let report = repo.fsck().unwrap();
5394
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5395
5396
    // Loading through the checkpoint equals a full load.
5397
    write(root, "short.txt", b"short, edited\n");
5398
    repo.commit("edit the short file", &[]).unwrap();
5399
    let heads = repo.bookmark_heads().unwrap();
5400
    let fast = repo.load_state(&heads).unwrap();
5401
    let full = repo.load_state_full(&heads).unwrap();
5402
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5403
5404
    // The next checkpoint shares the unchanged long file's graph.
5405
    let (r2, _, _) = repo.checkpoint().unwrap();
5406
    let cp2 = crate::objects::Checkpoint::decode(
5407
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5408
    )
5409
    .unwrap();
5410
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5411
5412
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5413
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5414
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5415
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5416
5417
    // A version 1 checkpoint written by an older oxy still loads.
5418
    let state = repo.load_state_full(&heads).unwrap();
5419
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5420
    let cp_old = crate::objects::Checkpoint {
5421
        heads: cp2.heads.clone(),
5422
        count: cp2.count,
5423
        payload: old,
5424
    };
5425
    let r_old = repo
5426
        .store()
5427
        .put(ObjectType::Checkpoint, &cp_old.encode())
5428
        .unwrap();
5429
    repo.install_checkpoint("main", &r_old).unwrap();
5430
    assert_eq!(
5431
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5432
        full.checkpoint_payload()
5433
    );
5434
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5435
5436
    // A lost graph blob fails the load loudly rather than dropping the
5437
    // file, and fsck reports it (a fresh repository, objects still loose).
5438
    let dir2 = tempfile::tempdir().unwrap();
5439
    let root2 = dir2.path();
5440
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5441
    write(root2, "long.txt", long.as_bytes());
5442
    repo2.commit("base", &[]).unwrap();
5443
    let (r, _, _) = repo2.checkpoint().unwrap();
5444
    let cp = crate::objects::Checkpoint::decode(
5445
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5446
    )
5447
    .unwrap();
5448
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
64818938 Andy McCall ↶ 5449
    repo2.store().remove_loose_for_test(&graph).unwrap();
afaba5f1 Andy McCall ↶ 5450
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5451
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5452
}
e3d071ce Andy McCall ↶ 5453
5454
/// A new repository has not stored the user's identity yet (that happens
5455
/// at the first signed change); looking it up falls back to the key
5456
/// directory, and a file there that does not hash to the key is refused.
5457
#[test]
5458
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5459
    hermetic();
5460
    let dir = tempfile::tempdir().unwrap();
5461
    let home = dir.path().join("home");
5462
    let mut first = Repo::init(&dir.path().join("a"))
5463
        .unwrap()
5464
        .with_home(home.clone());
5465
    let (key, _) = first
5466
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5467
        .unwrap();
5468
    let fresh = Repo::init(&dir.path().join("b"))
5469
        .unwrap()
5470
        .with_home(home.clone());
5471
    assert!(!fresh.store().has(&key), "nothing stored yet");
5472
    let id = fresh.identity(&key).unwrap();
5473
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5474
    // A key file that is not this identity is an error, not a wrong answer.
5475
    let keys = fresh.keys_dir.clone();
5476
    let (other, _) = first
5477
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5478
        .unwrap();
5479
    fs::copy(
5480
        keys.join(format!("{}.identity", other.to_hex())),
5481
        keys.join(format!("{}.identity", key.to_hex())),
5482
    )
5483
    .unwrap();
5484
    assert!(fresh
5485
        .identity(&key)
5486
        .unwrap_err()
5487
        .to_string()
5488
        .contains("does not hold identity"));
5489
}
cc7a0056 Andy McCall ↶ 5490
5491
/// Status snapshots (spec §12.3): a text file whose stat matches the
5492
/// manifest, and whose base graph key is the one the manifest recorded it
5493
/// equal to, is neither read nor rendered; any edit, and any change to the
5494
/// file's graph in the base, brings it back.
5495
#[cfg(unix)]
5496
#[test]
5497
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5498
    use std::os::unix::fs::PermissionsExt;
5499
    hermetic();
5500
    let dir = tempfile::tempdir().unwrap();
5501
    let root = dir.path();
5502
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5503
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5504
        write(root, p, c.as_bytes());
5505
    }
5506
    repo.commit("base", &[]).unwrap();
5507
    let age = |p: &str| {
5508
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5509
        fs::File::options()
5510
            .write(true)
5511
            .open(root.join(p))
5512
            .unwrap()
5513
            .set_modified(old)
5514
            .unwrap();
5515
    };
5516
    let lock = |p: &str, mode: u32| {
5517
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5518
    };
5519
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5520
        age(p);
5521
    }
5522
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5523
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5524
    assert!(
5525
        m.entries.values().all(|e| e.graph.is_some()),
5526
        "keys recorded"
5527
    );
5528
5529
    // Unreadable files prove they are not read; the status snapshot does
5530
    // not render them either, and its base lacks their graphs.
5531
    lock("a.txt", 0o000);
5532
    lock("b.txt", 0o000);
5533
    let snap = repo.snapshot_status("status").unwrap();
5534
    assert!(!snap.changed && snap.statuses.is_empty());
5535
    assert_eq!(
5536
        snap.base_snapshot
5537
            .unrendered
5538
            .iter()
5539
            .cloned()
5540
            .collect::<Vec<_>>(),
5541
        vec!["a.txt", "b.txt", "d/c.txt"]
5542
    );
5543
    assert!(!snap.base.is_full());
5544
    assert!(!snap.base_snapshot.is_conflicted());
5545
    // A full snapshot does not read them either, but renders everything.
5546
    let full = repo.snapshot("status").unwrap();
5547
    assert!(full.statuses.is_empty() && full.base.is_full());
5548
    assert!(full.base_snapshot.unrendered.is_empty());
5549
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5550
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5551
5552
    // An edit is seen; the file is rendered, the others still are not.
5553
    write(root, "d/c.txt", b"sea edited\n");
5554
    let snap = repo.snapshot_status("status").unwrap();
5555
    assert_eq!(
5556
        statuses(&snap),
5557
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5558
    );
5559
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5560
    // So is a mode change of an unread file.
5561
    lock("b.txt", 0o100);
5562
    assert_eq!(
5563
        statuses(&repo.snapshot_status("status").unwrap()),
5564
        vec![
5565
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5566
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5567
        ]
5568
    );
5569
    lock("b.txt", 0o000);
5570
5571
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5572
    // stays unread, c.txt is read once and then skipped too.
5573
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5574
        .unwrap();
5575
    age("d/c.txt");
5576
    let snap = repo.snapshot_status("status").unwrap();
5577
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5578
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5579
    lock("d/c.txt", 0o000);
5580
    let snap = repo.snapshot_status("status").unwrap();
5581
    assert!(snap.statuses.is_empty());
5582
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5583
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5584
        lock(p, 0o644);
5585
    }
5586
}
5587
5588
/// Attributes decide how a file compares with the base, so a changed
5589
/// `.oxyattributes` makes every text file be compared again.
5590
#[cfg(unix)]
5591
#[test]
5592
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5593
    hermetic();
5594
    let dir = tempfile::tempdir().unwrap();
5595
    let root = dir.path();
5596
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5597
    write(root, "a.txt", b"crlf\r\n");
5598
    repo.commit("base", &[]).unwrap();
5599
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5600
    fs::File::options()
5601
        .write(true)
5602
        .open(root.join("a.txt"))
5603
        .unwrap()
5604
        .set_modified(old)
5605
        .unwrap();
5606
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5607
    assert!(repo
5608
        .snapshot_status("status")
5609
        .unwrap()
5610
        .base_snapshot
5611
        .unrendered
5612
        .contains("a.txt"));
5613
    // With eol=lf, a.txt as stored no longer equals the base.
5614
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5615
    let snap = repo.snapshot_status("status").unwrap();
5616
    assert_eq!(
5617
        statuses(&snap),
5618
        vec![
5619
            (".oxyattributes".to_string(), ChangeStatus::Added),
5620
            ("a.txt".to_string(), ChangeStatus::Modified)
5621
        ]
5622
    );
5623
}
54cd08a1 Andy McCall ↶ 5624
5625
/// Bookmarks with `/` in their names: pushing records their
5626
/// attestations, and checkpoints are kept for them, beside `feature`
5627
/// itself.
5628
#[test]
5629
fn bookmarks_with_slashes_push_and_checkpoint() {
5630
    hermetic();
5631
    let dir = tempfile::tempdir().unwrap();
5632
    let root = dir.path();
5633
    let origin = Repo::init(&root.join("origin")).unwrap();
5634
    let url = root.join("origin").to_string_lossy().to_string();
5635
    let mut repo = Repo::clone(&url, &root.join("r"))
5636
        .unwrap()
5637
        .with_home(root.join("home"));
5638
    // With an identity, pushes carry reference attestations: the case
5639
    // that failed, since the attestation is a file named after the bookmark.
5640
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5641
        .unwrap();
5642
    let r = root.join("r");
5643
    write(&r, "a.txt", b"a\n");
5644
    let h_a = repo.commit("a", &[]).unwrap();
5645
    assert!(repo.push("origin", false).unwrap()[0].ok);
5646
    repo.bookmark_create("feature", None).unwrap();
5647
    repo.bookmark_create("feature/x", None).unwrap();
5648
    repo.bookmark_switch("feature/x", false).unwrap();
5649
    write(&r, "b.txt", b"b\n");
5650
    let h_b = repo.commit("b", &[]).unwrap();
5651
    for name in ["feature", "feature/x"] {
5652
        let res = repo.push_bookmark("origin", name, false).unwrap();
5653
        assert!(res[0].ok, "{name}: {res:?}");
5654
    }
5655
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5656
    assert_eq!(
5657
        origin.resolve_heads("feature/x").unwrap(),
5658
        repo.resolve_heads("feature/x").unwrap()
5659
    );
5660
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5661
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5662
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5663
5664
    // A checkpoint of feature/x is found again when loading its state.
5665
    let (cp, _, _) = repo.checkpoint().unwrap();
5666
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5667
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5668
    let heads = repo.resolve_heads("feature/x").unwrap();
5669
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
f8c69576 Andy McCall ↶ 5670
}
5671
5672
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5673
/// never the remote's own bookmark, and a bookmark created again later is
5674
/// accepted although the deletion's attestation stays the latest.
5675
#[test]
5676
fn bookmarks_are_deleted_on_a_remote() {
5677
    hermetic();
5678
    let dir = tempfile::tempdir().unwrap();
5679
    let root = dir.path();
5680
    let origin = Repo::init(&root.join("origin")).unwrap();
5681
    let url = root.join("origin").to_string_lossy().to_string();
5682
    let mut repo = Repo::clone(&url, &root.join("r"))
5683
        .unwrap()
5684
        .with_home(root.join("home"));
5685
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5686
        .unwrap();
5687
    let r = root.join("r");
5688
    write(&r, "a.txt", b"a\n");
5689
    repo.commit("a", &[]).unwrap();
5690
    assert!(repo.push("origin", false).unwrap()[0].ok);
5691
    repo.bookmark_create("feature/x", None).unwrap();
5692
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5693
    assert!(origin.resolve_heads("feature/x").is_ok());
5694
5695
    let res = repo.push_delete("origin", "feature/x").unwrap();
5696
    assert!(res[0].ok, "{res:?}");
5697
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5698
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5699
    assert!(
5700
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5701
        "the deletion is attested"
5702
    );
5703
    assert!(
5704
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5705
        "the local bookmark stays"
5706
    );
5707
    assert!(!repo
5708
        .view()
5709
        .unwrap()
5710
        .remotes
5711
        .get("origin")
5712
        .is_some_and(|m| m.contains_key("feature/x")));
5713
5714
    // Pushing it again creates it again, past the deletion's serial.
5715
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5716
    assert!(res[0].ok, "{res:?}");
5717
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5718
5719
    // Nothing to delete, and never the remote's own bookmark.
5720
    assert!(repo.push_delete("origin", "nope").is_err());
5721
    let res = repo.push_delete("origin", "main").unwrap();
5722
    assert!(
5723
        !res[0].ok && res[0].reason.contains("default bookmark"),
5724
        "{res:?}"
5725
    );
5726
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
54cd08a1 Andy McCall ↶ 5727
}
61e3bce7 Andy McCall ↶ 5728
5729
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5730
/// when the target has the same versions of the files it touches, and is
5731
/// refused, untouched, when it has others.
5732
#[test]
5733
fn switching_bookmarks_carries_uncommitted_work() {
5734
    hermetic();
5735
    let dir = tempfile::tempdir().unwrap();
5736
    let root = dir.path();
5737
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5738
    write(root, "a.txt", b"a\n");
5739
    write(root, "b.txt", b"b\n");
5740
    write(root, "gone.txt", b"gone\n");
5741
    repo.commit("base", &[]).unwrap();
5742
    repo.bookmark_create("feature", None).unwrap();
5743
    // Started on main, belongs on feature: edit, add, remove.
5744
    write(root, "a.txt", b"a\nmore\n");
5745
    write(root, "new.txt", b"new\n");
5746
    fs::remove_file(root.join("gone.txt")).unwrap();
5747
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5748
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5749
    assert_eq!(repo.config.bookmark, "feature");
5750
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5751
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5752
    assert!(!root.join("gone.txt").exists());
5753
    let snap = repo.snapshot("status").unwrap();
5754
    assert_eq!(
5755
        statuses(&snap),
5756
        vec![
5757
            ("a.txt".to_string(), ChangeStatus::Modified),
5758
            ("gone.txt".to_string(), ChangeStatus::Removed),
5759
            ("new.txt".to_string(), ChangeStatus::Added)
5760
        ]
5761
    );
5762
    repo.commit("the work", &[]).unwrap();
5763
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5764
5765
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5766
    repo.bookmark_switch("main", false).unwrap();
5767
    write(root, "b.txt", b"b on main\n");
5768
    repo.commit("b on main", &[]).unwrap();
5769
    repo.bookmark_switch("feature", false).unwrap();
5770
    write(root, "b.txt", b"b edited\n");
5771
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5772
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5773
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5774
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5775
}
1c2bd9ab Andy McCall ↶ 5776
5777
/// Merging and checking out (feedback 3): a working copy without changes
5778
/// follows a merge whichever state it sat on; a refused checkout names
5779
/// what is in the way; `checkout --carry` takes the work along.
5780
#[test]
5781
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5782
    hermetic();
5783
    let dir = tempfile::tempdir().unwrap();
5784
    let root = dir.path();
5785
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5786
    write(root, "a.txt", b"a\n");
5787
    let h1 = repo.commit("a", &[]).unwrap();
5788
    write(root, "b.txt", b"b\n");
5789
    repo.commit("b", &[]).unwrap();
5790
    repo.bookmark_create("feature", None).unwrap();
5791
    repo.bookmark_switch("feature", false).unwrap();
5792
    write(root, "c.txt", b"c\n");
5793
    repo.commit("c on feature", &[]).unwrap();
5794
    repo.bookmark_switch("main", false).unwrap();
5795
    // The working copy sits on an older state than main's heads.
5796
    repo.checkout(&[h1], false, "checkout").unwrap();
5797
    assert!(!root.join("b.txt").exists());
5798
    let m = repo.merge("feature").unwrap();
5799
    assert!(m.checked_out, "a clean working copy follows the merge");
5800
    for f in ["a.txt", "b.txt", "c.txt"] {
5801
        assert!(root.join(f).exists(), "{f}");
5802
    }
5803
5804
    // A refusal says which paths are in the way and what to do.
5805
    fs::remove_file(root.join("b.txt")).unwrap();
5806
    write(root, "a.txt", b"a edited\n");
5807
    let err = repo
5808
        .checkout(&[h1], false, "checkout")
5809
        .unwrap_err()
5810
        .to_string();
5811
    assert!(
5812
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5813
        "{err}"
5814
    );
5815
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5816
    // is carried as absent (h1 has none either, so that is refused).
5817
    let err = repo
5818
        .checkout_carry(&[h1], "the first change", "checkout")
5819
        .unwrap_err()
5820
        .to_string();
5821
    assert!(
5822
        err.contains("b.txt") && err.contains("the first change"),
5823
        "{err}"
5824
    );
5825
    write(root, "b.txt", b"b\n");
5826
    let (_, carried) = repo
5827
        .checkout_carry(&[h1], "the first change", "checkout")
5828
        .unwrap();
5829
    assert_eq!(carried, vec!["a.txt"]);
5830
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5831
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5832
}
e7ac6c2e Andy McCall ↶ 5833
5834
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5835
/// user identity not stored in a new repository yet is fine while its
5836
/// secret key is there; an added subrepo is listed as not committed yet.
5837
#[test]
5838
fn a_new_repository_is_healthy_before_its_first_commit() {
5839
    hermetic();
5840
    let dir = tempfile::tempdir().unwrap();
5841
    let root = dir.path();
5842
    let home = root.join("home");
5843
    let mut first = Repo::init(&root.join("first"))
5844
        .unwrap()
5845
        .with_home(home.clone());
5846
    let (key, _) = first
5847
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5848
        .unwrap();
5849
    let repo = Repo::init(&root.join("second"))
5850
        .unwrap()
5851
        .with_home(home.clone());
5852
    // Only the secret key: no identity object anywhere this repository sees.
5853
    let keys = repo.keys_dir.clone();
5854
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5855
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5856
    let r = repo.doctor(true);
5857
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5858
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5859
    assert!(id.message.contains("first signed change"), "{}", id.message);
5860
5861
    // A subrepo added and not committed yet is listed, pinned where it is.
5862
    let lib = root.join("lib");
5863
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5864
    write(&lib, "x.txt", b"x\n");
5865
    l.commit("x", &[]).unwrap();
5866
    let second = root.join("second");
5867
    write(&second, "a.txt", b"a\n");
5868
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5869
        .unwrap();
5870
    let subs = repo.subrepos().unwrap();
5871
    assert_eq!(subs.len(), 1);
5872
    assert_eq!(
5873
        (subs[0].path.as_str(), subs[0].committed),
5874
        ("deps/lib", false)
5875
    );
5876
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5877
    repo.commit("add lib", &[]).unwrap();
5878
    let subs = repo.subrepos().unwrap();
5879
    assert!(subs[0].committed, "committed now");
5880
}
8ab265dc Andy McCall ↶ 5881
5882
/// Commit, diff, hunks and discard use the partial snapshot: a file
5883
/// unchanged since the manifest is neither read nor rendered, and showing
5884
/// a change renders only what it edits, the same as from a full base.
5885
#[cfg(unix)]
5886
#[test]
5887
fn commits_and_diffs_leave_unchanged_files_alone() {
5888
    use std::os::unix::fs::PermissionsExt;
5889
    hermetic();
5890
    let dir = tempfile::tempdir().unwrap();
5891
    let root = dir.path();
5892
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5893
    write(root, "big.txt", b"lots\nof\nlines\n");
5894
    write(root, "a.txt", b"one\ntwo\n");
5895
    repo.commit("base", &[]).unwrap();
5896
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5897
    for f in ["big.txt", "a.txt"] {
5898
        fs::File::options()
5899
            .write(true)
5900
            .open(root.join(f))
5901
            .unwrap()
5902
            .set_modified(old)
5903
            .unwrap();
5904
    }
5905
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5906
    // big.txt cannot be read at all from here on.
5907
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5908
5909
    write(root, "a.txt", b"one\nTWO\nthree\n");
5910
    let diff = repo.diff_files(None).unwrap();
5911
    assert_eq!(
5912
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5913
        ["a.txt"]
5914
    );
5915
    let (_, hunks) = repo.hunks().unwrap();
5916
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5917
    let h = repo.commit("edit a", &[]).unwrap();
5918
5919
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5920
    let c = repo.store().get_change(&h).unwrap();
5921
    let full = repo.load_state(&c.deps).unwrap();
5922
    let want = render_change(&c, &full, &full.materialize());
5923
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5924
    let (base, snap) = repo.change_base(&c).unwrap();
5925
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5926
5927
    // Discarding works the same way.
5928
    write(root, "a.txt", b"scratch\n");
5929
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5930
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5931
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5932
}
f7510b63 Andy McCall ↶ 5933
5934
/// A replace conflict (spec §9.3) is settled by a change that writes one
5935
/// candidate, or new bytes, at the path when the caller names it; a plain
5936
/// snapshot of a checkout never settles it on its own.
5937
#[test]
5938
fn replace_conflicts_are_settled_when_asked() {
5939
    hermetic();
5940
    let dir = tempfile::tempdir().unwrap();
5941
    let root = dir.path();
5942
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5943
    let blob = |n: u8| {
5944
        let mut v = vec![0u8; 64];
5945
        v[1] = n;
5946
        v
5947
    };
5948
    write(root, "img.bin", &blob(1));
5949
    repo.commit("add img", &[]).unwrap();
5950
    repo.bookmark_create("other", None).unwrap();
5951
    write(root, "img.bin", &blob(2));
5952
    repo.commit("img two", &[]).unwrap();
5953
    repo.bookmark_switch("other", false).unwrap();
5954
    write(root, "img.bin", &blob(3));
5955
    repo.commit("img three", &[]).unwrap();
5956
    repo.bookmark_switch("main", false).unwrap();
5957
    repo.merge("other").unwrap();
5958
    let heads = repo.bookmark_heads().unwrap();
5959
    let merged = repo.load_state(&heads).unwrap().materialize();
5960
    assert!(
5961
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5962
        "a replace conflict"
5963
    );
5964
    // A snapshot of the checkout records nothing.
5965
    assert!(repo
5966
        .snapshot("status")
5967
        .unwrap()
5968
        .statuses
5969
        .iter()
5970
        .all(|s| s.path != "img.bin"));
5971
5972
    // Keeping candidate 3 settles it.
5973
    let author = repo.author();
5974
    let edits = [FileEdit {
5975
        path: "img.bin".into(),
5976
        content: Some(blob(3)),
5977
    }];
5978
    let c = repo
5979
        .build_change(&heads, &edits, "keep three", author)
5980
        .unwrap();
5981
    assert_eq!(c.kind, ChangeKind::Resolution);
5982
    let mut st = repo.load_state(&heads).unwrap();
5983
    for d in &c.deps {
5984
        assert!(st.contains(d));
5985
    }
5986
    assert!(
5987
        heads.iter().all(|h| c.deps.contains(h)),
5988
        "depends on both contributors"
5989
    );
5990
    st.add(c).unwrap();
5991
    let after = st.materialize();
5992
    assert!(!after.is_conflicted());
5993
    assert_eq!(
5994
        after.files["img.bin"].content,
5995
        FileContent::Opaque {
5996
            blobs: vec![Repo::blob_ref(&blob(3))]
5997
        }
5998
    );
5999
6000
    // New bytes settle it too.
6001
    let edits = [FileEdit {
6002
        path: "img.bin".into(),
6003
        content: Some(blob(9)),
6004
    }];
6005
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
6006
    let mut st = repo.load_state(&heads).unwrap();
6007
    st.add(c).unwrap();
6008
    assert_eq!(
6009
        st.materialize().files["img.bin"].content,
6010
        FileContent::Opaque {
6011
            blobs: vec![Repo::blob_ref(&blob(9))]
6012
        }
6013
    );
6014
}
83d61e80 Andy McCall ↶ 6015
6016
/// The history of a range of lines (spec §27): the changes that wrote
6017
/// or deleted its atoms, or deleted atoms from between them; edits outside
6018
/// the range and changes the range's lines survived are not in it.
6019
#[test]
6020
fn line_ranges_have_exact_histories() {
6021
    hermetic();
6022
    let dir = tempfile::tempdir().unwrap();
6023
    let root = dir.path();
6024
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6025
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
6026
    let base = repo.commit("add f", &[]).unwrap();
6027
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
6028
    let outside = repo.commit("change the import", &[]).unwrap();
6029
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
6030
    let inside = repo.commit("edit a line of a", &[]).unwrap();
6031
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
6032
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
6033
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
6034
    let after = repo.commit("add b after a", &[]).unwrap();
6035
    let heads = repo.bookmark_heads().unwrap();
6036
6037
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
6038
    let hist: Vec<ChangeHash> = repo
6039
        .line_history(&heads, "f.rs", 2, 4)
6040
        .unwrap()
6041
        .iter()
6042
        .map(|e| e.hash)
6043
        .collect();
6044
    for (h, what) in [
6045
        (base, "wrote it"),
6046
        (inside, "edited a line"),
6047
        (deleted, "deleted a line from inside"),
6048
    ] {
6049
        assert!(hist.contains(&h), "{what}");
6050
    }
6051
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
6052
        assert!(!hist.contains(&h), "{what}");
6053
    }
6054
    assert_eq!(hist[0], deleted, "newest first");
6055
    // One line: only what touched it.
6056
    let one: Vec<ChangeHash> = repo
6057
        .line_history(&heads, "f.rs", 1, 1)
6058
        .unwrap()
6059
        .iter()
6060
        .map(|e| e.hash)
6061
        .collect();
6062
    assert!(one.contains(&outside) && !one.contains(&inside));
6063
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
6064
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
6065
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
6066
}
fc1a466a Andy McCall ↶ 6067
6068
#[test]
6069
fn receipts_are_kept_with_their_state_and_verified() {
6070
    use crate::receipt::{Receipt, SignedReceipt};
6071
    hermetic();
6072
    let dir = tempfile::tempdir().unwrap();
6073
    let root = dir.path();
6074
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6075
    write(root, "a.txt", b"1\n");
6076
    repo.commit("A", &[]).unwrap();
6077
    let heads = repo.bookmark_heads().unwrap();
6078
    let state = repo
6079
        .store()
6080
        .put_state(&StateObject::new(heads.clone()))
6081
        .unwrap();
6082
    let out = repo.store_blob(b"built\n").unwrap();
6083
    let receipt = Receipt {
6084
        job_name: "build".into(),
6085
        pipeline_hash: ObjectRef([1; 32]),
6086
        scope_tree_hash: ObjectRef([2; 32]),
6087
        inputs: vec![],
6088
        environment: ObjectRef([3; 32]),
6089
        outputs: vec![out],
6090
        exit_code: 0,
6091
        duration_ms: 42,
6092
    };
6093
    let sk = SecretKey::generate();
6094
    let runner = sk.identity("earth-1", "runner@earth", 1);
6095
    let sr = SignedReceipt::sign(
6096
        receipt.clone(),
6097
        repo.id().unwrap(),
6098
        state,
6099
        "demo#1",
6100
        &runner,
6101
        &sk,
6102
    );
6103
6104
    let r = repo.add_receipt(&sr).unwrap();
6105
    let found = repo.receipts(&heads).unwrap();
6106
    assert_eq!(found.len(), 1);
6107
    assert_eq!(found[0].attest, r);
6108
    assert_eq!(found[0].signed, sr);
6109
    assert!(found[0].problem.is_none() && !found[0].revoked);
6110
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
6111
6112
    // Another repository's receipt, or a forged one, is refused.
6113
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
6114
    assert!(repo
6115
        .add_receipt(&elsewhere)
6116
        .unwrap_err()
6117
        .to_string()
6118
        .contains("another repository"));
6119
    let mut forged = sr.clone();
6120
    forged.receipt.exit_code = 1;
6121
    assert!(repo
6122
        .add_receipt(&forged)
6123
        .unwrap_err()
6124
        .to_string()
6125
        .contains("does not verify"));
6126
c63fed2e Andy McCall ↶ 6127
    // A receipt signed by a short-lived key keeps its certificate and the
6128
    // issuer's identity, and reads back with them (oxygenhub#241).
6129
    let hub_sk = SecretKey::generate();
6130
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
6131
    let job_sk = SecretKey::generate();
6132
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
6133
    let mut test_receipt = receipt.clone();
6134
    test_receipt.job_name = "test".into();
6135
    let plain = SignedReceipt::sign(
6136
        test_receipt,
6137
        repo.id().unwrap(),
6138
        state,
6139
        "demo#2",
6140
        &job,
6141
        &job_sk,
6142
    );
6143
    let now = plain.attest.hlc.wall_ms;
6144
    let cert = crate::cert::SignedCertificate::sign(
6145
        crate::cert::Certificate {
6146
            key: job.clone(),
6147
            issuer: hub.hash(),
6148
            subject: "repo:andy/demo:bookmark:main".into(),
6149
            claims: vec![],
6150
            scope: crate::identity::Scope::SEAL,
6151
            not_before: now - 1_000,
6152
            expires: now + 600_000,
a2387d54 Andy McCall ↶ 6153
            grant: None,
c63fed2e Andy McCall ↶ 6154
        },
6155
        &hub,
6156
        &hub_sk,
6157
    );
6158
    let certified = plain.with_certificate(cert, hub.clone());
6159
    repo.add_receipt(&certified).unwrap();
6160
    let found = repo.receipts(&heads).unwrap();
6161
    let got = found
6162
        .iter()
6163
        .find(|i| i.signed.receipt.job_name == "test")
6164
        .unwrap();
6165
    assert_eq!(got.signed, certified);
6166
    assert!(got.problem.is_none(), "{:?}", got.problem);
6167
6168
    // gc keeps the receipts, their runners, the certificate and its issuer,
6169
    // and the output while the state lives.
fc1a466a Andy McCall ↶ 6170
    repo.gc(true).unwrap();
c63fed2e Andy McCall ↶ 6171
    let found = repo.receipts(&heads).unwrap();
6172
    assert_eq!(found.len(), 2);
6173
    let got = found
6174
        .iter()
6175
        .find(|i| i.signed.receipt.job_name == "test")
6176
        .unwrap();
6177
    assert_eq!(got.signed, certified, "the certificate survives gc");
6178
    assert!(got.problem.is_none());
fc1a466a Andy McCall ↶ 6179
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
6180
    assert!(repo.fsck().unwrap().problems.is_empty());
dfb23a3a Andy McCall ↶ 6181
}
6182
6183
#[test]
6184
fn status_leaves_an_unchanged_manifest_alone() {
6185
    hermetic();
6186
    let dir = tempfile::tempdir().unwrap();
6187
    let root = dir.path();
6188
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6189
    write(root, "a.txt", b"1\n");
6190
    write(root, "b.txt", b"2\n");
6191
    repo.commit("A", &[]).unwrap();
6192
    // Files last touched well outside the racy window.
6193
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6194
    for f in ["a.txt", "b.txt"] {
6195
        fs::File::options()
6196
            .write(true)
6197
            .open(root.join(f))
6198
            .unwrap()
6199
            .set_modified(old)
6200
            .unwrap();
6201
    }
6202
    repo.snapshot_status("status").unwrap();
6203
    let path = repo.manifest_path();
6204
    let first = fs::read(&path).unwrap();
6205
    repo.snapshot_status("status").unwrap();
6206
    assert_eq!(
6207
        fs::read(&path).unwrap(),
6208
        first,
6209
        "an unchanged tree does not rewrite the manifest"
6210
    );
6211
    // A change rewrites it.
6212
    write(root, "a.txt", b"1\n2\n");
6213
    repo.snapshot_status("status").unwrap();
6214
    assert_ne!(fs::read(&path).unwrap(), first);
fc1a466a Andy McCall ↶ 6215
}
6f8aeb99 Andy McCall ↶ 6216
6217
#[test]
6218
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6219
    hermetic();
6220
    let dir = tempfile::tempdir().unwrap();
6221
    let root = dir.path();
6222
    let origin_path = root.join("origin");
6223
    Repo::init(&origin_path).unwrap();
6224
    let origin_url = origin_path.to_string_lossy().to_string();
6225
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6226
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6227
    write(&root.join("a"), "big.txt", big.as_bytes());
6228
    write(&root.join("a"), "small.txt", b"small\n");
6229
    let h1 = a.commit("large", &[]).unwrap();
6230
    let (_, body) = a.store().get(&h1).unwrap();
6231
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6232
    assert!(a.push("origin", false).unwrap()[0].ok);
6233
6234
    // A clone reads the text from the blobs that came with the change.
6235
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6236
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6237
    // An edit in the middle of the stored insert is an ordinary change.
6238
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6239
    write(&root.join("b"), "big.txt", edited.as_bytes());
6240
    let h2 = b.commit("edit", &[]).unwrap();
6241
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6242
    assert!(b.push("origin", false).unwrap()[0].ok);
6243
    assert!(a.pull("origin").unwrap().checked_out);
6244
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6245
    assert_eq!(
6246
        a.fsck().unwrap().errors(),
6247
        0,
6248
        "{:?}",
6249
        a.fsck().unwrap().problems
6250
    );
6251
6252
    // With zero retention gc keeps the text blobs of every kept change.
6253
    let mut a = Repo::open(&root.join("a")).unwrap();
6254
    a.config.set("core.op-retention", "0").unwrap();
6255
    a.save_config().unwrap();
6256
    let a = Repo::open(&root.join("a")).unwrap();
6257
    a.gc(true).unwrap();
6258
    let a = Repo::open(&root.join("a")).unwrap();
6259
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6260
    assert_eq!(
6261
        a.fsck().unwrap().errors(),
6262
        0,
6263
        "{:?}",
6264
        a.fsck().unwrap().problems
6265
    );
6266
    // And a clone of the packed repository reads them from its packs.
6267
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6268
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6269
    drop(c);
6caacfff Andy McCall ↶ 6270
}
6271
6272
#[test]
6273
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6274
    hermetic();
6275
    let dir = tempfile::tempdir().unwrap();
6276
    let root = dir.path();
6277
    let repo = Repo::init(root).unwrap();
6278
    write(root, "a.txt", b"a\n");
6279
    let a = repo.commit("a", &[]).unwrap();
6280
    write(root, "b.txt", b"b\n");
6281
    repo.commit("b", &[]).unwrap();
6282
    let (x, op) = repo.head_op().unwrap();
6283
    let ws = *op.view.workspaces.keys().next().unwrap();
6284
    let mut one = op.view.clone();
6285
    one.workspaces.insert(ws, a);
6286
    let mut two = op.view.clone();
6287
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6288
    let first = repo.record_op(&[x], "one", one).unwrap();
6289
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6290
    assert!(
6291
        e.to_string()
6292
            .contains("changed this working copy at the same time"),
6293
        "{e}"
6294
    );
6295
    assert_eq!(
6296
        repo.head_op().unwrap().0,
6297
        first,
6298
        "the second is not recorded"
6299
    );
6300
}
6301
6302
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6303
/// rewrote the working copy recorded the half-written files as edits, and
6304
/// its view replaced the switch's.
6305
#[test]
6306
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6307
    hermetic();
6308
    let dir = tempfile::tempdir().unwrap();
6309
    let root = dir.path().to_path_buf();
6310
    let mut repo = Repo::init(&root).unwrap();
6311
    write(&root, "keep.txt", b"keep\n");
6312
    repo.commit("base", &[]).unwrap();
6313
    repo.bookmark_create("small", None).unwrap();
6314
    for i in 0..300 {
6315
        write(
6316
            &root,
6317
            &format!("many/f{i}.txt"),
6318
            format!("file {i}\n").as_bytes(),
6319
        );
6320
    }
6321
    repo.commit("many", &[]).unwrap();
6322
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6323
    let watcher = {
6324
        let (root, stop) = (root.clone(), stop.clone());
6325
        std::thread::spawn(move || {
6326
            let r = Repo::open(&root).unwrap();
6327
            let mut ran = 0;
6328
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6329
                if r.snapshot_status("oxy status").is_ok() {
6330
                    ran += 1;
6331
                }
6332
            }
6333
            ran
6334
        })
6335
    };
6336
    for i in 0..20 {
6337
        let to = if i % 2 == 0 { "small" } else { "main" };
6338
        repo.bookmark_switch(to, false).unwrap();
6339
    }
6340
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6341
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6342
    // Back on main, clean, with every file where main has it.
6343
    let repo = Repo::open(&root).unwrap();
6344
    let s = repo.snapshot_status("oxy status").unwrap();
6345
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6346
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6347
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6348
    assert!(root.join("many/f299.txt").exists());
1a3b6203 Andy McCall ↶ 6349
}
6350
6351
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6352
/// put a subrepo that was ahead of its pin back at the pin and moved the
6353
/// subrepo's own bookmark backwards.
6354
#[test]
6355
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6356
    hermetic();
6357
    let dir = tempfile::tempdir().unwrap();
6358
    let root = dir.path();
6359
    Repo::init(&root.join("lib-origin")).unwrap();
6360
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6361
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6362
    write(&root.join("lib"), "lib.txt", b"v1\n");
6363
    lib.commit("lib v1", &[]).unwrap();
6364
    assert!(lib.push("origin", false).unwrap()[0].ok);
6365
6366
    let app_dir = root.join("app");
6367
    let mut app = Repo::init(&app_dir).unwrap();
6368
    write(&app_dir, "main.txt", b"app\n");
6369
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6370
    app.commit("app with lib", &[]).unwrap();
6371
    app.bookmark_create("feature", None).unwrap();
6372
6373
    // New work in the subrepo, not yet pinned by the parent.
6374
    let nested_dir = app_dir.join("libs/lib");
6375
    let nested = Repo::open(&nested_dir).unwrap();
6376
    write(&nested_dir, "new.txt", b"new\n");
6377
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6378
    drop(nested);
6379
6380
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6381
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6382
    let nested = Repo::open(&nested_dir).unwrap();
6383
    assert!(
6384
        nested.bookmark_heads().unwrap().contains(&l2),
6385
        "its bookmark kept its work"
6386
    );
6387
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6388
    let s = app.snapshot("status").unwrap();
6389
    assert_eq!(
6390
        statuses(&s),
6391
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6392
    );
6f8aeb99 Andy McCall ↶ 6393
}
7d9dab13 Andy McCall ↶ 6394
6395
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6396
/// moving `main` to a change this clone had pushed on another bookmark,
6397
/// the first `pull` said "Already up to date" while `main` was behind.
6398
#[test]
6399
fn pull_takes_a_remote_move_to_changes_already_here() {
6400
    hermetic();
6401
    let dir = tempfile::tempdir().unwrap();
6402
    let root = dir.path();
6403
    let origin_path = root.join("origin");
6404
    let origin = Repo::init(&origin_path).unwrap();
6405
    let url = origin_path.to_string_lossy().to_string();
6406
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6407
    write(&root.join("b"), "base.txt", b"base\n");
6408
    b.commit("base", &[]).unwrap();
6409
    assert!(b.push("origin", false).unwrap()[0].ok);
6410
6411
    // A feature bookmark with one change, pushed.
6412
    b.bookmark_create("feat", None).unwrap();
6413
    b.bookmark_switch("feat", false).unwrap();
6414
    write(&root.join("b"), "x.txt", b"x\n");
6415
    let x = b.commit("x", &[]).unwrap();
6416
    assert!(b.push("origin", false).unwrap()[0].ok);
6417
    b.bookmark_switch("main", false).unwrap();
6418
6419
    // The remote lands it: its main moves to the feature's state.
6420
    let feat = origin
6421
        .store()
6422
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6423
        .unwrap()
6424
        .heads;
6425
    origin.bookmark_set("main", &feat).unwrap();
6426
6427
    let r = b.pull("origin").unwrap();
6428
    assert!(r.changed, "{r:?}");
6429
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6430
    let main = b
6431
        .bookmarks()
6432
        .unwrap()
6433
        .into_iter()
6434
        .find(|m| m.name == "main")
6435
        .unwrap();
6436
    assert_eq!(main.behind, Some(0), "{main:?}");
6437
}
86e1824f Andy McCall ↶ 6438
14edbaaf Andy McCall ↶ 6439
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6440
/// to one only the remote has makes a local bookmark from it; a pull moves
6441
/// every local bookmark the remote has too; a clone checks out the remote's
6442
/// default bookmark.
6443
#[test]
6444
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6445
    hermetic();
6446
    let dir = tempfile::tempdir().unwrap();
6447
    let root = dir.path();
6448
    let origin_path = root.join("origin");
6449
    let mut origin = Repo::init(&origin_path).unwrap();
6450
    let url = origin_path.to_string_lossy().to_string();
6451
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6452
    write(&root.join("a"), "base.txt", b"base\n");
6453
    a.commit("base", &[]).unwrap();
6454
    assert!(a.push("origin", false).unwrap()[0].ok);
6455
    a.bookmark_create("develop", None).unwrap();
6456
    a.bookmark_switch("develop", false).unwrap();
6457
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6458
    let d1 = a.commit("d1", &[]).unwrap();
6459
    assert!(a.push("origin", false).unwrap()[0].ok);
6460
6461
    // A clone has main only; origin/develop is a name all the same.
6462
    let c_root = root.join("c");
6463
    let mut c = Repo::clone(&url, &c_root).unwrap();
6464
    assert_eq!(c.config.bookmark, "main");
6465
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6466
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6467
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6468
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6469
6470
    // Switching makes the local bookmark from origin's.
6471
    c.bookmark_switch("develop", false).unwrap();
6472
    assert_eq!(c.config.bookmark, "develop");
6473
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6474
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6475
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6476
    assert!(c.bookmark_switch("nowhere", false).is_err());
6477
6478
    // Both bookmarks move on the remote; one pull takes both.
6479
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6480
    let d2 = a.commit("d2", &[]).unwrap();
6481
    assert!(a.push("origin", false).unwrap()[0].ok);
6482
    a.bookmark_switch("main", false).unwrap();
6483
    write(&root.join("a"), "m.txt", b"m\n");
6484
    let m = a.commit("m", &[]).unwrap();
6485
    assert!(a.push("origin", false).unwrap()[0].ok);
6486
    let r = c.pull("origin").unwrap();
6487
    assert!(r.changed && r.checked_out, "{r:?}");
6488
    assert_eq!(r.heads, vec![d2]);
6489
    assert_eq!(r.others, vec!["main".to_string()]);
6490
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6491
    assert_eq!(
6492
        fs::read(c_root.join("base.txt")).unwrap(),
6493
        b"base\nd1\nd2\n"
6494
    );
6495
    let again = c.pull("origin").unwrap();
6496
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6497
6498
    // A clone checks out the remote's default bookmark.
6499
    origin.config.set("workspace.bookmark", "develop").unwrap();
6500
    origin.save_config().unwrap();
6501
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6502
    assert_eq!(e.config.bookmark, "develop");
6503
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6504
    let reopened = Repo::open(&root.join("e")).unwrap();
6505
    assert_eq!(reopened.config.bookmark, "develop");
6506
    // REMOTE/NAME names the remote's bookmark to switch to.
6507
    let mut e = reopened;
6508
    e.bookmark_switch("origin/main", false).unwrap();
6509
    assert_eq!(e.config.bookmark, "main");
6510
    assert!(e.bookmark_heads().unwrap().contains(&m));
6511
}
6512
98a1620a Andy McCall ↶ 6513
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6514
/// op restore goes back to an operation, files included, and undo takes
6515
/// the restore back whole; op revert undoes one operation alone; each
6516
/// operation's changes are described from the views.
6517
#[test]
6518
fn operations_can_be_read_restored_and_reverted() {
6519
    hermetic();
6520
    let dir = tempfile::tempdir().unwrap();
6521
    let root = dir.path();
6522
    let repo = Repo::init(root).unwrap();
6523
    write(root, "a.txt", b"a\n");
6524
    let first = repo.commit("first", &[]).unwrap();
6525
    write(root, "a.txt", b"a\nb\n");
6526
    let second = repo.commit("second", &[]).unwrap();
6527
    let at_second = repo.head_op().unwrap().0.to_hex();
6528
    repo.bookmark_create("keep", None).unwrap();
6529
    let created = repo.head_op().unwrap().0.to_hex();
6530
    write(root, "n.txt", b"n\n");
6531
    let third = repo.commit("third", &[]).unwrap();
6532
6533
    // What each operation changed.
6534
    let ops = repo.op_log().unwrap();
6535
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6536
    assert!(
6537
        changes
6538
            .iter()
6539
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6540
        "{changes:?}"
6541
    );
6542
    assert!(changes
6543
        .iter()
6544
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6545
6546
    // Reading at an earlier operation.
6547
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6548
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6549
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6550
    write(root, "z.txt", b"z\n");
6551
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6552
    fs::remove_file(root.join("z.txt")).unwrap();
6553
    assert!(repo.resolve_op("zz").is_err());
6554
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
6555
6556
    // Restore goes back, files and all; undo takes it back whole.
6557
    repo.op_restore(&at_second, false).unwrap();
6558
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
6559
    assert!(!root.join("n.txt").exists());
6560
    repo.undo().unwrap();
6561
    let mut heads = repo.bookmark_heads().unwrap();
6562
    heads.sort();
6563
    let mut want = vec![second, third];
6564
    want.sort();
6565
    assert_eq!(heads, want);
6566
    assert!(
6567
        root.join("n.txt").exists(),
6568
        "the files came back with the undo"
6569
    );
6570
6571
    // Revert the bookmark's creation alone: the commit after it stays.
6572
    let r = repo.op_revert(&created).unwrap();
6573
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6574
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6575
    assert!(repo
6576
        .load_state(&repo.bookmark_heads().unwrap())
6577
        .unwrap()
6578
        .contains(&third));
6579
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6580
    let _ = first;
6581
}
6582
36041796 Andy McCall ↶ 6583
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6584
/// from the status cache while every file is as the snapshot left it, and
6585
/// from a snapshot again as soon as one is not.
6586
#[test]
6587
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6588
    hermetic();
6589
    let dir = tempfile::tempdir().unwrap();
6590
    let root = dir.path();
6591
    let repo = Repo::init(root).unwrap();
6592
    write(root, "a.txt", b"a\n");
6593
    write(root, "b.txt", b"b\n");
6594
    repo.commit("base", &[]).unwrap();
6595
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6596
6597
    write(root, "a.txt", b"a\nmore\n");
6598
    assert_eq!(
6599
        repo.status_by_manifest().unwrap(),
6600
        None,
6601
        "no snapshot of the edit yet"
6602
    );
6603
    let snap = repo.snapshot_status("oxy status").unwrap();
6604
    assert_eq!(snap.statuses.len(), 1);
6605
    let cached = repo
6606
        .status_by_manifest()
6607
        .unwrap()
6608
        .expect("answered from the cache");
6609
    assert_eq!(cached.len(), 1);
6610
    assert_eq!(
6611
        (cached[0].path.as_str(), cached[0].status),
6612
        ("a.txt", ChangeStatus::Modified)
6613
    );
6614
6615
    // Any further change sends status back to a snapshot.
6616
    write(root, "a.txt", b"a\nmore\nand more\n");
6617
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6618
    repo.snapshot_status("oxy status").unwrap();
6619
    assert!(repo.status_by_manifest().unwrap().is_some());
6620
    write(root, "new.txt", b"n\n");
6621
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6622
    fs::remove_file(root.join("new.txt")).unwrap();
6623
    assert!(
6624
        repo.status_by_manifest().unwrap().is_some(),
6625
        "back as it was"
6626
    );
6627
    fs::remove_file(root.join("b.txt")).unwrap();
6628
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6629
    write(root, "b.txt", b"b\n");
6630
6631
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6632
    repo.snapshot_status("oxy status").unwrap();
6633
    repo.commit("more", &[]).unwrap();
6634
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6635
}
6636
77445673 Andy McCall ↶ 6637
/// oxygen#41: while the status cache holds, the working copy's diff is
6638
/// rendered from the stored working-copy change, and says exactly what a
6639
/// snapshot's diff says.
6640
#[test]
6641
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6642
    hermetic();
6643
    let dir = tempfile::tempdir().unwrap();
6644
    let root = dir.path();
6645
    let repo = Repo::init(root).unwrap();
6646
    write(root, "a.txt", b"one\ntwo\nthree\n");
6647
    write(root, "gone.txt", b"bye\n");
6648
    repo.commit("base", &[]).unwrap();
6649
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6650
    write(root, "new.txt", b"hello\n");
6651
    fs::remove_file(root.join("gone.txt")).unwrap();
6652
    let snap = repo.snapshot_status("oxy status").unwrap();
6653
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6654
    assert!(
6655
        repo.status_by_manifest().unwrap().is_some(),
6656
        "the cache holds"
6657
    );
6658
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6659
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6660
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6661
}
6662
1ec3f008 Andy McCall ↶ 6663
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6664
/// while none has moved, the check stats the tracked files without listing
6665
/// the tree, and a file added or removed anywhere moves its directory's
6666
/// time, so the tree is listed again.
6667
#[test]
6668
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6669
    hermetic();
6670
    let dir = tempfile::tempdir().unwrap();
6671
    let root = dir.path();
6672
    let repo = Repo::init(root).unwrap();
6673
    write(root, "a.txt", b"a\n");
6674
    write(root, "sub/deep/b.txt", b"b\n");
6675
    repo.commit("base", &[]).unwrap();
6676
    // Out of the racy window: every file and directory a minute old.
6677
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6678
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6679
        fs::File::open(root.join(p))
6680
            .unwrap()
6681
            .set_modified(old)
6682
            .unwrap();
6683
    }
6684
    repo.snapshot_status("oxy status").unwrap();
6685
    repo.write_manifest(false, false).unwrap();
6686
    let m = repo.read_manifest().unwrap().unwrap().2;
6687
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6688
    assert_eq!(
6689
        repo.disk_differs_by_dirs(&m),
6690
        Some(false),
6691
        "no listing needed"
6692
    );
6693
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6694
6695
    // A same-size edit with a new time: found by its stat.
6696
    write(root, "sub/deep/b.txt", b"c\n");
6697
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6698
    write(root, "sub/deep/b.txt", b"b\n");
6699
    fs::File::open(root.join("sub/deep/b.txt"))
6700
        .unwrap()
6701
        .set_modified(old)
6702
        .unwrap();
6703
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6704
6705
    // A new file moves its directory's time: the tree must be listed.
6706
    write(root, "sub/deep/new.txt", b"n\n");
6707
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6708
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6709
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6710
    // A removed one too.
6711
    fs::remove_file(root.join("a.txt")).unwrap();
6712
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6713
}
6714
e226a6cc Andy McCall ↶ 6715
/// oxygen#41: a commit right after a status takes the snapshot the status
6716
/// left (the status cache holds) rather than walking again, and commits
6717
/// exactly what a snapshot would have.
6718
#[test]
6719
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6720
    hermetic();
6721
    let dir = tempfile::tempdir().unwrap();
6722
    let root = dir.path();
6723
    let repo = Repo::init(root).unwrap();
6724
    write(root, "a.txt", b"a\nb\n");
6725
    write(root, ".oxyattributes", b"*.bin binary\n");
6726
    repo.commit("base", &[]).unwrap();
6727
    write(root, "a.txt", b"a\nB\n");
6728
    write(root, "new.txt", b"new\n");
6729
    let snap = repo.snapshot_status("oxy status").unwrap();
6730
    let cached = repo
6731
        .snapshot_from_cache()
6732
        .unwrap()
6733
        .expect("the cache holds");
6734
    assert_eq!(cached.wc_hash, snap.wc_hash);
6735
    assert_eq!(cached.statuses, snap.statuses);
6736
    assert!(
6737
        !cached.attributes.is_empty(),
6738
        "the .oxyattributes file was read"
6739
    );
6740
    let h = repo.commit("edit", &[]).unwrap();
6741
    let c = repo.store().get_change(&h).unwrap();
6742
    assert_eq!(
6743
        c.tree_ops.len() + c.edits.len(),
6744
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6745
    );
6746
    assert_eq!(
6747
        repo.status_by_manifest().unwrap(),
6748
        Some(vec![]),
6749
        "clean after the commit"
6750
    );
6751
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6752
}
6753
0389c3e8 Andy McCall ↶ 6754
/// oxygen#41: a clean check that verified racy entries restamps the
6755
/// manifest, so later checks can trust them, and a same-size rewrite
6756
/// straight afterwards is still found: entries within two seconds of the
6757
/// new time stay racy.
6758
#[test]
6759
fn a_verified_clean_check_restamps_the_manifest_safely() {
6760
    hermetic();
6761
    let dir = tempfile::tempdir().unwrap();
6762
    let root = dir.path();
6763
    let repo = Repo::init(root).unwrap();
6764
    write(root, "a.txt", b"one\n");
6765
    repo.commit("one", &[]).unwrap();
6766
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6767
    assert!(repo.clean_by_manifest().unwrap());
6768
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6769
    assert!(after > before, "restamped");
6770
    write(root, "a.txt", b"two\n");
6771
    assert!(
6772
        !repo.clean_by_manifest().unwrap(),
6773
        "a same-size rewrite is still seen"
6774
    );
6775
}
6776
86e1824f Andy McCall ↶ 6777
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6778
/// stored insert's text blob only when it builds that file's graph, and
6779
/// builds the same graph a full load does.
6780
#[test]
6781
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6782
    hermetic();
6783
    let dir = tempfile::tempdir().unwrap();
6784
    let root = dir.path();
6785
    let repo = Repo::init(root).unwrap();
6786
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6787
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6788
    write(root, "big.txt", big.as_bytes());
6789
    write(root, "other.txt", other.as_bytes());
6790
    let h = repo.commit("two large files", &[]).unwrap();
6791
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6792
    let h2 = repo.commit("append", &[]).unwrap();
6793
6794
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6795
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6796
        FileContent::Text { bytes, .. } => bytes.clone(),
6797
        other => panic!("{other:?}"),
6798
    };
6799
    // Built on demand, every graph renders as the full load's.
6800
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6801
    let big_node = full.files["big.txt"].node;
6802
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6803
    repo.load_all_graphs(&mut hist).unwrap();
6804
    let rendered = hist.materialize();
6805
    for p in ["big.txt", "other.txt"] {
6806
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6807
    }
6808
6809
    // Without other.txt's text blob, history still loads and big.txt still
6810
    // builds: nothing read the other text.
6811
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6812
    assert_eq!(texts.len(), 2);
6813
    let content = |r: &ObjectRef| -> Vec<u8> {
6814
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6815
        blob.chunks
6816
            .iter()
6817
            .flat_map(|c| repo.store().get(c).unwrap().1)
6818
            .collect()
6819
    };
6820
    let other_text = texts
6821
        .iter()
a4fad5b0 Andy McCall ↶ 6822
        .filter_map(|t| match t {
0f93f49c Andy McCall ↶ 6823
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
a4fad5b0 Andy McCall ↶ 6824
            _ => None,
6825
        })
86e1824f Andy McCall ↶ 6826
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6827
        .unwrap();
64818938 Andy McCall ↶ 6828
    repo.store().remove_loose_for_test(&other_text).unwrap();
86e1824f Andy McCall ↶ 6829
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6830
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6831
    assert!(repo
6832
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6833
        .is_err());
6834
}
6835
6836
/// oxygen#35: the first status after a commit read and rendered every
6837
/// file (79 s and more than 14 GB on the Linux tree), because the
6838
/// manifest had no graph keys for files the commit added.
6839
#[test]
6840
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6841
    use std::os::unix::fs::PermissionsExt;
6842
    hermetic();
6843
    let dir = tempfile::tempdir().unwrap();
6844
    let root = dir.path();
6845
    let repo = Repo::init(root).unwrap();
6846
    let files = ["a.txt", "b.txt", "d/c.txt"];
6847
    for p in files {
6848
        write(root, p, format!("{p}\n").as_bytes());
6849
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6850
        fs::File::options()
6851
            .write(true)
6852
            .open(root.join(p))
6853
            .unwrap()
6854
            .set_modified(old)
6855
            .unwrap();
6856
    }
6857
    repo.commit("added", &[]).unwrap();
6858
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6859
    assert!(
6860
        m.entries.values().all(|e| e.graph.is_some()),
6861
        "keys recorded at commit"
6862
    );
6863
    // Unreadable files prove the next status reads none of them.
6864
    for p in files {
6865
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6866
    }
6867
    let snap = repo.snapshot_status("status").unwrap();
6868
    for p in files {
6869
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6870
    }
6871
    assert!(!snap.changed && snap.statuses.is_empty());
6872
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6873
}
c5ce0367 Andy McCall ↶ 6874
6875
/// oxygen#35: a checkout reads, renders and writes only the files whose
6876
/// graphs differ, and renders the rest a batch at a time.
6877
#[test]
6878
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6879
    use std::os::unix::fs::PermissionsExt;
6880
    hermetic();
6881
    let dir = tempfile::tempdir().unwrap();
6882
    let root = dir.path();
6883
    let origin = root.join("origin");
6884
    let mut repo = Repo::init(&origin).unwrap();
6885
    // More files than one batch holds.
6886
    let n = 2100;
6887
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6888
    for i in 0..n {
6889
        let p = format!("f/{i:04}.txt");
6890
        write(&origin, &p, format!("file {i}\n").as_bytes());
6891
        fs::File::options()
6892
            .write(true)
6893
            .open(origin.join(&p))
6894
            .unwrap()
6895
            .set_modified(old)
6896
            .unwrap();
6897
    }
6898
    repo.commit("many", &[]).unwrap();
6899
    repo.bookmark_create("feature", None).unwrap();
6900
    repo.bookmark_switch("feature", false).unwrap();
6901
    write(&origin, "f/0007.txt", b"changed\n");
6902
    repo.commit("one change", &[]).unwrap();
6903
6904
    // Switching back to main must not read the unchanged files.
6905
    for i in 0..n {
6906
        if i != 7 {
6907
            let p = origin.join(format!("f/{i:04}.txt"));
6908
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6909
        }
6910
    }
6911
    let r = repo.bookmark_switch("main", false).unwrap();
6912
    for i in 0..n {
6913
        let p = origin.join(format!("f/{i:04}.txt"));
6914
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6915
    }
6916
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6917
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6918
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6919
6920
    // A clone renders every file, across batches.
6921
    let c = root.join("clone");
6922
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6923
    for i in [0, 2047, 2048, n - 1] {
6924
        assert_eq!(
6925
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6926
            format!("file {i}\n").as_bytes()
6927
        );
6928
    }
6929
    let cloned = Repo::open(&c).unwrap();
6930
    assert!(cloned
6931
        .snapshot_status("status")
6932
        .unwrap()
6933
        .statuses
6934
        .is_empty());
d3cd7ef9 Andy McCall ↶ 6935
}
6936
6937
/// A file written just before the manifest (inside the racy window) is
6938
/// checked by its hash: trusted when equal, caught when edited in place
6939
/// with the same size and time.
6940
#[test]
6941
fn a_racy_manifest_entry_is_checked_by_hash() {
6942
    hermetic();
6943
    let dir = tempfile::tempdir().unwrap();
6944
    let root = dir.path();
6945
    let repo = Repo::init(root).unwrap();
6946
    write(root, "a.txt", b"one\n");
6947
    repo.commit("fresh", &[]).unwrap();
6948
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6949
    let t = fs::metadata(root.join("a.txt"))
6950
        .unwrap()
6951
        .modified()
6952
        .unwrap();
6953
    write(root, "a.txt", b"two\n");
6954
    fs::File::options()
6955
        .write(true)
6956
        .open(root.join("a.txt"))
6957
        .unwrap()
6958
        .set_modified(t)
6959
        .unwrap();
6960
    assert!(
6961
        !repo.clean_by_manifest().unwrap(),
6962
        "same size and time, other bytes"
6963
    );
6964
    assert_eq!(
6965
        statuses(&repo.snapshot_status("status").unwrap()),
6966
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6967
    );
c5ce0367 Andy McCall ↶ 6968
}
2c75672f Andy McCall ↶ 6969
6970
/// A fetch on one machine moves changes as stored, text blobs among the
6971
/// objects; a change whose text blob did not come is refused, not stored.
6972
#[test]
6973
fn a_raw_bundle_without_a_changes_text_is_refused() {
6974
    hermetic();
6975
    let dir = tempfile::tempdir().unwrap();
6976
    let root = dir.path();
6977
    let a = Repo::init(&root.join("a")).unwrap();
6978
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6979
    write(&root.join("a"), "big.txt", big.as_bytes());
6980
    let h = a.commit("big", &[]).unwrap();
6981
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6982
    assert_eq!(bundle.raw_changes.len(), 1);
6983
    assert!(bundle.changes.is_empty());
6984
    let b = Repo::init(&root.join("b")).unwrap();
6985
    let mut without = bundle.clone();
6986
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6987
    let e = b.import_bundle(&without, false).unwrap_err();
6988
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6989
    assert!(!b.store().has(&h));
6990
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6991
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6992
}
a87c7b9d Andy McCall ↶ 6993
6994
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6995
/// again was a second node for one Git path, so a file moved into it on
6996
/// another line, where the first node still stood, ended up in two places.
6997
/// An import now brings the directory back rather than make a new one.
6998
#[test]
6999
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
7000
    hermetic();
7001
    if std::process::Command::new("git")
7002
        .arg("--version")
7003
        .output()
7004
        .is_err()
7005
    {
7006
        eprintln!("git not installed; skipping");
7007
        return;
7008
    }
7009
    let dir = tempfile::tempdir().unwrap();
7010
    let root = dir.path();
7011
    let g = root.join("src.git");
7012
    fs::create_dir_all(&g).unwrap();
7013
    let git = |args: &[&str]| -> String {
7014
        let out = std::process::Command::new("git")
7015
            .arg("-C")
7016
            .arg(&g)
7017
            .args([
7018
                "-c",
7019
                "user.name=Grace",
7020
                "-c",
7021
                "[email protected]",
7022
                "-c",
7023
                "commit.gpgsign=false",
7024
            ])
7025
            .args(args)
7026
            .output()
7027
            .unwrap();
7028
        assert!(
7029
            out.status.success(),
7030
            "git {args:?}: {}",
7031
            String::from_utf8_lossy(&out.stderr)
7032
        );
7033
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7034
    };
7035
    git(&["init", "-q", "-b", "main"]);
7036
    write(&g, "d/a.txt", b"a\n");
7037
    write(&g, "c/x.txt", b"x\n");
7038
    git(&["add", "."]);
7039
    git(&["commit", "-qm", "base"]);
7040
    // One line: move x into d while d still stands.
7041
    git(&["checkout", "-qb", "side"]);
7042
    git(&["mv", "c/x.txt", "d/x.txt"]);
7043
    git(&["commit", "-qm", "x into d"]);
7044
    // The other: d goes, comes back, and x moves into it too.
7045
    git(&["checkout", "-q", "main"]);
7046
    git(&["rm", "-q", "d/a.txt"]);
7047
    git(&["commit", "-qm", "d goes"]);
7048
    write(&g, "d/b.txt", b"b\n");
7049
    git(&["add", "."]);
7050
    git(&["commit", "-qm", "d comes back"]);
7051
    git(&["mv", "c/x.txt", "d/x.txt"]);
7052
    git(&["commit", "-qm", "x into d again"]);
7053
    git(&["merge", "-q", "--no-edit", "side"]);
7054
7055
    let repo = Repo::init(&root.join("o")).unwrap();
7056
    repo.import_git(&g, "main").unwrap();
7057
    let v = repo.verify_git_import(&g, "main").unwrap();
7058
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7059
    let st = repo
7060
        .load_state_history(&repo.bookmark_heads().unwrap())
7061
        .unwrap();
7062
    let view = st.tree().view();
7063
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7064
    // The directory is the one the first commit made.
7065
    // Commits made in one second tie on time: find the first by its message.
7066
    let first = repo
7067
        .log()
7068
        .unwrap()
7069
        .into_iter()
7070
        .find(|e| e.change.message.starts_with("base"))
7071
        .unwrap();
7072
    let base = repo
7073
        .load_state_history(&[first.hash])
7074
        .unwrap()
7075
        .tree()
7076
        .view();
7077
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
7078
}
7079
7080
/// oxygen#30, the rest: a placement left under a directory another line
7081
/// removed is out of sight, so no diff reaches it; the merge that settles
7082
/// where the file is retires it.
7083
#[test]
7084
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
7085
    hermetic();
7086
    if std::process::Command::new("git")
7087
        .arg("--version")
7088
        .output()
7089
        .is_err()
7090
    {
7091
        eprintln!("git not installed; skipping");
7092
        return;
7093
    }
7094
    let dir = tempfile::tempdir().unwrap();
7095
    let root = dir.path();
7096
    let g = root.join("src.git");
7097
    fs::create_dir_all(&g).unwrap();
7098
    let run = |args: &[&str]| {
7099
        std::process::Command::new("git")
7100
            .arg("-C")
7101
            .arg(&g)
7102
            .args([
7103
                "-c",
7104
                "user.name=Grace",
7105
                "-c",
7106
                "[email protected]",
7107
                "-c",
7108
                "commit.gpgsign=false",
7109
            ])
7110
            .args(args)
7111
            .output()
7112
            .unwrap()
7113
    };
7114
    let git = |args: &[&str]| {
7115
        let out = run(args);
7116
        assert!(
7117
            out.status.success(),
7118
            "git {args:?}: {}",
7119
            String::from_utf8_lossy(&out.stderr)
7120
        );
7121
    };
7122
    git(&["init", "-q", "-b", "main"]);
7123
    write(&g, "c/x.txt", b"x\n");
7124
    write(&g, "keep.txt", b"k\n");
7125
    git(&["add", "."]);
7126
    git(&["commit", "-qm", "base"]);
7127
    // One line renames the file within c; the other moves it out of c,
7128
    // which goes.
7129
    git(&["checkout", "-qb", "side"]);
7130
    git(&["mv", "c/x.txt", "c/y.txt"]);
7131
    git(&["commit", "-qm", "rename within c"]);
7132
    git(&["checkout", "-q", "main"]);
7133
    fs::create_dir_all(g.join("n")).unwrap();
7134
    git(&["mv", "c/x.txt", "n/x.txt"]);
7135
    git(&["commit", "-qm", "move out of c"]);
7136
    // Git cannot merge the two renames; the merge keeps n/x.txt.
7137
    let _ = run(&["merge", "-q", "side"]);
7138
    let _ = run(&[
7139
        "rm",
7140
        "-q",
7141
        "--cached",
7142
        "--ignore-unmatch",
7143
        "c/y.txt",
7144
        "c/x.txt",
7145
    ]);
7146
    let _ = std::fs::remove_dir_all(g.join("c"));
7147
    write(&g, "n/x.txt", b"x\n");
7148
    git(&["add", "-A"]);
7149
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
7150
7151
    let repo = Repo::init(&root.join("o")).unwrap();
7152
    repo.import_git(&g, "main").unwrap();
7153
    let v = repo.verify_git_import(&g, "main").unwrap();
7154
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7155
    let st = repo
7156
        .load_state_history(&repo.bookmark_heads().unwrap())
7157
        .unwrap();
7158
    let view = st.tree().view();
7159
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7160
    assert!(view.entries.contains_key("n/x.txt"));
7161
}
7162
7163
/// oxygen#30, orphans: a file added on one line into a directory the other
7164
/// line removed is placed where the tree cannot show it; Git's merge keeps
7165
/// the file, and the import's merge leaves exactly one of it.
7166
#[test]
7167
fn git_import_merge_leaves_no_orphan_behind() {
7168
    hermetic();
7169
    if std::process::Command::new("git")
7170
        .arg("--version")
7171
        .output()
7172
        .is_err()
7173
    {
7174
        eprintln!("git not installed; skipping");
7175
        return;
7176
    }
7177
    let dir = tempfile::tempdir().unwrap();
7178
    let root = dir.path();
7179
    let g = root.join("src.git");
7180
    fs::create_dir_all(&g).unwrap();
7181
    let git = |args: &[&str]| {
7182
        let out = std::process::Command::new("git")
7183
            .arg("-C")
7184
            .arg(&g)
7185
            .args([
7186
                "-c",
7187
                "user.name=Grace",
7188
                "-c",
7189
                "[email protected]",
7190
                "-c",
7191
                "commit.gpgsign=false",
7192
            ])
7193
            .args(args)
7194
            .output()
7195
            .unwrap();
7196
        assert!(
7197
            out.status.success(),
7198
            "git {args:?}: {}",
7199
            String::from_utf8_lossy(&out.stderr)
7200
        );
7201
    };
7202
    git(&["init", "-q", "-b", "main"]);
7203
    write(&g, "d/f.txt", b"f\n");
7204
    write(&g, "keep.txt", b"k\n");
7205
    git(&["add", "."]);
7206
    git(&["commit", "-qm", "base"]);
7207
    git(&["checkout", "-qb", "side"]);
7208
    write(&g, "d/new.txt", b"new\n");
7209
    git(&["add", "."]);
7210
    git(&["commit", "-qm", "add into d"]);
7211
    git(&["checkout", "-q", "main"]);
7212
    git(&["rm", "-q", "d/f.txt"]);
7213
    git(&["commit", "-qm", "d goes"]);
7214
    git(&["merge", "-q", "--no-edit", "side"]);
7215
7216
    let repo = Repo::init(&root.join("o")).unwrap();
7217
    repo.import_git(&g, "main").unwrap();
7218
    let v = repo.verify_git_import(&g, "main").unwrap();
7219
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7220
    let st = repo
7221
        .load_state_history(&repo.bookmark_heads().unwrap())
7222
        .unwrap();
7223
    let view = st.tree().view();
7224
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7225
    assert!(view.entries.contains_key("d/new.txt"));
7226
}
d77e1702 Andy McCall ↶ 7227
7228
/// fsck checks a change's text as the blobs it is stored in, without
7229
/// decoding it: a missing text blob is an error named for the change.
7230
#[test]
7231
fn fsck_names_a_missing_text_blob() {
7232
    hermetic();
7233
    let dir = tempfile::tempdir().unwrap();
7234
    let root = dir.path();
7235
    let repo = Repo::init(root).unwrap();
7236
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7237
    write(root, "big.txt", big.as_bytes());
7238
    let h = repo.commit("big", &[]).unwrap();
7239
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7240
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7241
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7242
        panic!("a stored text")
7243
    };
64818938 Andy McCall ↶ 7244
    repo.store().remove_loose_for_test(&b).unwrap();
d77e1702 Andy McCall ↶ 7245
    let rep = repo.fsck().unwrap();
7246
    assert!(rep.errors() > 0);
7247
    assert!(
7248
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7249
        "{:?}",
7250
        rep.problems
7251
    );
7252
}
a07f60a3 Andy McCall ↶ 7253
7254
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7255
/// reached with that remote's token and CA (a private subrepo then clones
7256
/// for anyone who can read the parent); another hub gets none of them.
7257
#[test]
7258
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7259
    hermetic();
7260
    let dir = tempfile::tempdir().unwrap();
7261
    let mut repo = Repo::init(dir.path()).unwrap();
7262
    repo.config
7263
        .set(
7264
            "remote.origin.url",
7265
            "https://Hub.example:7343/doomsdayone/metalgear",
7266
        )
7267
        .unwrap();
7268
    repo.config.set("remote.origin.token", "secret").unwrap();
7269
    repo.config
7270
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7271
        .unwrap();
7272
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7273
    assert_eq!(same.token.as_deref(), Some("secret"));
7274
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7275
    for other in [
7276
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7277
        "https://hub.example/doomsdayone/rstar-api",
7278
        "http://hub.example:7343/doomsdayone/rstar-api",
7279
    ] {
7280
        let o = repo.credentials_for(other);
7281
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7282
    }
7283
}
ce14f0d6 Andy McCall ↶ 7284
ff1f62fe Andy McCall ↶ 7285
/// oxygen#47: a remote with no token of its own uses the user's credential
7286
/// store for its hub, and a nested checkout finds its parent's remote
7287
/// token there instead of keeping a copy.
ce14f0d6 Andy McCall ↶ 7288
#[test]
ff1f62fe Andy McCall ↶ 7289
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7290
    hermetic();
7291
    let home = tempfile::tempdir().unwrap();
7292
    let dir = tempfile::tempdir().unwrap();
7293
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7294
    parent
7295
        .config
7296
        .set("remote.origin.url", "https://hub.example/o/parent")
7297
        .unwrap();
7298
    parent.save_config().unwrap();
7299
    assert_eq!(parent.remote_options("origin").token, None);
7300
    crate::credentials::Credentials::at(home.path())
7301
        .save("https://hub.example", "stored", Some("andy"), None)
7302
        .unwrap();
7303
    assert_eq!(
7304
        parent.remote_options("origin").token.as_deref(),
7305
        Some("stored")
7306
    );
7307
7308
    let empty_home = tempfile::tempdir().unwrap();
7309
    let nested = dir.path().join("deps").join("child");
7310
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7311
    child
7312
        .config
7313
        .set("remote.origin.url", "https://hub.example/o/child")
7314
        .unwrap();
7315
    child.save_config().unwrap();
7316
    assert_eq!(child.remote_options("origin").token, None);
7317
    parent
7318
        .config
7319
        .set("remote.origin.token", "checkout")
7320
        .unwrap();
7321
    parent.save_config().unwrap();
7322
    assert_eq!(
7323
        child.remote_options("origin").token.as_deref(),
7324
        Some("checkout")
7325
    );
7326
    // Another hub's checkout token is not borrowed.
7327
    child
7328
        .config
7329
        .set("remote.origin.url", "https://other.example/o/child")
7330
        .unwrap();
7331
    assert_eq!(child.remote_options("origin").token, None);
7332
}
7333
7334
#[test]
ce14f0d6 Andy McCall ↶ 7335
fn the_metadata_cache_survives_a_torn_tail() {
7336
    hermetic();
7337
    let dir = tempfile::tempdir().unwrap();
7338
    let root = dir.path();
7339
    let repo = Repo::init(root).unwrap();
7340
    write(root, "a.txt", b"1\n");
7341
    let h = repo.commit("first", &[]).unwrap();
7342
    let meta = repo.store().get_change_meta(&h).unwrap();
7343
    let cache = repo.store().dir().join("metas");
7344
    let len = fs::metadata(&cache).unwrap().len();
7345
    assert!(len > 0, "a change read is cached");
7346
    // A torn record at the end: the cache reads up to it and cuts it off.
7347
    fs::OpenOptions::new()
7348
        .append(true)
7349
        .open(&cache)
7350
        .unwrap()
7351
        .write_all(&[7; 20])
7352
        .unwrap();
7353
    let again = Repo::open(root).unwrap();
7354
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7355
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7356
}
f9466021 Andy McCall ↶ 7357
7358
#[test]
7359
fn a_manifest_that_does_not_check_reads_as_none() {
7360
    hermetic();
7361
    let dir = tempfile::tempdir().unwrap();
7362
    let root = dir.path();
7363
    let repo = Repo::init(root).unwrap();
7364
    write(root, "a.txt", b"1\n");
7365
    repo.commit("first", &[]).unwrap();
7366
    let path = repo.manifest_path();
7367
    let mut bytes = fs::read(&path).unwrap();
7368
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7369
    let last = bytes.len() - 1;
7370
    bytes[last] ^= 1;
7371
    fs::write(&path, &bytes).unwrap();
7372
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7373
    // The next status reads the files and writes it again.
7374
    let again = Repo::open(root).unwrap();
7375
    assert!(!again.snapshot("status").unwrap().changed);
7376
    assert!(again.read_manifest().unwrap().is_some());
7377
}
7378
7379
#[test]
7380
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7381
    hermetic();
7382
    let dir = tempfile::tempdir().unwrap();
7383
    let root = dir.path();
7384
    let repo = Repo::init(root).unwrap();
7385
    write(root, "a.txt", b"1\n");
7386
    write(root, "b.txt", b"2\n");
7387
    // b.txt outside the racy window, so snapshots take it as unchanged.
7388
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7389
    fs::File::options()
7390
        .write(true)
7391
        .open(root.join("b.txt"))
7392
        .unwrap()
7393
        .set_modified(old)
7394
        .unwrap();
7395
    repo.commit("first", &[]).unwrap();
7396
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7397
    repo.snapshot_status("status").unwrap();
7398
    write(root, "a.txt", b"1\n2\n");
7399
    repo.commit("second", &[]).unwrap();
7400
    assert!(
7401
        repo.clean_by_manifest().unwrap(),
7402
        "after a commit of one file"
7403
    );
7404
    // Edited, seen by a status, edited again, then committed: the status
7405
    // left the first edit's stat, which the commit must not keep.
7406
    write(root, "a.txt", b"1\n2\n3\n");
7407
    repo.snapshot_status("status").unwrap();
7408
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7409
    repo.commit("third", &[]).unwrap();
7410
    assert!(
7411
        repo.clean_by_manifest().unwrap(),
7412
        "after an edit a status saw"
7413
    );
7414
}
e266b7d4 Andy McCall ↶ 7415
7416
#[test]
7417
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7418
    hermetic();
7419
    let dir = tempfile::tempdir().unwrap();
7420
    let root = dir.path();
7421
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7422
    write(root, "a.txt", b"1\n2\n");
7423
    let a = repo.commit("A", &[]).unwrap();
7424
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7425
    write(root, "a.txt", b"1\nX\n");
7426
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7427
    repo.bookmark_switch("develop", false).unwrap();
7428
    write(root, "a.txt", b"1\nY\n");
7429
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7430
    repo.bookmark_switch("main", false).unwrap();
7431
7432
    let err = repo.rebase(&c, &[d]).unwrap_err();
7433
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7434
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7435
    assert!(r.changed && r.checked_out);
7436
    let snap = repo.snapshot_status("status").unwrap();
7437
    assert!(
7438
        snap.base_snapshot.is_conflicted(),
7439
        "the conflict is in the working copy"
7440
    );
7441
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7442
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7443
7444
    write(root, "a.txt", b"1\nXY\n");
7445
    repo.commit("Resolve", &[]).unwrap();
7446
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7447
    assert!(st.contains(&c) && st.contains(&d));
7448
    let files = st.materialize().files;
7449
    assert!(!files["a.txt"].is_conflicted());
7450
    assert!(
7451
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7452
    );
7453
7454
    // A change the current bookmark does not hold is refused.
7455
    repo.bookmark_switch("develop", false).unwrap();
7456
    write(root, "b.txt", b"b\n");
7457
    let e = repo.commit("E", &[]).unwrap();
7458
    repo.bookmark_switch("main", false).unwrap();
7459
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7460
    assert!(
7461
        err.to_string().contains("not on the current bookmark"),
7462
        "{err}"
7463
    );
7464
}
d4dbab97 Andy McCall ↶ 7465
7466
#[test]
7467
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7468
    hermetic();
7469
    let dir = tempfile::tempdir().unwrap();
7470
    let root = dir.path();
7471
    let repo = Repo::init(root).unwrap();
7472
    write(root, "a.txt", b"a\n");
7473
    write(root, "kept.log", b"tracked\n");
7474
    repo.commit("first", &[]).unwrap();
7475
    write(root, "build.log", b"made\n");
7476
    let snap = repo.snapshot_status("status").unwrap();
7477
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7478
    // A rule written afterwards leaves the added file out again, while the
7479
    // committed one stays tracked.
7480
    write(root, ".gitignore", b"*.log\n");
7481
    let snap = repo.snapshot_status("status").unwrap();
7482
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7483
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7484
    write(root, "kept.log", b"tracked, edited\n");
7485
    let snap = repo.snapshot_status("status").unwrap();
7486
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7487
}
fd280228 Andy McCall ↶ 7488
7489
#[test]
7490
fn shed_graphs_come_back_the_same() {
7491
    hermetic();
7492
    let dir = tempfile::tempdir().unwrap();
7493
    let root = dir.path();
7494
    let repo = Repo::init(root).unwrap();
7495
    write(root, "a.txt", b"1\n2\n3\n");
7496
    write(root, "b.txt", b"x\n");
7497
    repo.commit("first", &[]).unwrap();
7498
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7499
    repo.commit("second", &[]).unwrap();
7500
    let heads = repo.bookmark_heads().unwrap();
7501
    let mut st = repo.load_state_history(&heads).unwrap();
7502
    let view = st.tree().view();
7503
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7504
        .iter()
7505
        .map(|p| view.entries[*p].node)
7506
        .collect();
7507
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7508
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7509
    assert_eq!(st.built_count(), 2);
7510
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7511
    assert_eq!((shed, st.built_count()), (2, 0));
7512
    // A later change applies on top of the shed history.
7513
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7514
    let h3 = repo.commit("third", &[]).unwrap();
7515
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7516
    st.add_known(h3, skeleton, texts);
7517
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7518
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7519
    assert_eq!(after[1], before[1]);
7520
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7521
}
360aa74a Andy McCall ↶ 7522
7523
#[test]
7524
fn many_edited_files_diff_in_parallel() {
7525
    // Enough edited files that the builder diffs them in parallel; the
7526
    // commit must hold exactly what is on disk, and a second snapshot
7527
    // must find nothing left to commit.
7528
    hermetic();
7529
    let dir = tempfile::tempdir().unwrap();
7530
    let root = dir.path();
7531
    let repo = Repo::init(root).unwrap();
7532
    let text = |i: usize, round: usize| {
7533
        let mut s = String::new();
7534
        for line in 0..50 {
7535
            if round > 0 && line % 7 == i % 7 {
7536
                s.push_str(&format!("edited {round} {i} {line}\n"));
7537
            } else {
7538
                s.push_str(&format!("file {i} line {line}\n"));
7539
            }
7540
        }
7541
        if round > 0 && i.is_multiple_of(3) {
7542
            s.push_str("appended\n");
7543
        }
7544
        s
7545
    };
7546
    for i in 0..40 {
7547
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7548
    }
7549
    repo.commit("first", &[]).unwrap();
7550
    for i in 0..40 {
7551
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7552
    }
7553
    let h = repo.commit("edit every file", &[]).unwrap();
7554
    let snap = repo.load_state(&[h]).unwrap().materialize();
7555
    for i in 0..40 {
7556
        let want = text(i, 1);
7557
        assert!(
7558
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
7559
            "d/f{i}.txt as committed"
7560
        );
7561
    }
7562
    assert!(
7563
        repo.commit("nothing", &[]).is_err(),
7564
        "nothing left to commit"
7565
    );
7566
}
b35df36b Andy McCall ↶ 7567
7568
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7569
/// is known (fetch printed "up to date" while main was behind), a change
7570
/// only fetched resolves and says where it is, and a checkout whose only
7571
/// remote is not `origin` uses that one.
7572
#[test]
7573
fn a_fetched_change_shows_as_behind_and_resolves() {
7574
    hermetic();
7575
    let dir = tempfile::tempdir().unwrap();
7576
    let root = dir.path();
7577
    let origin = Repo::init(&root.join("origin")).unwrap();
7578
    drop(origin);
7579
    let url = root.join("origin").to_string_lossy().to_string();
7580
    let a = Repo::clone(&url, &root.join("a"))
7581
        .unwrap()
7582
        .with_home(root.join("home-a"));
7583
    write(&root.join("a"), "f.txt", b"one\n");
7584
    a.commit("one", &[]).unwrap();
7585
    a.push("origin", false).unwrap();
7586
    let b = Repo::clone(&url, &root.join("b"))
7587
        .unwrap()
7588
        .with_home(root.join("home-b"));
7589
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7590
7591
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7592
    let h2 = a.commit("two", &[]).unwrap();
7593
    a.push("origin", false).unwrap();
7594
    b.fetch("origin").unwrap();
7595
    // Fetched, not pulled: one behind, the change found and placed.
7596
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7597
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7598
    assert_eq!(
7599
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7600
            .unwrap(),
7601
        h2
7602
    );
7603
    assert_eq!(
7604
        b.remote_only_location(&h2).unwrap().as_deref(),
7605
        Some("origin/main")
7606
    );
7607
    // Fetching again changes nothing: still behind, which is what the
7608
    // CLI now says rather than "up to date".
7609
    b.fetch("origin").unwrap();
7610
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7611
    b.pull("origin").unwrap();
7612
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7613
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7614
7615
    // One remote, not called origin: it is the default.
7616
    let mut c = Repo::init(&root.join("c")).unwrap();
7617
    assert_eq!(c.default_remote(), "origin");
7618
    c.config.set("remote.earth.url", &url).unwrap();
7619
    assert_eq!(c.default_remote(), "earth");
7620
    c.config.set("remote.origin.url", &url).unwrap();
7621
    assert_eq!(c.default_remote(), "origin");
7622
}
827281ee Andy McCall ↶ 7623
7624
/// oxygen#57: a clone from a relative local path records the remote as an
7625
/// absolute path, so fetch still finds it from inside the clone.
7626
#[test]
7627
fn a_clone_from_a_relative_path_records_it_absolute() {
7628
    hermetic();
7629
    let dir = tempfile::tempdir().unwrap();
7630
    let root = dir.path();
7631
    Repo::init(&root.join("origin")).unwrap();
7632
    let rel = crate::protocol::stored_url("relative/repo");
7633
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7634
    assert_eq!(
7635
        crate::protocol::stored_url("https://hub.example/o/n"),
7636
        "https://hub.example/o/n"
7637
    );
7638
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8d803563 Andy McCall ↶ 7639
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7640
    // A bucket is kept as written: it is not a path.
7641
    assert_eq!(
7642
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7643
        "s3://bucket/prefix?profile=p"
7644
    );
827281ee Andy McCall ↶ 7645
    let url = root.join("origin").to_string_lossy().to_string();
7646
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7647
    assert_eq!(b.config.remotes["origin"], url);
7648
    b.fetch("origin").unwrap();
7649
}
a46f3e4f Andy McCall ↶ 7650
7651
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7652
/// and gets its subrepos at their pins from this workspace's copies, with
7653
/// their remotes pointing where the subrepos come from.
7654
#[test]
7655
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7656
    hermetic();
7657
    let dir = tempfile::tempdir().unwrap();
7658
    let root = dir.path();
7659
    Repo::init(&root.join("lib-origin")).unwrap();
7660
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7661
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7662
        .unwrap()
7663
        .with_home(root.join("home"));
7664
    write(&root.join("lib"), "lib.txt", b"v1\n");
7665
    let l1 = lib.commit("lib v1", &[]).unwrap();
7666
    assert!(lib.push("origin", false).unwrap()[0].ok);
7667
7668
    let app_dir = root.join("app");
7669
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7670
    write(&app_dir, "main.txt", b"app\n");
7671
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7672
    app.commit("app with lib", &[]).unwrap();
7673
    // A second bookmark, and the main workspace on another.
7674
    app.bookmark_create("develop", None).unwrap();
7675
    app.bookmark_create("feature", None).unwrap();
7676
    let mut app = app;
7677
    app.bookmark_switch("feature", false).unwrap();
7678
    assert_eq!(app.config.bookmark, "feature");
7679
7680
    // The library's origin goes away: the subrepo must come from here.
7681
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7682
    let heads = app.resolve_heads("develop").unwrap();
7683
    let ws = app
7684
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7685
        .unwrap();
7686
    assert_eq!(
7687
        ws.config.bookmark, "develop",
7688
        "the new workspace is on develop"
7689
    );
7690
    assert_eq!(
7691
        app.config.bookmark, "feature",
7692
        "and this one stays on its own"
7693
    );
7694
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7695
    assert_eq!(
7696
        sub.config.remotes["origin"], lib_url,
7697
        "its origin is the subrepo's URL"
7698
    );
7699
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7700
    assert_eq!(
7701
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7702
        b"v1\n"
7703
    );
7704
}
47ce8b8e Andy McCall ↶ 7705
7706
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7707
/// operators and the predicates, over a small graph with two heads and
7708
/// a rename.
7709
#[test]
7710
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7711
    hermetic();
7712
    let dir = tempfile::tempdir().unwrap();
7713
    let root = dir.path();
7714
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7715
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7716
        .unwrap();
7717
    write(root, "src/a.rs", b"one\n");
7718
    let a = repo.commit("first: add a", &[]).unwrap();
7719
    write(root, "src/a.rs", b"one\ntwo\n");
7720
    let b = repo.commit("second: grow a", &[]).unwrap();
7721
    // A second head, independent of b: a new file on top of a.
7722
    repo.checkout(&[a], false, "checkout a").unwrap();
7723
    write(root, "docs/notes.md", b"notes\n");
7724
    let c = repo.commit("third: notes", &[]).unwrap();
7725
    // Back to both heads, then rename a.rs: the node keeps its identity.
7726
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7727
        .unwrap();
7728
    fs::remove_file(root.join("src/a.rs")).unwrap();
7729
    write(root, "src/z.rs", b"one\ntwo\n");
7730
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7731
    let wc = repo.working_copy().unwrap().0;
7732
    // A saved revset is checked when set.
7733
    repo.set_user_config("revset.mine", "author(me) & ::main")
7734
        .unwrap();
7735
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7736
    let set = |src: &str| -> Vec<ChangeHash> {
7737
        let mut v = repo.revset(src).unwrap().hashes;
7738
        v.sort();
7739
        v
7740
    };
7741
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7742
        let mut v = hs.to_vec();
7743
        v.sort();
7744
        v
7745
    };
7746
7747
    // Changes commute: a new file depends on nothing and the rename on the
7748
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7749
    // copy on the three heads b, c, d.
7750
    let heads = sorted(&repo.bookmark_heads().unwrap());
7751
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7752
    assert!(heads.contains(&d) && heads.contains(&c));
7753
    // Symbols and closures.
7754
    assert_eq!(set("main"), heads);
7755
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7756
    assert_eq!(set("@"), vec![wc]);
7757
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7758
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7759
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7760
    assert_eq!(
7761
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7762
        sorted(&[a, b])
7763
    );
7764
    // Ranges: what main has beyond b, and `..` forms.
7765
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7766
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7767
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7768
    // Operators and precedence: ~ binds tighter than &, & than |.
7769
    assert_eq!(
7770
        set(&format!("::main ~ #{}", d.short(12))),
7771
        sorted(&[a, b, c])
7772
    );
7773
    assert_eq!(
7774
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7775
        sorted(&[b, c])
7776
    );
7777
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7778
    // Relations.
7779
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7780
    head_deps.sort();
7781
    head_deps.dedup();
7782
    assert_eq!(set("deps(main)"), head_deps);
7783
    let on_a: Vec<ChangeHash> = [b, c, d]
7784
        .into_iter()
7785
        .filter(|h| meta(h).deps.contains(&a))
7786
        .collect();
7787
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7788
    assert_eq!(set("heads(::main)"), heads);
7789
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7790
    assert_eq!(
7791
        set(&format!(
7792
            "heads(#{} | #{} | #{})",
7793
            a.short(12),
7794
            b.short(12),
7795
            c.short(12)
7796
        )),
7797
        sorted(&[b, c])
7798
    );
7799
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7800
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7801
    assert_eq!(set("none()"), vec![]);
7802
    // Predicates: author by name, email, key prefix and `me`.
7803
    let key = repo.config.author_key.unwrap();
7804
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7805
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7806
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7807
    assert_eq!(set("author(me) & ::main").len(), 4);
7808
    assert_eq!(set("author(nobody)"), vec![]);
7809
    assert_eq!(set("description(notes)"), vec![c]);
7810
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7811
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7812
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7813
    // touches follows the node through the rename, in the current state.
7814
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7815
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7816
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7817
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7818
    // Newest first in the result order.
7819
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7820
    // The saved revset, and errors that say what is wrong.
7821
    assert_eq!(set("mine()").len(), 4);
7822
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7823
    assert!(e.contains("unknown function nosuch()"), "{e}");
7824
    let e = repo.revset("main &").unwrap_err().to_string();
7825
    assert!(e.contains("at character"), "{e}");
7826
    let e = repo.revset("zzzz").unwrap_err().to_string();
7827
    assert!(e.contains("no change matches"), "{e}");
7828
    let e = repo
7829
        .revset_with_budget("::main", std::time::Duration::ZERO)
7830
        .unwrap_err()
7831
        .to_string();
7832
    assert!(e.contains("budget"), "{e}");
7833
    // The log entries carry the bookmark's heads and the working copy.
7834
    let entries = repo.log_revset("::@").unwrap();
7835
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
2c9ddac3 Andy McCall ↶ 7836
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7837
    // push); then a signed change, a tag, and a revocation.
7838
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7839
    assert_eq!(set("signed_by(me)"), vec![]);
7840
    repo.sign_change(&d).unwrap();
7841
    assert_eq!(set("signed_by(me)"), vec![d]);
7842
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7843
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7844
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7845
    assert_eq!(set("delegated()"), vec![]);
7846
    assert_eq!(set("revoked()"), vec![]);
7847
    assert_eq!(set("attested(tag)"), vec![]);
7848
    repo.tag_create("v1", &[b], "first").unwrap();
7849
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7850
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7851
    assert_eq!(set("attested(receipt)"), vec![]);
7852
    assert_eq!(set("built(test)"), vec![]);
7853
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7854
    assert!(e.contains("tag, receipt or ref"), "{e}");
7855
    repo.revoke_identity(&key, "test").unwrap();
7856
    assert_eq!(set("revoked()"), vec![d]);
7857
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
47ce8b8e Andy McCall ↶ 7858
}
614f55e1 Andy McCall ↶ 7859
7860
#[test]
7861
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7862
    let dir = tempfile::tempdir().unwrap();
7863
    let root = dir.path();
7864
    let home = root.join("home");
7865
    // Ada's identity lives in the user file; repository `a` pins the same
7866
    // key in its own file, repository `b` names none.
7867
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7868
    let (key, _) = a
7869
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7870
        .unwrap();
7871
    a.config.set("author.key", &key.to_hex()).unwrap();
7872
    a.save_config().unwrap();
7873
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7874
    let r = a
7875
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7876
        .unwrap();
7877
    assert_eq!(
7878
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7879
        r.new.to_hex(),
7880
        "the user file follows"
7881
    );
7882
    assert_eq!(
7883
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7884
        r.new.to_hex(),
7885
        "the pinning repository follows"
7886
    );
7887
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7888
    assert_eq!(
7889
        b.config.author_key,
7890
        Some(r.new),
7891
        "a checkout without a pin follows the user file"
7892
    );
7893
    // A repository-scoped identity leaves the user file alone.
7894
    let other_home = root.join("home2");
7895
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7896
    let (ck, _) = c
7897
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7898
        .unwrap();
7899
    assert!(!other_home.join("config.toml").exists());
7900
    let r2 = c.rotate_identity().unwrap();
7901
    assert_ne!(r2.new, ck);
7902
    assert_eq!(
7903
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7904
        r2.new.to_hex()
7905
    );
7906
    assert!(
7907
        !other_home.join("config.toml").exists(),
7908
        "a repository-scoped identity stays repository-scoped"
7909
    );
7910
    // Several delegates in one rotation; a repeat is refused.
7911
    let (d1, d2) = (
7912
        SecretKey::generate().identity("D1", "d1@x", 1),
7913
        SecretKey::generate().identity("D2", "d2@x", 1),
7914
    );
7915
    let r3 = c
7916
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7917
        .unwrap();
7918
    assert_eq!(r3.identity.delegates.len(), 2);
7919
    assert!(c
7920
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7921
        .is_err());
7922
}
33be2409 Andy McCall ↶ 7923
7924
/// Two unrelated histories that both add the same file, joined by two
7925
/// independent merges on two branches, then those branches merged: Git
7926
/// merges identical additions cleanly, and the import must too (#71,
7927
/// found in VS Code's history).
7928
#[test]
7929
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7930
    // Batches of one: every merge renders apart from the state, where a
7931
    // file whose graph the state had built came out empty (#71).
7932
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7933
    hermetic();
7934
    if std::process::Command::new("git")
7935
        .arg("--version")
7936
        .output()
7937
        .is_err()
7938
    {
7939
        eprintln!("git not installed; skipping");
7940
        return;
7941
    }
7942
    let dir = tempfile::tempdir().unwrap();
7943
    let root = dir.path();
7944
    let g = root.join("src.git");
7945
    fs::create_dir_all(&g).unwrap();
7946
    let git = |args: &[&str]| -> String {
7947
        let out = std::process::Command::new("git")
7948
            .arg("-C")
7949
            .arg(&g)
7950
            .args([
7951
                "-c",
7952
                "user.name=Grace",
7953
                "-c",
7954
                "[email protected]",
7955
                "-c",
7956
                "commit.gpgsign=false",
7957
            ])
7958
            .args(args)
7959
            .output()
7960
            .unwrap();
7961
        assert!(
7962
            out.status.success(),
7963
            "git {args:?}: {}",
7964
            String::from_utf8_lossy(&out.stderr)
7965
        );
7966
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7967
    };
7968
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7969
    // History A: main.
7970
    git(&["init", "-q", "-b", "main"]);
7971
    write(&g, "gulpfile.js", text);
7972
    write(&g, "a.txt", b"a\n");
7973
    git(&["add", "."]);
7974
    git(&["commit", "-q", "-m", "A root"]);
7975
    // History B: an unrelated root adding the same file, identical.
7976
    git(&["checkout", "-q", "--orphan", "fork"]);
7977
    git(&["rm", "-q", "-r", "--cached", "."]);
7978
    for f in ["gulpfile.js", "a.txt"] {
7979
        let _ = fs::remove_file(g.join(f));
7980
    }
7981
    write(&g, "gulpfile.js", text);
7982
    write(&g, "b.txt", b"b\n");
7983
    git(&["add", "."]);
7984
    git(&["commit", "-q", "-m", "B root"]);
7985
    // Two branches from main, each joining B on its own.
7986
    git(&["checkout", "-q", "-b", "one", "main"]);
7987
    git(&[
7988
        "merge",
7989
        "-q",
7990
        "--no-ff",
7991
        "--allow-unrelated-histories",
7992
        "-m",
7993
        "join on one",
7994
        "fork",
7995
    ]);
7996
    git(&["checkout", "-q", "-b", "two", "main"]);
7997
    write(&g, "a.txt", b"a\ntwo\n");
7998
    git(&["commit", "-q", "-am", "work on two"]);
7999
    git(&[
8000
        "merge",
8001
        "-q",
8002
        "--no-ff",
8003
        "--allow-unrelated-histories",
8004
        "-m",
8005
        "join on two",
8006
        "fork",
8007
    ]);
8008
    // Then the two joins meet, and the file is reformatted after.
8009
    git(&["checkout", "-q", "main"]);
8010
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
8011
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8012
    write(
8013
        &g,
8014
        "gulpfile.js",
8015
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
8016
    );
8017
    git(&["commit", "-q", "-am", "after"]);
8018
8019
    let dest = root.join("dest");
8020
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8021
    repo.import_git(&g, "main").unwrap();
8022
    let v = repo.verify_git_import(&g, "main").unwrap();
8023
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8024
    assert_eq!(
8025
        fs::read(dest.join("gulpfile.js")).unwrap(),
8026
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
8027
    );
8028
}
8029
8030
/// As above, but the two joins keep different copies (each branch had a
8031
/// different version when it joined), and later work edits each copy:
8032
/// the shape of VS Code's c67ef57cda90 (#71).
8033
#[test]
8034
fn git_import_joins_where_each_join_kept_a_different_copy() {
8035
    // Batches of one: every merge renders apart from the state, where a
8036
    // file whose graph the state had built came out empty (#71).
8037
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8038
    hermetic();
8039
    if std::process::Command::new("git")
8040
        .arg("--version")
8041
        .output()
8042
        .is_err()
8043
    {
8044
        eprintln!("git not installed; skipping");
8045
        return;
8046
    }
8047
    let dir = tempfile::tempdir().unwrap();
8048
    let root = dir.path();
8049
    let g = root.join("src.git");
8050
    fs::create_dir_all(&g).unwrap();
8051
    let run = |args: &[&str]| {
8052
        std::process::Command::new("git")
8053
            .arg("-C")
8054
            .arg(&g)
8055
            .args([
8056
                "-c",
8057
                "user.name=Grace",
8058
                "-c",
8059
                "[email protected]",
8060
                "-c",
8061
                "commit.gpgsign=false",
8062
            ])
8063
            .args(args)
8064
            .output()
8065
            .unwrap()
8066
    };
8067
    let git = |args: &[&str]| -> String {
8068
        let out = run(args);
8069
        assert!(
8070
            out.status.success(),
8071
            "git {args:?}: {}",
8072
            String::from_utf8_lossy(&out.stderr)
8073
        );
8074
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8075
    };
8076
    git(&["init", "-q", "-b", "main"]);
8077
    write(
8078
        &g,
8079
        "gulpfile.js",
8080
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
8081
    );
8082
    git(&["add", "."]);
8083
    git(&["commit", "-q", "-m", "A root"]);
8084
    write(
8085
        &g,
8086
        "gulpfile.js",
8087
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
8088
    );
8089
    git(&["commit", "-q", "-am", "whitespace"]);
8090
    git(&["checkout", "-q", "--orphan", "fork"]);
8091
    git(&["rm", "-q", "-r", "--cached", "."]);
8092
    let _ = fs::remove_file(g.join("gulpfile.js"));
8093
    write(
8094
        &g,
8095
        "gulpfile.js",
8096
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
8097
    );
8098
    git(&["add", "."]);
8099
    git(&["commit", "-q", "-m", "B root"]);
8100
    // Branch one joins B keeping main's copy; branch two keeps B's.
8101
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
8102
        git(&["checkout", "-q", "-b", branch, "main"]);
8103
        let _ = run(&[
8104
            "merge",
8105
            "-q",
8106
            "--no-ff",
8107
            "--allow-unrelated-histories",
8108
            "-m",
8109
            "join",
8110
            "fork",
8111
        ]);
8112
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
8113
        git(&["add", "gulpfile.js"]);
8114
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
8115
    }
8116
    // Each branch then edits its copy.
8117
    git(&["checkout", "-q", "one"]);
8118
    write(
8119
        &g,
8120
        "gulpfile.js",
8121
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
8122
    );
8123
    git(&["commit", "-q", "-am", "tslint on one"]);
8124
    git(&["checkout", "-q", "two"]);
8125
    write(
8126
        &g,
8127
        "gulpfile.js",
8128
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
8129
    );
8130
    write(&g, "extra.txt", b"x\n");
8131
    write(&g, "more.txt", b"m\n");
8132
    git(&["add", "."]);
8133
    git(&["commit", "-q", "-am", "fmt on two"]);
8134
    // They meet: resolved by hand.
8135
    git(&["checkout", "-q", "one"]);
8136
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8137
    write(
8138
        &g,
8139
        "gulpfile.js",
8140
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
8141
    );
8142
    git(&["add", "gulpfile.js"]);
8143
    git(&["commit", "-q", "-m", "merge two into one"]);
8144
8145
    let dest = root.join("dest");
8146
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8147
    repo.import_git(&g, "one").unwrap();
8148
    let v = repo.verify_git_import(&g, "one").unwrap();
8149
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8150
}
dd21fd82 Andy McCall ↶ 8151
8152
/// oxygen#68: on a store that is not this disk's directory, the operation
8153
/// head is the store's reference record, moved by compare-and-swap. Two
8154
/// handles recording from the same head both get through, merged; a swap
8155
/// from a stale version is refused; a second repository cannot start on a
8156
/// store that already holds one.
8157
#[test]
8158
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8159
    use crate::strata::{MemoryStore, Store as _};
8160
    let backend = std::sync::Arc::new(MemoryStore::new());
8161
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8162
    let dir = tempfile::tempdir().unwrap();
8163
    let a = Repo::init(dir.path()).unwrap();
8164
    assert!(
8165
        !dir.path().join(".oxy/ops/head").exists(),
8166
        "the head is not a file"
8167
    );
8168
    let (h0, op0) = a.head_op().unwrap();
8169
    let record = backend
8170
        .read_ref(HEAD_RECORD)
8171
        .unwrap()
8172
        .expect("the head is the store's record");
8173
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8174
8175
    let b = Repo::open(dir.path()).unwrap();
8176
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8177
    let mut va = op0.view.clone();
8178
    va.bookmarks.insert("from-a".into(), state);
8179
    let mut vb = op0.view.clone();
8180
    vb.bookmarks.insert("from-b".into(), state);
8181
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8182
    assert_eq!(b.head_ref().unwrap(), rb);
8183
    // a recorded from h0 too: the head moved, so the two are merged.
8184
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8185
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8186
    assert_eq!(head, ra);
8187
    assert!(
8188
        op.command.ends_with("(merged with a concurrent operation)"),
8189
        "{}",
8190
        op.command
8191
    );
8192
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8193
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8194
8195
    // A swap from a version that is no longer current moves nothing.
8196
    let (h, v) = a.read_head().unwrap();
8197
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8198
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8199
    assert_eq!(a.head_ref().unwrap(), rb);
8200
8201
    let other = tempfile::tempdir().unwrap();
8202
    let err = Repo::init(other.path())
8203
        .err()
8204
        .expect("the store already holds a log")
8205
        .to_string();
8206
    assert!(
8207
        err.contains("already holds a repository's operation log"),
8208
        "{err}"
8209
    );
8210
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8211
}
d069701a Andy McCall ↶ 8212
8213
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8214
/// objects and operation head there, with `.oxy/cache` in front: it works
8215
/// as one on disk does, reopens, and survives losing its cache.
8216
#[test]
8217
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8218
    hermetic();
8219
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8220
        return;
8221
    }
8222
    let dir = tempfile::tempdir().unwrap();
8223
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8224
    let url = format!("dir://{}", bucket.display());
8225
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8226
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8227
    write(&root, "a.txt", b"one\n");
8228
    let h1 = repo.commit("First", &[]).unwrap();
8229
    write(&root, "a.txt", b"one\ntwo\n");
8230
    let h2 = repo.commit("Second", &[]).unwrap();
8231
    assert!(
8232
        !root.join(".oxy/ops/head").exists(),
8233
        "the head is in the store"
8234
    );
8235
    assert!(bucket.join("ops/head").is_file());
8236
    assert!(root.join(".oxy/cache").is_dir());
8237
    drop(repo);
8238
8239
    // Reopened, and again with no cache at all: everything comes from the store.
8240
    for drop_cache in [false, true] {
8241
        if drop_cache {
8242
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8243
        }
8244
        let repo = Repo::open(&root).unwrap();
8245
        let log: Vec<String> = repo
8246
            .op_log()
8247
            .unwrap()
8248
            .into_iter()
8249
            .map(|(_, op)| op.command)
8250
            .collect();
8251
        assert!(log.len() >= 3, "{log:?}");
8252
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8253
        let heads = repo
8254
            .store()
8255
            .get_state(&repo.view().unwrap().bookmarks["main"])
8256
            .unwrap()
8257
            .heads;
8258
        assert_eq!(heads, vec![h2]);
8259
        assert_eq!(
8260
            repo.load_state(&heads).unwrap().materialize().files.len(),
8261
            1
8262
        );
8263
    }
8264
8265
    // A second repository cannot start on the same store.
8266
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8267
        .err()
8268
        .unwrap()
8269
        .to_string();
8270
    assert!(
8271
        err.contains("already holds a repository's operation log"),
8272
        "{err}"
8273
    );
8274
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8275
        .err()
8276
        .unwrap()
8277
        .to_string();
8278
    assert!(err.contains("cannot open that kind of store"), "{err}");
8279
}
80677b7a Andy McCall ↶ 8280
8281
/// oxygen#75: the prompt's quick check agrees with status in a repository
8282
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8283
/// another state, clean again once that pin is committed. (It compared the
8284
/// subrepo's directory as if it were a file, so it was always dirty.)
8285
#[test]
8286
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8287
    hermetic();
8288
    let dir = tempfile::tempdir().unwrap();
8289
    let root = dir.path();
8290
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8291
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8292
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8293
        .unwrap()
8294
        .with_home(root.join("home"));
8295
    write(&root.join("lib"), "lib.txt", b"v1\n");
8296
    lib.commit("lib v1", &[]).unwrap();
8297
    assert!(lib.push("origin", false).unwrap()[0].ok);
8298
    let app_dir = root.join("app");
8299
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8300
    write(&app_dir, "main.txt", b"app\n");
8301
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8302
    app.commit("app with lib", &[]).unwrap();
8303
    // Out of the racy window, so the stat-only path decides.
8304
    std::thread::sleep(std::time::Duration::from_millis(2100));
8305
    let reopen = || Repo::open(&app_dir).unwrap();
8306
    assert_eq!(
8307
        reopen().quick_dirty().unwrap(),
8308
        Some(false),
8309
        "clean, as status says"
8310
    );
8311
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8312
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8313
    nested.commit("lib v2", &[]).unwrap();
8314
    assert_eq!(
8315
        reopen().quick_dirty().unwrap(),
8316
        Some(true),
8317
        "the subrepo moved"
8318
    );
8319
    reopen().commit("pin lib v2", &[]).unwrap();
8320
    std::thread::sleep(std::time::Duration::from_millis(2100));
8321
    assert_eq!(
8322
        reopen().quick_dirty().unwrap(),
8323
        Some(false),
8324
        "the new pin is committed"
8325
    );
8326
}
7993d465 Andy McCall ↶ 8327
8328
#[test]
8329
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8330
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8331
    hermetic();
8332
    let dir = tempfile::tempdir().unwrap();
8333
    let root = dir.path();
8334
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8335
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8336
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8337
        .unwrap()
8338
        .with_home(root.join("home"));
8339
    write(&root.join("lib"), "lib.txt", b"v1\n");
8340
    lib.commit("lib v1", &[]).unwrap();
8341
    assert!(lib.push("origin", false).unwrap()[0].ok);
8342
    let app_dir = root.join("app");
8343
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8344
    write(
8345
        &app_dir,
8346
        ".oxymodules",
8347
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8348
    );
8349
    let unpinned = app.unpinned_modules().unwrap();
8350
    assert_eq!(unpinned.len(), 1);
8351
    assert_eq!(unpinned[0].0, "libs/lib");
8352
    assert_eq!(unpinned[0].1.url, lib_url);
8353
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8354
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8355
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8356
}
bf3a6781 Andy McCall ↶ 8357
8358
#[test]
8359
fn the_bookmark_revset_function_names_only_bookmarks() {
8360
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8361
    hermetic();
8362
    let dir = tempfile::tempdir().unwrap();
8363
    let repo = Repo::init(dir.path()).unwrap();
8364
    write(dir.path(), "a.txt", b"a\n");
8365
    let a = repo.commit("A", &[]).unwrap();
8366
    write(dir.path(), "b.txt", b"b\n");
8367
    let b = repo.commit("B", &[]).unwrap();
8368
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8369
    heads.sort();
8370
    let mut want = repo.bookmark_heads().unwrap();
8371
    want.sort();
8372
    assert_eq!(heads, want);
8373
    assert!(heads.contains(&b));
8374
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8375
    // A change prefix is a symbol, not a bookmark.
8376
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8377
    assert!(repo.revset(&prefix).is_ok());
8378
    let e = repo
8379
        .revset(&format!("bookmark({prefix})"))
8380
        .unwrap_err()
8381
        .to_string();
8382
    assert!(e.contains("no such bookmark"), "{e}");
8383
}
72484195 Andy McCall ↶ 8384
8385
#[test]
8386
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8387
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8388
    // pinning the subrepo, and the nested repository on disk at that pin.
8389
    hermetic();
8390
    let dir = tempfile::tempdir().unwrap();
8391
    let root = dir.path();
8392
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8393
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8394
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8395
        .unwrap()
8396
        .with_home(root.join("home"));
8397
    write(&root.join("lib"), "lib.txt", b"v1\n");
8398
    lib.commit("lib v1", &[]).unwrap();
8399
    assert!(lib.push("origin", false).unwrap()[0].ok);
8400
    let app_dir = root.join("app");
8401
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8402
    write(&app_dir, "main.txt", b"app\n");
8403
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8404
    // The stale state: registered in .oxymodules, never pinned.
8405
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8406
    app.commit("initial", &[]).unwrap();
8407
    let stale = app.bookmark_heads().unwrap();
8408
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8409
    app.commit("pin lib", &[]).unwrap();
8410
    let newer = app.bookmark_heads().unwrap();
8411
    app.checkout(&stale, false, "test").unwrap();
8412
    write(&app_dir, "notes.txt", b"mine\n");
8413
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8414
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8415
    assert!(app_dir.join("notes.txt").exists());
8416
}
8417
8418
#[test]
8419
fn a_bookmark_only_behind_its_remote_catches_up() {
8420
    // oxygen#74: switch takes the remote's state rather than a stale one.
8421
    hermetic();
8422
    let dir = tempfile::tempdir().unwrap();
8423
    let root = dir.path();
8424
    let _origin = Repo::init(&root.join("origin")).unwrap();
8425
    let url = root.join("origin").to_string_lossy().to_string();
8426
    let one = Repo::clone(&url, &root.join("one"))
8427
        .unwrap()
8428
        .with_home(root.join("home"));
8429
    write(&root.join("one"), "a.txt", b"a\n");
8430
    one.commit("A", &[]).unwrap();
8431
    assert!(one.push("origin", false).unwrap()[0].ok);
8432
    let two = Repo::clone(&url, &root.join("two"))
8433
        .unwrap()
8434
        .with_home(root.join("home"));
8435
    write(&root.join("two"), "b.txt", b"b\n");
8436
    two.commit("B", &[]).unwrap();
8437
    assert!(two.push("origin", false).unwrap()[0].ok);
8438
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8439
    one.fetch("origin").unwrap();
8440
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8441
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8442
    // Local work the remote lacks: left alone.
8443
    write(&root.join("one"), "c.txt", b"c\n");
8444
    one.commit("C", &[]).unwrap();
8445
    write(&root.join("two"), "d.txt", b"d\n");
8446
    two.commit("D", &[]).unwrap();
8447
    assert!(two.push("origin", false).unwrap()[0].ok);
8448
    one.fetch("origin").unwrap();
8449
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8450
}
42ccf504 Andy McCall ↶ 8451
8452
#[test]
8453
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8454
    // oxygen#83: remotes earth and gcs, origin removed.
8455
    hermetic();
8456
    let dir = tempfile::tempdir().unwrap();
8457
    let root = dir.path();
8458
    let _up = Repo::init(&root.join("up")).unwrap();
8459
    let url = root.join("up").to_string_lossy().to_string();
8460
    let other = Repo::clone(&url, &root.join("other"))
8461
        .unwrap()
8462
        .with_home(root.join("home"));
8463
    write(&root.join("other"), "a.txt", b"a\n");
8464
    other.commit("a", &[]).unwrap();
8465
    assert!(other.push("origin", false).unwrap()[0].ok);
8466
    let mut one = Repo::clone(&url, &root.join("one"))
8467
        .unwrap()
8468
        .with_home(root.join("home"));
8469
    one.config.set("remote.earth.url", &url).unwrap();
8470
    one.config.set("remote.gcs.url", &url).unwrap();
8471
    one.config.set("remote.origin.url", "").unwrap();
8472
    one.save_config().unwrap();
8473
    write(&root.join("other"), "b.txt", b"b\n");
8474
    other.commit("b", &[]).unwrap();
8475
    assert!(other.push("origin", false).unwrap()[0].ok);
8476
    one.fetch("earth").unwrap();
8477
    let b = one
8478
        .bookmarks()
8479
        .unwrap()
8480
        .into_iter()
8481
        .find(|b| b.name == "main")
8482
        .unwrap();
8483
    assert_eq!(
8484
        (b.remote.as_deref(), b.behind),
8485
        (Some("earth"), Some(1)),
8486
        "a stale origin copy is not used"
8487
    );
8488
    assert_eq!(
8489
        one.default_remote(),
8490
        "origin",
8491
        "no default chosen among several"
8492
    );
8493
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8494
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8495
    one.config.set("core.remote", "earth").unwrap();
8496
    assert_eq!(one.default_remote(), "earth");
8497
}
cbe8499a Andy McCall ↶ 8498
8499
#[test]
8500
fn a_missing_author_identity_says_how_to_fix_it() {
8501
    // oxygen#82: an agent home's author.key naming an identity the
8502
    // repository does not hold.
8503
    hermetic();
8504
    let dir = tempfile::tempdir().unwrap();
8505
    let mut repo = Repo::init(dir.path()).unwrap();
8506
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8507
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8508
    let e = repo.identity(&missing).unwrap_err().to_string();
8509
    assert!(
8510
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8511
        "{e}"
8512
    );
8513
    assert!(e.contains("this repository's config"), "{e}");
8514
}
f6dccc45 Andy McCall ↶ 8515
8516
#[test]
8517
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8518
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8519
    // the working copy, a pull with nothing new left it there, and status
8520
    // said "clean".
8521
    hermetic();
8522
    let dir = tempfile::tempdir().unwrap();
8523
    let root = dir.path();
8524
    let _up = Repo::init(&root.join("up")).unwrap();
8525
    let url = root.join("up").to_string_lossy().to_string();
8526
    let other = Repo::clone(&url, &root.join("other"))
8527
        .unwrap()
8528
        .with_home(root.join("home"));
8529
    write(&root.join("other"), "a.txt", b"a\n");
8530
    other.commit("a", &[]).unwrap();
8531
    assert!(other.push("origin", false).unwrap()[0].ok);
8532
    let one = Repo::clone(&url, &root.join("one"))
8533
        .unwrap()
8534
        .with_home(root.join("home"));
8535
    write(&root.join("other"), "b.txt", b"b\n");
8536
    other.commit("b", &[]).unwrap();
8537
    assert!(other.push("origin", false).unwrap()[0].ok);
8538
    one.fetch("origin").unwrap();
8539
    // The bookmark moves; the working copy does not.
8540
    let theirs = one.resolve_heads("origin/main").unwrap();
8541
    one.bookmark_set("main", &theirs).unwrap();
8542
    assert!(!root.join("one/b.txt").exists());
8543
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8544
    let r = one.pull("origin").unwrap();
8545
    assert!(
8546
        !r.changed && r.checked_out,
8547
        "nothing new, but the working copy caught up"
8548
    );
8549
    assert!(root.join("one/b.txt").exists());
8550
    assert_eq!(one.working_copy_behind().unwrap(), None);
8551
}
170bb436 Andy McCall ↶ 8552
8553
#[test]
8554
fn touched_nodes_cache_answers_as_the_changes_do() {
8555
    hermetic();
8556
    let dir = tempfile::tempdir().unwrap();
8557
    let repo = Repo::init(dir.path()).unwrap();
8558
    write(dir.path(), "a.txt", b"one\n");
8559
    write(dir.path(), "b.txt", b"x\n");
8560
    repo.snapshot("t").unwrap();
8561
    let c1 = repo.commit("first", &[]).unwrap();
8562
    write(dir.path(), "b.txt", b"y\n");
8563
    repo.snapshot("t").unwrap();
8564
    repo.commit("b only", &[]).unwrap();
8565
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8566
    write(dir.path(), "c.txt", b"one\ntwo\n");
8567
    repo.snapshot("t").unwrap();
8568
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8569
    // Uncommitted work, so the working copy touches a file too.
8570
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8571
    repo.snapshot("t").unwrap();
8572
8573
    let path = dir.path().join(".oxy/index/touched");
8574
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8575
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8576
    assert!(path.exists(), "the first query writes the cache");
8577
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8578
    assert_eq!(cold, warm, "the cache answers as the changes do");
8579
    let (wc, _) = repo.working_copy().unwrap();
8580
    assert_eq!(
8581
        cold,
8582
        vec![wc, c3, c1],
8583
        "renames followed, the working copy included"
8584
    );
8585
8586
    // Working-copy changes are not kept: they are replaced by every snapshot.
8587
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8588
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8589
    assert!(cached.contains(&c1) && cached.contains(&c3));
8590
8591
    // A damaged cache is ignored, not trusted.
8592
    let mut bytes = fs::read(&path).unwrap();
8593
    let last = bytes.len() - 40;
8594
    bytes[last] ^= 1;
8595
    fs::write(&path, &bytes).unwrap();
8596
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8597
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8598
    assert_eq!(hashes(touches), vec![c3, c1]);
8599
}
e8e6e0ca Andy McCall ↶ 8600
8601
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8602
/// file back where it was leave two placements at one place, which the
8603
/// tree shows as one file. Removing it, and then its directory, retires
8604
/// both, so no copy is left under a directory that is gone.
8605
#[test]
8606
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8607
    hermetic();
8608
    if std::process::Command::new("git")
8609
        .arg("--version")
8610
        .output()
8611
        .is_err()
8612
    {
8613
        eprintln!("git not installed; skipping");
8614
        return;
8615
    }
8616
    let dir = tempfile::tempdir().unwrap();
8617
    let root = dir.path();
8618
    let g = root.join("src.git");
8619
    fs::create_dir_all(&g).unwrap();
8620
    let git = |args: &[&str]| {
8621
        let out = std::process::Command::new("git")
8622
            .arg("-C")
8623
            .arg(&g)
8624
            .args([
8625
                "-c",
8626
                "user.name=Grace",
8627
                "-c",
8628
                "[email protected]",
8629
                "-c",
8630
                "commit.gpgsign=false",
8631
            ])
8632
            .args(args)
8633
            .output()
8634
            .unwrap();
8635
        assert!(
8636
            out.status.success(),
8637
            "git {args:?}: {}",
8638
            String::from_utf8_lossy(&out.stderr)
8639
        );
8640
    };
8641
    git(&["init", "-q", "-b", "main"]);
8642
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8643
    write(&g, "keep.txt", b"k\n");
8644
    git(&["add", "."]);
8645
    git(&["commit", "-qm", "base"]);
8646
    fs::create_dir_all(g.join("d/sub")).unwrap();
8647
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8648
    git(&["commit", "-qm", "into sub"]);
8649
    git(&["checkout", "-qb", "side"]);
8650
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8651
    git(&["commit", "-qm", "back, on side"]);
8652
    git(&["checkout", "-q", "main"]);
8653
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8654
    git(&["commit", "-qm", "back, on main"]);
8655
    git(&["merge", "-q", "--no-edit", "side"]);
8656
    git(&["rm", "-rq", "d"]);
8657
    git(&["commit", "-qm", "d goes"]);
8658
8659
    let repo = Repo::init(&root.join("o")).unwrap();
8660
    repo.import_git(&g, "main").unwrap();
8661
    let v = repo.verify_git_import(&g, "main").unwrap();
8662
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8663
    let st = repo
8664
        .load_state_history(&repo.bookmark_heads().unwrap())
8665
        .unwrap();
8666
    let view = st.tree().view();
8667
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8668
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8669
}
5552e69c Andy McCall ↶ 8670
8671
/// oxygen#94: a state index's file histories are read, and checked by
8672
/// their own hashes, only when a file is built. One found damaged is an
8673
/// error that says so, the index is removed, and the next read rebuilds it.
8674
#[test]
8675
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8676
    hermetic();
8677
    let dir = tempfile::tempdir().unwrap();
8678
    let repo = Repo::init(dir.path()).unwrap();
8679
    for i in 0..6 {
8680
        write(
8681
            dir.path(),
8682
            &format!("f{i}.txt"),
8683
            format!("one {i}\n").as_bytes(),
8684
        );
8685
    }
8686
    repo.snapshot("t").unwrap();
8687
    repo.commit("first", &[]).unwrap();
8688
    for i in 0..6 {
8689
        write(
8690
            dir.path(),
8691
            &format!("f{i}.txt"),
8692
            format!("one {i}\ntwo\n").as_bytes(),
8693
        );
8694
    }
8695
    repo.snapshot("t").unwrap();
8696
    repo.commit("second", &[]).unwrap();
8697
    let want: Vec<Vec<u8>> = (0..6)
8698
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8699
        .collect();
8700
    // The index of the working copy's base, holding every file's history
8701
    // (a few changes behind, an index is replayed onto, not rewritten).
8702
    let (_, wc) = repo.working_copy().unwrap();
8703
    let base = repo.load_state_history(&wc.deps).unwrap();
8704
    repo.write_state_index(&wc.deps, &base);
8705
    for (i, w) in want.iter().enumerate() {
8706
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8707
    }
8708
    let index = repo.state_indexes();
8709
    assert!(!index.is_empty(), "a state index was written");
8710
    // The histories are last in the file: damage the last of them.
8711
    let mut bytes = fs::read(&index[0]).unwrap();
8712
    let last = bytes.len() - 1;
8713
    bytes[last] ^= 0x40;
8714
    fs::write(&index[0], &bytes).unwrap();
8715
8716
    let reads: Vec<_> = (0..6)
8717
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8718
        .collect();
8719
    let damaged: Vec<String> = reads
8720
        .iter()
8721
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8722
        .collect();
8723
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8724
    assert!(
8725
        damaged[0].contains("state index was damaged")
8726
            && damaged[0].contains("run the command again"),
8727
        "{}",
8728
        damaged[0]
8729
    );
8730
    // Every file reads right again, from an index rebuilt from history.
8731
    for (i, w) in want.iter().enumerate() {
8732
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8733
    }
8734
}
cb8b8082 Andy McCall ↶ 8735
8736
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8737
/// objects alone and in dependency order, and the last moves the bookmark.
8738
/// The remote ends with every change and the same state, and says how each
8739
/// part went.
8740
#[test]
8741
fn a_long_push_goes_in_parts() {
8742
    hermetic();
8743
    let dir = tempfile::tempdir().unwrap();
8744
    let root = dir.path();
8745
    let origin = root.join("origin");
8746
    Repo::init_bare_unbound(&origin).unwrap();
8747
    let main = root.join("main");
8748
    let mut repo = Repo::init(&main).unwrap();
8749
    repo.config
8750
        .set("remote.origin.url", &origin.to_string_lossy())
8751
        .unwrap();
8752
    // One byte: every change is a part of its own.
8753
    repo.config.set("push.batch-bytes", "1").unwrap();
8754
    repo.save_config().unwrap();
8755
    for i in 0..6 {
8756
        write(
8757
            &main,
8758
            &format!("f{i}.txt"),
8759
            format!("file {i}\n").as_bytes(),
8760
        );
8761
        repo.commit(&format!("c{i}"), &[]).unwrap();
8762
    }
8763
    let mut parts = Vec::new();
8764
    let results = repo
8765
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8766
        .unwrap();
8767
    assert!(
8768
        results.iter().any(|r| r.ok && r.name == "main"),
8769
        "{results:?}"
8770
    );
8771
    assert_eq!(parts.len(), 6, "{parts:?}");
8772
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8773
8774
    let remote = Repo::open(&origin).unwrap();
8775
    let heads = repo.bookmark_heads().unwrap();
8776
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8777
    assert_eq!(
8778
        remote.log_state(&heads).unwrap().len(),
8779
        repo.log_state(&heads).unwrap().len()
8780
    );
8781
    // A push of objects alone reports how it went, as `objects`.
8782
    let got = remote
8783
        .receive_push(Bundle::default(), vec![], None, vec![])
8784
        .unwrap();
8785
    assert_eq!(got.len(), 1);
8786
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8787
}
d6e0d5b8 Andy McCall ↶ 8788
8789
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8790
/// own commits (Git author email = its email, any case) with its key, and
8791
/// leaves anyone else's with the zero key; the history verifies as before.
8792
#[test]
8793
fn git_import_claims_your_own_commits() {
8794
    hermetic();
8795
    if std::process::Command::new("git")
8796
        .arg("--version")
8797
        .output()
8798
        .is_err()
8799
    {
8800
        eprintln!("git not installed; skipping");
8801
        return;
8802
    }
8803
    let dir = tempfile::tempdir().unwrap();
8804
    let root = dir.path();
8805
    let g = root.join("src.git");
8806
    fs::create_dir_all(&g).unwrap();
8807
    let git = |who: &str, args: &[&str]| {
8808
        let (name, email) = who.split_once(' ').unwrap();
8809
        let out = std::process::Command::new("git")
8810
            .arg("-C")
8811
            .arg(&g)
8812
            .args([
8813
                "-c",
8814
                &format!("user.name={name}"),
8815
                "-c",
8816
                &format!("user.email={email}"),
8817
                "-c",
8818
                "commit.gpgsign=false",
8819
            ])
8820
            .args(args)
8821
            .output()
8822
            .unwrap();
8823
        assert!(
8824
            out.status.success(),
8825
            "git {args:?}: {}",
8826
            String::from_utf8_lossy(&out.stderr)
8827
        );
8828
    };
8829
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8830
    write(&g, "a.txt", b"a\n");
8831
    git("Grace [email protected]", &["add", "."]);
8832
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8833
    write(&g, "b.txt", b"b\n");
8834
    git("Ada [email protected]", &["add", "."]);
8835
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8836
8837
    let mut repo = Repo::init(&root.join("o")).unwrap();
8838
    let (key, _) = repo
8839
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8840
        .unwrap();
8841
    repo.config.set("git.claim", "true").unwrap();
8842
    repo.save_config().unwrap();
8843
    let repo = Repo::open(&root.join("o")).unwrap();
8844
    repo.import_git(&g, "main").unwrap();
8845
    let v = repo.verify_git_import(&g, "main").unwrap();
8846
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8847
    let heads = repo.bookmark_heads().unwrap();
8848
    let by_message: std::collections::HashMap<String, KeyId> = repo
8849
        .log_state(&heads)
8850
        .unwrap()
8851
        .into_iter()
8852
        .map(|e| {
8853
            (
8854
                e.change.message.lines().next().unwrap_or("").to_string(),
8855
                e.change.author,
8856
            )
8857
        })
8858
        .collect();
8859
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8860
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8861
}
34fad4a9 Andy McCall ↶ 8862
8863
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8864
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8865
#[test]
8866
fn removing_a_remote_leaves_nothing_of_it() {
8867
    hermetic();
8868
    let dir = tempfile::tempdir().unwrap();
8869
    let origin = dir.path().join("origin");
8870
    Repo::init_bare_unbound(&origin).unwrap();
8871
    let main = dir.path().join("main");
8872
    let mut repo = Repo::init(&main).unwrap();
8873
    repo.config
8874
        .set("remote.origin.url", &origin.to_string_lossy())
8875
        .unwrap();
8876
    repo.config
8877
        .set("remote.origin.token", "secret-ish")
8878
        .unwrap();
8879
    repo.config
8880
        .set("remote.keep.url", &origin.to_string_lossy())
8881
        .unwrap();
8882
    repo.save_config().unwrap();
8883
    write(&main, "a.txt", b"a\n");
8884
    repo.commit("a", &[]).unwrap();
8885
    assert!(repo.push("origin", false).unwrap()[0].ok);
8886
    assert!(
8887
        repo.view().unwrap().remotes.contains_key("origin"),
8888
        "a tracking bookmark"
8889
    );
8890
8891
    repo.remove_remote("origin").unwrap();
8892
    let again = Repo::open(&main).unwrap();
8893
    assert!(
8894
        !again
8895
            .config
8896
            .repo_layer()
8897
            .keys()
8898
            .any(|k| k.starts_with("remote.origin.")),
8899
        "{:?}",
8900
        again.config.repo_layer()
8901
    );
8902
    assert!(!again.config.remotes.contains_key("origin"));
8903
    assert!(
8904
        !again.view().unwrap().remotes.contains_key("origin"),
8905
        "its tracking bookmarks go"
8906
    );
8907
    assert!(
8908
        again.config.remotes.contains_key("keep"),
8909
        "another remote stays"
8910
    );
8911
    let mut again = again;
8912
    assert!(
8913
        again.remove_remote("origin").is_err(),
8914
        "a second removal is refused"
8915
    );
8916
}
9d580f21 Andy McCall ↶ 8917
8918
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
8919
/// unreachable from history, so gc prunes it, unless the host names it:
8920
/// then it and its chunks stay, and it reads back whole.
8921
#[test]
8922
fn gc_keeps_the_blobs_a_host_names() {
8923
    hermetic();
8924
    let dir = tempfile::tempdir().unwrap();
8925
    let repo = Repo::init(dir.path()).unwrap();
8926
    write(dir.path(), "a.txt", b"a\n");
8927
    repo.commit("a", &[]).unwrap();
8928
    // Large enough to be several chunks.
8929
    let body: Vec<u8> = (0..400_000u32)
8930
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
8931
        .collect();
8932
    let kept = repo.store_blob(&body).unwrap();
8933
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
8934
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
8935
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
8936
    assert!(!repo.store().has(&lost), "not named: pruned");
8937
    repo.gc(true).unwrap();
8938
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
8939
}
530a0fc6 Andy McCall ↶ 8940
8941
/// oxygen#99: undo in one workspace undoes that workspace's last command,
8942
/// never another workspace's, says what it undid, and goes further back
8943
/// when run again.
8944
#[test]
8945
fn undo_is_scoped_to_its_workspace() {
8946
    hermetic();
8947
    let dir = tempfile::tempdir().unwrap();
8948
    let root = dir.path().join("main");
8949
    let a = Repo::init(&root).unwrap();
8950
    write(&root, "base.txt", b"base\n");
8951
    let base = a.commit("base", &[]).unwrap();
8952
    a.bookmark_create("feature", None).unwrap();
8953
    let ws_dir = dir.path().join("ws");
8954
    let heads = a.resolve_heads("feature").unwrap();
8955
    let b = a
8956
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
8957
        .unwrap();
8958
8959
    // A commits on main, then B commits on feature: B's is the newest.
8960
    write(&root, "a.txt", b"a\n");
8961
    let ca = a.commit("from a", &[]).unwrap();
8962
    write(&ws_dir, "b.txt", b"b\n");
8963
    let cb = b.commit("from b", &[]).unwrap();
8964
8965
    // A's undo undoes A's commit and leaves B's.
8966
    let u = a.undo().unwrap();
8967
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8968
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
8969
    assert!(!u.changes.is_empty());
8970
    let view = a.view().unwrap();
8971
    // (Independent changes commute, so a bookmark's heads may hold base too.)
8972
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
8973
    assert!(
8974
        a.heads_of(&view, "feature").unwrap().contains(&cb),
8975
        "B's commit stands"
8976
    );
8977
    assert!(
8978
        a.store().get_change(&ca).is_ok(),
8979
        "the change itself is still in the store"
8980
    );
8981
    // A's working copy was clean, so its files followed; B's are untouched.
8982
    assert!(!root.join("a.txt").exists());
8983
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
8984
    assert!(ws_dir.join("b.txt").exists());
8985
8986
    // B's undo still finds B's own commit, under A's undo.
8987
    let u = b.undo().unwrap();
8988
    assert_eq!(u.command, "oxy commit -m \"from b\"");
8989
    assert!(!b
8990
        .heads_of(&b.view().unwrap(), "feature")
8991
        .unwrap()
8992
        .contains(&cb));
8993
    assert_eq!(
8994
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
8995
        vec![base],
8996
        "A's undo stands"
8997
    );
8998
8999
    // A's next undo goes past the commit it already undid, to adding B's
9000
    // workspace: refused, since B has worked there since.
9001
    let e = a.undo().unwrap_err().to_string();
9002
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
9003
}
9004
9005
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
9006
/// own commit's head, and the other workspace's head stays.
9007
#[test]
9008
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
9009
    hermetic();
9010
    let dir = tempfile::tempdir().unwrap();
9011
    let root = dir.path().join("main");
9012
    let a = Repo::init(&root).unwrap();
9013
    write(&root, "base.txt", b"base\n");
9014
    a.commit("base", &[]).unwrap();
9015
    let ws_dir = dir.path().join("ws");
9016
    let b = a.workspace_add(&ws_dir, None).unwrap();
9017
    write(&root, "a.txt", b"a\n");
9018
    let ca = a.commit("from a", &[]).unwrap();
9019
    write(&ws_dir, "b.txt", b"b\n");
9020
    let cb = b.commit("from b", &[]).unwrap();
9021
    let u = a.undo().unwrap();
9022
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9023
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
9024
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
9025
}
9026
9027
/// oxygen#99: an undo that would also take back what another workspace
9028
/// did since to the same bookmark is refused, naming it.
9029
#[test]
9030
fn undo_refuses_to_take_back_another_workspaces_work() {
9031
    hermetic();
9032
    let dir = tempfile::tempdir().unwrap();
9033
    let root = dir.path().join("main");
9034
    let a = Repo::init(&root).unwrap();
9035
    write(&root, "base.txt", b"base\n");
9036
    a.commit("base", &[]).unwrap();
9037
    let ws_dir = dir.path().join("ws");
9038
    let b = a.workspace_add(&ws_dir, None).unwrap();
9039
    // Both on main: A commits, then B builds on it, editing A's file.
9040
    write(&root, "a.txt", b"a\n");
9041
    a.commit("from a", &[]).unwrap();
9042
    let heads = b.resolve_heads("main").unwrap();
9043
    b.checkout(&heads, false, "oxy checkout").unwrap();
9044
    write(&ws_dir, "a.txt", b"a, then b\n");
9045
    b.commit("from b", &[]).unwrap();
9046
    let e = a.undo().unwrap_err().to_string();
9047
    assert!(
9048
        e.contains("bookmark main") && e.contains("builds on"),
9049
        "{e}"
9050
    );
9051
    assert!(e.contains("oxy op restore"), "{e}");
9052
}
9053
9054
/// oxygen#99: undoing a commit that was already pushed says so: the remote
9055
/// still has it.
9056
#[test]
9057
fn undo_says_when_the_commit_was_pushed() {
9058
    hermetic();
9059
    let dir = tempfile::tempdir().unwrap();
9060
    let root = dir.path();
9061
    Repo::init(&root.join("origin")).unwrap();
9062
    let url = root.join("origin").to_string_lossy().to_string();
9063
    let repo = Repo::clone(&url, &root.join("work"))
9064
        .unwrap()
9065
        .with_home(root.join("home"));
9066
    write(&root.join("work"), "a.txt", b"a\n");
9067
    repo.commit("a", &[]).unwrap();
9068
    assert!(repo.push("origin", false).unwrap()[0].ok);
9069
    // The push itself is passed over: the remote keeps what it was sent.
9070
    let u = repo.undo().unwrap();
9071
    assert_eq!(u.command, "oxy commit -m \"a\"");
9072
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
9073
}