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