OXYGENHUB
◆ v0.4.3 oxygen / crates / oxy-core / src / repo / tests.rs
307.6 KiB · Rust · last changed git import and fetch --claim: author your own commits with your key 25 days ago source blame history raw
98286406 Andy McCall ↶ 1
//! Tests for the repository layer.
2
3
use super::*;
75167672 Andy McCall 4
use crate::protocol::SignedPolicy;
957fee30 Andy McCall ↶ 5
use crate::repo::{BisectStep, Selection};
98286406 Andy McCall ↶ 6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
75167672 Andy McCall 26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
98286406 Andy McCall ↶ 30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
75167672 Andy McCall 80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
98286406 Andy McCall ↶ 85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
75167672 Andy McCall 103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
98286406 Andy McCall ↶ 108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
75167672 Andy McCall 114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
98286406 Andy McCall ↶ 121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
0912a033 Andy McCall ↶ 137
    assert!(
138
        d.lines()
139
            .any(|l| l.starts_with("M ") && l.ends_with("main.rs")),
140
        "a modified file is in the summary too: {d}"
141
    );
98286406 Andy McCall ↶ 142
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
143
    assert!(d.contains("-fn main() {}"), "{d}");
144
145
    // Resolution by prefix.
146
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
75167672 Andy McCall 147
    assert_eq!(
148
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
149
        h1
150
    );
98286406 Andy McCall ↶ 151
    assert!(repo.resolve_change("zzzz").is_err());
152
153
    // Undo the commit: bookmark and working copy go back.
154
    repo.undo().unwrap();
155
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
156
    let s = repo.snapshot("oxy status").unwrap();
75167672 Andy McCall 157
    assert!(
158
        !s.changed,
159
        "files on disk still match the pre-commit working copy"
160
    );
98286406 Andy McCall ↶ 161
    assert_eq!(s.statuses.len(), 3);
162
}
163
164
/// Make `main` conflicted: two commits on the same base that edit the same line.
165
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
166
    let dir = tempfile::tempdir().unwrap();
167
    let root = dir.path();
168
    let repo = Repo::init(root).unwrap();
169
    write(root, "f.txt", b"a\nb\nc\n");
170
    let h1 = repo.commit("base", &[]).unwrap();
171
    write(root, "f.txt", b"a\nB\nc\n");
172
    let h2 = repo.commit("upper", &[]).unwrap();
173
    repo.checkout(&[h1], false, "checkout").unwrap();
174
    write(root, "f.txt", b"a\nX\nc\n");
175
    let h3 = repo.commit("ex", &[]).unwrap();
176
    (dir, repo, h1, h2, h3)
177
}
178
179
#[test]
180
fn concurrent_edits_conflict_and_can_be_resolved() {
181
    hermetic();
182
    let (dir, repo, h1, h2, h3) = conflicted_repo();
183
    let root = dir.path();
184
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
185
    assert_eq!(heads, [h2, h3].into_iter().collect());
186
    let st = repo.load_state(&[h2, h3]).unwrap();
187
    assert!(st.materialize().is_conflicted());
188
189
    // Checking out main writes markers.
75167672 Andy McCall 190
    let r = repo
191
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
192
        .unwrap();
98286406 Andy McCall ↶ 193
    assert!(r.conflicted);
194
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 195
    assert!(
196
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
197
        "{marked}"
198
    );
199
    assert!(
200
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
201
        "{marked}"
202
    );
98286406 Andy McCall ↶ 203
    assert!(has_conflict_markers(marked.as_bytes()));
204
    // Untouched markers: clean working copy; commit has nothing to do.
205
    let s = repo.snapshot("status").unwrap();
206
    assert!(s.statuses.is_empty());
207
    assert!(!s.resolves);
208
209
    // Partially edited file that still has markers cannot be committed.
210
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
211
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 212
    assert_eq!(
213
        statuses(&s),
214
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
215
    );
98286406 Andy McCall ↶ 216
    assert!(repo.commit("no", &[]).is_err());
217
218
    // Resolve by keeping one side and adding a line elsewhere.
219
    write(root, "f.txt", b"a\nX\nc\nd\n");
220
    let s = repo.snapshot("status").unwrap();
221
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
222
    assert!(s.resolves);
223
    let h4 = repo.commit("resolve", &[]).unwrap();
224
    let c4 = repo.store().get_change(&h4).unwrap();
225
    assert_eq!(c4.kind, ChangeKind::Resolution);
226
    let mut want = vec![h1, h2, h3];
227
    want.sort();
75167672 Andy McCall 228
    assert_eq!(
229
        c4.deps, want,
230
        "a resolution depends on exactly the contributors and what it references"
231
    );
98286406 Andy McCall ↶ 232
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
233
    let snap = repo.load_state(&[h4]).unwrap().materialize();
234
    assert!(!snap.is_conflicted());
75167672 Andy McCall 235
    assert!(
236
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
237
    );
98286406 Andy McCall ↶ 238
    assert!(!repo.snapshot("status").unwrap().changed);
239
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
240
    // whatever order the changes arrive in.
241
    let mut st = State::new();
242
    for h in [h4, h3, h1, h2] {
243
        st.add_unchecked(repo.store().get_change(&h).unwrap());
244
    }
245
    st.validate().unwrap();
75167672 Andy McCall 246
    assert!(
247
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
248
    );
98286406 Andy McCall ↶ 249
}
250
251
#[test]
252
fn resolution_may_keep_both_sides_or_neither() {
253
    hermetic();
254
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
255
    let root = dir.path();
75167672 Andy McCall 256
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
257
        .unwrap();
98286406 Andy McCall ↶ 258
    // Keep both sides in a chosen order.
259
    write(root, "f.txt", b"a\nX\nB\nc\n");
260
    let h = repo.commit("both", &[]).unwrap();
261
    let snap = repo.load_state(&[h]).unwrap().materialize();
262
    assert!(!snap.is_conflicted());
75167672 Andy McCall 263
    assert!(
264
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
265
    );
98286406 Andy McCall ↶ 266
    // Undo and instead drop the whole region.
267
    repo.undo().unwrap();
268
    write(root, "f.txt", b"a\nc\n");
269
    let h = repo.commit("neither", &[]).unwrap();
270
    let snap = repo.load_state(&[h]).unwrap().materialize();
271
    assert!(!snap.is_conflicted());
75167672 Andy McCall 272
    assert!(
273
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
274
    );
98286406 Andy McCall ↶ 275
}
276
277
#[test]
278
fn name_conflict_resolved_by_removing_a_candidate() {
279
    hermetic();
280
    let dir = tempfile::tempdir().unwrap();
281
    let root = dir.path();
282
    let repo = Repo::init(root).unwrap();
283
    write(root, "keep.txt", b"k\n");
284
    let h1 = repo.commit("base", &[]).unwrap();
285
    write(root, "new.txt", b"one\n");
286
    repo.commit("one", &[]).unwrap();
287
    repo.checkout(&[h1], false, "checkout").unwrap();
288
    write(root, "new.txt", b"two\n");
289
    repo.commit("two", &[]).unwrap();
75167672 Andy McCall 290
    let r = repo
291
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
292
        .unwrap();
98286406 Andy McCall ↶ 293
    assert!(r.conflicted);
75167672 Andy McCall 294
    assert!(
295
        root.join("new.txt.oxy-conflict-1").exists()
296
            && root.join("new.txt.oxy-conflict-2").exists()
297
    );
98286406 Andy McCall ↶ 298
    assert!(!root.join("new.txt").exists());
299
    // Candidate numbering follows change-hash order, so pick by content:
300
    // keep the "two" candidate under the real name and drop the other.
75167672 Andy McCall 301
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
302
        (1, 2)
303
    } else {
304
        (2, 1)
305
    };
98286406 Andy McCall ↶ 306
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
75167672 Andy McCall 307
    fs::rename(
308
        root.join(format!("new.txt.oxy-conflict-{keep}")),
309
        root.join("new.txt"),
310
    )
311
    .unwrap();
98286406 Andy McCall ↶ 312
    let h = repo.commit("pick two", &[]).unwrap();
75167672 Andy McCall 313
    assert_eq!(
314
        repo.store().get_change(&h).unwrap().kind,
315
        ChangeKind::Resolution
316
    );
98286406 Andy McCall ↶ 317
    // The resolution does not touch keep.txt, so it does not depend on h1;
318
    // the bookmark keeps both as heads and their union is the state.
319
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
320
    assert_eq!(heads, [h1, h].into_iter().collect());
75167672 Andy McCall 321
    let snap = repo
322
        .load_state(&repo.bookmark_heads().unwrap())
323
        .unwrap()
324
        .materialize();
98286406 Andy McCall ↶ 325
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
75167672 Andy McCall 326
    assert_eq!(
327
        snap.files.keys().cloned().collect::<Vec<_>>(),
328
        ["keep.txt", "new.txt"]
329
    );
330
    assert!(
331
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
332
    );
98286406 Andy McCall ↶ 333
}
334
335
#[test]
336
fn identities_and_signed_commits() {
337
    hermetic();
338
    let dir = tempfile::tempdir().unwrap();
339
    let root = dir.path();
340
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
341
    write(root, "a.txt", b"a\n");
342
    let h0 = repo.commit("unsigned", &[]).unwrap();
343
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
75167672 Andy McCall 344
    assert_eq!(
345
        repo.store().get_change(&h0).unwrap().author,
346
        ObjectRef::ZERO
347
    );
98286406 Andy McCall ↶ 348
75167672 Andy McCall 349
    let (key, id) = repo
350
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
351
        .unwrap();
98286406 Andy McCall ↶ 352
    assert_eq!(id.hash(), key);
353
    assert_eq!(repo.config.author_key, Some(key));
354
    // Config survives reopen; the secret key is found again.
355
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
356
    assert_eq!(reopened.config.author_key, Some(key));
357
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
358
359
    // Default core.sign = seal: commits carry the author but no signature.
360
    write(root, "a.txt", b"a\nb\n");
361
    let h1 = repo.commit("authored", &[]).unwrap();
362
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
363
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
364
    // Signing later works too.
365
    repo.sign_change(&h1).unwrap();
75167672 Andy McCall 366
    assert!(
367
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
368
    );
98286406 Andy McCall ↶ 369
370
    repo.config.set("core.sign", "change").unwrap();
371
    repo.save_config().unwrap();
372
    write(root, "a.txt", b"a\nb\nc\n");
373
    let h2 = repo.commit("signed", &[]).unwrap();
75167672 Andy McCall 374
    assert_eq!(
375
        repo.verify_change(&h2).unwrap(),
376
        SignatureStatus::Valid {
377
            key,
378
            name: "Ada".into(),
379
            email: "[email protected]".into(),
380
            sealed: false,
381
            revoked: false
382
        }
383
    );
98286406 Andy McCall ↶ 384
05e71ed6 Andy McCall ↶ 385
    // A signature by a key that is not the author or a delegate is rejected
386
    // when the change names an author; an anonymous change (made before any
387
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
98286406 Andy McCall ↶ 388
    let other = SecretKey::generate();
389
    let other_id = other.identity("Mallory", "[email protected]", 0);
390
    let other_key = repo.store().put_identity(&other_id).unwrap();
05e71ed6 Andy McCall ↶ 391
    write(root, "a.txt", b"a\nb\nc\nd\n");
392
    repo.config.set("core.sign", "seal").unwrap();
393
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
394
    let forged = other.sign(Domain::Change, &other_key, &h3);
395
    repo.store().put_signature(&h3, &forged).unwrap();
75167672 Andy McCall 396
    assert!(
05e71ed6 Andy McCall ↶ 397
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
75167672 Andy McCall 398
    );
05e71ed6 Andy McCall ↶ 399
    let adopted = other.sign(Domain::Change, &other_key, &h0);
400
    repo.store().put_signature(&h0, &adopted).unwrap();
401
    assert!(
402
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
403
    );
98286406 Andy McCall ↶ 404
405
    // Tampering with the stored signature invalidates it.
406
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
407
    sig.ed[0] ^= 1;
408
    repo.store().put_signature(&h2, &sig).unwrap();
75167672 Andy McCall 409
    assert!(matches!(
410
        repo.verify_change(&h2).unwrap(),
411
        SignatureStatus::Invalid(_)
412
    ));
98286406 Andy McCall ↶ 413
414
    // Without the secret key, signing at commit fails cleanly.
415
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
416
    write(root, "a.txt", b"z\n");
417
    assert!(no_keys.commit("cannot sign", &[]).is_err());
418
}
419
420
#[test]
421
fn checkout_moves_the_working_copy() {
422
    hermetic();
423
    let dir = tempfile::tempdir().unwrap();
424
    let root = dir.path();
425
    let repo = Repo::init(root).unwrap();
426
    write(root, "a.txt", b"one\n");
427
    write(root, "sub/deep/b.txt", b"b\n");
428
    let h1 = repo.commit("first", &[]).unwrap();
429
    write(root, "a.txt", b"two\n");
430
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
431
    write(root, "bin.dat", &[0, 1, 2, 3]);
432
    let h2 = repo.commit("second", &[]).unwrap();
433
434
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
75167672 Andy McCall 435
    assert_eq!(
436
        r,
437
        CheckoutReport {
438
            written: 2,
439
            removed: 1,
440
            conflicted: false,
d3cd7ef9 Andy McCall ↶ 441
            notes: vec![],
442
            lacks: 1,
75167672 Andy McCall 443
        }
444
    );
98286406 Andy McCall ↶ 445
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
446
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
447
    assert!(!root.join("bin.dat").exists());
448
    let (_, wc) = repo.working_copy().unwrap();
449
    assert_eq!(wc.deps, vec![h1]);
75167672 Andy McCall 450
    assert!(
451
        !repo.snapshot("status").unwrap().changed,
452
        "checkout leaves a clean working copy"
453
    );
98286406 Andy McCall ↶ 454
    // The bookmark still points at h2.
455
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
456
457
    // Dirty working copy refuses without --discard.
458
    write(root, "a.txt", b"dirty\n");
459
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
75167672 Andy McCall 460
    let r = repo
461
        .checkout(&[h2], true, "oxy checkout --discard")
462
        .unwrap();
98286406 Andy McCall ↶ 463
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
464
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
465
    assert!(!root.join("sub").exists(), "empty directories are pruned");
466
    assert_eq!(r.removed, 1);
467
    assert!(!repo.snapshot("status").unwrap().changed);
468
469
    // Refuses to write through a symlinked directory.
470
    #[cfg(unix)]
471
    {
472
        fs::remove_dir_all(root.join("sub")).ok();
473
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
474
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
475
    }
476
}
477
478
#[test]
479
fn large_files_are_chunked_and_read_back() {
480
    hermetic();
481
    let dir = tempfile::tempdir().unwrap();
482
    let repo = Repo::init(dir.path()).unwrap();
483
    let mut big = vec![0u8; 700 * 1024];
484
    for (i, b) in big.iter_mut().enumerate() {
485
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
486
    }
487
    let r = repo.store_blob(&big).unwrap();
488
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
489
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
490
    assert_eq!(repo.read_blob(&r).unwrap(), big);
491
    assert_eq!(Repo::blob_ref(&big), r);
492
}
493
494
#[test]
495
fn clone_push_pull_with_seals_and_attestations() {
496
    hermetic();
497
    let dir = tempfile::tempdir().unwrap();
498
    let root = dir.path();
499
    let origin_path = root.join("origin");
500
    let origin = Repo::init(&origin_path).unwrap();
501
    let origin_url = origin_path.to_string_lossy().to_string();
502
503
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
75167672 Andy McCall 504
    let mut a = Repo::clone(&origin_url, &root.join("a"))
505
        .unwrap()
506
        .with_home(root.join("home-a"));
98286406 Andy McCall ↶ 507
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
75167672 Andy McCall 508
    let (key_a, _) = a
509
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
510
        .unwrap();
98286406 Andy McCall ↶ 511
    write(&root.join("a"), "f.txt", b"a\n");
512
    let h1 = a.commit("first", &[]).unwrap();
513
    let results = a.push("origin", false).unwrap();
514
    assert!(results[0].ok, "{}", results[0].reason);
515
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
516
    // The change was sealed at push and the reference attested.
75167672 Andy McCall 517
    assert!(
518
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
519
    );
520
    assert_eq!(
521
        origin.verify_change(&h1).unwrap(),
522
        SignatureStatus::Unsigned
523
    );
f8c69576 Andy McCall ↶ 524
    let serial_of = |att: &SignedAttest| match att.attest.body {
525
        AttestBody::Ref { serial, .. } => serial,
526
        _ => unreachable!(),
527
    };
98286406 Andy McCall ↶ 528
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 529
    // A bookmark new to the remote starts at the clock (past any deleted
530
    // namesake's serial); later updates count up from there.
531
    let first = serial_of(&att);
532
    assert!(first > 1_000_000_000_000, "{first}");
98286406 Andy McCall ↶ 533
    let again = a.push("origin", false).unwrap();
534
    assert!(again[0].ok && again[0].reason.contains("up to date"));
535
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 536
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
98286406 Andy McCall ↶ 537
538
    // B clones and sees the file and the seal.
539
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
540
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
541
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
75167672 Andy McCall 542
    assert!(matches!(
543
        b.authenticate_change(&h1).unwrap(),
544
        SignatureStatus::Valid { sealed: true, .. }
545
    ));
98286406 Andy McCall ↶ 546
547
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
548
    write(&root.join("b"), "f.txt", b"a\nb\n");
549
    let h2 = b.commit("second", &[]).unwrap();
550
    assert!(b.push("origin", false).unwrap()[0].ok);
551
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
552
553
    // A commits an independent change; push is refused until A pulls.
554
    write(&root.join("a"), "g.txt", b"g\n");
555
    let h3 = a.commit("third", &[]).unwrap();
556
    assert!(a.push("origin", false).is_err());
557
    let pr = a.pull("origin").unwrap();
558
    assert!(pr.changed && pr.checked_out);
559
    let mut want = vec![h2, h3];
560
    want.sort();
561
    assert_eq!(pr.heads, want);
562
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
563
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
564
    let results = a.push("origin", false).unwrap();
565
    assert!(results[0].ok, "{}", results[0].reason);
566
    let mut origin_heads = origin.bookmark_heads().unwrap();
567
    origin_heads.sort();
568
    assert_eq!(origin_heads, want);
569
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 570
    assert_eq!(serial_of(&att), first + 1);
98286406 Andy McCall ↶ 571
572
    // B pulls and ends up identical.
573
    let pr = b.pull("origin").unwrap();
574
    assert_eq!(pr.heads, want);
575
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
576
    assert!(!b.snapshot("status").unwrap().changed);
577
578
    // Concurrent edits of the same line: the union is a reified conflict.
579
    write(&root.join("a"), "f.txt", b"a\nA\n");
580
    a.commit("a-edit", &[]).unwrap();
581
    a.push("origin", false).unwrap();
582
    write(&root.join("b"), "f.txt", b"a\nB\n");
583
    b.commit("b-edit", &[]).unwrap();
584
    let pr = b.pull("origin").unwrap();
585
    assert!(pr.changed && pr.checked_out);
586
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
587
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
588
    write(&root.join("b"), "f.txt", b"a\nAB\n");
589
    let hr = b.commit("resolve", &[]).unwrap();
75167672 Andy McCall 590
    assert_eq!(
591
        b.store().get_change(&hr).unwrap().kind,
592
        ChangeKind::Resolution
593
    );
98286406 Andy McCall ↶ 594
    assert!(b.push("origin", false).unwrap()[0].ok);
595
    a.pull("origin").unwrap();
596
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
597
    // The resolution depends on the conflicting edits, but nothing depends
598
    // on "third" (it only added g.txt), so it stays a head beside it.
599
    let mut want = vec![hr, h3];
600
    want.sort();
601
    assert_eq!(a.bookmark_heads().unwrap(), want);
602
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
603
}
604
605
#[test]
606
fn receive_push_rejects_bad_updates() {
607
    hermetic();
608
    let dir = tempfile::tempdir().unwrap();
609
    let root = dir.path();
610
    let origin = Repo::init(&root.join("origin")).unwrap();
611
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 612
    let mut a = Repo::clone(&url, &root.join("a"))
613
        .unwrap()
614
        .with_home(root.join("home"));
615
    let (key, _) = a
616
        .create_identity("Ada", "a@b", IdentityScope::Repo)
617
        .unwrap();
98286406 Andy McCall ↶ 618
    write(&root.join("a"), "f.txt", b"x\n");
619
    let h1 = a.commit("one", &[]).unwrap();
620
    assert!(a.push("origin", false).unwrap()[0].ok);
621
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
75167672 Andy McCall 622
    let s1 = origin
623
        .store()
624
        .put_state(&StateObject::new(vec![h1]))
625
        .unwrap();
98286406 Andy McCall ↶ 626
627
    // Missing head.
75167672 Andy McCall 628
    let ghost = origin
629
        .store()
630
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
631
        .unwrap();
632
    let r = origin
633
        .receive_push(
634
            Bundle::default(),
635
            vec![RefUpdate {
636
                name: "main".into(),
637
                old_state: s1,
638
                new_state: ghost,
639
                force: false,
640
                attestation: None,
641
            }],
642
            None,
643
            vec![],
644
        )
645
        .unwrap();
646
    assert!(
647
        !r[0].ok && r[0].reason.contains("missing"),
648
        "{}",
649
        r[0].reason
650
    );
98286406 Andy McCall ↶ 651
652
    // Stale old_state.
75167672 Andy McCall 653
    let r = origin
654
        .receive_push(
655
            Bundle::default(),
656
            vec![RefUpdate {
657
                name: "main".into(),
658
                old_state: empty,
659
                new_state: s1,
660
                force: false,
661
                attestation: None,
662
            }],
663
            None,
664
            vec![],
665
        )
666
        .unwrap();
98286406 Andy McCall ↶ 667
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
668
669
    // Non-fast-forward without force is refused; with force it passes.
75167672 Andy McCall 670
    let r = origin
671
        .receive_push(
672
            Bundle::default(),
673
            vec![RefUpdate {
674
                name: "main".into(),
675
                old_state: s1,
676
                new_state: empty,
677
                force: false,
678
                attestation: None,
679
            }],
680
            None,
681
            vec![],
682
        )
683
        .unwrap();
684
    assert!(
685
        !r[0].ok && r[0].reason.contains("fast-forward"),
686
        "{}",
687
        r[0].reason
688
    );
689
    let r = origin
690
        .receive_push(
691
            Bundle::default(),
692
            vec![RefUpdate {
693
                name: "main".into(),
694
                old_state: s1,
695
                new_state: empty,
696
                force: true,
697
                attestation: None,
698
            }],
699
            None,
700
            vec![],
701
        )
702
        .unwrap();
98286406 Andy McCall ↶ 703
    assert!(r[0].ok);
704
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
705
706
    // Attestation with a stale serial is a rollback and is refused.
75167672 Andy McCall 707
    let sa = a
708
        .sign_attest(&Attest {
709
            repo: a.id().unwrap(),
710
            hlc: Hlc::now(),
711
            body: AttestBody::Ref {
712
                name: "main".into(),
713
                old_state: empty,
714
                new_state: s1,
715
                serial: 1,
716
            },
717
        })
718
        .unwrap();
719
    let r = origin
720
        .receive_push(
721
            Bundle::default(),
722
            vec![RefUpdate {
723
                name: "main".into(),
724
                old_state: empty,
725
                new_state: s1,
726
                force: false,
727
                attestation: Some(sa.clone()),
728
            }],
729
            None,
730
            vec![],
731
        )
732
        .unwrap();
733
    assert!(
734
        !r[0].ok && r[0].reason.contains("serial"),
735
        "{}",
736
        r[0].reason
737
    );
98286406 Andy McCall ↶ 738
    // An attestation for a different update is refused too.
75167672 Andy McCall 739
    let sa2 = a
740
        .sign_attest(&Attest {
741
            repo: a.id().unwrap(),
742
            hlc: Hlc::now(),
743
            body: AttestBody::Ref {
744
                name: "main".into(),
745
                old_state: s1,
746
                new_state: empty,
747
                serial: 5,
748
            },
749
        })
750
        .unwrap();
751
    let r = origin
752
        .receive_push(
753
            Bundle::default(),
754
            vec![RefUpdate {
755
                name: "main".into(),
756
                old_state: empty,
757
                new_state: s1,
758
                force: false,
759
                attestation: Some(sa2),
760
            }],
761
            None,
762
            vec![],
763
        )
764
        .unwrap();
765
    assert!(
766
        !r[0].ok && r[0].reason.contains("describe"),
767
        "{}",
768
        r[0].reason
769
    );
98286406 Andy McCall ↶ 770
    let _ = key;
771
}
772
773
#[test]
774
fn user_config_supplies_defaults_and_clones_sign() {
775
    hermetic();
776
    let dir = tempfile::tempdir().unwrap();
777
    let root = dir.path();
778
    let home = root.join("home");
779
    let origin = Repo::init(&root.join("origin")).unwrap();
780
    let url = root.join("origin").to_string_lossy().to_string();
781
782
    // Identity at user scope: the repository file stays free of author keys.
783
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
75167672 Andy McCall 784
    let (key, _) = a
785
        .create_identity("Ada", "[email protected]", IdentityScope::User)
786
        .unwrap();
98286406 Andy McCall ↶ 787
    assert!(!a.config.repo_layer().contains_key("author.key"));
788
    assert_eq!(a.config.author_key, Some(key));
789
    assert!(home.join("config.toml").exists());
790
    a.set_user_config("core.sign", "change").unwrap();
791
    assert!(a.config.sign_changes);
792
793
    // Repository settings override user settings and are the only ones saved.
794
    a.config.set("core.sign", "seal").unwrap();
795
    a.save_config().unwrap();
796
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
797
    assert!(!again.config.sign_changes);
798
    assert_eq!(again.config.author_key, Some(key));
75167672 Andy McCall 799
    assert_eq!(
800
        read_config_file(&root.join("a/.oxy/config"))
801
            .unwrap()
802
            .get("core.sign")
803
            .map(String::as_str),
804
        Some("seal")
805
    );
98286406 Andy McCall ↶ 806
807
    // A fresh clone made by this user signs with the user-level identity,
808
    // even though the clone's store has never seen the identity object.
809
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
810
    assert!(b.config.sign_changes);
811
    write(&root.join("b"), "f.txt", b"f\n");
812
    let h = b.commit("signed from a clone", &[]).unwrap();
75167672 Andy McCall 813
    assert!(
814
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
815
    );
98286406 Andy McCall ↶ 816
    assert!(b.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 817
    assert!(matches!(
818
        origin.verify_change(&h).unwrap(),
819
        SignatureStatus::Valid { .. }
820
    ));
98286406 Andy McCall ↶ 821
}
822
823
#[test]
824
fn format1_repositories_are_migrated_on_open() {
825
    hermetic();
826
    use crate::oplog::{Format1Op, Format1View};
827
    let dir = tempfile::tempdir().unwrap();
828
    let root = dir.path();
829
    let repo = Repo::init(root).unwrap();
830
    write(root, "a.txt", b"a\n");
831
    let h1 = repo.commit("one", &[]).unwrap();
832
    let (wc_hash, _) = repo.working_copy().unwrap();
833
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
834
    let mut v1 = Format1View::default();
835
    v1.bookmarks.insert("main".into(), vec![]);
836
    v1.workspaces.insert(repo.workspace(), wc_hash);
75167672 Andy McCall 837
    let init = Format1Op {
838
        parents: vec![],
839
        hlc: Hlc::default(),
840
        command: "oxy init".into(),
841
        view: v1.clone(),
842
    };
98286406 Andy McCall ↶ 843
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
844
    v1.bookmarks.insert("main".into(), vec![h1]);
75167672 Andy McCall 845
    let commit = Format1Op {
846
        parents: vec![init_ref],
847
        hlc: Hlc::default(),
848
        command: "oxy commit".into(),
849
        view: v1,
850
    };
98286406 Andy McCall ↶ 851
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
852
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
853
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
854
    drop(repo);
855
856
    let repo = Repo::open(root).unwrap();
75167672 Andy McCall 857
    assert_eq!(
858
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
859
        FORMAT_LINE
860
    );
98286406 Andy McCall ↶ 861
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
862
    let ops = repo.op_log().unwrap();
75167672 Andy McCall 863
    assert_eq!(
864
        ops.iter()
865
            .map(|(_, o)| o.command.as_str())
866
            .collect::<Vec<_>>(),
867
        ["oxy commit", "oxy init"]
868
    );
98286406 Andy McCall ↶ 869
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
870
    assert!(!repo.snapshot("status").unwrap().changed);
871
    // Reopening again is a no-op.
872
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
873
}
874
875
#[test]
876
fn undo_skips_snapshot_operations() {
877
    hermetic();
878
    let dir = tempfile::tempdir().unwrap();
879
    let root = dir.path();
880
    let repo = Repo::init(root).unwrap();
881
    write(root, "a.txt", b"a\n");
882
    let h1 = repo.commit("a", &[]).unwrap();
883
    // A later command snapshots new edits on top of the commit.
884
    write(root, "b.txt", b"b\n");
885
    let s = repo.snapshot("oxy status").unwrap();
886
    assert!(s.changed);
887
    assert!(repo.head_op().unwrap().1.is_snapshot());
888
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
889
    // Undo must undo the commit, not the snapshot.
890
    repo.undo().unwrap();
891
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
892
    let s = repo.snapshot("oxy status").unwrap();
893
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
75167672 Andy McCall 894
    assert_eq!(
895
        paths,
896
        ["a.txt", "b.txt"],
897
        "both files are back in the working copy"
898
    );
98286406 Andy McCall ↶ 899
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
900
    // Only snapshots remain above `init`, so there is nothing left to undo.
901
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
902
    assert!(repo.undo().is_err());
903
}
904
905
#[test]
906
fn independent_changes_commute_and_make_multiple_heads() {
907
    hermetic();
908
    let dir = tempfile::tempdir().unwrap();
909
    let root = dir.path();
910
    let repo = Repo::init(root).unwrap();
911
    write(root, "a.txt", b"a\n");
912
    let h1 = repo.commit("a", &[]).unwrap();
913
    write(root, "b.txt", b"b\n");
914
    let h2 = repo.commit("b", &[]).unwrap();
915
    let c2 = repo.store().get_change(&h2).unwrap();
916
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
917
    let mut heads = repo.bookmark_heads().unwrap();
918
    heads.sort();
919
    let mut want = vec![h1, h2];
920
    want.sort();
921
    assert_eq!(heads, want);
922
    // Editing a.txt depends on h1 only.
923
    write(root, "a.txt", b"a\na2\n");
924
    let h3 = repo.commit("a2", &[]).unwrap();
925
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
926
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
927
    assert_eq!(heads, [h2, h3].into_iter().collect());
928
    // Explicit dependency.
929
    write(root, "c.txt", b"c\n");
930
    let h4 = repo.commit("c", &[h2]).unwrap();
931
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
932
}
933
934
#[test]
935
fn mode_change_and_text_binary_switch() {
936
    hermetic();
937
    let dir = tempfile::tempdir().unwrap();
938
    let root = dir.path();
939
    let repo = Repo::init(root).unwrap();
940
    write(root, "run.sh", b"#!/bin/sh\n");
941
    repo.commit("add script", &[]).unwrap();
942
    #[cfg(unix)]
943
    {
944
        use std::os::unix::fs::PermissionsExt;
945
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
946
        let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 947
        assert_eq!(
948
            statuses(&s),
949
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
950
        );
98286406 Andy McCall ↶ 951
        let h = repo.commit("exec", &[]).unwrap();
952
        let snap = repo.load_state(&[h]).unwrap().materialize();
953
        assert!(snap.files["run.sh"].mode.exec);
954
    }
955
    // Text → binary → text.
956
    write(root, "run.sh", b"\0binary");
957
    let h = repo.commit("binary", &[]).unwrap();
958
    let snap = repo.load_state(&[h]).unwrap().materialize();
959
    assert!(snap.files["run.sh"].mode.opaque);
960
    write(root, "run.sh", b"text again\n");
961
    let h = repo.commit("text", &[]).unwrap();
962
    let snap = repo.load_state(&[h]).unwrap().materialize();
963
    assert!(!snap.files["run.sh"].mode.opaque);
75167672 Andy McCall 964
    assert!(
965
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
966
    );
98286406 Andy McCall ↶ 967
    assert!(!snap.is_conflicted());
968
}
83e0677b Andy McCall ↶ 969
6eae06b6 Andy McCall ↶ 970
/// oxygen#87: a binary file given new contents and the executable bit in
971
/// one commit kept the contents and lost the bit.
972
#[cfg(unix)]
973
#[test]
974
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
975
    use std::os::unix::fs::PermissionsExt;
976
    hermetic();
977
    let dir = tempfile::tempdir().unwrap();
978
    let root = dir.path();
979
    let repo = Repo::init(root).unwrap();
980
    write(root, "tool.exe", b"MZ\0one");
981
    repo.commit("add", &[]).unwrap();
982
    write(root, "tool.exe", b"MZ\0two");
983
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
984
    let h = repo.commit("update and +x", &[]).unwrap();
985
    let snap = repo.load_state(&[h]).unwrap().materialize();
986
    let f = &snap.files["tool.exe"];
987
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
988
    assert!(
989
        repo.snapshot("status").unwrap().statuses.is_empty(),
990
        "nothing left to commit"
991
    );
992
}
993
83e0677b Andy McCall ↶ 994
#[test]
995
fn trust_policy_governs_pushes_and_fetches() {
996
    hermetic();
997
    let dir = tempfile::tempdir().unwrap();
998
    let root = dir.path();
999
    let origin = Repo::init(&root.join("origin")).unwrap();
1000
    let url = root.join("origin").to_string_lossy().to_string();
1001
1002
    // A is the root. Before the policy, an unsigned push from B is fine.
75167672 Andy McCall 1003
    let mut a = Repo::clone(&url, &root.join("a"))
1004
        .unwrap()
1005
        .with_home(root.join("home-a"));
1006
    let (key_a, _) = a
1007
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1008
        .unwrap();
1009
    let mut b = Repo::clone(&url, &root.join("b"))
1010
        .unwrap()
1011
        .with_home(root.join("home-b"));
83e0677b Andy McCall ↶ 1012
    write(&root.join("b"), "b.txt", b"b\n");
1013
    b.commit("unsigned before policy", &[]).unwrap();
1014
    assert!(b.push("origin", false).unwrap()[0].ok);
1015
1016
    // A creates the policy and pushes it; origin now enforces it.
1017
    write(&root.join("a"), "a.txt", b"a\n");
1018
    a.commit("a", &[]).unwrap();
1019
    let sp = a.policy_init().unwrap();
1020
    assert_eq!(sp.policy.serial, 1);
1021
    a.pull("origin").unwrap();
1022
    let results = a.push("origin", false).unwrap();
1023
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1024
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1025
1026
    // B pulls the policy. Without an identity B cannot push at all.
1027
    b.pull("origin").unwrap();
75167672 Andy McCall 1028
    assert!(
1029
        b.current_policy().unwrap().is_some(),
1030
        "the policy arrived with the fetch"
1031
    );
83e0677b Andy McCall ↶ 1032
    assert!(b.push("origin", false).is_err());
1033
    // With an identity the policy does not list, the push is rejected by origin.
75167672 Andy McCall 1034
    let (key_b, id_b) = b
1035
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1036
        .unwrap();
83e0677b Andy McCall ↶ 1037
    write(&root.join("b"), "b.txt", b"b2\n");
1038
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1039
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1040
    let r = b.push("origin", false).unwrap();
75167672 Andy McCall 1041
    assert!(
1042
        !r[0].ok && r[0].reason.contains("may not update"),
1043
        "{:?}",
1044
        r
1045
    );
83e0677b Andy McCall ↶ 1046
1047
    // A grants B (identity handed over as a file) and publishes the policy.
1048
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1049
    assert_eq!(sp.policy.serial, 2);
1050
    let r = a.push("origin", false).unwrap();
1051
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1052
    // B must fetch the new policy before pushing.
75167672 Andy McCall 1053
    assert!(b
1054
        .push("origin", false)
1055
        .unwrap_or_else(|e| vec![RefResult {
1056
            name: "main".into(),
1057
            ok: false,
1058
            reason: e.to_string()
1059
        }])
1060
        .iter()
1061
        .all(|x| !x.ok));
83e0677b Andy McCall ↶ 1062
    b.pull("origin").unwrap();
1063
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1064
    let r = b.push("origin", false).unwrap();
1065
    assert!(r[0].ok, "{:?}", r);
1066
    // Origin verified B's change under the policy.
1067
    let heads = origin.bookmark_heads().unwrap();
1068
    for h in &heads {
1069
        let c = origin.store().get_change(h).unwrap();
1070
        if c.author == key_b {
75167672 Andy McCall 1071
            origin
1072
                .change_allowed(
1073
                    h,
1074
                    &origin.current_policy().unwrap().unwrap().1.policy,
1075
                    "main",
1076
                )
1077
                .unwrap();
83e0677b Andy McCall ↶ 1078
        }
1079
    }
1080
1081
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1082
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1083
    forged.serial = 3;
1084
    forged.roots = vec![key_b];
1085
    let fh = forged.hash();
1086
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 1087
    let forged = SignedPolicy {
1088
        policy: forged,
1089
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1090
    };
1091
    let r = origin
1092
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1093
        .unwrap();
83e0677b Andy McCall ↶ 1094
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1095
    let stale = a.current_policy().unwrap().unwrap().1;
1096
    let mut old = stale.clone();
1097
    old.policy.serial = 1;
75167672 Andy McCall 1098
    let r = origin
1099
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1100
        .unwrap();
83e0677b Andy McCall ↶ 1101
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1102
1103
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1104
    a.pull("origin").unwrap();
1105
    a.policy_revoke(&key_b).unwrap();
1106
    let r = a.push("origin", false).unwrap();
1107
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1108
    b.pull("origin").unwrap();
1109
    write(&root.join("b"), "b.txt", b"b3\n");
1110
    b.commit("b3", &[]).unwrap();
1111
    let r = b.push("origin", false).unwrap();
1112
    assert!(!r[0].ok, "{:?}", r);
1113
1114
    // A clone by a third party receives and verifies everything.
75167672 Andy McCall 1115
    let c = Repo::clone(&url, &root.join("c"))
1116
        .unwrap()
1117
        .with_home(root.join("home-c"));
83e0677b Andy McCall ↶ 1118
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
75167672 Andy McCall 1119
    assert!(c
1120
        .current_policy()
1121
        .unwrap()
1122
        .unwrap()
1123
        .1
1124
        .policy
1125
        .roots
1126
        .contains(&key_a));
83e0677b Andy McCall ↶ 1127
    assert!(!c.snapshot("status").unwrap().changed);
1128
}
d02e545d Andy McCall ↶ 1129
9ae4d15a Andy McCall ↶ 1130
/// oxygen#66: a gc says what it is doing, phase by phase.
d02e545d Andy McCall ↶ 1131
#[test]
9ae4d15a Andy McCall ↶ 1132
fn gc_reports_its_phases() {
1133
    hermetic();
1134
    let dir = tempfile::tempdir().unwrap();
1135
    let repo = Repo::init(dir.path()).unwrap();
1136
    for i in 0..3 {
1137
        write(
1138
            dir.path(),
1139
            &format!("f{i}.txt"),
1140
            format!("{i}\n").as_bytes(),
1141
        );
1142
        repo.commit(&format!("c{i}"), &[]).unwrap();
1143
    }
1144
    let mut phases = Vec::new();
1145
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1146
        .unwrap();
1147
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1148
    assert!(
1149
        phases.iter().any(|p| p.starts_with("pruning")),
1150
        "{phases:?}"
1151
    );
1152
    assert!(
1153
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1154
        "{phases:?}"
1155
    );
1156
    assert!(
1157
        phases
1158
            .iter()
1159
            .any(|p| p.starts_with("writing the index of ")),
1160
        "{phases:?}"
1161
    );
1162
}
1163
1164
#[test]
d02e545d Andy McCall ↶ 1165
fn gc_packs_objects_and_history_still_works() {
1166
    hermetic();
1167
    let dir = tempfile::tempdir().unwrap();
1168
    let root = dir.path();
1169
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1170
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1171
        .unwrap();
d02e545d Andy McCall ↶ 1172
    repo.set_user_config("core.sign", "change").unwrap();
1173
    write(root, "a.txt", b"one\n");
1174
    let h1 = repo.commit("one", &[]).unwrap();
1175
    write(root, "a.txt", b"two\n");
1176
    write(root, "big.bin", &vec![0u8; 100_000]);
1177
    let h2 = repo.commit("two", &[]).unwrap();
ba160f60 Andy McCall ↶ 1178
    // Several snapshots leave superseded working-copy versions behind.
1179
    for i in 0..5 {
1180
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1181
        repo.snapshot("status").unwrap();
1182
    }
1183
    write(root, "a.txt", b"two\n");
1184
    repo.snapshot("status").unwrap();
d02e545d Andy McCall ↶ 1185
    let before = repo.store().list().unwrap();
1186
    assert!(repo.store().loose_count().unwrap() > 0);
ba160f60 Andy McCall ↶ 1187
1188
    // With the default retention every operation's view is a root: nothing prunes.
1189
    let r = repo.gc(true).unwrap();
1190
    assert_eq!(r.packed.objects, before.len());
1191
    assert_eq!(r.pruned.objects, 0);
d02e545d Andy McCall ↶ 1192
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1193
    assert_eq!(repo.store().list().unwrap(), before);
ba160f60 Andy McCall ↶ 1194
1195
    // With zero retention only the current view is a root: superseded
1196
    // working copies go, everything reachable stays.
1197
    repo.config.set("core.op-retention", "0").unwrap();
1198
    repo.save_config().unwrap();
21b2aec2 Andy McCall ↶ 1199
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
ba160f60 Andy McCall ↶ 1200
    let r = repo.gc(true).unwrap();
1201
    assert!(r.pruned.objects >= 5, "{r:?}");
1202
    let after = repo.store().list().unwrap();
1203
    assert!(after.len() < before.len());
1204
    assert!(after.contains(&h1) && after.contains(&h2));
1205
    for (_, op) in repo.op_log().unwrap() {
1206
        assert!(!op.command.is_empty(), "operation objects are all kept");
1207
    }
1208
    // Everything still works from the pruned, packed store.
d02e545d Andy McCall ↶ 1209
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
75167672 Andy McCall 1210
    assert!(matches!(
1211
        repo.verify_change(&h2).unwrap(),
1212
        SignatureStatus::Valid { .. }
1213
    ));
d02e545d Andy McCall ↶ 1214
    assert_eq!(repo.log().unwrap().len(), 3);
1215
    repo.checkout(&[h1], false, "checkout").unwrap();
1216
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1217
    repo.checkout(&[h2], false, "checkout").unwrap();
1218
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1219
    assert!(!repo.snapshot("status").unwrap().changed);
ba160f60 Andy McCall ↶ 1220
    // Grace period defers pruning of young garbage.
d02e545d Andy McCall ↶ 1221
    write(root, "a.txt", b"three\n");
1222
    repo.commit("three", &[]).unwrap();
ba160f60 Andy McCall ↶ 1223
    let r = repo.gc(false).unwrap();
1224
    assert_eq!(r.pruned.objects, 0);
1225
    assert!(r.pruned.deferred > 0);
1226
    let r = repo.gc(true).unwrap();
1227
    assert!(r.pruned.objects > 0);
1228
    assert_eq!(repo.log().unwrap().len(), 4);
21b2aec2 Andy McCall ↶ 1229
    // Restoring the default retention makes the old views roots again; the
1230
    // working copies they name were pruned, which gc tolerates.
1231
    repo.config.set("core.op-retention", "90").unwrap();
1232
    repo.save_config().unwrap();
1233
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1234
    let r = repo.gc(false).unwrap();
1235
    assert_eq!(r.pruned.objects, 0);
1236
    assert_eq!(repo.log().unwrap().len(), 4);
d02e545d Andy McCall ↶ 1237
}
614541c3 Andy McCall ↶ 1238
1239
#[test]
1240
fn describe_amend_abandon_heads() {
1241
    hermetic();
1242
    let dir = tempfile::tempdir().unwrap();
1243
    let root = dir.path();
1244
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1245
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1246
        .unwrap();
614541c3 Andy McCall ↶ 1247
    repo.set_user_config("core.sign", "change").unwrap();
1248
    write(root, "a.txt", b"one\n");
1249
    let h1 = repo.commit("first", &[]).unwrap();
1250
    write(root, "a.txt", b"one\ntwo\n");
1251
    let h2 = repo.commit("secnod", &[]).unwrap();
1252
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1253
1254
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1255
    let h2b = repo.describe(&h2, "second").unwrap();
1256
    assert_ne!(h2b, h2);
1257
    let c = repo.store().get_change(&h2b).unwrap();
75167672 Andy McCall 1258
    assert_eq!(
1259
        (c.change_id, c.message.as_str(), c.deps.clone()),
1260
        (id2, "second", vec![h1])
1261
    );
614541c3 Andy McCall ↶ 1262
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
75167672 Andy McCall 1263
    assert!(matches!(
1264
        repo.verify_change(&h2b).unwrap(),
1265
        SignatureStatus::Valid { .. }
1266
    ));
614541c3 Andy McCall ↶ 1267
    let s = repo.snapshot("status").unwrap();
1268
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
75167672 Andy McCall 1269
    assert_eq!(
1270
        repo.resolve_change(&id2.short(8)).unwrap(),
1271
        h2b,
1272
        "the old object is no longer reachable from the log"
1273
    );
c07e0e7d Andy McCall ↶ 1274
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1275
    let h1b = repo.describe(&h1, "first, described").unwrap();
1276
    assert_ne!(h1b, h1);
1277
    let heads = repo.bookmark_heads().unwrap();
1278
    assert_eq!(heads.len(), 1);
1279
    let top = repo.store().get_change(&heads[0]).unwrap();
1280
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
75167672 Andy McCall 1281
    assert!(
1282
        matches!(
1283
            repo.verify_change(&heads[0]).unwrap(),
1284
            SignatureStatus::Valid { .. }
1285
        ),
1286
        "rewritten own change is re-signed"
1287
    );
c07e0e7d Andy McCall ↶ 1288
    let (_, wc) = repo.working_copy().unwrap();
75167672 Andy McCall 1289
    assert_eq!(
1290
        wc.deps,
1291
        vec![heads[0]],
1292
        "the working copy follows the rewrite"
1293
    );
c07e0e7d Andy McCall ↶ 1294
    assert!(!repo.snapshot("status").unwrap().changed);
1295
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 1296
    assert!(
1297
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1298
    );
614541c3 Andy McCall ↶ 1299
1300
    // amend: fold an edit into the head; the result is one change from h1.
1301
    write(root, "a.txt", b"one\ntwo\nthree\n");
1302
    write(root, "b.txt", b"b\n");
1303
    let h2c = repo.amend(None).unwrap();
1304
    let c = repo.store().get_change(&h2c).unwrap();
1305
    assert_eq!(c.change_id, id2);
1306
    assert_eq!(c.message, "second");
1307
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
75167672 Andy McCall 1308
    assert_eq!(
1309
        repo.log().unwrap().len(),
1310
        3,
1311
        "working copy, amended head, first"
1312
    );
614541c3 Andy McCall ↶ 1313
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
75167672 Andy McCall 1314
    assert!(
1315
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1316
    );
614541c3 Andy McCall ↶ 1317
    assert!(snap.files.contains_key("b.txt"));
1318
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 1319
    assert!(
1320
        repo.amend(None).is_err(),
1321
        "clean working copy and no message"
1322
    );
614541c3 Andy McCall ↶ 1323
    let h2d = repo.amend(Some("second, amended")).unwrap();
75167672 Andy McCall 1324
    assert_eq!(
1325
        repo.store().get_change(&h2d).unwrap().message,
1326
        "second, amended"
1327
    );
614541c3 Andy McCall ↶ 1328
1329
    // abandon: the head goes, its content stays as uncommitted work.
1330
    repo.abandon(&h2d).unwrap();
75167672 Andy McCall 1331
    assert_eq!(
1332
        repo.bookmark_heads().unwrap(),
1333
        vec![h1b],
1334
        "the described first change is the head again"
1335
    );
614541c3 Andy McCall ↶ 1336
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 1337
    let paths: Vec<_> = s
1338
        .statuses
1339
        .iter()
1340
        .map(|p| (p.path.as_str(), p.status))
1341
        .collect();
1342
    assert_eq!(
1343
        paths,
1344
        vec![
1345
            ("a.txt", ChangeStatus::Modified),
1346
            ("b.txt", ChangeStatus::Added)
1347
        ]
1348
    );
614541c3 Andy McCall ↶ 1349
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1350
    let h3 = repo.commit("recommitted", &[]).unwrap();
1351
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1352
    // undo brings the abandoned head back.
1353
    repo.undo().unwrap();
1354
    repo.undo().unwrap();
1355
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
c07e0e7d Andy McCall ↶ 1356
6706bdcf Andy McCall ↶ 1357
    // Abandoning a non-head whose dependent references its atoms reifies
1358
    // the references (here: a.txt vanishes with it, so the dependent's edit
1359
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
c07e0e7d Andy McCall ↶ 1360
    let base = repo.bookmark_heads().unwrap()[0];
1361
    let base_change = repo.store().get_change(&base).unwrap();
1362
    let h1_now = base_change.deps[0];
6706bdcf Andy McCall ↶ 1363
    let notes = repo.abandon(&h1_now).unwrap();
75167672 Andy McCall 1364
    assert!(
1365
        !notes.is_empty(),
1366
        "the dependent's edit of a.txt was reified"
1367
    );
6706bdcf Andy McCall ↶ 1368
    let heads = repo.bookmark_heads().unwrap();
1369
    let after = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 1370
    assert!(
1371
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1372
        "{:?}",
1373
        after.files.keys()
1374
    );
6706bdcf Andy McCall ↶ 1375
    repo.undo().unwrap();
1376
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
c07e0e7d Andy McCall ↶ 1377
    write(root, "c.txt", b"c\n");
1378
    let hc = repo.commit("c", &[]).unwrap();
1379
    write(root, "d.txt", b"d\n");
1380
    let hd = repo.commit("d", &[hc]).unwrap();
1381
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1382
    repo.abandon(&hc).unwrap();
1383
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1384
    assert!(!heads.contains(&hc));
75167672 Andy McCall 1385
    let d_now = heads
1386
        .iter()
1387
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1388
        .copied()
1389
        .unwrap();
1390
    assert!(
1391
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1392
        "d inherited c's (empty) dependencies"
1393
    );
c07e0e7d Andy McCall ↶ 1394
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 1395
    assert_eq!(
1396
        s.statuses
1397
            .iter()
1398
            .map(|p| p.path.as_str())
1399
            .collect::<Vec<_>>(),
1400
        vec!["c.txt"],
1401
        "c's content is now uncommitted work"
1402
    );
614541c3 Andy McCall ↶ 1403
}
79ab8528 Andy McCall ↶ 1404
1405
#[test]
1406
fn git_export_mirrors_history() {
1407
    hermetic();
75167672 Andy McCall 1408
    if std::process::Command::new("git")
1409
        .arg("--version")
1410
        .output()
1411
        .is_err()
1412
    {
79ab8528 Andy McCall ↶ 1413
        eprintln!("git not installed; skipping");
1414
        return;
1415
    }
1416
    let dir = tempfile::tempdir().unwrap();
1417
    let root = dir.path();
75167672 Andy McCall 1418
    let mut repo = Repo::init(&root.join("r"))
1419
        .unwrap()
1420
        .with_home(root.join("home"));
1421
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1422
        .unwrap();
79ab8528 Andy McCall ↶ 1423
    let r = root.join("r");
1424
    write(&r, "README.md", b"hello\n");
1425
    write(&r, "src/main.rs", b"fn main() {}\n");
1426
    let h1 = repo.commit("first", &[]).unwrap();
1427
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1428
    write(&r, "logo.png", b"\x89PNG\0\0");
1429
    let h2 = repo.commit("second", &[]).unwrap();
1430
1431
    let git_dir = root.join("mirror.git");
1432
    let rep = repo.git_export(&git_dir).unwrap();
1433
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1434
    let git = |args: &[&str]| -> String {
75167672 Andy McCall 1435
        let out = std::process::Command::new("git")
1436
            .arg("-C")
1437
            .arg(&git_dir)
1438
            .args(args)
1439
            .output()
1440
            .unwrap();
1441
        assert!(
1442
            out.status.success(),
1443
            "{}",
1444
            String::from_utf8_lossy(&out.stderr)
1445
        );
79ab8528 Andy McCall ↶ 1446
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1447
    };
1448
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1449
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1450
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1451
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 1452
    assert!(
1453
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1454
        "{body}"
1455
    );
79ab8528 Andy McCall ↶ 1456
    assert!(body.contains("Change-Id: "), "{body}");
75167672 Andy McCall 1457
    assert_eq!(
1458
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1459
        "Ada Lovelace <[email protected]>"
1460
    );
1461
    assert_eq!(
1462
        git(&["ls-tree", "--name-only", "main"]),
1463
        "README.md\nlogo.png\nsrc"
1464
    );
79ab8528 Andy McCall ↶ 1465
1466
    // Re-export is incremental.
1467
    let rep = repo.git_export(&git_dir).unwrap();
1468
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1469
1470
    // An independent change makes two heads; the next state is one more
1471
    // commit on the linear branch whose tree is the union.
1472
    repo.checkout(&[h1], false, "checkout").unwrap();
1473
    write(&r, "other.txt", b"o\n");
1474
    let h3 = repo.commit("third", &[]).unwrap();
1475
    let rep = repo.git_export(&git_dir).unwrap();
1476
    assert_eq!((rep.exported, rep.heads), (1, 2));
1477
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1478
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1479
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1480
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1481
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
75167672 Andy McCall 1482
    assert_eq!(
1483
        git(&["ls-tree", "--name-only", "main"]),
1484
        "README.md\nlogo.png\nother.txt\nsrc"
1485
    );
79ab8528 Andy McCall ↶ 1486
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 1487
    assert!(
1488
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1489
        "{body}"
1490
    );
79ab8528 Andy McCall ↶ 1491
    // A rewrite is a new state whose one new change is the rewritten one.
1492
    repo.describe(&h3, "third, described").unwrap();
1493
    let rep = repo.git_export(&git_dir).unwrap();
1494
    assert_eq!(rep.exported, 1);
75167672 Andy McCall 1495
    assert_eq!(
1496
        git(&["log", "-1", "--format=%s", "main"]),
1497
        "third, described"
1498
    );
79ab8528 Andy McCall ↶ 1499
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1500
    let _ = h2;
1501
}
c3069537 Andy McCall ↶ 1502
1503
#[test]
1504
fn git_import_reproduces_trees() {
c3d2ef61 Andy McCall ↶ 1505
    git_import_reproduces_trees_with(None);
1506
}
1507
1508
/// The same import with every merge rendered in batches of one file
1509
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1510
#[test]
1511
fn git_import_reproduces_trees_in_batches() {
1512
    git_import_reproduces_trees_with(Some(1));
1513
}
1514
1515
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1516
    crate::repo::git::set_merge_batch_for_tests(batch);
c3069537 Andy McCall ↶ 1517
    hermetic();
75167672 Andy McCall 1518
    if std::process::Command::new("git")
1519
        .arg("--version")
1520
        .output()
1521
        .is_err()
1522
    {
c3069537 Andy McCall ↶ 1523
        eprintln!("git not installed; skipping");
1524
        return;
1525
    }
1526
    let dir = tempfile::tempdir().unwrap();
1527
    let root = dir.path();
1528
    let g = root.join("src.git");
1529
    fs::create_dir_all(&g).unwrap();
1530
    let git = |args: &[&str]| -> String {
1531
        let out = std::process::Command::new("git")
1532
            .arg("-C")
1533
            .arg(&g)
75167672 Andy McCall 1534
            .args([
1535
                "-c",
1536
                "user.name=Grace",
1537
                "-c",
1538
                "[email protected]",
1539
                "-c",
1540
                "commit.gpgsign=false",
1541
            ])
c3069537 Andy McCall ↶ 1542
            .args(args)
1543
            .output()
1544
            .unwrap();
75167672 Andy McCall 1545
        assert!(
1546
            out.status.success(),
1547
            "git {args:?}: {}",
1548
            String::from_utf8_lossy(&out.stderr)
1549
        );
c3069537 Andy McCall ↶ 1550
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1551
    };
1552
    git(&["init", "-q", "-b", "main"]);
1553
    write(&g, "README.md", b"# Hi\n");
1554
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1555
    git(&["add", "."]);
1556
    git(&["commit", "-q", "-m", "initial"]);
1557
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1558
    write(&g, "run.sh", b"#!/bin/sh\n");
1559
    #[cfg(unix)]
1560
    {
1561
        use std::os::unix::fs::PermissionsExt;
1562
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1563
    }
1564
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1565
    git(&["add", "."]);
75167672 Andy McCall 1566
    git(&[
1567
        "commit",
1568
        "-q",
1569
        "-m",
1570
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1571
    ]);
c3069537 Andy McCall ↶ 1572
    // A branch that edits README, merged back with a conflict-free merge.
1573
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1574
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1575
    git(&["commit", "-q", "-am", "readme"]);
1576
    git(&["checkout", "-q", "main"]);
1577
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1578
    // A branch from the initial commit inserting at the same place as
1579
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1580
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1581
    git(&["checkout", "-q", "-b", "clash", &initial]);
1582
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1583
    git(&["commit", "-q", "-am", "clash"]);
1584
    git(&["checkout", "-q", "main"]);
7df9007b Andy McCall ↶ 1585
    // Expected to stop at the conflict, so its status is ignored; the
1586
    // identity is passed as for every other git call here, or a machine
1587
    // without one refuses to start the merge at all.
75167672 Andy McCall 1588
    let _ = std::process::Command::new("git")
1589
        .arg("-C")
1590
        .arg(&g)
7df9007b Andy McCall ↶ 1591
        .args([
1592
            "-c",
1593
            "user.name=Grace",
1594
            "-c",
1595
            "[email protected]",
1596
            "merge",
1597
            "-q",
1598
            "clash",
1599
        ])
75167672 Andy McCall 1600
        .output();
7df9007b Andy McCall ↶ 1601
    assert!(
1602
        g.join(".git/MERGE_HEAD").exists(),
1603
        "the clash merge stopped at its conflict"
1604
    );
75167672 Andy McCall 1605
    write(
1606
        &g,
1607
        "src/lib.rs",
1608
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1609
    );
c3069537 Andy McCall ↶ 1610
    git(&["add", "."]);
1611
    git(&["commit", "-q", "-m", "resolve clash"]);
1612
    git(&["rm", "-q", "logo.png"]);
1613
    git(&["commit", "-q", "-m", "drop logo"]);
6e723b81 Andy McCall ↶ 1614
    // A rename with a small edit is imported as a move of the same node.
1615
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
75167672 Andy McCall 1616
    write(
1617
        &g,
1618
        "src/lib2.rs",
1619
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1620
    );
6e723b81 Andy McCall ↶ 1621
    git(&["add", "."]);
1622
    git(&["commit", "-q", "-m", "rename lib"]);
958fb27d Andy McCall ↶ 1623
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1624
    // run.sh is the same as in the first parent's tree, but the merged
1625
    // change touched it, so the importer must compare it, not skip it.
1626
    git(&["checkout", "-q", "-b", "discarded"]);
1627
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1628
    git(&["commit", "-q", "-am", "discarded edit"]);
1629
    git(&["checkout", "-q", "main"]);
314db9b4 Andy McCall ↶ 1630
    git(&[
1631
        "merge",
1632
        "-q",
1633
        "-s",
1634
        "ours",
1635
        "-m",
1636
        "merge discarded, keeping ours",
1637
        "discarded",
1638
    ]);
c3069537 Andy McCall ↶ 1639
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1640
1641
    let dest = root.join("oxy");
1642
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1643
    let rep = repo.import_git(&g, "main").unwrap();
1644
    assert_eq!(rep.commits, expected_count);
958fb27d Andy McCall ↶ 1645
    assert_eq!(rep.merges, 3);
314db9b4 Andy McCall ↶ 1646
    assert_eq!(
1647
        fs::read(dest.join("run.sh")).unwrap(),
1648
        b"#!/bin/sh\n",
1649
        "the ours merge kept main's run.sh"
1650
    );
958fb27d Andy McCall ↶ 1651
    let v = repo.verify_git_import(&g, "main").unwrap();
1652
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1653
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
c3069537 Andy McCall ↶ 1654
    // The working copy equals the Git tree at main.
75167672 Andy McCall 1655
    assert_eq!(
1656
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1657
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1658
    );
6e723b81 Andy McCall ↶ 1659
    assert!(!dest.join("src/lib.rs").exists());
75167672 Andy McCall 1660
    assert_eq!(
1661
        fs::read(dest.join("README.md")).unwrap(),
1662
        b"# Hi\n\nMore.\n"
1663
    );
c3069537 Andy McCall ↶ 1664
    assert!(!dest.join("logo.png").exists());
1665
    #[cfg(unix)]
1666
    {
1667
        use std::os::unix::fs::PermissionsExt;
75167672 Andy McCall 1668
        assert!(
1669
            fs::metadata(dest.join("run.sh"))
1670
                .unwrap()
1671
                .permissions()
1672
                .mode()
1673
                & 0o111
1674
                != 0
1675
        );
c3069537 Andy McCall ↶ 1676
    }
75167672 Andy McCall 1677
    assert!(
1678
        !repo.snapshot("status").unwrap().changed,
1679
        "clean after import"
1680
    );
c3069537 Andy McCall ↶ 1681
    let heads = repo.bookmark_heads().unwrap();
1682
    let st = repo.load_state(&heads).unwrap();
1683
    assert!(!st.materialize().is_conflicted());
1684
    assert_eq!(st.len(), expected_count);
75167672 Andy McCall 1685
    let tip = repo
1686
        .log()
1687
        .unwrap()
1688
        .into_iter()
1689
        .find(|e| e.change.message.starts_with("rename lib"))
1690
        .unwrap();
6e723b81 Andy McCall ↶ 1691
    let c = repo.store().get_change(&tip.hash).unwrap();
75167672 Andy McCall 1692
    assert!(
1693
        c.tree_ops
1694
            .iter()
1695
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1696
        "{:?}",
1697
        c.tree_ops
1698
    );
1699
    assert!(!c
1700
        .tree_ops
1701
        .iter()
1702
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
c3069537 Andy McCall ↶ 1703
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1704
    let log = repo.log().unwrap();
75167672 Andy McCall 1705
    let second = log
1706
        .iter()
1707
        .find(|e| e.change.message.starts_with("second"))
1708
        .unwrap();
1709
    assert_eq!(
1710
        second.change.change_id,
1711
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1712
    );
1713
    assert!(second
1714
        .change
1715
        .message
1716
        .contains("Git-Author: Grace <[email protected]>"));
1717
    let resolve = log
1718
        .iter()
1719
        .find(|e| e.change.message.starts_with("resolve clash"))
1720
        .unwrap();
1721
    assert_eq!(
1722
        resolve.change.kind,
1723
        ChangeKind::Resolution,
1724
        "a conflicting Git merge becomes a resolution"
1725
    );
c3069537 Andy McCall ↶ 1726
    // Re-importing into another fresh repository gives the same ChangeIds.
75167672 Andy McCall 1727
    let repo2 = Repo::init(&root.join("oxy2"))
1728
        .unwrap()
1729
        .with_home(root.join("home"));
c3069537 Andy McCall ↶ 1730
    repo2.import_git(&g, "main").unwrap();
dfb23a3a Andy McCall ↶ 1731
    // New nodes' identifiers derive from the commit (spec §23), so the
1732
    // re-import is not just the same ChangeIds but the same changes.
1733
    assert_eq!(
1734
        repo2.bookmark_heads().unwrap(),
1735
        repo.bookmark_heads().unwrap()
1736
    );
75167672 Andy McCall 1737
    let ids: BTreeSet<ChangeId> = repo
1738
        .log()
1739
        .unwrap()
1740
        .iter()
1741
        .filter(|e| !e.is_working_copy)
1742
        .map(|e| e.change.change_id)
1743
        .collect();
1744
    let ids2: BTreeSet<ChangeId> = repo2
1745
        .log()
1746
        .unwrap()
1747
        .iter()
1748
        .filter(|e| !e.is_working_copy)
1749
        .map(|e| e.change.change_id)
1750
        .collect();
c3069537 Andy McCall ↶ 1751
    assert_eq!(ids, ids2);
1752
    // Round trip back out to Git reproduces the tip tree.
1753
    let mirror = root.join("mirror.git");
1754
    repo.git_export(&mirror).unwrap();
75167672 Andy McCall 1755
    let out = std::process::Command::new("git")
1756
        .arg("-C")
1757
        .arg(&mirror)
1758
        .args(["show", "main:src/lib2.rs"])
1759
        .output()
1760
        .unwrap();
1761
    assert_eq!(
1762
        String::from_utf8_lossy(&out.stdout),
1763
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1764
    );
1765
    let out = std::process::Command::new("git")
1766
        .arg("-C")
1767
        .arg(&mirror)
1768
        .args(["show", "main:src/lib.rs"])
1769
        .output()
1770
        .unwrap();
1771
    assert!(
1772
        !out.status.success(),
1773
        "the old path is gone from the export"
1774
    );
c3069537 Andy McCall ↶ 1775
}
252e8cb2 Andy McCall ↶ 1776
1777
#[test]
1778
fn checkpoints_accelerate_loading_and_stay_correct() {
1779
    hermetic();
1780
    let dir = tempfile::tempdir().unwrap();
1781
    let root = dir.path();
1782
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1783
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1784
    repo.save_config().unwrap();
1785
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1786
    let mut hashes = Vec::new();
1787
    for i in 0..12 {
75167672 Andy McCall 1788
        write(
1789
            root,
1790
            "a.txt",
1791
            format!(
1792
                "{}\n",
1793
                (0..=i)
1794
                    .map(|k| k.to_string())
1795
                    .collect::<Vec<_>>()
1796
                    .join("\n")
1797
            )
1798
            .as_bytes(),
1799
        );
252e8cb2 Andy McCall ↶ 1800
        write(root, &format!("f{i}.txt"), b"x\n");
1801
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1802
    }
75167672 Andy McCall 1803
    let (_, cp) = repo
1804
        .latest_checkpoint("main")
1805
        .unwrap()
1806
        .expect("automatic checkpoint");
252e8cb2 Andy McCall ↶ 1807
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1808
    // Loading through the checkpoint equals loading everything.
1809
    let heads = repo.bookmark_heads().unwrap();
1810
    let fast = repo.load_state(&heads).unwrap();
1811
    let full = repo.load_state_full(&heads).unwrap();
1812
    assert_eq!(fast.len(), full.len());
1813
    assert_eq!(fast.heads(), full.heads());
1814
    let (a, b) = (fast.materialize(), full.materialize());
75167672 Andy McCall 1815
    assert_eq!(
1816
        a.files.keys().collect::<Vec<_>>(),
1817
        b.files.keys().collect::<Vec<_>>()
1818
    );
252e8cb2 Andy McCall ↶ 1819
    for (p, f) in &a.files {
1820
        assert_eq!(f.content, b.files[p].content, "{p}");
1821
    }
1822
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1823
    // A head set that does not contain the checkpoint's heads falls back.
75167672 Andy McCall 1824
    assert!(repo
1825
        .load_state_checkpointed(&[hashes[0]])
1826
        .unwrap()
1827
        .is_none());
252e8cb2 Andy McCall ↶ 1828
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1829
    // Everything else keeps working on top of the checkpoint.
1830
    assert!(!repo.snapshot("status").unwrap().changed);
1831
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1832
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1833
    let (r, n, bytes) = repo.checkpoint().unwrap();
1834
    assert!(n >= 12 && bytes > 0);
1835
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1836
    write(root, "a.txt", b"after\n");
1837
    let h_after = repo.commit("after", &[]).unwrap();
1838
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1839
    assert!(st.contains(&h_after));
75167672 Andy McCall 1840
    assert!(
1841
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1842
    );
252e8cb2 Andy McCall ↶ 1843
    assert_eq!(repo.log().unwrap().len(), 14);
1844
    // Checkpoints survive gc.
1845
    repo.gc(true).unwrap();
1846
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
75167672 Andy McCall 1847
    assert!(repo
1848
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1849
        .unwrap()
1850
        .is_some());
252e8cb2 Andy McCall ↶ 1851
}
135212de Andy McCall ↶ 1852
1853
#[test]
1854
fn quick_status_for_prompts() {
1855
    hermetic();
1856
    let dir = tempfile::tempdir().unwrap();
1857
    let root = dir.path();
1858
    let origin = Repo::init(&root.join("origin")).unwrap();
1859
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 1860
    let a = Repo::clone(&url, &root.join("a"))
1861
        .unwrap()
1862
        .with_home(root.join("home"));
135212de Andy McCall ↶ 1863
    let ops_before = a.op_log().unwrap().len();
1864
    let info = a.quick_status().unwrap();
75167672 Andy McCall 1865
    assert_eq!(
1866
        (
1867
            info.bookmark.as_str(),
1868
            info.heads,
1869
            info.dirty,
1870
            info.conflicted,
1871
            info.ahead,
1872
            info.behind
1873
        ),
1874
        ("main", 0, false, false, Some(0), Some(0))
1875
    );
135212de Andy McCall ↶ 1876
    write(&root.join("a"), "f.txt", b"f\n");
1877
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
75167672 Andy McCall 1878
    assert_eq!(
1879
        a.op_log().unwrap().len(),
1880
        ops_before,
1881
        "quick_status records nothing"
1882
    );
135212de Andy McCall ↶ 1883
    // A snapshotted but uncommitted change is still dirty.
1884
    a.snapshot("status").unwrap();
1885
    assert!(a.quick_status().unwrap().dirty);
1886
    a.commit("f", &[]).unwrap();
1887
    let info = a.quick_status().unwrap();
1888
    assert!(!info.dirty, "clean right after a commit");
1889
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
75167672 Andy McCall 1890
    assert_eq!(
1891
        info.format("%b %c%d%x%A%D"),
1892
        format!("main {}+1", info.change_id)
1893
    );
135212de Andy McCall ↶ 1894
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1895
    // Touching a file without changing it is not dirty; changing content of
1896
    // the same size is.
1897
    let p = root.join("a/f.txt");
1898
    let content = fs::read(&p).unwrap();
1899
    fs::write(&p, &content).unwrap();
1900
    assert!(!a.quick_status().unwrap().dirty);
1901
    fs::write(&p, b"g\n").unwrap();
1902
    assert!(a.quick_status().unwrap().dirty);
1903
    fs::write(&p, b"f\n").unwrap();
1904
    // Push, then a second clone commits and pushes: we are behind.
1905
    assert!(a.push("origin", false).unwrap()[0].ok);
1906
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
75167672 Andy McCall 1907
    let b = Repo::clone(&url, &root.join("b"))
1908
        .unwrap()
1909
        .with_home(root.join("home-b"));
135212de Andy McCall ↶ 1910
    write(&root.join("b"), "g.txt", b"g\n");
1911
    b.commit("g", &[]).unwrap();
1912
    b.push("origin", false).unwrap();
1913
    a.fetch("origin").unwrap();
1914
    let info = a.quick_status().unwrap();
1915
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1916
    assert_eq!(info.format("%A%D"), "-1");
1917
    let _ = origin;
1918
}
b3c5a59a Andy McCall ↶ 1919
1920
#[test]
1921
fn lazy_blobs_are_fetched_on_first_read() {
1922
    hermetic();
1923
    let dir = tempfile::tempdir().unwrap();
1924
    let root = dir.path();
1925
    let origin_dir = root.join("origin");
75167672 Andy McCall 1926
    let origin = Repo::init(&origin_dir)
1927
        .unwrap()
1928
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 1929
    let url = origin_dir.to_string_lossy().to_string();
1930
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1931
    write(&origin_dir, "big.bin", &big);
1932
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1933
    write(&origin_dir, "t.txt", b"t\n");
1934
    let h = origin.commit("blobs", &[]).unwrap();
1935
    let big_ref = Repo::blob_ref(&big);
1936
1937
    // Fetch only (no checkout) with a filter: the big blob stays absent.
75167672 Andy McCall 1938
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1939
        .unwrap()
1940
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 1941
    let a = {
1942
        let mut a = a;
1943
        a.config.set("remote.origin.url", &url).unwrap();
1944
        a.config.set("filter.max-blob", "100K").unwrap();
1945
        a.save_config().unwrap();
1946
        a
1947
    };
1948
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1949
    a.fetch("origin").unwrap();
1950
    assert!(a.store().has(&h));
1951
    assert!(!a.store().has(&big_ref), "withheld");
75167672 Andy McCall 1952
    assert!(
1953
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1954
        "small blob came along"
1955
    );
b3c5a59a Andy McCall ↶ 1956
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1957
1958
    // status and commit do not need it: adopt the state, edit a text file, commit.
1959
    let (op_ref, op) = a.head_op().unwrap();
1960
    let mut view = op.view.clone();
75167672 Andy McCall 1961
    view.bookmarks.insert(
1962
        "main".into(),
1963
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1964
    );
b3c5a59a Andy McCall ↶ 1965
    a.record_op(&[op_ref], "adopt", view).unwrap();
1966
    // Checkout reads the blob lazily, which fetches it.
1967
    a.checkout(&[h], true, "checkout").unwrap();
1968
    assert!(a.store().has(&big_ref), "fetched on first read");
1969
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1970
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1971
    write(&root.join("a"), "t.txt", b"t2\n");
1972
    a.commit("text edit", &[]).unwrap();
1973
1974
    // clone --max-blob records the filter; the checkout fetches lazily.
7421309f Andy McCall ↶ 1975
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
b3c5a59a Andy McCall ↶ 1976
    assert_eq!(b.config.max_blob, Some(1024));
1977
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1978
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1979
    assert!(parse_size("lots").is_err());
1980
}
7421309f Andy McCall ↶ 1981
1982
#[test]
1983
fn sparse_checkout_materializes_only_chosen_paths() {
1984
    hermetic();
1985
    let dir = tempfile::tempdir().unwrap();
1986
    let root = dir.path();
1987
    let origin_dir = root.join("origin");
75167672 Andy McCall 1988
    let origin = Repo::init(&origin_dir)
1989
        .unwrap()
1990
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 1991
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1992
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1993
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1994
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1995
    write(&origin_dir, "docs/logo.png", &logo);
1996
    write(&origin_dir, "README.md", b"# top\n");
1997
    let h1 = origin.commit("tree", &[]).unwrap();
1998
    let url = origin_dir.to_string_lossy().to_string();
1999
75167672 Andy McCall 2000
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2001
        .unwrap()
2002
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 2003
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2004
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2005
    assert!(root.join("a/src/main.rs").exists());
2006
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
75167672 Andy McCall 2007
    assert!(
2008
        !a.store().has(&Repo::blob_ref(&logo)),
2009
        "out-of-scope blob never fetched"
2010
    );
2011
    assert!(
2012
        !a.snapshot("status").unwrap().changed,
2013
        "out-of-scope files are not removals"
2014
    );
05e71ed6 Andy McCall ↶ 2015
    assert!(!a.quick_status().unwrap().dirty);
7421309f Andy McCall ↶ 2016
2017
    // Edits in scope commit normally and keep the rest of the tree intact.
75167672 Andy McCall 2018
    write(
2019
        &root.join("a"),
2020
        "src/lib.rs",
2021
        b"pub fn a() {}\npub fn b() {}\n",
2022
    );
7421309f Andy McCall ↶ 2023
    let h2 = a.commit("edit lib", &[]).unwrap();
2024
    let st = a.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 2025
    assert!(
2026
        st.files.contains_key("docs/guide.md"),
2027
        "the state still has everything"
2028
    );
7421309f Andy McCall ↶ 2029
    assert!(a.push("origin", false).unwrap()[0].ok);
2030
    // Files created outside the scope are ignored by status.
2031
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2032
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2033
2034
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2035
    let mut a = a;
2036
    a.config.set("filter.paths", "src,docs").unwrap();
2037
    a.save_config().unwrap();
75167672 Andy McCall 2038
    let r = a
2039
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2040
        .unwrap();
7421309f Andy McCall ↶ 2041
    assert!(r.written >= 2);
75167672 Andy McCall 2042
    assert_eq!(
2043
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2044
        logo,
2045
        "now fetched lazily"
2046
    );
7421309f Andy McCall ↶ 2047
    assert!(!root.join("a/README.md").exists());
2048
    // Origin sees the change made under a sparse checkout with the full tree intact.
2049
    origin.pull("origin").err();
75167672 Andy McCall 2050
    let full = origin
2051
        .load_state(&origin.bookmark_heads().unwrap())
2052
        .unwrap()
2053
        .materialize();
2054
    assert!(
2055
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2056
    );
7421309f Andy McCall ↶ 2057
    assert!(full.files.contains_key("README.md"));
2058
    let _ = h1;
2059
}
2863456a Andy McCall ↶ 2060
2061
#[test]
2062
fn shallow_clone_and_deepen() {
2063
    hermetic();
2064
    let dir = tempfile::tempdir().unwrap();
2065
    let root = dir.path();
2066
    let origin_dir = root.join("origin");
75167672 Andy McCall 2067
    let origin = Repo::init(&origin_dir)
2068
        .unwrap()
2069
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2070
    let mut hashes = Vec::new();
2071
    for i in 0..8 {
75167672 Andy McCall 2072
        write(
2073
            &origin_dir,
2074
            "a.txt",
2075
            format!(
2076
                "{}\n",
2077
                (0..=i)
2078
                    .map(|k| k.to_string())
2079
                    .collect::<Vec<_>>()
2080
                    .join("\n")
2081
            )
2082
            .as_bytes(),
2083
        );
2863456a Andy McCall ↶ 2084
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2085
    }
2086
    let url = origin_dir.to_string_lossy().to_string();
75167672 Andy McCall 2087
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2088
        .unwrap()
2089
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2090
    assert!(a.is_shallow());
75167672 Andy McCall 2091
    assert_eq!(
2092
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2093
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2094
    );
2095
    assert!(
2096
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2097
        "three levels present"
2098
    );
2863456a Andy McCall ↶ 2099
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2100
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
75167672 Andy McCall 2101
    assert_eq!(
2102
        a.log().unwrap().len(),
2103
        9,
2104
        "the log shows every change from the checkpoint's metadata"
2105
    );
2863456a Andy McCall ↶ 2106
    assert!(!a.snapshot("status").unwrap().changed);
2107
    assert_eq!(a.quick_status().unwrap().heads, 1);
2108
2109
    // Work continues on top of the shallow history and pushes back.
2110
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2111
    let h_new = a.commit("c8", &[]).unwrap();
2112
    assert!(a.push("origin", false).unwrap()[0].ok);
2113
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2114
    // Fetching new work from origin into the shallow clone works too.
2115
    write(&origin_dir, "b.txt", b"b\n");
2116
    origin.pull("origin").err();
2117
    let (_, wc) = origin.working_copy().unwrap();
2118
    let _ = wc;
75167672 Andy McCall 2119
    origin
2120
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2121
        .unwrap();
2863456a Andy McCall ↶ 2122
    write(&origin_dir, "b.txt", b"b\n");
2123
    let h_b = origin.commit("b", &[]).unwrap();
2124
    let pr = a.pull("origin").unwrap();
2125
    assert!(pr.changed);
2126
    assert!(a.store().has(&h_b));
2127
    assert!(root.join("a/b.txt").exists());
2128
2129
    // Deepening fetches older history until the boundary is gone.
2130
    // Every commit also depends on the change that created the file, so two
2131
    // levels below the boundary hold h4, h3, and the root.
2132
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2133
    assert!(a.store().has(&hashes[3]));
2134
    assert!(a.is_shallow());
2135
    a.deepen("origin", 100).unwrap();
2136
    assert!(!a.is_shallow(), "boundary reached the root");
2137
    assert!(a.store().has(&hashes[0]));
75167672 Andy McCall 2138
    assert_eq!(
2139
        a.load_state_full(&a.bookmark_heads().unwrap())
2140
            .unwrap()
2141
            .len(),
2142
        10
2143
    );
2863456a Andy McCall ↶ 2144
}
132b884b Andy McCall ↶ 2145
2146
#[test]
2147
fn tags_are_immutable_named_states_and_travel() {
2148
    hermetic();
2149
    let dir = tempfile::tempdir().unwrap();
2150
    let root = dir.path();
2151
    let origin = Repo::init(&root.join("origin")).unwrap();
2152
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2153
    let mut a = Repo::clone(&url, &root.join("a"))
2154
        .unwrap()
2155
        .with_home(root.join("home-a"));
2156
    let (key_a, _) = a
2157
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2158
        .unwrap();
132b884b Andy McCall ↶ 2159
    write(&root.join("a"), "f.txt", b"1\n");
2160
    let h1 = a.commit("one", &[]).unwrap();
2161
    write(&root.join("a"), "f.txt", b"1\n2\n");
2162
    let h2 = a.commit("two", &[]).unwrap();
2163
2164
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
75167672 Andy McCall 2165
    assert_eq!(
2166
        (t.heads.clone(), t.signer.as_deref()),
2167
        (vec![h1], Some("Ada"))
2168
    );
132b884b Andy McCall ↶ 2169
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2170
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2171
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2172
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2173
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2174
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2175
    assert_eq!(sa.sigs[0].key, key_a);
2176
    // Checkout by tag.
75167672 Andy McCall 2177
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2178
        .unwrap();
132b884b Andy McCall ↶ 2179
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
75167672 Andy McCall 2180
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2181
        .unwrap();
132b884b Andy McCall ↶ 2182
2183
    // Push carries the tag; a second attestation for the name is refused.
2184
    let r = a.push("origin", false).unwrap();
2185
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2186
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
75167672 Andy McCall 2187
    let mut forged = a
2188
        .tag_refs()
2189
        .unwrap()
2190
        .into_iter()
2191
        .find(|t| t.name == "v1")
2192
        .unwrap();
2193
    forged.state = origin
2194
        .store()
2195
        .put_state(&StateObject::new(vec![h2]))
2196
        .unwrap();
132b884b Andy McCall ↶ 2197
    forged.heads = vec![h2];
2198
    forged.attestation = None;
75167672 Andy McCall 2199
    let r = origin
2200
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2201
        .unwrap();
132b884b Andy McCall ↶ 2202
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2203
2204
    // A clone gets the tag; a later tag arrives on fetch.
75167672 Andy McCall 2205
    let b = Repo::clone(&url, &root.join("b"))
2206
        .unwrap()
2207
        .with_home(root.join("home-b"));
132b884b Andy McCall ↶ 2208
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2209
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2210
    a.tag_create("v2", &[h2], "second").unwrap();
2211
    a.push("origin", false).unwrap();
2212
    let rep = b.fetch("origin").unwrap();
2213
    assert_eq!(rep.new_tags, 1);
2214
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2215
2216
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2217
    a.policy_init().unwrap();
2218
    a.push("origin", false).unwrap();
75167672 Andy McCall 2219
    let unattested = crate::protocol::TagRef {
2220
        name: "v3".into(),
2221
        state: origin
2222
            .store()
2223
            .put_state(&StateObject::new(vec![h2]))
2224
            .unwrap(),
2225
        heads: vec![h2],
2226
        attestation: None,
2227
    };
2228
    let r = origin
2229
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2230
        .unwrap();
132b884b Andy McCall ↶ 2231
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2232
    a.tag_create("v3", &[h2], "").unwrap();
2233
    let r = a.push("origin", false).unwrap();
2234
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2235
    assert!(a.gc(true).is_ok());
2236
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2237
}
4e88e774 Andy McCall ↶ 2238
2239
#[test]
2240
fn multiple_workspaces_share_a_repository() {
2241
    hermetic();
2242
    let dir = tempfile::tempdir().unwrap();
2243
    let root = dir.path();
2244
    let main_dir = root.join("main");
2245
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2246
    write(&main_dir, "a.txt", b"a\n");
2247
    let h1 = repo.commit("a", &[]).unwrap();
2248
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2249
2250
    // A second workspace elsewhere, checked out on the bookmark.
2251
    let ws_dir = root.join("ws2");
2252
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2253
    assert!(ws_dir.join(".oxy").is_file());
2254
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2255
    assert_ne!(ws.workspace(), repo.workspace());
2256
    let list = repo.workspaces().unwrap();
2257
    assert_eq!(list.len(), 2);
75167672 Andy McCall 2258
    assert!(list
2259
        .iter()
2260
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
4e88e774 Andy McCall ↶ 2261
    assert!(!ws.snapshot("status").unwrap().changed);
2262
2263
    // Work in the second workspace: its own working copy, shared bookmark.
2264
    write(&ws_dir, "b.txt", b"b\n");
2265
    let s = ws.snapshot("status").unwrap();
2266
    assert_eq!(s.statuses.len(), 1);
75167672 Andy McCall 2267
    assert!(
2268
        !repo.snapshot("status").unwrap().changed,
2269
        "the first workspace is untouched"
2270
    );
4e88e774 Andy McCall ↶ 2271
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2272
    let mut heads = repo.bookmark_heads().unwrap();
2273
    heads.sort();
2274
    let mut want = vec![h1, h2];
2275
    want.sort();
2276
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2277
    assert!(!main_dir.join("b.txt").exists());
75167672 Andy McCall 2278
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2279
        .unwrap();
4e88e774 Andy McCall ↶ 2280
    assert!(main_dir.join("b.txt").exists());
2281
2282
    // Reopening from inside the second workspace finds the shared repository.
2283
    let reopened = Repo::open(&ws_dir).unwrap();
2284
    assert_eq!(reopened.workspace(), ws.workspace());
2285
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2286
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2287
2288
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2289
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2290
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2291
    repo.workspace_forget(&ws.workspace()).unwrap();
2292
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2293
    assert!(ws_dir.join("b.txt").exists());
75167672 Andy McCall 2294
    assert!(
2295
        ws.snapshot("status").is_err(),
2296
        "a forgotten workspace is no longer in the view"
2297
    );
4e88e774 Andy McCall ↶ 2298
6caacfff Andy McCall ↶ 2299
    // The working-copy lock: re-entrant in a thread; a lock whose process
2300
    // is gone is taken over, and a live process's is not, however old.
4e88e774 Andy McCall ↶ 2301
    let lock = repo.lock_snapshot().unwrap();
6caacfff Andy McCall ↶ 2302
    let again = repo.lock_working_copy().unwrap();
2303
    drop(again);
4e88e774 Andy McCall ↶ 2304
    drop(lock);
75167672 Andy McCall 2305
    let lock_path = main_dir
2306
        .join(".oxy/workspaces")
2307
        .join(repo.workspace().to_hex())
2308
        .join("lock");
4e88e774 Andy McCall ↶ 2309
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
6caacfff Andy McCall ↶ 2310
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2311
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2312
    age(&lock_path);
2313
    assert!(
2314
        !super::workspace::lock_is_stale(&lock_path),
2315
        "a live process keeps its lock"
2316
    );
2317
    fs::write(&lock_path, "4294967295").unwrap();
2318
    age(&lock_path);
4e88e774 Andy McCall ↶ 2319
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2320
}
cdb5beba Andy McCall ↶ 2321
2322
#[test]
2323
fn attributes_binary_eol_nocompress_lockable() {
2324
    hermetic();
2325
    let dir = tempfile::tempdir().unwrap();
2326
    let root = dir.path();
2327
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2328
    write(
2329
        root,
2330
        ".oxyattributes",
2331
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2332
    );
cdb5beba Andy McCall ↶ 2333
    write(root, "plain.dat", b"no nul bytes here\n");
2334
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2335
    write(root, "assets/model.bin", b"\0model");
2336
    let h = repo.commit("attrs", &[]).unwrap();
2337
    let snap = repo.load_state(&[h]).unwrap().materialize();
75167672 Andy McCall 2338
    assert!(
2339
        snap.files["plain.dat"].mode.opaque,
2340
        "binary attribute forces opaque without NUL bytes"
2341
    );
2342
    assert!(
2343
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2344
        "stored with LF"
2345
    );
2346
    assert!(
2347
        !repo.snapshot("status").unwrap().changed,
2348
        "CRLF on disk equals LF in the state"
2349
    );
cdb5beba Andy McCall ↶ 2350
    // nocompress chunks pack raw.
2351
    let r = repo.gc(true).unwrap();
2352
    assert!(r.packed.objects > 0);
2353
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2354
    fs::remove_file(root.join("notes.txt")).unwrap();
2355
    repo.checkout(&[h], true, "co").unwrap();
2356
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
75167672 Andy McCall 2357
    assert!(fs::metadata(root.join("assets/model.bin"))
2358
        .unwrap()
2359
        .permissions()
2360
        .readonly());
cdb5beba Andy McCall ↶ 2361
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2362
    repo.lock_path("assets/model.bin").unwrap();
75167672 Andy McCall 2363
    assert!(!fs::metadata(root.join("assets/model.bin"))
2364
        .unwrap()
2365
        .permissions()
2366
        .readonly());
cdb5beba Andy McCall ↶ 2367
    assert!(repo.is_locked("assets/model.bin"));
2368
    write(root, "assets/model.bin", b"\0model2");
2369
    repo.commit("edit model", &[]).unwrap();
2370
    repo.unlock_path("assets/model.bin").unwrap();
75167672 Andy McCall 2371
    assert!(fs::metadata(root.join("assets/model.bin"))
2372
        .unwrap()
2373
        .permissions()
2374
        .readonly());
cdb5beba Andy McCall ↶ 2375
    // A later checkout can still overwrite a read-only lockable file.
2376
    repo.checkout(&[h], true, "co").unwrap();
2377
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2378
}
6d3eefbc Andy McCall ↶ 2379
2380
#[cfg(unix)]
2381
#[test]
2382
fn hooks_can_veto_observe_and_add_dependencies() {
2383
    use std::os::unix::fs::PermissionsExt;
2384
    hermetic();
2385
    let dir = tempfile::tempdir().unwrap();
2386
    let root = dir.path();
2387
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2388
    let hooks = root.join(".oxy/hooks");
2389
    fs::create_dir_all(&hooks).unwrap();
2390
    let hook = |name: &str, body: &str| {
2391
        let p = hooks.join(name);
2392
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2393
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2394
    };
2395
    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");
2396
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2397
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2398
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2399
    write(root, ".oxyignore", b".last-*\n");
2400
    write(root, "a.txt", b"a\n");
2401
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2402
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2403
    let h1 = repo.commit("first", &[]).unwrap();
2404
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
75167672 Andy McCall 2405
    assert!(
2406
        pre.contains("\"event\":\"pre-commit\"")
2407
            && pre.contains("\"path\":\"a.txt\"")
2408
            && pre.contains("\"message\":\"first\""),
2409
        "{pre}"
2410
    );
6d3eefbc Andy McCall ↶ 2411
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2412
    assert!(post.contains(&h1.to_hex()), "{post}");
2413
    repo.checkout(&[h1], false, "co").unwrap();
75167672 Andy McCall 2414
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2415
        .unwrap()
2416
        .contains("post-checkout"));
6d3eefbc Andy McCall ↶ 2417
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2418
    repo.save_config().unwrap();
2419
    let err = repo.push("origin", false).unwrap_err().to_string();
2420
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2421
2422
    // semantic-deps: only when enabled; adds an explicit dependency.
2423
    write(root, "b.txt", b"b\n");
75167672 Andy McCall 2424
    hook(
2425
        "semantic-deps",
2426
        &format!(
2427
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2428
            h1.to_hex()
2429
        ),
2430
    );
6d3eefbc Andy McCall ↶ 2431
    let h2 = repo.commit("b without hook", &[]).unwrap();
75167672 Andy McCall 2432
    assert!(
2433
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2434
        "hook disabled by default"
2435
    );
6d3eefbc Andy McCall ↶ 2436
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2437
    repo.save_config().unwrap();
2438
    write(root, "c.txt", b"c\n");
2439
    let h3 = repo.commit("c with hook", &[]).unwrap();
2440
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2441
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
75167672 Andy McCall 2442
    assert!(
2443
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2444
        "{sem}"
2445
    );
6d3eefbc Andy McCall ↶ 2446
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2447
}
23b217d7 Andy McCall ↶ 2448
2449
#[test]
2450
fn amend_into_older_change_and_split() {
2451
    hermetic();
2452
    let dir = tempfile::tempdir().unwrap();
2453
    let root = dir.path();
2454
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2455
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2456
        .unwrap();
23b217d7 Andy McCall ↶ 2457
    repo.set_user_config("core.sign", "change").unwrap();
2458
    write(root, "a.txt", b"one\ntwo\n");
2459
    let h0 = repo.commit("base", &[]).unwrap();
2460
    write(root, "a.txt", b"one\nTWO\n");
2461
    let h1 = repo.commit("edit two", &[]).unwrap();
2462
    write(root, "a.txt", b"one\nTWO\nthree\n");
2463
    let h2 = repo.commit("add three", &[]).unwrap();
2464
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2465
2466
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2467
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2468
    let h1b = repo.amend_into(&h1, None).unwrap();
2469
    assert_ne!(h1b, h1);
2470
    let c1b = repo.store().get_change(&h1b).unwrap();
2471
    assert_eq!(c1b.change_id, id1);
2472
    assert_eq!(c1b.deps, vec![h0]);
75167672 Andy McCall 2473
    assert!(matches!(
2474
        repo.verify_change(&h1b).unwrap(),
2475
        SignatureStatus::Valid { .. }
2476
    ));
23b217d7 Andy McCall ↶ 2477
    let heads = repo.bookmark_heads().unwrap();
2478
    assert_eq!(heads.len(), 1);
2479
    let top = repo.store().get_change(&heads[0]).unwrap();
2480
    assert_eq!(top.message, "add three");
75167672 Andy McCall 2481
    assert_eq!(
2482
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2483
        [h0, h1b].into_iter().collect(),
2484
        "depends on the file's creator and the rewritten line"
2485
    );
23b217d7 Andy McCall ↶ 2486
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 2487
    assert!(
2488
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2489
    );
2490
    assert!(
2491
        !repo.snapshot("status").unwrap().changed,
2492
        "the working copy is clean after folding"
2493
    );
23b217d7 Andy McCall ↶ 2494
    // Only h1b's own state shows the fix without "three".
2495
    let only = repo.load_state(&[h1b]).unwrap().materialize();
75167672 Andy McCall 2496
    assert!(
2497
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2498
    );
23b217d7 Andy McCall ↶ 2499
    assert_eq!(repo.log().unwrap().len(), 4);
2500
2501
    // An edit to a line introduced by h2 cannot fold into h1.
2502
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2503
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2504
    assert!(err.contains("introduced after"), "{err}");
75167672 Andy McCall 2505
    assert!(
2506
        repo.snapshot("status").unwrap().statuses.len() == 1,
2507
        "nothing was changed by the refusal"
2508
    );
23b217d7 Andy McCall ↶ 2509
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2510
2511
    // Split the head that touches two files.
2512
    write(root, "b.txt", b"b\n");
2513
    write(root, "c.txt", b"c\n");
2514
    let h3 = repo.commit("b and c", &[]).unwrap();
2515
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2516
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2517
    let c_1 = repo.store().get_change(&p1).unwrap();
2518
    let c_2 = repo.store().get_change(&p2).unwrap();
2519
    assert!(c_1.message.contains("part 1: b.txt"));
2520
    assert_eq!(c_2.change_id, id3);
2521
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
75167672 Andy McCall 2522
    assert!(
2523
        heads.contains(&p1) && heads.contains(&p2),
2524
        "independent parts are both heads"
2525
    );
2526
    let snap = repo
2527
        .load_state(&repo.bookmark_heads().unwrap())
2528
        .unwrap()
2529
        .materialize();
23b217d7 Andy McCall ↶ 2530
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2531
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2532
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2533
    assert!(!repo.snapshot("status").unwrap().changed);
2534
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2535
    let _ = h2;
2536
}
28fc23d7 Andy McCall ↶ 2537
2538
#[test]
2539
fn identity_lifecycle() {
2540
    hermetic();
2541
    let dir = tempfile::tempdir().unwrap();
2542
    let root = dir.path();
2543
    let origin = Repo::init(&root.join("origin")).unwrap();
2544
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2545
    let mut a = Repo::clone(&url, &root.join("a"))
2546
        .unwrap()
2547
        .with_home(root.join("home-a"));
28fc23d7 Andy McCall ↶ 2548
    a.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 2549
    let (key_a, _) = a
2550
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2551
        .unwrap();
28fc23d7 Andy McCall ↶ 2552
    write(&root.join("a"), "a.txt", b"a\n");
2553
    let h1 = a.commit("one", &[]).unwrap();
2554
    assert!(a.policy_init().unwrap().applied);
2555
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2556
2557
    // Expiry: an identity that had expired when the change was made does not authenticate it.
75167672 Andy McCall 2558
    let mut e = Repo::init(&root.join("e"))
2559
        .unwrap()
2560
        .with_home(root.join("home-e"));
28fc23d7 Andy McCall ↶ 2561
    e.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 2562
    e.create_identity_with(
2563
        "Eve",
2564
        "[email protected]",
2565
        IdentityScope::User,
2566
        Some(Hlc::now().wall_ms - 1),
2567
    )
2568
    .unwrap();
28fc23d7 Andy McCall ↶ 2569
    write(&root.join("e"), "e.txt", b"e\n");
2570
    let he = e.commit("late", &[]).unwrap();
75167672 Andy McCall 2571
    assert!(
2572
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2573
    );
28fc23d7 Andy McCall ↶ 2574
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
75167672 Andy McCall 2575
    let r = e
2576
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2577
        .unwrap();
28fc23d7 Andy McCall ↶ 2578
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2579
    write(&root.join("e"), "e.txt", b"e2\n");
2580
    let he2 = e.commit("in time", &[]).unwrap();
75167672 Andy McCall 2581
    assert!(
2582
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2583
    );
28fc23d7 Andy McCall ↶ 2584
2585
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2586
    let r = a.rotate_identity().unwrap();
2587
    assert_eq!(r.old, key_a);
2588
    assert_eq!(a.config.author_key, Some(r.new));
2589
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2590
    assert!(r.policy.as_ref().unwrap().applied);
2591
    let (_, sp) = a.current_policy().unwrap().unwrap();
75167672 Andy McCall 2592
    assert_eq!(
2593
        (sp.policy.serial, sp.policy.roots.clone()),
2594
        (2, vec![r.new])
2595
    );
2596
    assert!(
2597
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2598
        "superseded, not revoked"
2599
    );
28fc23d7 Andy McCall ↶ 2600
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
75167672 Andy McCall 2601
    assert!(
2602
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2603
    );
28fc23d7 Andy McCall ↶ 2604
    write(&root.join("a"), "a.txt", b"a2\n");
2605
    let h2 = a.commit("two", &[]).unwrap();
75167672 Andy McCall 2606
    assert!(
2607
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2608
    );
28fc23d7 Andy McCall ↶ 2609
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2610
    let res = a.push("origin", false).unwrap();
2611
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2612
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2613
    let key_a = r.new;
2614
2615
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2616
    // identity object, so Ada's KeyId changes while her keys stay the same.
75167672 Andy McCall 2617
    let mut b = Repo::clone(&url, &root.join("b"))
2618
        .unwrap()
2619
        .with_home(root.join("home-b"));
2620
    let (key_b, id_b) = b
2621
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2622
        .unwrap();
7ba155f2 Andy McCall ↶ 2623
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
28fc23d7 Andy McCall ↶ 2624
    assert_eq!(r.old, key_a);
2625
    let key_a2 = r.new;
75167672 Andy McCall 2626
    assert_eq!(
7ba155f2 Andy McCall ↶ 2627
        a.identity(&key_a2).unwrap().delegates,
2628
        vec![Delegate::full(key_b)]
2629
    );
2630
    assert_eq!(
75167672 Andy McCall 2631
        a.identity(&key_a2).unwrap().ed25519_pk,
2632
        a.identity(&key_a).unwrap().ed25519_pk
7ba155f2 Andy McCall ↶ 2633
    );
2634
    assert!(
2635
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2636
        "already a delegate"
75167672 Andy McCall 2637
    );
28fc23d7 Andy McCall ↶ 2638
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2639
    write(&root.join("a"), "a.txt", b"a3\n");
2640
    let h3 = a.commit("three", &[]).unwrap();
75167672 Andy McCall 2641
    assert!(
2642
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2643
        "the same secret signs under the new KeyId"
2644
    );
28fc23d7 Andy McCall ↶ 2645
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2646
    a.set_user_config("core.sign", "seal").unwrap();
2647
    write(&root.join("a"), "a.txt", b"a4\n");
2648
    let h4 = a.commit("four", &[]).unwrap();
2649
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2650
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 2651
    a.store()
2652
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2653
        .unwrap();
2654
    assert!(
2655
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2656
    );
28fc23d7 Andy McCall ↶ 2657
    a.set_user_config("core.sign", "change").unwrap();
2658
    // Withdrawing the delegation re-issues the identity again.
2659
    let r = a.delegate_remove(&key_b).unwrap();
2660
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2661
    assert!(a.delegate_remove(&key_b).is_err());
2662
    let key_a3 = r.new;
2663
    let res = a.push("origin", false).unwrap();
2664
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2665
2666
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2667
    // both applied under the old threshold of 1. A grant then needs Bob too.
2668
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2669
    assert!(a.policy_root_add(id_b.clone()).is_err());
2670
    assert!(a.policy_set_threshold(3).is_err());
2671
    assert!(a.policy_set_threshold(2).unwrap().applied);
2672
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2673
    b.pull("origin").unwrap();
75167672 Andy McCall 2674
    assert_eq!(
2675
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2676
        2
2677
    );
2678
    let mut c = Repo::init(&root.join("c"))
2679
        .unwrap()
2680
        .with_home(root.join("home-c"));
2681
    let (key_c, id_c) = c
2682
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2683
        .unwrap();
28fc23d7 Andy McCall ↶ 2684
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2685
    let proposal = a.policy_grant(id_c, None).unwrap();
2686
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2687
    assert_eq!(proposal.policy.serial, serial_before + 1);
75167672 Andy McCall 2688
    assert_eq!(
2689
        a.current_policy().unwrap().unwrap().1.policy.serial,
2690
        serial_before,
2691
        "a proposal changes nothing yet"
2692
    );
28fc23d7 Andy McCall ↶ 2693
    // Bob signs the proposal, handed over as a file, and it applies for him.
2694
    let bytes = proposal.signed().encode();
75167672 Andy McCall 2695
    let signed = b
2696
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2697
        .unwrap();
28fc23d7 Andy McCall ↶ 2698
    assert!(signed.applied && signed.sigs.len() == 2);
75167672 Andy McCall 2699
    assert!(b
2700
        .current_policy()
2701
        .unwrap()
2702
        .unwrap()
2703
        .1
2704
        .policy
2705
        .authorizes(&key_c, "main"));
2706
    assert!(
2707
        b.policy_sign(signed.signed()).is_err(),
2708
        "a stale proposal is refused"
2709
    );
28fc23d7 Andy McCall ↶ 2710
    // Bob publishes it and Ada picks it up.
75167672 Andy McCall 2711
    assert!(b
2712
        .push("origin", false)
2713
        .unwrap()
2714
        .iter()
2715
        .any(|x| x.name == "policy" && x.ok));
28fc23d7 Andy McCall ↶ 2716
    a.pull("origin").unwrap();
75167672 Andy McCall 2717
    assert_eq!(
2718
        a.current_policy().unwrap().unwrap().1.policy.serial,
2719
        serial_before + 1
2720
    );
28fc23d7 Andy McCall ↶ 2721
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2722
    assert!(a.policy_revoke(&key_a3).is_err());
75167672 Andy McCall 2723
    let u = a
2724
        .revoke_identity(&key_c, "left the project")
2725
        .unwrap()
2726
        .unwrap();
28fc23d7 Andy McCall ↶ 2727
    assert!(!u.applied);
2728
    assert!(a.is_revoked(&key_c).unwrap());
2729
    assert!(!b.is_revoked(&key_c).unwrap());
2730
    let u = b.policy_sign(u.signed()).unwrap();
2731
    assert!(u.applied && u.policy.is_revoked(&key_c));
2732
    assert!(b.is_revoked(&key_c).unwrap());
2733
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
75167672 Andy McCall 2734
    assert!(
2735
        b.policy_revoke(&key_a3).is_err(),
2736
        "would leave one root for a threshold of 2"
2737
    );
28fc23d7 Andy McCall ↶ 2738
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2739
    let key_c_own = c.config.author_key.unwrap();
75167672 Andy McCall 2740
    assert!(c
2741
        .revoke_identity(&key_c_own, "lost laptop")
2742
        .unwrap()
2743
        .is_none());
28fc23d7 Andy McCall ↶ 2744
    assert!(c.is_revoked(&key_c_own).unwrap());
2745
    assert_eq!(key_c_own, key_c);
2746
}
2747
6e723b81 Andy McCall ↶ 2748
#[test]
2749
fn renames_are_detected_and_tracked_as_moves() {
2750
    hermetic();
2751
    let dir = tempfile::tempdir().unwrap();
2752
    let root = dir.path();
2753
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2754
    write(
2755
        root,
2756
        "src/old.rs",
2757
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2758
    );
6e723b81 Andy McCall ↶ 2759
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2760
    write(root, "tiny.txt", b"x\n");
2761
    let h1 = repo.commit("base", &[]).unwrap();
2762
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2763
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2764
2765
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2766
    // that shares nothing with the removed file.
2767
    fs::remove_file(root.join("src/old.rs")).unwrap();
75167672 Andy McCall 2768
    write(
2769
        root,
2770
        "lib/new.rs",
2771
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2772
    );
6e723b81 Andy McCall ↶ 2773
    fs::remove_file(root.join("img.bin")).unwrap();
2774
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2775
    fs::remove_file(root.join("tiny.txt")).unwrap();
2776
    write(root, "other.txt", b"completely different\n");
2777
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 2778
    let statuses: Vec<(&str, ChangeStatus)> = snap
2779
        .statuses
2780
        .iter()
2781
        .map(|s| (s.path.as_str(), s.status))
2782
        .collect();
6e723b81 Andy McCall ↶ 2783
    assert_eq!(
2784
        statuses,
75167672 Andy McCall 2785
        vec![
2786
            ("assets/img.bin", ChangeStatus::Renamed),
2787
            ("lib/new.rs", ChangeStatus::Renamed),
2788
            ("other.txt", ChangeStatus::Added),
2789
            ("src", ChangeStatus::Removed),
2790
            ("tiny.txt", ChangeStatus::Removed)
2791
        ]
6e723b81 Andy McCall ↶ 2792
    );
2793
    let h2 = repo.commit("move things", &[]).unwrap();
2794
    let c = repo.store().get_change(&h2).unwrap();
75167672 Andy McCall 2795
    let moves: Vec<_> = c
2796
        .tree_ops
2797
        .iter()
2798
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2799
        .collect();
6e723b81 Andy McCall ↶ 2800
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
75167672 Andy McCall 2801
    assert!(c.tree_ops.iter().any(
2802
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2803
    ));
2804
    assert!(c.tree_ops.iter().any(
2805
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2806
    ));
6e723b81 Andy McCall ↶ 2807
    let snap = repo.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 2808
    assert_eq!(
2809
        snap.files["lib/new.rs"].node, node_old,
2810
        "the node survives the rename"
2811
    );
2812
    assert!(
2813
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2814
    );
6e723b81 Andy McCall ↶ 2815
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
75167672 Andy McCall 2816
    assert!(render_change(
2817
        &c,
2818
        &repo.load_state(&[h1]).unwrap(),
2819
        &repo.load_state(&[h1]).unwrap().materialize()
2820
    )
0912a033 Andy McCall ↶ 2821
    .contains("R src/old.rs -> lib/new.rs"));
6e723b81 Andy McCall ↶ 2822
    // A fresh checkout reproduces the tree.
2823
    let other = tempfile::tempdir().unwrap();
2824
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
75167672 Andy McCall 2825
    assert_eq!(
2826
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2827
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2828
    );
6e723b81 Andy McCall ↶ 2829
    assert!(!other.path().join("src").exists());
2830
    assert!(!clone.snapshot("status").unwrap().changed);
2831
    // Similarity is line based, byte weighted.
2832
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2833
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2834
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2835
    assert_eq!(similarity(b"", b"x\n"), 0);
2836
}
2837
30ea9c1e Andy McCall ↶ 2838
#[test]
2839
fn git_fetch_and_push_round_trip() {
2840
    hermetic();
75167672 Andy McCall 2841
    if std::process::Command::new("git")
2842
        .arg("--version")
2843
        .output()
2844
        .is_err()
2845
    {
30ea9c1e Andy McCall ↶ 2846
        eprintln!("git not installed; skipping");
2847
        return;
2848
    }
2849
    let dir = tempfile::tempdir().unwrap();
2850
    let root = dir.path();
2851
    let git_in = |d: &Path, args: &[&str]| -> String {
2852
        let out = std::process::Command::new("git")
2853
            .arg("-C")
2854
            .arg(d)
75167672 Andy McCall 2855
            .args([
2856
                "-c",
2857
                "user.name=Grace",
2858
                "-c",
2859
                "[email protected]",
2860
                "-c",
2861
                "commit.gpgsign=false",
2862
            ])
30ea9c1e Andy McCall ↶ 2863
            .args(args)
2864
            .output()
2865
            .unwrap();
75167672 Andy McCall 2866
        assert!(
2867
            out.status.success(),
2868
            "git {args:?}: {}",
2869
            String::from_utf8_lossy(&out.stderr)
2870
        );
30ea9c1e Andy McCall ↶ 2871
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2872
    };
2873
    // A bare "remote" and a work tree that pushes to it.
2874
    let remote = root.join("remote.git");
2875
    fs::create_dir_all(&remote).unwrap();
2876
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2877
    let work = root.join("work");
75167672 Andy McCall 2878
    git_in(
2879
        root,
2880
        &[
2881
            "clone",
2882
            "-q",
2883
            remote.to_str().unwrap(),
2884
            work.to_str().unwrap(),
2885
        ],
2886
    );
30ea9c1e Andy McCall ↶ 2887
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2888
    write(&work, "README.md", b"# Project\n");
2889
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2890
    git_in(&work, &["add", "."]);
2891
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2892
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2893
    git_in(&work, &["commit", "-q", "-am", "second"]);
2894
    git_in(&work, &["push", "-q", "origin", "main"]);
2895
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2896
2897
    // Fetch into a fresh oxy repository.
2898
    let o = root.join("oxy");
2899
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2900
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2901
        .unwrap();
30ea9c1e Andy McCall ↶ 2902
    let url = remote.to_string_lossy().to_string();
2903
    let r = repo.git_fetch(&url, "main").unwrap();
2904
    assert_eq!((r.commits, r.heads), (2, 1));
75167672 Andy McCall 2905
    assert_eq!(
2906
        fs::read(o.join("src/lib.rs")).unwrap(),
2907
        b"pub fn a() {}\npub fn b() {}\n"
2908
    );
30ea9c1e Andy McCall ↶ 2909
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 2910
    assert_eq!(
2911
        repo.git_fetch(&url, "main").unwrap().commits,
2912
        0,
2913
        "nothing new"
2914
    );
30ea9c1e Andy McCall ↶ 2915
2916
    // An oxy change, pushed back: one commit on top of the Git tip.
75167672 Andy McCall 2917
    write(
2918
        &o,
2919
        "src/lib.rs",
2920
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2921
    );
30ea9c1e Andy McCall ↶ 2922
    write(&o, "NOTES.md", b"from oxy\n");
2923
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2924
    let r = repo.git_push(&url, "main").unwrap();
2925
    assert_eq!(r.exported, 1, "{r:?}");
2926
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
75167672 Andy McCall 2927
    assert_eq!(
2928
        git_in(&work, &["log", "--format=%s", "main"]),
2929
        "add c and notes\nsecond\ninitial"
2930
    );
30ea9c1e Andy McCall ↶ 2931
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2932
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2933
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
75167672 Andy McCall 2934
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2935
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2936
    assert_eq!(
2937
        repo.git_push(&url, "main").unwrap().exported,
2938
        0,
2939
        "already pushed"
2940
    );
30ea9c1e Andy McCall ↶ 2941
2942
    // Git moves on; pushing without fetching is refused, fetching brings
2943
    // the commit in and the working copy follows.
2944
    write(&work, "README.md", b"# Project\n\nMore.\n");
2945
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2946
    git_in(&work, &["push", "-q", "origin", "main"]);
2947
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
75167672 Andy McCall 2948
    assert!(repo
2949
        .git_push(&url, "main")
2950
        .unwrap_err()
2951
        .to_string()
2952
        .contains("fetch"));
30ea9c1e Andy McCall ↶ 2953
    let r = repo.git_fetch(&url, "main").unwrap();
75167672 Andy McCall 2954
    assert_eq!(
2955
        (r.commits, r.heads),
2956
        (1, 2),
2957
        "the Git change and the oxy change commute"
2958
    );
2959
    assert_eq!(
2960
        fs::read(o.join("README.md")).unwrap(),
2961
        b"# Project\n\nMore.\n"
2962
    );
30ea9c1e Andy McCall ↶ 2963
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2964
    assert!(!repo.snapshot("status").unwrap().changed);
2965
    // Another oxy change pushes on top of Git's newest commit.
2966
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2967
    repo.commit("notes again", &[]).unwrap();
2968
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2969
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2970
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
75167672 Andy McCall 2971
    assert_eq!(
2972
        fs::read(work.join("NOTES.md")).unwrap(),
2973
        b"from oxy\nagain\n"
2974
    );
2975
    assert_eq!(
2976
        git_in(&work, &["log", "--format=%s", "main"])
2977
            .lines()
2978
            .count(),
2979
        5
2980
    );
30ea9c1e Andy McCall ↶ 2981
}
2982
2b872d07 Andy McCall ↶ 2983
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2984
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2985
#[test]
2986
#[ignore]
2987
fn bench_one_gibibyte_file() {
2988
    hermetic();
2989
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2990
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2991
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2992
        None => tempfile::tempdir().unwrap(),
2993
    };
2994
    let root = dir.path();
75167672 Andy McCall 2995
    let repo = Repo::init(&root.join("r"))
2996
        .unwrap()
2997
        .with_home(root.join("home"));
2b872d07 Andy McCall ↶ 2998
    let size = 1usize << 30;
2999
    let mut data = vec![0u8; size];
3000
    let mut x = 0x9e3779b97f4a7c15u64;
3001
    for chunk in data.chunks_mut(8) {
3002
        x ^= x << 13;
3003
        x ^= x >> 7;
3004
        x ^= x << 17;
3005
        let b = x.to_le_bytes();
3006
        chunk.copy_from_slice(&b[..chunk.len()]);
3007
    }
3008
    let t = std::time::Instant::now();
3009
    write(&root.join("r"), "big.bin", &data);
3010
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3011
    let t = std::time::Instant::now();
3012
    let h = repo.commit("big", &[]).unwrap();
3013
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3014
    let t = std::time::Instant::now();
3015
    assert!(!repo.snapshot("status").unwrap().changed);
3016
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3017
    let t = std::time::Instant::now();
3018
    let objects = repo.store().list().unwrap().len();
3019
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3020
    let t = std::time::Instant::now();
3021
    let g = repo.gc(true).unwrap();
3022
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3023
    let t = std::time::Instant::now();
3024
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3025
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3026
    let t = std::time::Instant::now();
3027
    let back = fs::read(root.join("c/big.bin")).unwrap();
3028
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3029
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3030
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3031
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
75167672 Andy McCall 3032
    eprintln!(
3033
        "store size: {:.1} MiB for 1 GiB of data",
3034
        store_bytes as f64 / (1024.0 * 1024.0)
3035
    );
2b872d07 Andy McCall ↶ 3036
}
3037
3038
fn walkdir_size(p: &Path) -> u64 {
3039
    let mut total = 0;
3040
    if let Ok(rd) = fs::read_dir(p) {
3041
        for e in rd.flatten() {
3042
            let path = e.path();
3043
            if path.is_dir() {
3044
                total += walkdir_size(&path);
3045
            } else if let Ok(m) = fs::metadata(&path) {
3046
                total += m.len();
3047
            }
3048
        }
3049
    }
3050
    total
3051
}
3052
b7f102fc Andy McCall ↶ 3053
/// An opaque file whose size and mtime match the manifest is not read on
3054
/// the next snapshot: its blob comes from the manifest's stat cache.
3055
#[cfg(unix)]
3056
#[test]
3057
fn stat_cache_skips_reading_unchanged_opaque_files() {
3058
    use std::os::unix::fs::PermissionsExt;
3059
    hermetic();
3060
    let dir = tempfile::tempdir().unwrap();
3061
    let root = dir.path();
3062
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3063
    let mut big = vec![0u8; 300 * 1024];
3064
    for (i, b) in big.iter_mut().enumerate() {
3065
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3066
    }
3067
    big[0] = 0;
3068
    write(root, "big.bin", &big);
3069
    write(root, "a.txt", b"text\n");
3070
    let h1 = repo.commit("base", &[]).unwrap();
3071
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
75167672 Andy McCall 3072
    assert!(
3073
        m.entries["big.bin"].blob.is_some(),
3074
        "opaque files record their blob"
3075
    );
b7f102fc Andy McCall ↶ 3076
    assert!(m.entries["a.txt"].blob.is_none());
3077
    let blob = m.entries["big.bin"].blob.unwrap();
3078
    assert!(repo.store().has(&blob));
3079
3080
    // Files modified within two seconds of the manifest are racy and still
3081
    // read; age the file so the cache applies, then snapshot to record it.
3082
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
75167672 Andy McCall 3083
    fs::File::options()
3084
        .write(true)
3085
        .open(root.join("big.bin"))
3086
        .unwrap()
3087
        .set_modified(old)
3088
        .unwrap();
b7f102fc Andy McCall ↶ 3089
    assert!(!repo.snapshot("status").unwrap().changed);
3090
    // Now the file cannot be read at all; the snapshot succeeds without it.
3091
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3092
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3093
    assert!(
3094
        !snap.changed && snap.statuses.is_empty(),
3095
        "{:?}",
3096
        snap.statuses
3097
    );
b7f102fc Andy McCall ↶ 3098
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3099
    // A real change (new mtime, new content) is seen and committed correctly.
3100
    let mut big2 = big.clone();
3101
    big2[10] ^= 0xff;
3102
    write(root, "big.bin", &big2);
3103
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3104
    assert_eq!(
3105
        snap.statuses
3106
            .iter()
3107
            .map(|s| (s.path.as_str(), s.status))
3108
            .collect::<Vec<_>>(),
3109
        vec![("big.bin", ChangeStatus::Modified)]
3110
    );
b7f102fc Andy McCall ↶ 3111
    let h2 = repo.commit("edit", &[]).unwrap();
3112
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 3113
    assert_eq!(
3114
        files["big.bin"].content,
3115
        FileContent::Opaque {
3116
            blobs: vec![Repo::blob_ref(&big2)]
3117
        }
3118
    );
b7f102fc Andy McCall ↶ 3119
    // Checkout writes a manifest with blobs too, so the next status is cached.
3120
    repo.checkout(&[h1], false, "checkout").unwrap();
3121
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3122
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3123
    assert!(!repo.snapshot("status").unwrap().changed);
3124
}
3125
50a046e4 Andy McCall ↶ 3126
#[test]
3127
fn status_json_lists_conflicts_with_contributors() {
3128
    hermetic();
3129
    let dir = tempfile::tempdir().unwrap();
3130
    let root = dir.path();
3131
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3132
    write(root, "a.txt", b"one\n");
3133
    let h1 = repo.commit("base", &[]).unwrap();
3134
    write(root, "a.txt", b"one\nleft\n");
3135
    let ha = repo.commit("left", &[]).unwrap();
3136
    repo.checkout(&[h1], true, "checkout").unwrap();
3137
    write(root, "a.txt", b"one\nright\n");
3138
    let hb = repo.commit("right", &[]).unwrap();
3139
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3140
    let snap = repo.snapshot("status").unwrap();
3141
    assert!(snap.base_snapshot.is_conflicted());
3142
    let json = repo.status_json(&snap).unwrap();
3143
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3144
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3145
    assert!(json.contains("\"conflicted\":true"), "{json}");
75167672 Andy McCall 3146
    assert!(
3147
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3148
        "{json}"
3149
    );
50a046e4 Andy McCall ↶ 3150
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3151
    assert!(json.contains("\"resolved\":false"), "{json}");
3152
    assert!(json.starts_with('{') && json.ends_with('}'));
3153
    // Resolve and the report says so; a clean copy has no conflicts.
3154
    write(root, "a.txt", b"one\nleft\nright\n");
3155
    let snap = repo.snapshot("status").unwrap();
3156
    let json = repo.status_json(&snap).unwrap();
3157
    assert!(json.contains("\"resolved\":true"), "{json}");
3158
    repo.commit("resolve", &[]).unwrap();
3159
    let snap = repo.snapshot("status").unwrap();
3160
    let json = repo.status_json(&snap).unwrap();
75167672 Andy McCall 3161
    assert!(
3162
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3163
        "{json}"
3164
    );
50a046e4 Andy McCall ↶ 3165
}
3166
9ac1fbe2 Andy McCall ↶ 3167
#[test]
3168
fn ignore_rules_do_not_untrack_files() {
3169
    hermetic();
3170
    let dir = tempfile::tempdir().unwrap();
3171
    let root = dir.path();
3172
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3173
    write(root, "src.c", b"int x;\n");
3174
    write(root, "build/out.o", b"\0obj");
3175
    write(root, "sub/keep.log", b"keep\n");
3176
    write(root, "sub/junk.log", b"junk\n");
3177
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3178
    let snap = repo.snapshot("status").unwrap();
3179
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 3180
    assert_eq!(
3181
        added,
3182
        vec![".oxyignore", "src.c", "sub/keep.log"],
3183
        "anchored, glob, and negated rules"
3184
    );
9ac1fbe2 Andy McCall ↶ 3185
    let h1 = repo.commit("base", &[]).unwrap();
3186
    // Ignoring a tracked file changes nothing about it.
3187
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3188
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3189
    assert_eq!(
3190
        snap.statuses
3191
            .iter()
3192
            .map(|s| s.path.as_str())
3193
            .collect::<Vec<_>>(),
3194
        vec![".oxyignore"]
3195
    );
9ac1fbe2 Andy McCall ↶ 3196
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
75167672 Andy McCall 3197
    assert!(repo
3198
        .load_state(&[h2])
3199
        .unwrap()
3200
        .materialize()
3201
        .files
3202
        .contains_key("src.c"));
9ac1fbe2 Andy McCall ↶ 3203
    // Its edits are still seen, by status and by the prompt.
3204
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3205
    write(root, "src.c", b"int x, y;\n");
3206
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3207
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3208
    assert_eq!(
3209
        snap.statuses
3210
            .iter()
3211
            .map(|s| (s.path.as_str(), s.status))
3212
            .collect::<Vec<_>>(),
3213
        vec![("src.c", ChangeStatus::Modified)]
3214
    );
9ac1fbe2 Andy McCall ↶ 3215
    let h3 = repo.commit("edit src.c", &[]).unwrap();
75167672 Andy McCall 3216
    assert!(
3217
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3218
    );
9ac1fbe2 Andy McCall ↶ 3219
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3220
    fs::remove_file(root.join("src.c")).unwrap();
3221
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3222
    assert_eq!(
3223
        snap.statuses
3224
            .iter()
3225
            .map(|s| (s.path.as_str(), s.status))
3226
            .collect::<Vec<_>>(),
3227
        vec![("src.c", ChangeStatus::Removed)]
3228
    );
9ac1fbe2 Andy McCall ↶ 3229
    repo.checkout(&[h3], true, "checkout").unwrap();
3230
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3231
    assert!(!repo.snapshot("status").unwrap().changed);
3232
    let _ = h1;
3233
}
3234
b837d2b5 Andy McCall ↶ 3235
#[test]
3236
fn split_works_on_non_heads_by_node() {
3237
    hermetic();
3238
    let dir = tempfile::tempdir().unwrap();
3239
    let root = dir.path();
3240
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3241
    write(root, "a.txt", b"one\n");
3242
    write(root, "junk/x.lock", b"lock\n");
3243
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3244
    write(root, "a.txt", b"one\ntwo\n");
3245
    let h2 = repo.commit("more work", &[]).unwrap();
3246
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3247
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3248
    // h1 is not a head: split it by node.
3249
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3250
    assert_ne!(h1b, h1);
75167672 Andy McCall 3251
    assert_eq!(
3252
        repo.store().get_change(&h1b).unwrap().change_id,
3253
        id1,
3254
        "the rest keeps the ChangeId"
3255
    );
b837d2b5 Andy McCall ↶ 3256
    let junk = repo.store().get_change(&hj).unwrap();
75167672 Andy McCall 3257
    assert!(junk.tree_ops.iter().all(
3258
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3259
    ));
b837d2b5 Andy McCall ↶ 3260
    let heads = repo.bookmark_heads().unwrap();
75167672 Andy McCall 3261
    assert!(
3262
        heads.contains(&hj),
3263
        "the split-off part is a head of its own"
3264
    );
b837d2b5 Andy McCall ↶ 3265
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 3266
    assert!(
3267
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3268
        "the dependent was rewritten onto the new hash"
3269
    );
b837d2b5 Andy McCall ↶ 3270
    assert!(snap.files.contains_key("junk/x.lock"));
75167672 Andy McCall 3271
    let h2b = heads
3272
        .iter()
3273
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3274
        .copied()
3275
        .unwrap();
b837d2b5 Andy McCall ↶ 3276
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3277
    assert!(!repo.snapshot("status").unwrap().changed);
3278
    // Abandoning the split-off head removes the junk from history.
3279
    repo.abandon(&hj).unwrap();
3280
    let heads = repo.bookmark_heads().unwrap();
3281
    let snap = repo.load_state(&heads).unwrap().materialize();
3282
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3283
    assert!(snap.files.contains_key("a.txt"));
3284
    // A dependent that touches the split-off paths blocks the split.
3285
    write(root, "junk/y.lock", b"y\n");
3286
    let hb = repo.commit("junk base", &[]).unwrap();
3287
    write(root, "junk/y.lock", b"yy\n");
3288
    write(root, "b.txt", b"b\n");
3289
    repo.commit("touches junk", &[]).unwrap();
3290
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3291
    assert!(err.contains("depends on the split-off paths"), "{err}");
3292
}
3293
7b9809e6 Andy McCall ↶ 3294
#[test]
3295
fn bookmarks_switch_merge_and_push() {
3296
    hermetic();
3297
    let dir = tempfile::tempdir().unwrap();
3298
    let root = dir.path();
3299
    let origin = Repo::init(&root.join("origin")).unwrap();
3300
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3301
    let mut repo = Repo::clone(&url, &root.join("r"))
3302
        .unwrap()
3303
        .with_home(root.join("home"));
7b9809e6 Andy McCall ↶ 3304
    let r = root.join("r");
3305
    write(&r, "a.txt", b"a\n");
3306
    let h_a = repo.commit("a", &[]).unwrap();
3307
    assert!(repo.push("origin", false).unwrap()[0].ok);
3308
3309
    // A bookmark at the working copy's base, then work on it.
3310
    assert!(repo.bookmark_create("bad name..", None).is_err());
3311
    assert!(repo.bookmark_create("-x", None).is_err());
3312
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3313
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3314
    repo.bookmark_switch("feature", false).unwrap();
3315
    assert_eq!(repo.config.bookmark, "feature");
3316
    write(&r, "a.txt", b"a\nb\n");
3317
    write(&r, "b.txt", b"b\n");
3318
    let h_b = repo.commit("b on feature", &[]).unwrap();
75167672 Andy McCall 3319
    assert_eq!(
3320
        repo.bookmark_heads().unwrap(),
3321
        vec![h_b],
3322
        "b edits a.txt, so it depends on a"
3323
    );
3324
    assert_eq!(
3325
        repo.resolve_heads("main").unwrap(),
3326
        vec![h_a],
3327
        "main is untouched"
3328
    );
3329
    assert_eq!(
3330
        repo.resolve_change("feature").unwrap(),
3331
        h_b,
3332
        "a one-head bookmark names its change"
3333
    );
7b9809e6 Andy McCall ↶ 3334
    // Reopening keeps the workspace's bookmark.
3335
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3336
    assert_eq!(reopened.config.bookmark, "feature");
3337
    // Back to main: b.txt goes away; work there.
3338
    repo.bookmark_switch("main", false).unwrap();
3339
    assert!(!r.join("b.txt").exists());
3340
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3341
    write(&r, "c.txt", b"c\n");
3342
    let h_c = repo.commit("c on main", &[]).unwrap();
3343
    let list = repo.bookmarks().unwrap();
75167672 Andy McCall 3344
    assert_eq!(
3345
        list.iter()
3346
            .map(|b| (b.name.as_str(), b.current))
3347
            .collect::<Vec<_>>(),
3348
        vec![("feature", false), ("main", true)]
3349
    );
3350
    assert_eq!(
3351
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3352
        Some(1),
3353
        "c is not on origin yet"
3354
    );
7b9809e6 Andy McCall ↶ 3355
    // Merge feature into main: the union, both heads, no merge change.
3356
    let m = repo.merge("feature").unwrap();
3357
    assert!(m.changed && m.checked_out);
3358
    let mut want = vec![h_b, h_c];
3359
    want.sort();
3360
    assert_eq!(m.heads, want);
3361
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3362
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3363
    assert!(repo.merge("main").is_err());
3364
    // The other bookmark can be pushed by name and appears at origin.
3365
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3366
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3367
    assert!(repo.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 3368
    assert_eq!(
3369
        repo.bookmarks()
3370
            .unwrap()
3371
            .iter()
3372
            .find(|b| b.name == "main")
3373
            .unwrap()
3374
            .ahead,
3375
        Some(0)
3376
    );
7b9809e6 Andy McCall ↶ 3377
    // A second workspace inherits the current bookmark and can switch independently.
3378
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3379
    assert_eq!(ws.config.bookmark, "main");
3380
    let mut ws = ws;
3381
    ws.bookmark_switch("feature", false).unwrap();
75167672 Andy McCall 3382
    assert_eq!(
3383
        Repo::open(&r).unwrap().config.bookmark,
3384
        "main",
3385
        "the first workspace is unaffected"
3386
    );
3387
    assert!(
3388
        repo.bookmark_delete("feature").is_err(),
3389
        "current bookmark of another workspace"
3390
    );
7b9809e6 Andy McCall ↶ 3391
    ws.bookmark_switch("main", false).unwrap();
3392
    // Set and delete.
3393
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3394
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3395
    repo.bookmark_delete("feature").unwrap();
3396
    assert!(repo.resolve_heads("feature").is_err());
3397
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
75167672 Andy McCall 3398
    assert!(
3399
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3400
        "changes of a deleted bookmark remain"
3401
    );
7b9809e6 Andy McCall ↶ 3402
}
3403
4dee277c Andy McCall ↶ 3404
#[test]
3405
fn oxygen_subrepos_pin_follow_and_update() {
3406
    hermetic();
3407
    let dir = tempfile::tempdir().unwrap();
3408
    let root = dir.path();
3409
    // A library repository with two commits, and a bare-ish origin for it.
3410
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3411
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
75167672 Andy McCall 3412
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3413
        .unwrap()
3414
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3415
    write(&root.join("lib"), "lib.txt", b"v1\n");
3416
    let l1 = lib.commit("lib v1", &[]).unwrap();
3417
    assert!(lib.push("origin", false).unwrap()[0].ok);
3418
    let _ = lib_origin;
3419
3420
    // The application (a clone of its own origin) adds it as a subrepo.
3421
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3422
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3423
    let _ = app_origin;
3424
    let app_dir = root.join("app");
75167672 Andy McCall 3425
    let app = Repo::clone(&app_url, &app_dir)
3426
        .unwrap()
3427
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3428
    write(&app_dir, "main.txt", b"app\n");
3429
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3430
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3431
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3432
    let snap = app.snapshot("status").unwrap();
3433
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 3434
    assert_eq!(
3435
        paths,
3436
        vec![".oxymodules", "libs/lib", "main.txt"],
3437
        "the nested files are not walked"
3438
    );
4dee277c Andy McCall ↶ 3439
    let a1 = app.commit("app with lib", &[]).unwrap();
3440
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3441
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3442
    assert!(!files.contains_key("libs/lib/lib.txt"));
3443
    assert!(!app.snapshot("status").unwrap().changed);
3444
    let subs = app.subrepos().unwrap();
3445
    assert_eq!(subs.len(), 1);
3446
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3447
3448
    // Advance the nested repository: the parent sees a modified pin.
75167672 Andy McCall 3449
    let nested = Repo::open(&app_dir.join("libs/lib"))
3450
        .unwrap()
3451
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3452
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3453
    let l2 = nested.commit("lib v2", &[]).unwrap();
3454
    assert!(nested.push("origin", false).unwrap()[0].ok);
3455
    let snap = app.snapshot("status").unwrap();
75167672 Andy McCall 3456
    assert_eq!(
3457
        snap.statuses
3458
            .iter()
3459
            .map(|s| (s.path.as_str(), s.status))
3460
            .collect::<Vec<_>>(),
3461
        vec![("libs/lib", ChangeStatus::Modified)]
3462
    );
4dee277c Andy McCall ↶ 3463
    let a2 = app.commit("bump lib", &[]).unwrap();
1a3b6203 Andy McCall ↶ 3464
    // Checking out the older app state brings the nested working copy back
3465
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4dee277c Andy McCall ↶ 3466
    let r = app.checkout(&[a1], false, "checkout").unwrap();
1a3b6203 Andy McCall ↶ 3467
    assert!(
3468
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3469
        "{:?}",
3470
        r.notes
3471
    );
4dee277c Andy McCall ↶ 3472
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
1a3b6203 Andy McCall ↶ 3473
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3474
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3475
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4dee277c Andy McCall ↶ 3476
    assert!(!app.snapshot("status").unwrap().changed);
3477
    // A dirty nested repository is left alone and reported.
3478
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3479
    let r = app.checkout(&[a2], false, "checkout").unwrap();
75167672 Andy McCall 3480
    assert!(
3481
        r.notes.iter().any(|n| n.contains("uncommitted")),
3482
        "{:?}",
3483
        r.notes
3484
    );
4dee277c Andy McCall ↶ 3485
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3486
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3487
    let r = app.submodule_update(false, &[]).unwrap();
3488
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3489
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3490
    let _ = l2;
3491
3492
    // A fresh clone of the app has the pin but no nested repository until update --init.
3493
    assert!(app.push("origin", false).unwrap()[0].ok);
3494
    let clone_dir = root.join("app-clone");
75167672 Andy McCall 3495
    let clone = Repo::clone(&app_url, &clone_dir)
3496
        .unwrap()
3497
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3498
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
75167672 Andy McCall 3499
    assert_eq!(
3500
        clone.submodule_update(false, &[]).unwrap(),
3501
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3502
    );
3503
    assert_eq!(
3504
        clone.submodule_update(true, &[]).unwrap(),
3505
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3506
    );
3507
    assert_eq!(
3508
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3509
        b"v2\n"
3510
    );
4dee277c Andy McCall ↶ 3511
    assert!(!clone.snapshot("status").unwrap().changed);
3512
    // Removing the subrepo leaves the directory and drops the node.
3513
    clone.submodule_remove("libs/lib").unwrap();
3514
    let snap = clone.snapshot("status").unwrap();
75167672 Andy McCall 3515
    assert!(
3516
        snap.statuses
3517
            .iter()
3518
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3519
        "{:?}",
3520
        snap.statuses
3521
    );
4dee277c Andy McCall ↶ 3522
    let c = clone.commit("drop lib", &[]).unwrap();
75167672 Andy McCall 3523
    assert!(!clone
3524
        .load_state(&[c])
3525
        .unwrap()
3526
        .materialize()
3527
        .files
3528
        .contains_key("libs/lib"));
4dee277c Andy McCall ↶ 3529
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
75167672 Andy McCall 3530
    assert!(
3531
        !clone.snapshot("status").unwrap().changed,
3532
        "an unregistered nested repository is ignored"
3533
    );
4dee277c Andy McCall ↶ 3534
}
3535
3536
#[test]
3537
fn git_submodules_import_and_export_as_gitlinks() {
3538
    hermetic();
75167672 Andy McCall 3539
    if std::process::Command::new("git")
3540
        .arg("--version")
3541
        .output()
3542
        .is_err()
3543
    {
4dee277c Andy McCall ↶ 3544
        eprintln!("git not installed; skipping");
3545
        return;
3546
    }
3547
    let dir = tempfile::tempdir().unwrap();
3548
    let root = dir.path();
3549
    let git_in = |d: &Path, args: &[&str]| -> String {
3550
        let out = std::process::Command::new("git")
3551
            .arg("-C")
3552
            .arg(d)
75167672 Andy McCall 3553
            .args([
3554
                "-c",
3555
                "user.name=Grace",
3556
                "-c",
3557
                "[email protected]",
3558
                "-c",
3559
                "commit.gpgsign=false",
3560
                "-c",
3561
                "protocol.file.allow=always",
3562
            ])
4dee277c Andy McCall ↶ 3563
            .args(args)
3564
            .output()
3565
            .unwrap();
75167672 Andy McCall 3566
        assert!(
3567
            out.status.success(),
3568
            "git {args:?}: {}",
3569
            String::from_utf8_lossy(&out.stderr)
3570
        );
4dee277c Andy McCall ↶ 3571
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3572
    };
3573
    let sub = root.join("sub");
3574
    fs::create_dir_all(&sub).unwrap();
3575
    git_in(&sub, &["init", "-q", "-b", "main"]);
3576
    write(&sub, "s.txt", b"sub\n");
3577
    git_in(&sub, &["add", "."]);
3578
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3579
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3580
    let g = root.join("main.git");
3581
    fs::create_dir_all(&g).unwrap();
3582
    git_in(&g, &["init", "-q", "-b", "main"]);
3583
    write(&g, "README.md", b"# app\n");
3584
    git_in(&g, &["add", "."]);
3585
    git_in(&g, &["commit", "-q", "-m", "initial"]);
75167672 Andy McCall 3586
    git_in(
3587
        &g,
3588
        &[
3589
            "submodule",
3590
            "add",
3591
            "-q",
3592
            sub.to_str().unwrap(),
3593
            "vendor/sub",
3594
        ],
3595
    );
4dee277c Andy McCall ↶ 3596
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3597
3598
    let dest = root.join("oxy");
3599
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3600
    let rep = repo.import_git(&g, "main").unwrap();
3601
    assert_eq!((rep.commits, rep.submodules), (2, 1));
75167672 Andy McCall 3602
    let files = repo
3603
        .load_state(&repo.bookmark_heads().unwrap())
3604
        .unwrap()
3605
        .materialize()
3606
        .files;
4dee277c Andy McCall ↶ 3607
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
75167672 Andy McCall 3608
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3609
        panic!()
3610
    };
3611
    assert_eq!(
3612
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3613
        crate::subrepo::Pin::Git {
3614
            sha: sub_sha.clone(),
3615
            branch: "HEAD".into()
3616
        }
3617
    );
3618
    let modules =
3619
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4dee277c Andy McCall ↶ 3620
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3621
    assert!(modules.entries["vendor/sub"].git);
75167672 Andy McCall 3622
    assert!(
3623
        files.contains_key(".gitmodules"),
3624
        "the Git file is kept for round trips"
3625
    );
3626
    assert!(
3627
        !dest.join("vendor/sub/.git").exists(),
3628
        "not cloned until update --init"
3629
    );
4dee277c Andy McCall ↶ 3630
    assert!(!repo.snapshot("status").unwrap().changed);
3631
    // update --init clones it at the pinned commit; status is unchanged.
75167672 Andy McCall 3632
    assert_eq!(
3633
        repo.submodule_update(true, &[]).unwrap(),
3634
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3635
    );
3636
    assert_eq!(
3637
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3638
        sub_sha
3639
    );
4dee277c Andy McCall ↶ 3640
    assert!(!repo.snapshot("status").unwrap().changed);
3641
    // Export writes the gitlink and .gitmodules back.
3642
    let mirror = root.join("mirror.git");
3643
    let rep = repo.git_export(&mirror).unwrap();
3644
    assert_eq!(rep.skipped_subrepos, 0);
3645
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
75167672 Andy McCall 3646
    assert!(
3647
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3648
        "{ls}"
3649
    );
3650
    assert_eq!(
3651
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3652
        ".gitmodules\nREADME.md\nvendor"
3653
    );
4dee277c Andy McCall ↶ 3654
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
75167672 Andy McCall 3655
    assert_eq!(
3656
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3657
        orig_tree,
3658
        "tree round trip"
3659
    );
4dee277c Andy McCall ↶ 3660
}
3661
957fee30 Andy McCall ↶ 3662
#[test]
3663
fn partial_commits_by_path_and_by_hunk() {
3664
    hermetic();
3665
    let dir = tempfile::tempdir().unwrap();
3666
    let root = dir.path();
3667
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3668
    write(root, "a.txt", b"1\n2\n3\n");
3669
    write(root, "b.txt", b"b\n");
3670
    let h0 = repo.commit("base", &[]).unwrap();
3671
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3672
    write(root, "b.txt", b"b\nbb\n");
3673
    write(root, "c.txt", b"c\n");
3674
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
75167672 Andy McCall 3675
    let h1 = repo
3676
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3677
        .unwrap();
957fee30 Andy McCall ↶ 3678
    let c1 = repo.store().get_change(&h1).unwrap();
75167672 Andy McCall 3679
    assert!(
3680
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3681
        "{:?}",
3682
        c1.tree_ops
3683
    );
957fee30 Andy McCall ↶ 3684
    assert_eq!(c1.deps, vec![h0]);
3685
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
75167672 Andy McCall 3686
    assert!(
3687
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3688
    );
957fee30 Andy McCall ↶ 3689
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3690
    assert!(!files.contains_key("c.txt"));
3691
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3692
    assert_eq!(
3693
        snap.statuses
3694
            .iter()
3695
            .map(|s| (s.path.as_str(), s.status))
3696
            .collect::<Vec<_>>(),
3697
        vec![
3698
            ("b.txt", ChangeStatus::Modified),
3699
            ("c.txt", ChangeStatus::Added)
3700
        ]
3701
    );
3702
    assert_eq!(
3703
        fs::read(root.join("b.txt")).unwrap(),
3704
        b"b\nbb\n",
3705
        "disk untouched"
3706
    );
957fee30 Andy McCall ↶ 3707
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3708
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 3709
    let b_hunk = hunks
3710
        .iter()
3711
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3712
        .unwrap()
3713
        .index;
3714
    let h2 = repo
3715
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3716
        .unwrap();
957fee30 Andy McCall ↶ 3717
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 3718
    assert!(
3719
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3720
    );
957fee30 Andy McCall ↶ 3721
    assert!(!files.contains_key("c.txt"));
3722
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3723
    assert_eq!(
3724
        snap.statuses
3725
            .iter()
3726
            .map(|s| s.path.as_str())
3727
            .collect::<Vec<_>>(),
3728
        vec!["c.txt"]
3729
    );
957fee30 Andy McCall ↶ 3730
    // Choosing only the content hunk of a file in a new directory pulls in
3731
    // the directory and file additions it needs.
3732
    write(root, "d/e.txt", b"e\n");
3733
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 3734
    let e_insert = hunks
3735
        .iter()
3736
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3737
        .unwrap()
3738
        .index;
3739
    let h3 = repo
3740
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3741
        .unwrap();
957fee30 Andy McCall ↶ 3742
    let c3 = repo.store().get_change(&h3).unwrap();
3743
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3744
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3745
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
d8c086ca Andy McCall ↶ 3746
    // Choosing a new file's addition hunk brings its content along.
3747
    write(root, "f/g.txt", b"g\n");
3748
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 3749
    let g_add = hunks
3750
        .iter()
3751
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3752
        .unwrap()
3753
        .index;
3754
    let h4 = repo
3755
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3756
        .unwrap();
d8c086ca Andy McCall ↶ 3757
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
75167672 Andy McCall 3758
    assert!(
3759
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3760
    );
3761
    assert!(!repo
3762
        .snapshot("status")
3763
        .unwrap()
3764
        .statuses
3765
        .iter()
3766
        .any(|s| s.path == "f/g.txt"));
957fee30 Andy McCall ↶ 3767
    // Everything left commits normally; the working copy is then clean.
3768
    repo.commit("the rest", &[]).unwrap();
3769
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 3770
    let files = repo
3771
        .load_state(&repo.bookmark_heads().unwrap())
3772
        .unwrap()
3773
        .materialize()
3774
        .files;
957fee30 Andy McCall ↶ 3775
    assert!(files.contains_key("c.txt"));
3776
}
3777
3778
#[test]
3779
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3780
    hermetic();
3781
    let dir = tempfile::tempdir().unwrap();
3782
    let root = dir.path();
3783
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3784
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3785
        .unwrap();
957fee30 Andy McCall ↶ 3786
    write(root, "a.txt", b"one\n");
3787
    let h1 = repo.commit("first", &[]).unwrap();
3788
    write(root, "a.txt", b"one\ntwo\n");
3789
    let h2 = repo.commit("second", &[]).unwrap();
3790
    let b = repo.blame("a.txt").unwrap();
75167672 Andy McCall 3791
    assert_eq!(
3792
        b.iter()
3793
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3794
            .collect::<Vec<_>>(),
3795
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3796
    );
957fee30 Andy McCall ↶ 3797
    assert!(b.iter().all(|l| l.author == "Ada"));
75167672 Andy McCall 3798
    assert_eq!(
3799
        b[0].change_id,
3800
        repo.store().get_change(&h1).unwrap().change_id
3801
    );
957fee30 Andy McCall ↶ 3802
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3803
    repo.commit("rename", &[]).unwrap();
3804
    let b = repo.blame("b.txt").unwrap();
75167672 Andy McCall 3805
    assert_eq!(
3806
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3807
        vec![h1, h2],
3808
        "the node survives the rename"
3809
    );
957fee30 Andy McCall ↶ 3810
    assert!(repo.blame("a.txt").is_err());
3811
}
3812
3813
#[test]
3814
fn bisect_finds_the_first_bad_change() {
3815
    hermetic();
3816
    let dir = tempfile::tempdir().unwrap();
3817
    let root = dir.path();
3818
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3819
    let mut content = String::new();
3820
    let mut hashes = Vec::new();
3821
    for i in 1..=8 {
3822
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3823
        write(root, "f.txt", content.as_bytes());
3824
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3825
    }
3826
    // Each step appends after the previous line, so the chain is linear.
3827
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3828
    repo.bisect_start().unwrap();
75167672 Andy McCall 3829
    assert!(matches!(
3830
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3831
        BisectStep::NeedMarks { good: 1, bad: 0 }
3832
    ));
957fee30 Andy McCall ↶ 3833
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
75167672 Andy McCall 3834
    assert!(
3835
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3836
        "{step:?}"
3837
    );
957fee30 Andy McCall ↶ 3838
    // Automated: bad when the bug line is present.
75167672 Andy McCall 3839
    let step = repo
3840
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3841
        .unwrap();
957fee30 Andy McCall ↶ 3842
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
75167672 Andy McCall 3843
    assert_eq!(
3844
        repo.bisect_status().unwrap(),
3845
        Some(BisectStep::Found { culprit: hashes[4] })
3846
    );
957fee30 Andy McCall ↶ 3847
    repo.bisect_reset().unwrap();
3848
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3849
    assert!(repo.bisect_status().unwrap().is_none());
3850
    assert!(!repo.snapshot("status").unwrap().changed);
3851
    // Manual marks and a skip.
3852
    repo.bisect_start().unwrap();
3853
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3854
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3855
    let mut skipped_once = false;
3856
    let mut guard = 0;
3857
    while let BisectStep::Testing { .. } = step {
3858
        guard += 1;
3859
        assert!(guard < 20);
3860
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3861
        if !skipped_once && text.contains("line 6") {
3862
            // An untestable state away from the boundary: the search routes around it.
3863
            skipped_once = true;
3864
            step = repo.bisect_mark(None, &[]).unwrap();
3865
            continue;
3866
        }
3867
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3868
    }
3869
    assert!(skipped_once);
3870
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3871
    repo.bisect_reset().unwrap();
3872
    // Skipping the culprit itself leaves it among the candidates reported.
3873
    repo.bisect_start().unwrap();
3874
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3875
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3876
    let mut guard = 0;
3877
    while let BisectStep::Testing { heads, .. } = &step {
3878
        guard += 1;
3879
        assert!(guard < 20);
3880
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 3881
        let is_culprit_state =
3882
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3883
        step = if is_culprit_state {
3884
            repo.bisect_mark(None, &[]).unwrap()
3885
        } else {
3886
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3887
        };
957fee30 Andy McCall ↶ 3888
    }
3889
    match step {
75167672 Andy McCall 3890
        BisectStep::Inconclusive { candidates } => assert!(
3891
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3892
            "{candidates:?}"
3893
        ),
957fee30 Andy McCall ↶ 3894
        other => panic!("{other:?}"),
3895
    }
3896
    repo.bisect_reset().unwrap();
3897
}
3898
728da0f9 Andy McCall ↶ 3899
#[test]
3900
fn squash_folds_a_change_into_its_dependency() {
3901
    hermetic();
3902
    let dir = tempfile::tempdir().unwrap();
3903
    let root = dir.path();
3904
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3905
    write(root, "a.txt", b"1\n");
3906
    let a = repo.commit("A", &[]).unwrap();
3907
    write(root, "a.txt", b"1\n2\n");
3908
    let c = repo.commit("C", &[]).unwrap();
3909
    write(root, "a.txt", b"1\n2\n3\n");
3910
    let e = repo.commit("E", &[]).unwrap();
3911
    write(root, "b.txt", b"b\n");
3912
    let b = repo.commit("B", &[]).unwrap();
3913
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3914
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3915
    // E depends on C which A lacks: refused, naming it.
3916
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3917
    assert!(err.contains(&c.short(12)), "{err}");
3918
    // C into A: A' has both, C is gone, E follows and still reads the same.
3919
    let a2 = repo.squash(&c, &a).unwrap();
3920
    let a2c = repo.store().get_change(&a2).unwrap();
3921
    assert_eq!(a2c.change_id, id_a);
3922
    assert!(a2c.deps.is_empty());
3923
    let heads = repo.bookmark_heads().unwrap();
3924
    let st = repo.load_state(&heads).unwrap();
3925
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
75167672 Andy McCall 3926
    let e2 = st
3927
        .changes()
3928
        .find(|(_, m)| m.change_id == id_e)
3929
        .map(|(h, _)| *h)
3930
        .unwrap();
3931
    assert_eq!(
3932
        repo.store().get_change(&e2).unwrap().deps,
3933
        vec![a2],
3934
        "E now depends on A' alone"
3935
    );
728da0f9 Andy McCall ↶ 3936
    let files = st.materialize().files;
75167672 Andy McCall 3937
    assert!(
3938
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3939
    );
728da0f9 Andy McCall ↶ 3940
    assert!(files.contains_key("b.txt"));
3941
    assert!(st.contains(&b));
3942
    assert!(!repo.snapshot("status").unwrap().changed);
3943
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3944
    // Undo restores the three original changes.
3945
    repo.undo().unwrap();
3946
    repo.undo().unwrap();
3947
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3948
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3949
}
3950
3951
#[test]
3952
fn rebase_re_expresses_a_change_against_another_base() {
3953
    hermetic();
3954
    let dir = tempfile::tempdir().unwrap();
3955
    let root = dir.path();
3956
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3957
    write(root, "a.txt", b"1\n2\n");
3958
    let a = repo.commit("A", &[]).unwrap();
3959
    write(root, "a.txt", b"1\n2\n3\n");
3960
    let c = repo.commit("C: append 3", &[]).unwrap();
3961
    write(root, "a.txt", b"1\n2\n3\n4\n");
3962
    let e = repo.commit("E: append 4", &[]).unwrap();
3963
    // A different base: A plus a change that prepends a line.
3964
    repo.checkout(&[a], true, "checkout").unwrap();
3965
    write(root, "a.txt", b"0\n1\n2\n");
3966
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3967
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3968
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3969
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3970
    let c2 = repo.rebase(&c, &[d]).unwrap();
3971
    let c2c = repo.store().get_change(&c2).unwrap();
3972
    assert_eq!(c2c.change_id, id_c);
3973
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3974
    let heads = repo.bookmark_heads().unwrap();
3975
    let st = repo.load_state(&heads).unwrap();
3976
    assert!(!st.contains(&c) && st.contains(&d));
75167672 Andy McCall 3977
    let e2 = st
3978
        .changes()
3979
        .find(|(_, m)| m.change_id == id_e)
3980
        .map(|(h, _)| *h)
3981
        .unwrap();
728da0f9 Andy McCall ↶ 3982
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
75167672 Andy McCall 3983
    assert!(
3984
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3985
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3986
    );
728da0f9 Andy McCall ↶ 3987
    let files = st.materialize().files;
75167672 Andy McCall 3988
    assert!(
3989
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3990
        "{:?}",
3991
        files["a.txt"].content
3992
    );
728da0f9 Andy McCall ↶ 3993
    assert!(!files["a.txt"].is_conflicted());
3994
    // Rebasing onto a state that already contains the change is refused.
3995
    assert!(repo.rebase(&c2, &[c2]).is_err());
3996
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
75167672 Andy McCall 3997
    assert!(
3998
        err.contains("lacks dependencies"),
3999
        "E needs C, which D's state does not have: {err}"
4000
    );
728da0f9 Andy McCall ↶ 4001
}
4002
c792033a Andy McCall ↶ 4003
#[test]
4004
fn unsigned_tags_keep_their_message() {
4005
    hermetic();
4006
    let dir = tempfile::tempdir().unwrap();
4007
    let root = dir.path();
4008
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4009
    write(root, "a.txt", b"a\n");
4010
    repo.commit("a", &[]).unwrap();
4011
    assert!(repo.secret_key().unwrap().is_none());
75167672 Andy McCall 4012
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4013
        .unwrap();
c792033a Andy McCall ↶ 4014
    let tags = repo.tags().unwrap();
75167672 Andy McCall 4015
    assert_eq!(
4016
        (
4017
            tags[0].name.as_str(),
4018
            tags[0].message.as_str(),
4019
            tags[0].signer.as_deref()
4020
        ),
4021
        ("v1", "first release", None)
4022
    );
4023
    assert!(
4024
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4025
        "an unsigned attestation is not advertised"
4026
    );
c792033a Andy McCall ↶ 4027
}
387335ff Andy McCall ↶ 4028
4029
#[test]
4030
fn fsck_passes_a_sound_repository_and_names_each_fault() {
64818938 Andy McCall ↶ 4031
    // Files on disk are what this tests: tampering with them, and the
4032
    // directory store's crash points.
4033
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4034
        return;
4035
    }
387335ff Andy McCall ↶ 4036
    hermetic();
4037
    let dir = tempfile::tempdir().unwrap();
4038
    let root = dir.path();
4039
    let origin_path = root.join("origin");
4040
    let origin = Repo::init(&origin_path).unwrap();
4041
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4042
        .unwrap()
4043
        .with_home(root.join("home-a"));
4044
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4045
        .unwrap();
4046
    write(&root.join("a"), "f.txt", b"one\n");
4047
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4048
    let h1 = a.commit("first", &[]).unwrap();
4049
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4050
    let h2 = a.commit("second", &[]).unwrap();
4051
    a.tag_create("v1", &[h2], "first release").unwrap();
4052
    a.checkpoint().unwrap();
4053
    assert!(a.push("origin", false).unwrap()[0].ok);
4054
4055
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4056
    for repo in [&a, &origin] {
4057
        let rep = repo.fsck().unwrap();
4058
        assert_eq!(rep.problems, vec![], "{rep:?}");
4059
        // The two commits, plus the working copy's change in `a`.
4060
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4061
        assert!(rep.ops > 1 && rep.objects > 5);
4062
    }
4063
    assert!(origin.fsck().unwrap().attestations >= 1);
4064
4065
    // A flipped byte in a stored object is corruption, named by hash.
4066
    let c1 = a.store().path_for(&h1);
4067
    let pristine = fs::read(&c1).unwrap();
4068
    let mut bytes = pristine.clone();
4069
    *bytes.last_mut().unwrap() ^= 1;
4070
    fs::write(&c1, &bytes).unwrap();
4071
    let rep = a.fsck().unwrap();
4072
    assert!(rep.errors() >= 1);
4073
    assert!(
4074
        rep.problems
4075
            .iter()
4076
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4077
        "{rep:?}"
4078
    );
4079
    fs::write(&c1, &pristine).unwrap();
4080
    assert_eq!(a.fsck().unwrap().errors(), 0);
4081
4082
    // A missing change is named with what needed it.
4083
    fs::remove_file(&c1).unwrap();
4084
    let rep = a.fsck().unwrap();
4085
    assert!(
4086
        rep.problems.iter().any(|p| p.severity == Severity::Error
4087
            && p.object == Some(h1)
4088
            && p.what.contains("change missing, needed by change")),
4089
        "{rep:?}"
4090
    );
4091
    fs::write(&c1, &pristine).unwrap();
4092
4093
    // A missing blob is an error in a full clone.
4094
    let c2 = a.store().get_change(&h1).unwrap();
4095
    let blob = c2
4096
        .edits
4097
        .iter()
4098
        .find_map(|e| match e {
4099
            Edit::Replace { new: Some(b), .. } => Some(*b),
4100
            _ => None,
4101
        })
4102
        .expect("the binary file is a blob");
4103
    let bp = a.store().path_for(&blob);
4104
    let blob_bytes = fs::read(&bp).unwrap();
4105
    fs::remove_file(&bp).unwrap();
4106
    let rep = a.fsck().unwrap();
4107
    assert!(
4108
        rep.problems
4109
            .iter()
4110
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4111
        "{rep:?}"
4112
    );
4113
    fs::write(&bp, &blob_bytes).unwrap();
4114
4115
    // A broken op log head is reported, not a crash.
4116
    let head = root.join("a/.oxy/ops/head");
4117
    let saved = fs::read(&head).unwrap();
4118
    fs::write(&head, b"not a hash").unwrap();
4119
    let rep = a.fsck().unwrap();
4120
    assert!(
4121
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4122
        "{rep:?}"
4123
    );
4124
    fs::write(&head, saved).unwrap();
4125
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4126
}
4dcb8c09 Andy McCall ↶ 4127
4128
/// Copy a directory tree (for restoring a pristine repository).
4129
fn copy_tree(from: &Path, to: &Path) {
4130
    fs::create_dir_all(to).unwrap();
4131
    for e in fs::read_dir(from).unwrap() {
4132
        let e = e.unwrap();
4133
        let target = to.join(e.file_name());
4134
        if e.file_type().unwrap().is_dir() {
4135
            copy_tree(&e.path(), &target);
4136
        } else {
4137
            fs::copy(e.path(), &target).unwrap();
4138
        }
4139
    }
4140
}
4141
4142
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4143
/// would, and check that both repositories still open, pass `fsck`, and
4144
/// accept the same operation again.
4145
#[test]
4146
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
64818938 Andy McCall ↶ 4147
    // Files on disk are what this tests: tampering with them, and the
4148
    // directory store's crash points.
4149
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4150
        return;
4151
    }
4dcb8c09 Andy McCall ↶ 4152
    use crate::durable::failpoint;
4153
    hermetic();
4154
    let dir = tempfile::tempdir().unwrap();
4155
    let pristine = dir.path().join("pristine");
4156
    let origin_path = pristine.join("origin");
4157
    Repo::init(&origin_path).unwrap();
4158
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4159
        .unwrap()
4160
        .with_home(dir.path().join("home"));
4161
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4162
        .unwrap();
4163
    write(&pristine.join("a"), "f.txt", b"one\n");
4164
    a.commit("first", &[]).unwrap();
4165
    assert!(a.push("origin", false).unwrap()[0].ok);
4166
    drop(a);
4167
4168
    type Op = fn(&Repo) -> Result<()>;
4169
    let edit_and_commit: Op = |r| {
4170
        write(r.root(), "f.txt", b"one\ntwo\n");
4171
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4172
        r.commit("second", &[]).map(|_| ())
4173
    };
4174
    let push: Op = |r| {
4175
        let res = r.push("origin", false)?;
4176
        if res.iter().all(|x| x.ok) {
4177
            Ok(())
4178
        } else {
4179
            Err(RepoError::Msg(format!("{res:?}")))
4180
        }
4181
    };
4182
4183
    for (name, prepare, op) in [
4184
        ("commit", None, edit_and_commit),
4185
        ("push", Some(edit_and_commit), push),
4186
    ] {
4187
        let mut steps = 0;
4188
        for n in 1.. {
4189
            let run = dir.path().join(format!("{name}-{n}"));
4190
            copy_tree(&pristine, &run);
4191
            // Clones record their remote by path; point it at this copy.
4192
            let open = |p: &Path| {
4193
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4194
                r.config
4195
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4196
                    .unwrap();
4197
                r.save_config().unwrap();
4198
                r
4199
            };
4200
            let a = open(&run.join("a"));
4201
            if let Some(prep) = prepare {
4202
                prep(&a).unwrap();
4203
            }
4204
            failpoint::crash_after(n);
4205
            let outcome = op(&a);
4206
            let crashed = failpoint::disarm();
4207
            drop(a);
4208
            if !crashed {
4209
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4210
                steps = n - 1;
4211
                break;
4212
            }
4213
            assert!(
4214
                outcome.is_err(),
4215
                "{name}: a crash at step {n} was swallowed"
4216
            );
4217
            for repo in ["a", "origin"] {
4218
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4219
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4220
                });
4221
                let rep = r.fsck().unwrap();
4222
                assert_eq!(
4223
                    rep.errors(),
4224
                    0,
4225
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4226
                    rep.problems
4227
                );
4228
            }
4229
            // The interrupted operation can simply be run again.
4230
            let a = open(&run.join("a"));
4231
            // A crash after the commit point leaves the commit done.
4232
            let landed = a
4233
                .bookmark_heads()
4234
                .unwrap()
4235
                .iter()
4236
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4237
            let again = match (name, landed) {
4238
                ("commit", true) => Ok(()),
4239
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4240
                _ => op(&a),
4241
            };
4242
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4243
            assert_eq!(a.fsck().unwrap().errors(), 0);
4244
            fs::remove_dir_all(&run).unwrap();
4245
        }
4246
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4247
    }
4248
}
19555025 Andy McCall ↶ 4249
4250
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4251
/// running at the same time lose nothing: every commit ends up on the
4252
/// bookmark, locally and on the remote, and the repository passes fsck.
4253
#[test]
4254
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4255
    hermetic();
4256
    let dir = tempfile::tempdir().unwrap();
4257
    let root = dir.path();
4258
    let origin = root.join("origin");
4259
    Repo::init_bare_unbound(&origin).unwrap();
4260
    let main = root.join("main");
4261
    let mut repo = Repo::init(&main).unwrap();
4262
    repo.config
4263
        .set("remote.origin.url", &origin.to_string_lossy())
4264
        .unwrap();
4265
    repo.save_config().unwrap();
4266
    write(&main, "seed.txt", b"seed\n");
4267
    repo.commit("seed", &[]).unwrap();
4268
    let second = root.join("second");
4269
    repo.workspace_add(&second, None).unwrap();
4270
    drop(repo);
4271
4272
    const EACH: usize = 15;
4273
    std::thread::scope(|s| {
4274
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4275
            s.spawn(move || {
4276
                let r = Repo::open(&dir).unwrap();
4277
                for i in 0..EACH {
4278
                    write(
4279
                        &dir,
4280
                        &format!("{tag}-{i}.txt"),
4281
                        format!("{tag} {i}\n").as_bytes(),
4282
                    );
4283
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4284
                    if push && i % 5 == 4 {
4285
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4286
                        let _ = r.push("origin", false);
4287
                    }
4288
                }
4289
            });
4290
        }
4291
    });
4292
4293
    let repo = Repo::open(&main).unwrap();
4294
    let heads = repo.bookmark_heads().unwrap();
4295
    let state = repo.load_state(&heads).unwrap();
4296
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4297
    for tag in ["a", "b"] {
4298
        for i in 0..EACH {
4299
            assert!(
4300
                messages.contains(&format!("{tag} {i}")),
4301
                "lost commit {tag} {i}; have {messages:?}"
4302
            );
4303
        }
4304
    }
4305
    let rep = repo.fsck().unwrap();
4306
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4307
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4308
    let hosted = Repo::open(&origin).unwrap();
4309
    let hosted_heads = hosted.bookmark_heads().unwrap();
4310
    assert_eq!(
4311
        hosted.load_state(&hosted_heads).unwrap().len(),
4312
        state.len(),
4313
        "the remote has every commit"
4314
    );
4315
}
4316
4317
/// Two operations recorded from the same parent (what two processes do
4318
/// when they race) are merged: both bookmarks' heads survive, and a
4319
/// change made on one side only is kept.
4320
#[test]
4321
fn operations_from_the_same_parent_are_merged() {
4322
    hermetic();
4323
    let dir = tempfile::tempdir().unwrap();
4324
    let root = dir.path();
4325
    let repo = Repo::init(root).unwrap();
4326
    write(root, "a.txt", b"a\n");
4327
    let a = repo.commit("a", &[]).unwrap();
4328
    write(root, "b.txt", b"b\n");
4329
    let b = repo.commit("b", &[]).unwrap();
4330
    let (x, op) = repo.head_op().unwrap();
4331
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4332
4333
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4334
    let mut one = op.view.clone();
4335
    one.bookmarks.insert("main".into(), state(vec![a]));
4336
    one.bookmarks.insert("topic".into(), state(vec![a]));
4337
    let mut two = op.view.clone();
4338
    two.bookmarks.insert("main".into(), state(vec![b]));
4339
    repo.record_op(&[x], "one", one).unwrap();
4340
    let merged = repo.record_op(&[x], "two", two).unwrap();
4341
4342
    let (head, op) = repo.head_op().unwrap();
4343
    assert_eq!(head, merged);
4344
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4345
    assert!(op.command.contains("merged with a concurrent operation"));
4346
    let mut main = repo
4347
        .store()
4348
        .get_state(&op.view.bookmarks["main"])
4349
        .unwrap()
4350
        .heads;
4351
    main.sort();
4352
    let mut want = vec![a, b];
4353
    want.sort();
4354
    assert_eq!(main, want, "both sides' heads are kept");
4355
    assert!(
4356
        op.view.bookmarks.contains_key("topic"),
4357
        "a one-sided change survives"
4358
    );
4359
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4360
}
3e5772cc Andy McCall ↶ 4361
4362
#[test]
4363
fn failed_requests_come_with_a_next_step() {
4364
    use crate::protocol::hint_for;
4365
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4366
        .unwrap()
4367
        .contains("token"));
4368
    assert!(hint_for("…: HTTP 403: forbidden")
4369
        .unwrap()
4370
        .contains("repo:write"));
4371
    assert!(hint_for("…: HTTP 404: no such repository")
4372
        .unwrap()
4373
        .contains("owner and repository name"));
4374
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4375
        .unwrap()
4376
        .contains("oxyhub-ca.pem"));
4377
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4378
        .unwrap()
4379
        .contains("running"));
4380
    assert!(hint_for("Dns Failed: failed to lookup address information")
4381
        .unwrap()
4382
        .contains("resolve"));
4383
    assert_eq!(hint_for("something else entirely"), None);
4384
}
4385
4386
#[test]
4387
fn doctor_names_problems_and_what_to_do() {
4388
    hermetic();
4389
    let dir = tempfile::tempdir().unwrap();
4390
    let root = dir.path();
4391
    let origin = root.join("origin");
4392
    Repo::init_bare_unbound(&origin).unwrap();
4393
    let mut repo = Repo::init(&root.join("r"))
4394
        .unwrap()
4395
        .with_home(root.join("home"));
4396
    let find = |r: &DoctorReport, area: &str, h: Health| {
4397
        r.checks
4398
            .iter()
4399
            .find(|c| c.area == area && c.health == h)
4400
            .cloned()
4401
    };
4402
4403
    let r = repo.doctor(true);
4404
    assert!(find(&r, "identity", Health::Warn)
4405
        .unwrap()
4406
        .hint
4407
        .unwrap()
4408
        .contains("oxy identity create"));
4409
    assert!(find(&r, "repository", Health::Ok).is_some());
4410
4411
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4412
        .unwrap();
4413
    repo.config.set("author.name", "Ada").unwrap();
4414
    repo.config.set("author.email", "[email protected]").unwrap();
4415
    repo.config
4416
        .set("remote.origin.url", &origin.to_string_lossy())
4417
        .unwrap();
4418
    repo.config
4419
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4420
        .unwrap();
4421
    repo.config.set("remote.down.token", "t").unwrap();
4422
    repo.config
4423
        .set("remote.badca.url", "https://example.invalid/a/b")
4424
        .unwrap();
4425
    repo.config
4426
        .set(
4427
            "remote.badca.ca",
4428
            &root.join("missing.pem").to_string_lossy(),
4429
        )
4430
        .unwrap();
4431
    repo.save_config().unwrap();
4432
4433
    let r = repo.doctor(true);
4434
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4435
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4436
    assert!(find(&r, "remote origin", Health::Ok)
4437
        .unwrap()
4438
        .message
4439
        .contains("first push binds it"));
4440
    let down = find(&r, "remote down", Health::Fail).unwrap();
4441
    assert!(
4442
        down.hint.as_deref().unwrap_or("").contains("running"),
4443
        "{down:?}"
4444
    );
4445
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4446
    assert!(
4447
        badca.hint.unwrap().contains("remote.badca.ca"),
4448
        "the remote's own name is in the hint"
4449
    );
4450
    assert_eq!(r.worst(), Health::Fail);
4451
4452
    // Offline, nothing is contacted.
4453
    let r = repo.doctor(false);
4454
    assert!(find(&r, "remote down", Health::Fail).is_none());
4455
    assert!(find(&r, "remote down", Health::Ok)
4456
        .unwrap()
4457
        .message
4458
        .contains("not contacted"));
4459
}
62794ecc Andy McCall ↶ 4460
4461
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4462
/// after it. Inserting after `b` and then deleting `b`, one commit after
4463
/// the other, must not leave a delete/insert conflict.
4464
#[test]
4465
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4466
    hermetic();
4467
    let dir = tempfile::tempdir().unwrap();
4468
    let root = dir.path();
4469
    let repo = Repo::init(root).unwrap();
4470
    write(root, "f", b"a\nb\nc\n");
4471
    repo.commit("base", &[]).unwrap();
4472
    write(root, "f", b"a\nb\nx\nc\n");
4473
    let insert = repo.commit("insert x after b", &[]).unwrap();
4474
    write(root, "f", b"a\nx\nc\n");
4475
    let delete = repo.commit("delete b", &[]).unwrap();
4476
    assert!(
4477
        repo.store()
4478
            .get_change(&delete)
4479
            .unwrap()
4480
            .deps
4481
            .contains(&insert),
4482
        "the deletion depends on the insertion below the deleted line"
4483
    );
4484
    let heads = repo.bookmark_heads().unwrap();
4485
    assert_eq!(heads, vec![delete]);
4486
    let snap = repo.load_state(&heads).unwrap().materialize();
4487
    assert!(!snap.is_conflicted());
4488
    assert!(
4489
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4490
    );
4491
}
4492
4493
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4494
/// replacement depends on the change that set the blob it replaces.
4495
#[test]
4496
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4497
    hermetic();
4498
    let dir = tempfile::tempdir().unwrap();
4499
    let root = dir.path();
4500
    let repo = Repo::init(root).unwrap();
4501
    write(root, "bin", b"\0A");
4502
    let v1 = repo.commit("v1", &[]).unwrap();
4503
    write(root, "bin", b"\0B");
4504
    let v2 = repo.commit("v2", &[]).unwrap();
4505
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4506
    write(root, "bin", b"\0A");
4507
    let v3 = repo.commit("back to A", &[]).unwrap();
4508
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4509
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4510
    let state = repo.load_state(&[v3]).unwrap();
4511
    let snap = state.materialize();
4512
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4513
        panic!("opaque")
4514
    };
4515
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4516
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4517
}
4518
4519
/// Spec §23: a binary file changed on two branches and merged in Git to
4520
/// one side's version comes back as that version at the merge, and the
4521
/// import verifies commit by commit.
4522
#[test]
4523
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4524
    hermetic();
4525
    if std::process::Command::new("git")
4526
        .arg("--version")
4527
        .output()
4528
        .is_err()
4529
    {
4530
        eprintln!("git not installed; skipping");
4531
        return;
4532
    }
4533
    let dir = tempfile::tempdir().unwrap();
4534
    let root = dir.path();
4535
    let g = root.join("src.git");
4536
    fs::create_dir_all(&g).unwrap();
4537
    let git = |args: &[&str]| -> String {
4538
        let out = std::process::Command::new("git")
4539
            .arg("-C")
4540
            .arg(&g)
4541
            .args([
4542
                "-c",
4543
                "user.name=Grace",
4544
                "-c",
4545
                "[email protected]",
4546
                "-c",
4547
                "commit.gpgsign=false",
4548
            ])
4549
            .args(args)
4550
            .output()
4551
            .unwrap();
4552
        assert!(
4553
            out.status.success(),
4554
            "git {args:?}: {}",
4555
            String::from_utf8_lossy(&out.stderr)
4556
        );
4557
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4558
    };
4559
    git(&["init", "-q", "-b", "main"]);
4560
    write(&g, "logo.bin", b"\0base");
4561
    write(&g, "notes.txt", b"a\nb\nc\n");
4562
    git(&["add", "."]);
4563
    git(&["commit", "-qm", "base"]);
4564
    git(&["checkout", "-qb", "side"]);
4565
    write(&g, "logo.bin", b"\0side");
4566
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4567
    git(&["commit", "-qam", "side"]);
4568
    git(&["checkout", "-q", "main"]);
4569
    write(&g, "logo.bin", b"\0main");
4570
    git(&["commit", "-qam", "main"]);
4571
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4572
    let _ = std::process::Command::new("git")
4573
        .arg("-C")
4574
        .arg(&g)
4575
        .args([
4576
            "-c",
4577
            "user.name=G",
4578
            "-c",
4579
            "user.email=g@e",
4580
            "merge",
4581
            "-q",
4582
            "side",
4583
        ])
4584
        .output();
4585
    write(&g, "logo.bin", b"\0main");
4586
    git(&["add", "."]);
4587
    git(&["commit", "-qm", "merge side"]);
4588
    // Then a revert of the binary to its first version.
4589
    write(&g, "logo.bin", b"\0base");
4590
    git(&["commit", "-qam", "back to base"]);
4591
4592
    let repo = Repo::init(&root.join("o")).unwrap();
4593
    let rep = repo.import_git(&g, "main").unwrap();
4594
    assert_eq!(rep.merges, 1);
4595
    let v = repo.verify_git_import(&g, "main").unwrap();
4596
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4597
    assert_eq!(v.commits, 5);
4598
    let snap = repo
4599
        .load_state(&repo.bookmark_heads().unwrap())
4600
        .unwrap()
4601
        .materialize();
4602
    assert!(!snap.is_conflicted());
4603
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4604
        panic!("opaque")
4605
    };
4606
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4607
}
c863c7a7 Andy McCall ↶ 4608
4609
/// Spec §7.7 on a file system without executable bits or symlinks: the
4610
/// recorded bit is kept, and a symlink checked out as a plain file holding
4611
/// its target is still that symlink.
4612
#[cfg(unix)]
4613
#[test]
4614
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4615
    use crate::portable::Platform;
4616
    use std::os::unix::fs::PermissionsExt;
4617
    hermetic();
4618
    let dir = tempfile::tempdir().unwrap();
4619
    let root = dir.path();
4620
    let repo = Repo::init(root).unwrap();
4621
    write(root, "run.sh", b"#!/bin/sh\n");
4622
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4623
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4624
    repo.commit("script and link", &[]).unwrap();
4625
    drop(repo);
4626
4627
    // What checking out on Windows leaves: no exec bit, the link as a file.
4628
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4629
    fs::remove_file(root.join("link")).unwrap();
4630
    write(root, "link", b"run.sh");
4631
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4632
    let s = win.snapshot("oxy status").unwrap();
4633
    assert!(
4634
        s.statuses.is_empty(),
4635
        "nothing changed on Windows: {:?}",
4636
        statuses(&s)
4637
    );
4638
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4639
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4640
    write(root, "link", b"other");
4641
    let h = win.commit("edit on Windows", &[]).unwrap();
4642
    let snap = win.load_state(&[h]).unwrap().materialize();
4643
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4644
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4645
    // The same working copy read as Linux sees the lost bit and the plain file.
4646
    let linux = Repo::open(root).unwrap();
4647
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4648
}
4649
4650
/// Paths that collide on case-insensitive or Windows file systems are
4651
/// named at checkout there, and by doctor everywhere.
4652
#[test]
4653
fn paths_other_platforms_cannot_hold_are_reported() {
4654
    use crate::portable::Platform;
4655
    hermetic();
4656
    let dir = tempfile::tempdir().unwrap();
4657
    let root = dir.path();
4658
    let repo = Repo::init(root).unwrap();
4659
    write(root, "README.md", b"a\n");
4660
    write(root, "readme.md", b"b\n");
4661
    write(root, "src/aux.c", b"int x;\n");
4662
    let h = repo.commit("unportable", &[]).unwrap();
4663
    let r = repo.doctor(false);
4664
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4665
    assert_eq!(port.health, Health::Warn);
4666
    assert!(
4667
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4668
        "{}",
4669
        port.message
4670
    );
4671
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4672
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4673
    assert!(
4674
        rep.notes
4675
            .iter()
4676
            .any(|n| n.contains("README.md and readme.md")),
4677
        "{:?}",
4678
        rep.notes
4679
    );
4680
    assert!(
4681
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4682
        "macOS allows aux.c"
4683
    );
4684
}
bc489b6c Andy McCall ↶ 4685
4686
#[test]
4687
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4688
    hermetic();
4689
    let dir = tempfile::tempdir().unwrap();
4690
    let repo = Repo::init(dir.path()).unwrap();
4691
    write(dir.path(), "a.txt", b"one\n");
4692
    write(dir.path(), "other.txt", b"x\n");
4693
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4694
    repo.snapshot("t").unwrap();
4695
    let c1 = repo.commit("first", &[]).unwrap();
4696
    write(dir.path(), "other.txt", b"y\n");
4697
    repo.snapshot("t").unwrap();
4698
    repo.commit("other only", &[]).unwrap();
4699
    write(dir.path(), "a.txt", b"one\ntwo\n");
4700
    repo.snapshot("t").unwrap();
4701
    let c3 = repo.commit("second line", &[]).unwrap();
4702
    write(dir.path(), "other.txt", b"z\n");
4703
    repo.snapshot("t").unwrap();
4704
    repo.commit("other again", &[]).unwrap();
4705
4706
    let heads = repo.bookmark_heads().unwrap();
4707
    let state = repo.load_state(&heads).unwrap();
4708
    let full: Vec<ChangeHash> = repo
4709
        .log_for_path_in("a.txt", &heads)
4710
        .unwrap()
4711
        .iter()
4712
        .map(|e| e.hash)
4713
        .collect();
4714
    assert_eq!(
4715
        full,
4716
        vec![c3, c1],
4717
        "newest first, only changes touching the path"
4718
    );
4719
    let newest: Vec<ChangeHash> = repo
4720
        .log_for_path_of(&state, "a.txt", Some(1))
4721
        .unwrap()
4722
        .iter()
4723
        .map(|e| e.hash)
4724
        .collect();
4725
    assert_eq!(newest, vec![c3], "stops at the first");
4726
    assert_eq!(
4727
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4728
        2
4729
    );
4730
    assert!(repo
4731
        .log_for_path_of(&state, "missing.txt", Some(1))
4732
        .is_err());
4733
    assert_eq!(
4734
        repo.log_state(&heads).unwrap().len(),
4735
        repo.log_of(&state).len()
4736
    );
4737
4738
    let tree = state.tree().view();
4739
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4740
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4741
    assert_eq!(
4742
        via_state
4743
            .iter()
4744
            .map(|l| (l.hash, l.text.clone()))
4745
            .collect::<Vec<_>>(),
4746
        via_heads
4747
            .iter()
4748
            .map(|l| (l.hash, l.text.clone()))
4749
            .collect::<Vec<_>>()
4750
    );
4751
    assert_eq!(
4752
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4753
        vec![c1, c3]
4754
    );
4755
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4756
}
696bbf29 Andy McCall ↶ 4757
4758
/// A text file whose stat matches the manifest and whose recorded hash is
4759
/// the base's content is taken from the base without reading it; anything
4760
/// else is read, so no edit is missed (spec §12.3).
4761
#[cfg(unix)]
4762
#[test]
4763
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4764
    use std::os::unix::fs::PermissionsExt;
4765
    hermetic();
4766
    let dir = tempfile::tempdir().unwrap();
4767
    let root = dir.path();
4768
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4769
    write(root, "a.txt", b"one\ntwo\n");
4770
    write(root, "b.txt", b"bee\n");
4771
    repo.commit("base", &[]).unwrap();
4772
    let age = |p: &str| {
4773
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4774
        fs::File::options()
4775
            .write(true)
4776
            .open(root.join(p))
4777
            .unwrap()
4778
            .set_modified(old)
4779
            .unwrap();
4780
    };
4781
    age("a.txt");
4782
    age("b.txt");
4783
    assert!(
4784
        !repo.snapshot("status").unwrap().changed,
4785
        "records the aged stat"
4786
    );
4787
4788
    // Clean and equal to the base: not read at all.
4789
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4790
    let snap = repo.snapshot("status").unwrap();
4791
    assert!(
4792
        !snap.changed && snap.statuses.is_empty(),
4793
        "{:?}",
4794
        snap.statuses
4795
    );
4796
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4797
4798
    // An uncommitted edit that is older than the manifest: stat-clean, but
4799
    // its hash is not the base's, so it is read and stays visible.
4800
    write(root, "b.txt", b"bee edited\n");
4801
    age("b.txt");
4802
    let first = repo.snapshot("status").unwrap();
4803
    assert_eq!(
4804
        statuses(&first),
4805
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4806
    );
4807
    let again = repo.snapshot("status").unwrap();
4808
    assert_eq!(
4809
        statuses(&again),
4810
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4811
        "still seen once stat-clean"
4812
    );
4813
    assert!(!again.changed, "and the working copy hashes the same");
4814
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4815
    assert!(
4816
        repo.snapshot("status").is_err(),
4817
        "an edited file must be read, never taken from the base"
4818
    );
4819
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4820
4821
    // A same-size edit made just now is racy and read.
4822
    write(root, "a.txt", b"one\nTWO\n");
4823
    assert_eq!(
4824
        statuses(&repo.snapshot("status").unwrap()),
4825
        vec![
4826
            ("a.txt".to_string(), ChangeStatus::Modified),
4827
            ("b.txt".to_string(), ChangeStatus::Modified)
4828
        ]
4829
    );
4830
    // Committing makes the edits the base: both are clean and served from it again.
4831
    repo.commit("edits", &[]).unwrap();
4832
    age("a.txt");
4833
    age("b.txt");
4834
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4835
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4836
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4837
    let snap = repo.snapshot("status").unwrap();
4838
    assert!(!snap.changed && snap.statuses.is_empty());
4839
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4840
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4841
}
afaba5f1 Andy McCall ↶ 4842
4843
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4844
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4845
/// file is unchanged, and loading through the checkpoint equals a full load.
4846
#[test]
4847
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4848
    hermetic();
4849
    let dir = tempfile::tempdir().unwrap();
4850
    let root = dir.path();
4851
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4852
    let long: String = (0..300)
4853
        .map(|i| format!("line {i} of a long file\n"))
4854
        .collect();
4855
    write(root, "long.txt", long.as_bytes());
4856
    write(root, "short.txt", b"short\n");
4857
    repo.commit("base", &[]).unwrap();
4858
    let (r1, _, _) = repo.checkpoint().unwrap();
4859
    let cp1 = crate::objects::Checkpoint::decode(
4860
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4861
    )
4862
    .unwrap();
4863
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4864
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4865
4866
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4867
    repo.gc(true).unwrap();
4868
    assert!(repo.store().has(&graphs1[0]));
4869
    let report = repo.fsck().unwrap();
4870
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4871
4872
    // Loading through the checkpoint equals a full load.
4873
    write(root, "short.txt", b"short, edited\n");
4874
    repo.commit("edit the short file", &[]).unwrap();
4875
    let heads = repo.bookmark_heads().unwrap();
4876
    let fast = repo.load_state(&heads).unwrap();
4877
    let full = repo.load_state_full(&heads).unwrap();
4878
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4879
4880
    // The next checkpoint shares the unchanged long file's graph.
4881
    let (r2, _, _) = repo.checkpoint().unwrap();
4882
    let cp2 = crate::objects::Checkpoint::decode(
4883
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
4884
    )
4885
    .unwrap();
4886
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
4887
4888
    // A shallow clone's bundle carries the graph blob with the checkpoint.
4889
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
4890
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
4891
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
4892
4893
    // A version 1 checkpoint written by an older oxy still loads.
4894
    let state = repo.load_state_full(&heads).unwrap();
4895
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
4896
    let cp_old = crate::objects::Checkpoint {
4897
        heads: cp2.heads.clone(),
4898
        count: cp2.count,
4899
        payload: old,
4900
    };
4901
    let r_old = repo
4902
        .store()
4903
        .put(ObjectType::Checkpoint, &cp_old.encode())
4904
        .unwrap();
4905
    repo.install_checkpoint("main", &r_old).unwrap();
4906
    assert_eq!(
4907
        repo.load_state(&heads).unwrap().checkpoint_payload(),
4908
        full.checkpoint_payload()
4909
    );
4910
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4911
4912
    // A lost graph blob fails the load loudly rather than dropping the
4913
    // file, and fsck reports it (a fresh repository, objects still loose).
4914
    let dir2 = tempfile::tempdir().unwrap();
4915
    let root2 = dir2.path();
4916
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
4917
    write(root2, "long.txt", long.as_bytes());
4918
    repo2.commit("base", &[]).unwrap();
4919
    let (r, _, _) = repo2.checkpoint().unwrap();
4920
    let cp = crate::objects::Checkpoint::decode(
4921
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
4922
    )
4923
    .unwrap();
4924
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
64818938 Andy McCall ↶ 4925
    repo2.store().remove_loose_for_test(&graph).unwrap();
afaba5f1 Andy McCall ↶ 4926
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
4927
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
4928
}
e3d071ce Andy McCall ↶ 4929
4930
/// A new repository has not stored the user's identity yet (that happens
4931
/// at the first signed change); looking it up falls back to the key
4932
/// directory, and a file there that does not hash to the key is refused.
4933
#[test]
4934
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
4935
    hermetic();
4936
    let dir = tempfile::tempdir().unwrap();
4937
    let home = dir.path().join("home");
4938
    let mut first = Repo::init(&dir.path().join("a"))
4939
        .unwrap()
4940
        .with_home(home.clone());
4941
    let (key, _) = first
4942
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4943
        .unwrap();
4944
    let fresh = Repo::init(&dir.path().join("b"))
4945
        .unwrap()
4946
        .with_home(home.clone());
4947
    assert!(!fresh.store().has(&key), "nothing stored yet");
4948
    let id = fresh.identity(&key).unwrap();
4949
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
4950
    // A key file that is not this identity is an error, not a wrong answer.
4951
    let keys = fresh.keys_dir.clone();
4952
    let (other, _) = first
4953
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4954
        .unwrap();
4955
    fs::copy(
4956
        keys.join(format!("{}.identity", other.to_hex())),
4957
        keys.join(format!("{}.identity", key.to_hex())),
4958
    )
4959
    .unwrap();
4960
    assert!(fresh
4961
        .identity(&key)
4962
        .unwrap_err()
4963
        .to_string()
4964
        .contains("does not hold identity"));
4965
}
cc7a0056 Andy McCall ↶ 4966
4967
/// Status snapshots (spec §12.3): a text file whose stat matches the
4968
/// manifest, and whose base graph key is the one the manifest recorded it
4969
/// equal to, is neither read nor rendered; any edit, and any change to the
4970
/// file's graph in the base, brings it back.
4971
#[cfg(unix)]
4972
#[test]
4973
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
4974
    use std::os::unix::fs::PermissionsExt;
4975
    hermetic();
4976
    let dir = tempfile::tempdir().unwrap();
4977
    let root = dir.path();
4978
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4979
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
4980
        write(root, p, c.as_bytes());
4981
    }
4982
    repo.commit("base", &[]).unwrap();
4983
    let age = |p: &str| {
4984
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4985
        fs::File::options()
4986
            .write(true)
4987
            .open(root.join(p))
4988
            .unwrap()
4989
            .set_modified(old)
4990
            .unwrap();
4991
    };
4992
    let lock = |p: &str, mode: u32| {
4993
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
4994
    };
4995
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4996
        age(p);
4997
    }
4998
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4999
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5000
    assert!(
5001
        m.entries.values().all(|e| e.graph.is_some()),
5002
        "keys recorded"
5003
    );
5004
5005
    // Unreadable files prove they are not read; the status snapshot does
5006
    // not render them either, and its base lacks their graphs.
5007
    lock("a.txt", 0o000);
5008
    lock("b.txt", 0o000);
5009
    let snap = repo.snapshot_status("status").unwrap();
5010
    assert!(!snap.changed && snap.statuses.is_empty());
5011
    assert_eq!(
5012
        snap.base_snapshot
5013
            .unrendered
5014
            .iter()
5015
            .cloned()
5016
            .collect::<Vec<_>>(),
5017
        vec!["a.txt", "b.txt", "d/c.txt"]
5018
    );
5019
    assert!(!snap.base.is_full());
5020
    assert!(!snap.base_snapshot.is_conflicted());
5021
    // A full snapshot does not read them either, but renders everything.
5022
    let full = repo.snapshot("status").unwrap();
5023
    assert!(full.statuses.is_empty() && full.base.is_full());
5024
    assert!(full.base_snapshot.unrendered.is_empty());
5025
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5026
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5027
5028
    // An edit is seen; the file is rendered, the others still are not.
5029
    write(root, "d/c.txt", b"sea edited\n");
5030
    let snap = repo.snapshot_status("status").unwrap();
5031
    assert_eq!(
5032
        statuses(&snap),
5033
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5034
    );
5035
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5036
    // So is a mode change of an unread file.
5037
    lock("b.txt", 0o100);
5038
    assert_eq!(
5039
        statuses(&repo.snapshot_status("status").unwrap()),
5040
        vec![
5041
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5042
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5043
        ]
5044
    );
5045
    lock("b.txt", 0o000);
5046
5047
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5048
    // stays unread, c.txt is read once and then skipped too.
5049
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5050
        .unwrap();
5051
    age("d/c.txt");
5052
    let snap = repo.snapshot_status("status").unwrap();
5053
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5054
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5055
    lock("d/c.txt", 0o000);
5056
    let snap = repo.snapshot_status("status").unwrap();
5057
    assert!(snap.statuses.is_empty());
5058
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5059
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5060
        lock(p, 0o644);
5061
    }
5062
}
5063
5064
/// Attributes decide how a file compares with the base, so a changed
5065
/// `.oxyattributes` makes every text file be compared again.
5066
#[cfg(unix)]
5067
#[test]
5068
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5069
    hermetic();
5070
    let dir = tempfile::tempdir().unwrap();
5071
    let root = dir.path();
5072
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5073
    write(root, "a.txt", b"crlf\r\n");
5074
    repo.commit("base", &[]).unwrap();
5075
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5076
    fs::File::options()
5077
        .write(true)
5078
        .open(root.join("a.txt"))
5079
        .unwrap()
5080
        .set_modified(old)
5081
        .unwrap();
5082
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5083
    assert!(repo
5084
        .snapshot_status("status")
5085
        .unwrap()
5086
        .base_snapshot
5087
        .unrendered
5088
        .contains("a.txt"));
5089
    // With eol=lf, a.txt as stored no longer equals the base.
5090
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5091
    let snap = repo.snapshot_status("status").unwrap();
5092
    assert_eq!(
5093
        statuses(&snap),
5094
        vec![
5095
            (".oxyattributes".to_string(), ChangeStatus::Added),
5096
            ("a.txt".to_string(), ChangeStatus::Modified)
5097
        ]
5098
    );
5099
}
54cd08a1 Andy McCall ↶ 5100
5101
/// Bookmarks with `/` in their names: pushing records their
5102
/// attestations, and checkpoints are kept for them, beside `feature`
5103
/// itself.
5104
#[test]
5105
fn bookmarks_with_slashes_push_and_checkpoint() {
5106
    hermetic();
5107
    let dir = tempfile::tempdir().unwrap();
5108
    let root = dir.path();
5109
    let origin = Repo::init(&root.join("origin")).unwrap();
5110
    let url = root.join("origin").to_string_lossy().to_string();
5111
    let mut repo = Repo::clone(&url, &root.join("r"))
5112
        .unwrap()
5113
        .with_home(root.join("home"));
5114
    // With an identity, pushes carry reference attestations: the case
5115
    // that failed, since the attestation is a file named after the bookmark.
5116
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5117
        .unwrap();
5118
    let r = root.join("r");
5119
    write(&r, "a.txt", b"a\n");
5120
    let h_a = repo.commit("a", &[]).unwrap();
5121
    assert!(repo.push("origin", false).unwrap()[0].ok);
5122
    repo.bookmark_create("feature", None).unwrap();
5123
    repo.bookmark_create("feature/x", None).unwrap();
5124
    repo.bookmark_switch("feature/x", false).unwrap();
5125
    write(&r, "b.txt", b"b\n");
5126
    let h_b = repo.commit("b", &[]).unwrap();
5127
    for name in ["feature", "feature/x"] {
5128
        let res = repo.push_bookmark("origin", name, false).unwrap();
5129
        assert!(res[0].ok, "{name}: {res:?}");
5130
    }
5131
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5132
    assert_eq!(
5133
        origin.resolve_heads("feature/x").unwrap(),
5134
        repo.resolve_heads("feature/x").unwrap()
5135
    );
5136
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5137
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5138
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5139
5140
    // A checkpoint of feature/x is found again when loading its state.
5141
    let (cp, _, _) = repo.checkpoint().unwrap();
5142
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5143
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5144
    let heads = repo.resolve_heads("feature/x").unwrap();
5145
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
f8c69576 Andy McCall ↶ 5146
}
5147
5148
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5149
/// never the remote's own bookmark, and a bookmark created again later is
5150
/// accepted although the deletion's attestation stays the latest.
5151
#[test]
5152
fn bookmarks_are_deleted_on_a_remote() {
5153
    hermetic();
5154
    let dir = tempfile::tempdir().unwrap();
5155
    let root = dir.path();
5156
    let origin = Repo::init(&root.join("origin")).unwrap();
5157
    let url = root.join("origin").to_string_lossy().to_string();
5158
    let mut repo = Repo::clone(&url, &root.join("r"))
5159
        .unwrap()
5160
        .with_home(root.join("home"));
5161
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5162
        .unwrap();
5163
    let r = root.join("r");
5164
    write(&r, "a.txt", b"a\n");
5165
    repo.commit("a", &[]).unwrap();
5166
    assert!(repo.push("origin", false).unwrap()[0].ok);
5167
    repo.bookmark_create("feature/x", None).unwrap();
5168
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5169
    assert!(origin.resolve_heads("feature/x").is_ok());
5170
5171
    let res = repo.push_delete("origin", "feature/x").unwrap();
5172
    assert!(res[0].ok, "{res:?}");
5173
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5174
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5175
    assert!(
5176
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5177
        "the deletion is attested"
5178
    );
5179
    assert!(
5180
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5181
        "the local bookmark stays"
5182
    );
5183
    assert!(!repo
5184
        .view()
5185
        .unwrap()
5186
        .remotes
5187
        .get("origin")
5188
        .is_some_and(|m| m.contains_key("feature/x")));
5189
5190
    // Pushing it again creates it again, past the deletion's serial.
5191
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5192
    assert!(res[0].ok, "{res:?}");
5193
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5194
5195
    // Nothing to delete, and never the remote's own bookmark.
5196
    assert!(repo.push_delete("origin", "nope").is_err());
5197
    let res = repo.push_delete("origin", "main").unwrap();
5198
    assert!(
5199
        !res[0].ok && res[0].reason.contains("default bookmark"),
5200
        "{res:?}"
5201
    );
5202
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
54cd08a1 Andy McCall ↶ 5203
}
61e3bce7 Andy McCall ↶ 5204
5205
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5206
/// when the target has the same versions of the files it touches, and is
5207
/// refused, untouched, when it has others.
5208
#[test]
5209
fn switching_bookmarks_carries_uncommitted_work() {
5210
    hermetic();
5211
    let dir = tempfile::tempdir().unwrap();
5212
    let root = dir.path();
5213
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5214
    write(root, "a.txt", b"a\n");
5215
    write(root, "b.txt", b"b\n");
5216
    write(root, "gone.txt", b"gone\n");
5217
    repo.commit("base", &[]).unwrap();
5218
    repo.bookmark_create("feature", None).unwrap();
5219
    // Started on main, belongs on feature: edit, add, remove.
5220
    write(root, "a.txt", b"a\nmore\n");
5221
    write(root, "new.txt", b"new\n");
5222
    fs::remove_file(root.join("gone.txt")).unwrap();
5223
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5224
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5225
    assert_eq!(repo.config.bookmark, "feature");
5226
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5227
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5228
    assert!(!root.join("gone.txt").exists());
5229
    let snap = repo.snapshot("status").unwrap();
5230
    assert_eq!(
5231
        statuses(&snap),
5232
        vec![
5233
            ("a.txt".to_string(), ChangeStatus::Modified),
5234
            ("gone.txt".to_string(), ChangeStatus::Removed),
5235
            ("new.txt".to_string(), ChangeStatus::Added)
5236
        ]
5237
    );
5238
    repo.commit("the work", &[]).unwrap();
5239
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5240
5241
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5242
    repo.bookmark_switch("main", false).unwrap();
5243
    write(root, "b.txt", b"b on main\n");
5244
    repo.commit("b on main", &[]).unwrap();
5245
    repo.bookmark_switch("feature", false).unwrap();
5246
    write(root, "b.txt", b"b edited\n");
5247
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5248
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5249
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5250
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5251
}
1c2bd9ab Andy McCall ↶ 5252
5253
/// Merging and checking out (feedback 3): a working copy without changes
5254
/// follows a merge whichever state it sat on; a refused checkout names
5255
/// what is in the way; `checkout --carry` takes the work along.
5256
#[test]
5257
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5258
    hermetic();
5259
    let dir = tempfile::tempdir().unwrap();
5260
    let root = dir.path();
5261
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5262
    write(root, "a.txt", b"a\n");
5263
    let h1 = repo.commit("a", &[]).unwrap();
5264
    write(root, "b.txt", b"b\n");
5265
    repo.commit("b", &[]).unwrap();
5266
    repo.bookmark_create("feature", None).unwrap();
5267
    repo.bookmark_switch("feature", false).unwrap();
5268
    write(root, "c.txt", b"c\n");
5269
    repo.commit("c on feature", &[]).unwrap();
5270
    repo.bookmark_switch("main", false).unwrap();
5271
    // The working copy sits on an older state than main's heads.
5272
    repo.checkout(&[h1], false, "checkout").unwrap();
5273
    assert!(!root.join("b.txt").exists());
5274
    let m = repo.merge("feature").unwrap();
5275
    assert!(m.checked_out, "a clean working copy follows the merge");
5276
    for f in ["a.txt", "b.txt", "c.txt"] {
5277
        assert!(root.join(f).exists(), "{f}");
5278
    }
5279
5280
    // A refusal says which paths are in the way and what to do.
5281
    fs::remove_file(root.join("b.txt")).unwrap();
5282
    write(root, "a.txt", b"a edited\n");
5283
    let err = repo
5284
        .checkout(&[h1], false, "checkout")
5285
        .unwrap_err()
5286
        .to_string();
5287
    assert!(
5288
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5289
        "{err}"
5290
    );
5291
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5292
    // is carried as absent (h1 has none either, so that is refused).
5293
    let err = repo
5294
        .checkout_carry(&[h1], "the first change", "checkout")
5295
        .unwrap_err()
5296
        .to_string();
5297
    assert!(
5298
        err.contains("b.txt") && err.contains("the first change"),
5299
        "{err}"
5300
    );
5301
    write(root, "b.txt", b"b\n");
5302
    let (_, carried) = repo
5303
        .checkout_carry(&[h1], "the first change", "checkout")
5304
        .unwrap();
5305
    assert_eq!(carried, vec!["a.txt"]);
5306
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5307
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5308
}
e7ac6c2e Andy McCall ↶ 5309
5310
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5311
/// user identity not stored in a new repository yet is fine while its
5312
/// secret key is there; an added subrepo is listed as not committed yet.
5313
#[test]
5314
fn a_new_repository_is_healthy_before_its_first_commit() {
5315
    hermetic();
5316
    let dir = tempfile::tempdir().unwrap();
5317
    let root = dir.path();
5318
    let home = root.join("home");
5319
    let mut first = Repo::init(&root.join("first"))
5320
        .unwrap()
5321
        .with_home(home.clone());
5322
    let (key, _) = first
5323
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5324
        .unwrap();
5325
    let repo = Repo::init(&root.join("second"))
5326
        .unwrap()
5327
        .with_home(home.clone());
5328
    // Only the secret key: no identity object anywhere this repository sees.
5329
    let keys = repo.keys_dir.clone();
5330
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5331
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5332
    let r = repo.doctor(true);
5333
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5334
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5335
    assert!(id.message.contains("first signed change"), "{}", id.message);
5336
5337
    // A subrepo added and not committed yet is listed, pinned where it is.
5338
    let lib = root.join("lib");
5339
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5340
    write(&lib, "x.txt", b"x\n");
5341
    l.commit("x", &[]).unwrap();
5342
    let second = root.join("second");
5343
    write(&second, "a.txt", b"a\n");
5344
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5345
        .unwrap();
5346
    let subs = repo.subrepos().unwrap();
5347
    assert_eq!(subs.len(), 1);
5348
    assert_eq!(
5349
        (subs[0].path.as_str(), subs[0].committed),
5350
        ("deps/lib", false)
5351
    );
5352
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5353
    repo.commit("add lib", &[]).unwrap();
5354
    let subs = repo.subrepos().unwrap();
5355
    assert!(subs[0].committed, "committed now");
5356
}
8ab265dc Andy McCall ↶ 5357
5358
/// Commit, diff, hunks and discard use the partial snapshot: a file
5359
/// unchanged since the manifest is neither read nor rendered, and showing
5360
/// a change renders only what it edits, the same as from a full base.
5361
#[cfg(unix)]
5362
#[test]
5363
fn commits_and_diffs_leave_unchanged_files_alone() {
5364
    use std::os::unix::fs::PermissionsExt;
5365
    hermetic();
5366
    let dir = tempfile::tempdir().unwrap();
5367
    let root = dir.path();
5368
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5369
    write(root, "big.txt", b"lots\nof\nlines\n");
5370
    write(root, "a.txt", b"one\ntwo\n");
5371
    repo.commit("base", &[]).unwrap();
5372
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5373
    for f in ["big.txt", "a.txt"] {
5374
        fs::File::options()
5375
            .write(true)
5376
            .open(root.join(f))
5377
            .unwrap()
5378
            .set_modified(old)
5379
            .unwrap();
5380
    }
5381
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5382
    // big.txt cannot be read at all from here on.
5383
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5384
5385
    write(root, "a.txt", b"one\nTWO\nthree\n");
5386
    let diff = repo.diff_files(None).unwrap();
5387
    assert_eq!(
5388
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5389
        ["a.txt"]
5390
    );
5391
    let (_, hunks) = repo.hunks().unwrap();
5392
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5393
    let h = repo.commit("edit a", &[]).unwrap();
5394
5395
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5396
    let c = repo.store().get_change(&h).unwrap();
5397
    let full = repo.load_state(&c.deps).unwrap();
5398
    let want = render_change(&c, &full, &full.materialize());
5399
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5400
    let (base, snap) = repo.change_base(&c).unwrap();
5401
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5402
5403
    // Discarding works the same way.
5404
    write(root, "a.txt", b"scratch\n");
5405
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5406
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5407
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5408
}
f7510b63 Andy McCall ↶ 5409
5410
/// A replace conflict (spec §9.3) is settled by a change that writes one
5411
/// candidate, or new bytes, at the path when the caller names it; a plain
5412
/// snapshot of a checkout never settles it on its own.
5413
#[test]
5414
fn replace_conflicts_are_settled_when_asked() {
5415
    hermetic();
5416
    let dir = tempfile::tempdir().unwrap();
5417
    let root = dir.path();
5418
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5419
    let blob = |n: u8| {
5420
        let mut v = vec![0u8; 64];
5421
        v[1] = n;
5422
        v
5423
    };
5424
    write(root, "img.bin", &blob(1));
5425
    repo.commit("add img", &[]).unwrap();
5426
    repo.bookmark_create("other", None).unwrap();
5427
    write(root, "img.bin", &blob(2));
5428
    repo.commit("img two", &[]).unwrap();
5429
    repo.bookmark_switch("other", false).unwrap();
5430
    write(root, "img.bin", &blob(3));
5431
    repo.commit("img three", &[]).unwrap();
5432
    repo.bookmark_switch("main", false).unwrap();
5433
    repo.merge("other").unwrap();
5434
    let heads = repo.bookmark_heads().unwrap();
5435
    let merged = repo.load_state(&heads).unwrap().materialize();
5436
    assert!(
5437
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5438
        "a replace conflict"
5439
    );
5440
    // A snapshot of the checkout records nothing.
5441
    assert!(repo
5442
        .snapshot("status")
5443
        .unwrap()
5444
        .statuses
5445
        .iter()
5446
        .all(|s| s.path != "img.bin"));
5447
5448
    // Keeping candidate 3 settles it.
5449
    let author = repo.author();
5450
    let edits = [FileEdit {
5451
        path: "img.bin".into(),
5452
        content: Some(blob(3)),
5453
    }];
5454
    let c = repo
5455
        .build_change(&heads, &edits, "keep three", author)
5456
        .unwrap();
5457
    assert_eq!(c.kind, ChangeKind::Resolution);
5458
    let mut st = repo.load_state(&heads).unwrap();
5459
    for d in &c.deps {
5460
        assert!(st.contains(d));
5461
    }
5462
    assert!(
5463
        heads.iter().all(|h| c.deps.contains(h)),
5464
        "depends on both contributors"
5465
    );
5466
    st.add(c).unwrap();
5467
    let after = st.materialize();
5468
    assert!(!after.is_conflicted());
5469
    assert_eq!(
5470
        after.files["img.bin"].content,
5471
        FileContent::Opaque {
5472
            blobs: vec![Repo::blob_ref(&blob(3))]
5473
        }
5474
    );
5475
5476
    // New bytes settle it too.
5477
    let edits = [FileEdit {
5478
        path: "img.bin".into(),
5479
        content: Some(blob(9)),
5480
    }];
5481
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5482
    let mut st = repo.load_state(&heads).unwrap();
5483
    st.add(c).unwrap();
5484
    assert_eq!(
5485
        st.materialize().files["img.bin"].content,
5486
        FileContent::Opaque {
5487
            blobs: vec![Repo::blob_ref(&blob(9))]
5488
        }
5489
    );
5490
}
83d61e80 Andy McCall ↶ 5491
5492
/// The history of a range of lines (spec §27): the changes that wrote
5493
/// or deleted its atoms, or deleted atoms from between them; edits outside
5494
/// the range and changes the range's lines survived are not in it.
5495
#[test]
5496
fn line_ranges_have_exact_histories() {
5497
    hermetic();
5498
    let dir = tempfile::tempdir().unwrap();
5499
    let root = dir.path();
5500
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5501
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5502
    let base = repo.commit("add f", &[]).unwrap();
5503
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5504
    let outside = repo.commit("change the import", &[]).unwrap();
5505
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5506
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5507
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5508
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5509
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5510
    let after = repo.commit("add b after a", &[]).unwrap();
5511
    let heads = repo.bookmark_heads().unwrap();
5512
5513
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5514
    let hist: Vec<ChangeHash> = repo
5515
        .line_history(&heads, "f.rs", 2, 4)
5516
        .unwrap()
5517
        .iter()
5518
        .map(|e| e.hash)
5519
        .collect();
5520
    for (h, what) in [
5521
        (base, "wrote it"),
5522
        (inside, "edited a line"),
5523
        (deleted, "deleted a line from inside"),
5524
    ] {
5525
        assert!(hist.contains(&h), "{what}");
5526
    }
5527
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5528
        assert!(!hist.contains(&h), "{what}");
5529
    }
5530
    assert_eq!(hist[0], deleted, "newest first");
5531
    // One line: only what touched it.
5532
    let one: Vec<ChangeHash> = repo
5533
        .line_history(&heads, "f.rs", 1, 1)
5534
        .unwrap()
5535
        .iter()
5536
        .map(|e| e.hash)
5537
        .collect();
5538
    assert!(one.contains(&outside) && !one.contains(&inside));
5539
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5540
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5541
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5542
}
fc1a466a Andy McCall ↶ 5543
5544
#[test]
5545
fn receipts_are_kept_with_their_state_and_verified() {
5546
    use crate::receipt::{Receipt, SignedReceipt};
5547
    hermetic();
5548
    let dir = tempfile::tempdir().unwrap();
5549
    let root = dir.path();
5550
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5551
    write(root, "a.txt", b"1\n");
5552
    repo.commit("A", &[]).unwrap();
5553
    let heads = repo.bookmark_heads().unwrap();
5554
    let state = repo
5555
        .store()
5556
        .put_state(&StateObject::new(heads.clone()))
5557
        .unwrap();
5558
    let out = repo.store_blob(b"built\n").unwrap();
5559
    let receipt = Receipt {
5560
        job_name: "build".into(),
5561
        pipeline_hash: ObjectRef([1; 32]),
5562
        scope_tree_hash: ObjectRef([2; 32]),
5563
        inputs: vec![],
5564
        environment: ObjectRef([3; 32]),
5565
        outputs: vec![out],
5566
        exit_code: 0,
5567
        duration_ms: 42,
5568
    };
5569
    let sk = SecretKey::generate();
5570
    let runner = sk.identity("earth-1", "runner@earth", 1);
5571
    let sr = SignedReceipt::sign(
5572
        receipt.clone(),
5573
        repo.id().unwrap(),
5574
        state,
5575
        "demo#1",
5576
        &runner,
5577
        &sk,
5578
    );
5579
5580
    let r = repo.add_receipt(&sr).unwrap();
5581
    let found = repo.receipts(&heads).unwrap();
5582
    assert_eq!(found.len(), 1);
5583
    assert_eq!(found[0].attest, r);
5584
    assert_eq!(found[0].signed, sr);
5585
    assert!(found[0].problem.is_none() && !found[0].revoked);
5586
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5587
5588
    // Another repository's receipt, or a forged one, is refused.
5589
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5590
    assert!(repo
5591
        .add_receipt(&elsewhere)
5592
        .unwrap_err()
5593
        .to_string()
5594
        .contains("another repository"));
5595
    let mut forged = sr.clone();
5596
    forged.receipt.exit_code = 1;
5597
    assert!(repo
5598
        .add_receipt(&forged)
5599
        .unwrap_err()
5600
        .to_string()
5601
        .contains("does not verify"));
5602
5603
    // gc keeps the receipt, its runner and its output while the state lives.
5604
    repo.gc(true).unwrap();
5605
    assert_eq!(repo.receipts(&heads).unwrap().len(), 1);
5606
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5607
    assert!(repo.fsck().unwrap().problems.is_empty());
dfb23a3a Andy McCall ↶ 5608
}
5609
5610
#[test]
5611
fn status_leaves_an_unchanged_manifest_alone() {
5612
    hermetic();
5613
    let dir = tempfile::tempdir().unwrap();
5614
    let root = dir.path();
5615
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5616
    write(root, "a.txt", b"1\n");
5617
    write(root, "b.txt", b"2\n");
5618
    repo.commit("A", &[]).unwrap();
5619
    // Files last touched well outside the racy window.
5620
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5621
    for f in ["a.txt", "b.txt"] {
5622
        fs::File::options()
5623
            .write(true)
5624
            .open(root.join(f))
5625
            .unwrap()
5626
            .set_modified(old)
5627
            .unwrap();
5628
    }
5629
    repo.snapshot_status("status").unwrap();
5630
    let path = repo.manifest_path();
5631
    let first = fs::read(&path).unwrap();
5632
    repo.snapshot_status("status").unwrap();
5633
    assert_eq!(
5634
        fs::read(&path).unwrap(),
5635
        first,
5636
        "an unchanged tree does not rewrite the manifest"
5637
    );
5638
    // A change rewrites it.
5639
    write(root, "a.txt", b"1\n2\n");
5640
    repo.snapshot_status("status").unwrap();
5641
    assert_ne!(fs::read(&path).unwrap(), first);
fc1a466a Andy McCall ↶ 5642
}
6f8aeb99 Andy McCall ↶ 5643
5644
#[test]
5645
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5646
    hermetic();
5647
    let dir = tempfile::tempdir().unwrap();
5648
    let root = dir.path();
5649
    let origin_path = root.join("origin");
5650
    Repo::init(&origin_path).unwrap();
5651
    let origin_url = origin_path.to_string_lossy().to_string();
5652
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5653
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5654
    write(&root.join("a"), "big.txt", big.as_bytes());
5655
    write(&root.join("a"), "small.txt", b"small\n");
5656
    let h1 = a.commit("large", &[]).unwrap();
5657
    let (_, body) = a.store().get(&h1).unwrap();
5658
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5659
    assert!(a.push("origin", false).unwrap()[0].ok);
5660
5661
    // A clone reads the text from the blobs that came with the change.
5662
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5663
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5664
    // An edit in the middle of the stored insert is an ordinary change.
5665
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5666
    write(&root.join("b"), "big.txt", edited.as_bytes());
5667
    let h2 = b.commit("edit", &[]).unwrap();
5668
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5669
    assert!(b.push("origin", false).unwrap()[0].ok);
5670
    assert!(a.pull("origin").unwrap().checked_out);
5671
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5672
    assert_eq!(
5673
        a.fsck().unwrap().errors(),
5674
        0,
5675
        "{:?}",
5676
        a.fsck().unwrap().problems
5677
    );
5678
5679
    // With zero retention gc keeps the text blobs of every kept change.
5680
    let mut a = Repo::open(&root.join("a")).unwrap();
5681
    a.config.set("core.op-retention", "0").unwrap();
5682
    a.save_config().unwrap();
5683
    let a = Repo::open(&root.join("a")).unwrap();
5684
    a.gc(true).unwrap();
5685
    let a = Repo::open(&root.join("a")).unwrap();
5686
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5687
    assert_eq!(
5688
        a.fsck().unwrap().errors(),
5689
        0,
5690
        "{:?}",
5691
        a.fsck().unwrap().problems
5692
    );
5693
    // And a clone of the packed repository reads them from its packs.
5694
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5695
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5696
    drop(c);
6caacfff Andy McCall ↶ 5697
}
5698
5699
#[test]
5700
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5701
    hermetic();
5702
    let dir = tempfile::tempdir().unwrap();
5703
    let root = dir.path();
5704
    let repo = Repo::init(root).unwrap();
5705
    write(root, "a.txt", b"a\n");
5706
    let a = repo.commit("a", &[]).unwrap();
5707
    write(root, "b.txt", b"b\n");
5708
    repo.commit("b", &[]).unwrap();
5709
    let (x, op) = repo.head_op().unwrap();
5710
    let ws = *op.view.workspaces.keys().next().unwrap();
5711
    let mut one = op.view.clone();
5712
    one.workspaces.insert(ws, a);
5713
    let mut two = op.view.clone();
5714
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5715
    let first = repo.record_op(&[x], "one", one).unwrap();
5716
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5717
    assert!(
5718
        e.to_string()
5719
            .contains("changed this working copy at the same time"),
5720
        "{e}"
5721
    );
5722
    assert_eq!(
5723
        repo.head_op().unwrap().0,
5724
        first,
5725
        "the second is not recorded"
5726
    );
5727
}
5728
5729
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5730
/// rewrote the working copy recorded the half-written files as edits, and
5731
/// its view replaced the switch's.
5732
#[test]
5733
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5734
    hermetic();
5735
    let dir = tempfile::tempdir().unwrap();
5736
    let root = dir.path().to_path_buf();
5737
    let mut repo = Repo::init(&root).unwrap();
5738
    write(&root, "keep.txt", b"keep\n");
5739
    repo.commit("base", &[]).unwrap();
5740
    repo.bookmark_create("small", None).unwrap();
5741
    for i in 0..300 {
5742
        write(
5743
            &root,
5744
            &format!("many/f{i}.txt"),
5745
            format!("file {i}\n").as_bytes(),
5746
        );
5747
    }
5748
    repo.commit("many", &[]).unwrap();
5749
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5750
    let watcher = {
5751
        let (root, stop) = (root.clone(), stop.clone());
5752
        std::thread::spawn(move || {
5753
            let r = Repo::open(&root).unwrap();
5754
            let mut ran = 0;
5755
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
5756
                if r.snapshot_status("oxy status").is_ok() {
5757
                    ran += 1;
5758
                }
5759
            }
5760
            ran
5761
        })
5762
    };
5763
    for i in 0..20 {
5764
        let to = if i % 2 == 0 { "small" } else { "main" };
5765
        repo.bookmark_switch(to, false).unwrap();
5766
    }
5767
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
5768
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
5769
    // Back on main, clean, with every file where main has it.
5770
    let repo = Repo::open(&root).unwrap();
5771
    let s = repo.snapshot_status("oxy status").unwrap();
5772
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
5773
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
5774
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
5775
    assert!(root.join("many/f299.txt").exists());
1a3b6203 Andy McCall ↶ 5776
}
5777
5778
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
5779
/// put a subrepo that was ahead of its pin back at the pin and moved the
5780
/// subrepo's own bookmark backwards.
5781
#[test]
5782
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
5783
    hermetic();
5784
    let dir = tempfile::tempdir().unwrap();
5785
    let root = dir.path();
5786
    Repo::init(&root.join("lib-origin")).unwrap();
5787
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5788
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
5789
    write(&root.join("lib"), "lib.txt", b"v1\n");
5790
    lib.commit("lib v1", &[]).unwrap();
5791
    assert!(lib.push("origin", false).unwrap()[0].ok);
5792
5793
    let app_dir = root.join("app");
5794
    let mut app = Repo::init(&app_dir).unwrap();
5795
    write(&app_dir, "main.txt", b"app\n");
5796
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5797
    app.commit("app with lib", &[]).unwrap();
5798
    app.bookmark_create("feature", None).unwrap();
5799
5800
    // New work in the subrepo, not yet pinned by the parent.
5801
    let nested_dir = app_dir.join("libs/lib");
5802
    let nested = Repo::open(&nested_dir).unwrap();
5803
    write(&nested_dir, "new.txt", b"new\n");
5804
    let l2 = nested.commit("lib: new file", &[]).unwrap();
5805
    drop(nested);
5806
5807
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
5808
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
5809
    let nested = Repo::open(&nested_dir).unwrap();
5810
    assert!(
5811
        nested.bookmark_heads().unwrap().contains(&l2),
5812
        "its bookmark kept its work"
5813
    );
5814
    assert!(nested_dir.join("new.txt").exists(), "and its files");
5815
    let s = app.snapshot("status").unwrap();
5816
    assert_eq!(
5817
        statuses(&s),
5818
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
5819
    );
6f8aeb99 Andy McCall ↶ 5820
}
7d9dab13 Andy McCall ↶ 5821
5822
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
5823
/// moving `main` to a change this clone had pushed on another bookmark,
5824
/// the first `pull` said "Already up to date" while `main` was behind.
5825
#[test]
5826
fn pull_takes_a_remote_move_to_changes_already_here() {
5827
    hermetic();
5828
    let dir = tempfile::tempdir().unwrap();
5829
    let root = dir.path();
5830
    let origin_path = root.join("origin");
5831
    let origin = Repo::init(&origin_path).unwrap();
5832
    let url = origin_path.to_string_lossy().to_string();
5833
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
5834
    write(&root.join("b"), "base.txt", b"base\n");
5835
    b.commit("base", &[]).unwrap();
5836
    assert!(b.push("origin", false).unwrap()[0].ok);
5837
5838
    // A feature bookmark with one change, pushed.
5839
    b.bookmark_create("feat", None).unwrap();
5840
    b.bookmark_switch("feat", false).unwrap();
5841
    write(&root.join("b"), "x.txt", b"x\n");
5842
    let x = b.commit("x", &[]).unwrap();
5843
    assert!(b.push("origin", false).unwrap()[0].ok);
5844
    b.bookmark_switch("main", false).unwrap();
5845
5846
    // The remote lands it: its main moves to the feature's state.
5847
    let feat = origin
5848
        .store()
5849
        .get_state(&origin.view().unwrap().bookmarks["feat"])
5850
        .unwrap()
5851
        .heads;
5852
    origin.bookmark_set("main", &feat).unwrap();
5853
5854
    let r = b.pull("origin").unwrap();
5855
    assert!(r.changed, "{r:?}");
5856
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
5857
    let main = b
5858
        .bookmarks()
5859
        .unwrap()
5860
        .into_iter()
5861
        .find(|m| m.name == "main")
5862
        .unwrap();
5863
    assert_eq!(main.behind, Some(0), "{main:?}");
5864
}
86e1824f Andy McCall ↶ 5865
14edbaaf Andy McCall ↶ 5866
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
5867
/// to one only the remote has makes a local bookmark from it; a pull moves
5868
/// every local bookmark the remote has too; a clone checks out the remote's
5869
/// default bookmark.
5870
#[test]
5871
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
5872
    hermetic();
5873
    let dir = tempfile::tempdir().unwrap();
5874
    let root = dir.path();
5875
    let origin_path = root.join("origin");
5876
    let mut origin = Repo::init(&origin_path).unwrap();
5877
    let url = origin_path.to_string_lossy().to_string();
5878
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
5879
    write(&root.join("a"), "base.txt", b"base\n");
5880
    a.commit("base", &[]).unwrap();
5881
    assert!(a.push("origin", false).unwrap()[0].ok);
5882
    a.bookmark_create("develop", None).unwrap();
5883
    a.bookmark_switch("develop", false).unwrap();
5884
    write(&root.join("a"), "base.txt", b"base\nd1\n");
5885
    let d1 = a.commit("d1", &[]).unwrap();
5886
    assert!(a.push("origin", false).unwrap()[0].ok);
5887
5888
    // A clone has main only; origin/develop is a name all the same.
5889
    let c_root = root.join("c");
5890
    let mut c = Repo::clone(&url, &c_root).unwrap();
5891
    assert_eq!(c.config.bookmark, "main");
5892
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
5893
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
5894
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
5895
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
5896
5897
    // Switching makes the local bookmark from origin's.
5898
    c.bookmark_switch("develop", false).unwrap();
5899
    assert_eq!(c.config.bookmark, "develop");
5900
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
5901
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
5902
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
5903
    assert!(c.bookmark_switch("nowhere", false).is_err());
5904
5905
    // Both bookmarks move on the remote; one pull takes both.
5906
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
5907
    let d2 = a.commit("d2", &[]).unwrap();
5908
    assert!(a.push("origin", false).unwrap()[0].ok);
5909
    a.bookmark_switch("main", false).unwrap();
5910
    write(&root.join("a"), "m.txt", b"m\n");
5911
    let m = a.commit("m", &[]).unwrap();
5912
    assert!(a.push("origin", false).unwrap()[0].ok);
5913
    let r = c.pull("origin").unwrap();
5914
    assert!(r.changed && r.checked_out, "{r:?}");
5915
    assert_eq!(r.heads, vec![d2]);
5916
    assert_eq!(r.others, vec!["main".to_string()]);
5917
    assert!(c.resolve_heads("main").unwrap().contains(&m));
5918
    assert_eq!(
5919
        fs::read(c_root.join("base.txt")).unwrap(),
5920
        b"base\nd1\nd2\n"
5921
    );
5922
    let again = c.pull("origin").unwrap();
5923
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
5924
5925
    // A clone checks out the remote's default bookmark.
5926
    origin.config.set("workspace.bookmark", "develop").unwrap();
5927
    origin.save_config().unwrap();
5928
    let e = Repo::clone(&url, &root.join("e")).unwrap();
5929
    assert_eq!(e.config.bookmark, "develop");
5930
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
5931
    let reopened = Repo::open(&root.join("e")).unwrap();
5932
    assert_eq!(reopened.config.bookmark, "develop");
5933
    // REMOTE/NAME names the remote's bookmark to switch to.
5934
    let mut e = reopened;
5935
    e.bookmark_switch("origin/main", false).unwrap();
5936
    assert_eq!(e.config.bookmark, "main");
5937
    assert!(e.bookmark_heads().unwrap().contains(&m));
5938
}
5939
98a1620a Andy McCall ↶ 5940
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
5941
/// op restore goes back to an operation, files included, and undo takes
5942
/// the restore back whole; op revert undoes one operation alone; each
5943
/// operation's changes are described from the views.
5944
#[test]
5945
fn operations_can_be_read_restored_and_reverted() {
5946
    hermetic();
5947
    let dir = tempfile::tempdir().unwrap();
5948
    let root = dir.path();
5949
    let repo = Repo::init(root).unwrap();
5950
    write(root, "a.txt", b"a\n");
5951
    let first = repo.commit("first", &[]).unwrap();
5952
    write(root, "a.txt", b"a\nb\n");
5953
    let second = repo.commit("second", &[]).unwrap();
5954
    let at_second = repo.head_op().unwrap().0.to_hex();
5955
    repo.bookmark_create("keep", None).unwrap();
5956
    let created = repo.head_op().unwrap().0.to_hex();
5957
    write(root, "n.txt", b"n\n");
5958
    let third = repo.commit("third", &[]).unwrap();
5959
5960
    // What each operation changed.
5961
    let ops = repo.op_log().unwrap();
5962
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
5963
    assert!(
5964
        changes
5965
            .iter()
5966
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
5967
        "{changes:?}"
5968
    );
5969
    assert!(changes
5970
        .iter()
5971
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
5972
5973
    // Reading at an earlier operation.
5974
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
5975
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
5976
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
5977
    write(root, "z.txt", b"z\n");
5978
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
5979
    fs::remove_file(root.join("z.txt")).unwrap();
5980
    assert!(repo.resolve_op("zz").is_err());
5981
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
5982
5983
    // Restore goes back, files and all; undo takes it back whole.
5984
    repo.op_restore(&at_second, false).unwrap();
5985
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
5986
    assert!(!root.join("n.txt").exists());
5987
    repo.undo().unwrap();
5988
    let mut heads = repo.bookmark_heads().unwrap();
5989
    heads.sort();
5990
    let mut want = vec![second, third];
5991
    want.sort();
5992
    assert_eq!(heads, want);
5993
    assert!(
5994
        root.join("n.txt").exists(),
5995
        "the files came back with the undo"
5996
    );
5997
5998
    // Revert the bookmark's creation alone: the commit after it stays.
5999
    let r = repo.op_revert(&created).unwrap();
6000
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6001
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6002
    assert!(repo
6003
        .load_state(&repo.bookmark_heads().unwrap())
6004
        .unwrap()
6005
        .contains(&third));
6006
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6007
    let _ = first;
6008
}
6009
36041796 Andy McCall ↶ 6010
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6011
/// from the status cache while every file is as the snapshot left it, and
6012
/// from a snapshot again as soon as one is not.
6013
#[test]
6014
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6015
    hermetic();
6016
    let dir = tempfile::tempdir().unwrap();
6017
    let root = dir.path();
6018
    let repo = Repo::init(root).unwrap();
6019
    write(root, "a.txt", b"a\n");
6020
    write(root, "b.txt", b"b\n");
6021
    repo.commit("base", &[]).unwrap();
6022
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6023
6024
    write(root, "a.txt", b"a\nmore\n");
6025
    assert_eq!(
6026
        repo.status_by_manifest().unwrap(),
6027
        None,
6028
        "no snapshot of the edit yet"
6029
    );
6030
    let snap = repo.snapshot_status("oxy status").unwrap();
6031
    assert_eq!(snap.statuses.len(), 1);
6032
    let cached = repo
6033
        .status_by_manifest()
6034
        .unwrap()
6035
        .expect("answered from the cache");
6036
    assert_eq!(cached.len(), 1);
6037
    assert_eq!(
6038
        (cached[0].path.as_str(), cached[0].status),
6039
        ("a.txt", ChangeStatus::Modified)
6040
    );
6041
6042
    // Any further change sends status back to a snapshot.
6043
    write(root, "a.txt", b"a\nmore\nand more\n");
6044
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6045
    repo.snapshot_status("oxy status").unwrap();
6046
    assert!(repo.status_by_manifest().unwrap().is_some());
6047
    write(root, "new.txt", b"n\n");
6048
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6049
    fs::remove_file(root.join("new.txt")).unwrap();
6050
    assert!(
6051
        repo.status_by_manifest().unwrap().is_some(),
6052
        "back as it was"
6053
    );
6054
    fs::remove_file(root.join("b.txt")).unwrap();
6055
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6056
    write(root, "b.txt", b"b\n");
6057
6058
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6059
    repo.snapshot_status("oxy status").unwrap();
6060
    repo.commit("more", &[]).unwrap();
6061
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6062
}
6063
77445673 Andy McCall ↶ 6064
/// oxygen#41: while the status cache holds, the working copy's diff is
6065
/// rendered from the stored working-copy change, and says exactly what a
6066
/// snapshot's diff says.
6067
#[test]
6068
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6069
    hermetic();
6070
    let dir = tempfile::tempdir().unwrap();
6071
    let root = dir.path();
6072
    let repo = Repo::init(root).unwrap();
6073
    write(root, "a.txt", b"one\ntwo\nthree\n");
6074
    write(root, "gone.txt", b"bye\n");
6075
    repo.commit("base", &[]).unwrap();
6076
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6077
    write(root, "new.txt", b"hello\n");
6078
    fs::remove_file(root.join("gone.txt")).unwrap();
6079
    let snap = repo.snapshot_status("oxy status").unwrap();
6080
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6081
    assert!(
6082
        repo.status_by_manifest().unwrap().is_some(),
6083
        "the cache holds"
6084
    );
6085
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6086
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6087
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6088
}
6089
1ec3f008 Andy McCall ↶ 6090
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6091
/// while none has moved, the check stats the tracked files without listing
6092
/// the tree, and a file added or removed anywhere moves its directory's
6093
/// time, so the tree is listed again.
6094
#[test]
6095
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6096
    hermetic();
6097
    let dir = tempfile::tempdir().unwrap();
6098
    let root = dir.path();
6099
    let repo = Repo::init(root).unwrap();
6100
    write(root, "a.txt", b"a\n");
6101
    write(root, "sub/deep/b.txt", b"b\n");
6102
    repo.commit("base", &[]).unwrap();
6103
    // Out of the racy window: every file and directory a minute old.
6104
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6105
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6106
        fs::File::open(root.join(p))
6107
            .unwrap()
6108
            .set_modified(old)
6109
            .unwrap();
6110
    }
6111
    repo.snapshot_status("oxy status").unwrap();
6112
    repo.write_manifest(false, false).unwrap();
6113
    let m = repo.read_manifest().unwrap().unwrap().2;
6114
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6115
    assert_eq!(
6116
        repo.disk_differs_by_dirs(&m),
6117
        Some(false),
6118
        "no listing needed"
6119
    );
6120
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6121
6122
    // A same-size edit with a new time: found by its stat.
6123
    write(root, "sub/deep/b.txt", b"c\n");
6124
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6125
    write(root, "sub/deep/b.txt", b"b\n");
6126
    fs::File::open(root.join("sub/deep/b.txt"))
6127
        .unwrap()
6128
        .set_modified(old)
6129
        .unwrap();
6130
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6131
6132
    // A new file moves its directory's time: the tree must be listed.
6133
    write(root, "sub/deep/new.txt", b"n\n");
6134
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6135
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6136
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6137
    // A removed one too.
6138
    fs::remove_file(root.join("a.txt")).unwrap();
6139
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6140
}
6141
e226a6cc Andy McCall ↶ 6142
/// oxygen#41: a commit right after a status takes the snapshot the status
6143
/// left (the status cache holds) rather than walking again, and commits
6144
/// exactly what a snapshot would have.
6145
#[test]
6146
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6147
    hermetic();
6148
    let dir = tempfile::tempdir().unwrap();
6149
    let root = dir.path();
6150
    let repo = Repo::init(root).unwrap();
6151
    write(root, "a.txt", b"a\nb\n");
6152
    write(root, ".oxyattributes", b"*.bin binary\n");
6153
    repo.commit("base", &[]).unwrap();
6154
    write(root, "a.txt", b"a\nB\n");
6155
    write(root, "new.txt", b"new\n");
6156
    let snap = repo.snapshot_status("oxy status").unwrap();
6157
    let cached = repo
6158
        .snapshot_from_cache()
6159
        .unwrap()
6160
        .expect("the cache holds");
6161
    assert_eq!(cached.wc_hash, snap.wc_hash);
6162
    assert_eq!(cached.statuses, snap.statuses);
6163
    assert!(
6164
        !cached.attributes.is_empty(),
6165
        "the .oxyattributes file was read"
6166
    );
6167
    let h = repo.commit("edit", &[]).unwrap();
6168
    let c = repo.store().get_change(&h).unwrap();
6169
    assert_eq!(
6170
        c.tree_ops.len() + c.edits.len(),
6171
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6172
    );
6173
    assert_eq!(
6174
        repo.status_by_manifest().unwrap(),
6175
        Some(vec![]),
6176
        "clean after the commit"
6177
    );
6178
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6179
}
6180
0389c3e8 Andy McCall ↶ 6181
/// oxygen#41: a clean check that verified racy entries restamps the
6182
/// manifest, so later checks can trust them, and a same-size rewrite
6183
/// straight afterwards is still found: entries within two seconds of the
6184
/// new time stay racy.
6185
#[test]
6186
fn a_verified_clean_check_restamps_the_manifest_safely() {
6187
    hermetic();
6188
    let dir = tempfile::tempdir().unwrap();
6189
    let root = dir.path();
6190
    let repo = Repo::init(root).unwrap();
6191
    write(root, "a.txt", b"one\n");
6192
    repo.commit("one", &[]).unwrap();
6193
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6194
    assert!(repo.clean_by_manifest().unwrap());
6195
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6196
    assert!(after > before, "restamped");
6197
    write(root, "a.txt", b"two\n");
6198
    assert!(
6199
        !repo.clean_by_manifest().unwrap(),
6200
        "a same-size rewrite is still seen"
6201
    );
6202
}
6203
86e1824f Andy McCall ↶ 6204
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6205
/// stored insert's text blob only when it builds that file's graph, and
6206
/// builds the same graph a full load does.
6207
#[test]
6208
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6209
    hermetic();
6210
    let dir = tempfile::tempdir().unwrap();
6211
    let root = dir.path();
6212
    let repo = Repo::init(root).unwrap();
6213
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6214
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6215
    write(root, "big.txt", big.as_bytes());
6216
    write(root, "other.txt", other.as_bytes());
6217
    let h = repo.commit("two large files", &[]).unwrap();
6218
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6219
    let h2 = repo.commit("append", &[]).unwrap();
6220
6221
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6222
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6223
        FileContent::Text { bytes, .. } => bytes.clone(),
6224
        other => panic!("{other:?}"),
6225
    };
6226
    // Built on demand, every graph renders as the full load's.
6227
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6228
    let big_node = full.files["big.txt"].node;
6229
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6230
    repo.load_all_graphs(&mut hist).unwrap();
6231
    let rendered = hist.materialize();
6232
    for p in ["big.txt", "other.txt"] {
6233
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6234
    }
6235
6236
    // Without other.txt's text blob, history still loads and big.txt still
6237
    // builds: nothing read the other text.
6238
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6239
    assert_eq!(texts.len(), 2);
6240
    let content = |r: &ObjectRef| -> Vec<u8> {
6241
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6242
        blob.chunks
6243
            .iter()
6244
            .flat_map(|c| repo.store().get(c).unwrap().1)
6245
            .collect()
6246
    };
6247
    let other_text = texts
6248
        .iter()
a4fad5b0 Andy McCall ↶ 6249
        .filter_map(|t| match t {
0f93f49c Andy McCall ↶ 6250
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
a4fad5b0 Andy McCall ↶ 6251
            _ => None,
6252
        })
86e1824f Andy McCall ↶ 6253
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6254
        .unwrap();
64818938 Andy McCall ↶ 6255
    repo.store().remove_loose_for_test(&other_text).unwrap();
86e1824f Andy McCall ↶ 6256
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6257
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6258
    assert!(repo
6259
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6260
        .is_err());
6261
}
6262
6263
/// oxygen#35: the first status after a commit read and rendered every
6264
/// file (79 s and more than 14 GB on the Linux tree), because the
6265
/// manifest had no graph keys for files the commit added.
6266
#[test]
6267
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6268
    use std::os::unix::fs::PermissionsExt;
6269
    hermetic();
6270
    let dir = tempfile::tempdir().unwrap();
6271
    let root = dir.path();
6272
    let repo = Repo::init(root).unwrap();
6273
    let files = ["a.txt", "b.txt", "d/c.txt"];
6274
    for p in files {
6275
        write(root, p, format!("{p}\n").as_bytes());
6276
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6277
        fs::File::options()
6278
            .write(true)
6279
            .open(root.join(p))
6280
            .unwrap()
6281
            .set_modified(old)
6282
            .unwrap();
6283
    }
6284
    repo.commit("added", &[]).unwrap();
6285
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6286
    assert!(
6287
        m.entries.values().all(|e| e.graph.is_some()),
6288
        "keys recorded at commit"
6289
    );
6290
    // Unreadable files prove the next status reads none of them.
6291
    for p in files {
6292
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6293
    }
6294
    let snap = repo.snapshot_status("status").unwrap();
6295
    for p in files {
6296
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6297
    }
6298
    assert!(!snap.changed && snap.statuses.is_empty());
6299
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6300
}
c5ce0367 Andy McCall ↶ 6301
6302
/// oxygen#35: a checkout reads, renders and writes only the files whose
6303
/// graphs differ, and renders the rest a batch at a time.
6304
#[test]
6305
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6306
    use std::os::unix::fs::PermissionsExt;
6307
    hermetic();
6308
    let dir = tempfile::tempdir().unwrap();
6309
    let root = dir.path();
6310
    let origin = root.join("origin");
6311
    let mut repo = Repo::init(&origin).unwrap();
6312
    // More files than one batch holds.
6313
    let n = 2100;
6314
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6315
    for i in 0..n {
6316
        let p = format!("f/{i:04}.txt");
6317
        write(&origin, &p, format!("file {i}\n").as_bytes());
6318
        fs::File::options()
6319
            .write(true)
6320
            .open(origin.join(&p))
6321
            .unwrap()
6322
            .set_modified(old)
6323
            .unwrap();
6324
    }
6325
    repo.commit("many", &[]).unwrap();
6326
    repo.bookmark_create("feature", None).unwrap();
6327
    repo.bookmark_switch("feature", false).unwrap();
6328
    write(&origin, "f/0007.txt", b"changed\n");
6329
    repo.commit("one change", &[]).unwrap();
6330
6331
    // Switching back to main must not read the unchanged files.
6332
    for i in 0..n {
6333
        if i != 7 {
6334
            let p = origin.join(format!("f/{i:04}.txt"));
6335
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6336
        }
6337
    }
6338
    let r = repo.bookmark_switch("main", false).unwrap();
6339
    for i in 0..n {
6340
        let p = origin.join(format!("f/{i:04}.txt"));
6341
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6342
    }
6343
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6344
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6345
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6346
6347
    // A clone renders every file, across batches.
6348
    let c = root.join("clone");
6349
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6350
    for i in [0, 2047, 2048, n - 1] {
6351
        assert_eq!(
6352
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6353
            format!("file {i}\n").as_bytes()
6354
        );
6355
    }
6356
    let cloned = Repo::open(&c).unwrap();
6357
    assert!(cloned
6358
        .snapshot_status("status")
6359
        .unwrap()
6360
        .statuses
6361
        .is_empty());
d3cd7ef9 Andy McCall ↶ 6362
}
6363
6364
/// A file written just before the manifest (inside the racy window) is
6365
/// checked by its hash: trusted when equal, caught when edited in place
6366
/// with the same size and time.
6367
#[test]
6368
fn a_racy_manifest_entry_is_checked_by_hash() {
6369
    hermetic();
6370
    let dir = tempfile::tempdir().unwrap();
6371
    let root = dir.path();
6372
    let repo = Repo::init(root).unwrap();
6373
    write(root, "a.txt", b"one\n");
6374
    repo.commit("fresh", &[]).unwrap();
6375
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6376
    let t = fs::metadata(root.join("a.txt"))
6377
        .unwrap()
6378
        .modified()
6379
        .unwrap();
6380
    write(root, "a.txt", b"two\n");
6381
    fs::File::options()
6382
        .write(true)
6383
        .open(root.join("a.txt"))
6384
        .unwrap()
6385
        .set_modified(t)
6386
        .unwrap();
6387
    assert!(
6388
        !repo.clean_by_manifest().unwrap(),
6389
        "same size and time, other bytes"
6390
    );
6391
    assert_eq!(
6392
        statuses(&repo.snapshot_status("status").unwrap()),
6393
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6394
    );
c5ce0367 Andy McCall ↶ 6395
}
2c75672f Andy McCall ↶ 6396
6397
/// A fetch on one machine moves changes as stored, text blobs among the
6398
/// objects; a change whose text blob did not come is refused, not stored.
6399
#[test]
6400
fn a_raw_bundle_without_a_changes_text_is_refused() {
6401
    hermetic();
6402
    let dir = tempfile::tempdir().unwrap();
6403
    let root = dir.path();
6404
    let a = Repo::init(&root.join("a")).unwrap();
6405
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6406
    write(&root.join("a"), "big.txt", big.as_bytes());
6407
    let h = a.commit("big", &[]).unwrap();
6408
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6409
    assert_eq!(bundle.raw_changes.len(), 1);
6410
    assert!(bundle.changes.is_empty());
6411
    let b = Repo::init(&root.join("b")).unwrap();
6412
    let mut without = bundle.clone();
6413
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6414
    let e = b.import_bundle(&without, false).unwrap_err();
6415
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6416
    assert!(!b.store().has(&h));
6417
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6418
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6419
}
a87c7b9d Andy McCall ↶ 6420
6421
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6422
/// again was a second node for one Git path, so a file moved into it on
6423
/// another line, where the first node still stood, ended up in two places.
6424
/// An import now brings the directory back rather than make a new one.
6425
#[test]
6426
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6427
    hermetic();
6428
    if std::process::Command::new("git")
6429
        .arg("--version")
6430
        .output()
6431
        .is_err()
6432
    {
6433
        eprintln!("git not installed; skipping");
6434
        return;
6435
    }
6436
    let dir = tempfile::tempdir().unwrap();
6437
    let root = dir.path();
6438
    let g = root.join("src.git");
6439
    fs::create_dir_all(&g).unwrap();
6440
    let git = |args: &[&str]| -> String {
6441
        let out = std::process::Command::new("git")
6442
            .arg("-C")
6443
            .arg(&g)
6444
            .args([
6445
                "-c",
6446
                "user.name=Grace",
6447
                "-c",
6448
                "[email protected]",
6449
                "-c",
6450
                "commit.gpgsign=false",
6451
            ])
6452
            .args(args)
6453
            .output()
6454
            .unwrap();
6455
        assert!(
6456
            out.status.success(),
6457
            "git {args:?}: {}",
6458
            String::from_utf8_lossy(&out.stderr)
6459
        );
6460
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6461
    };
6462
    git(&["init", "-q", "-b", "main"]);
6463
    write(&g, "d/a.txt", b"a\n");
6464
    write(&g, "c/x.txt", b"x\n");
6465
    git(&["add", "."]);
6466
    git(&["commit", "-qm", "base"]);
6467
    // One line: move x into d while d still stands.
6468
    git(&["checkout", "-qb", "side"]);
6469
    git(&["mv", "c/x.txt", "d/x.txt"]);
6470
    git(&["commit", "-qm", "x into d"]);
6471
    // The other: d goes, comes back, and x moves into it too.
6472
    git(&["checkout", "-q", "main"]);
6473
    git(&["rm", "-q", "d/a.txt"]);
6474
    git(&["commit", "-qm", "d goes"]);
6475
    write(&g, "d/b.txt", b"b\n");
6476
    git(&["add", "."]);
6477
    git(&["commit", "-qm", "d comes back"]);
6478
    git(&["mv", "c/x.txt", "d/x.txt"]);
6479
    git(&["commit", "-qm", "x into d again"]);
6480
    git(&["merge", "-q", "--no-edit", "side"]);
6481
6482
    let repo = Repo::init(&root.join("o")).unwrap();
6483
    repo.import_git(&g, "main").unwrap();
6484
    let v = repo.verify_git_import(&g, "main").unwrap();
6485
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6486
    let st = repo
6487
        .load_state_history(&repo.bookmark_heads().unwrap())
6488
        .unwrap();
6489
    let view = st.tree().view();
6490
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6491
    // The directory is the one the first commit made.
6492
    // Commits made in one second tie on time: find the first by its message.
6493
    let first = repo
6494
        .log()
6495
        .unwrap()
6496
        .into_iter()
6497
        .find(|e| e.change.message.starts_with("base"))
6498
        .unwrap();
6499
    let base = repo
6500
        .load_state_history(&[first.hash])
6501
        .unwrap()
6502
        .tree()
6503
        .view();
6504
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6505
}
6506
6507
/// oxygen#30, the rest: a placement left under a directory another line
6508
/// removed is out of sight, so no diff reaches it; the merge that settles
6509
/// where the file is retires it.
6510
#[test]
6511
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6512
    hermetic();
6513
    if std::process::Command::new("git")
6514
        .arg("--version")
6515
        .output()
6516
        .is_err()
6517
    {
6518
        eprintln!("git not installed; skipping");
6519
        return;
6520
    }
6521
    let dir = tempfile::tempdir().unwrap();
6522
    let root = dir.path();
6523
    let g = root.join("src.git");
6524
    fs::create_dir_all(&g).unwrap();
6525
    let run = |args: &[&str]| {
6526
        std::process::Command::new("git")
6527
            .arg("-C")
6528
            .arg(&g)
6529
            .args([
6530
                "-c",
6531
                "user.name=Grace",
6532
                "-c",
6533
                "[email protected]",
6534
                "-c",
6535
                "commit.gpgsign=false",
6536
            ])
6537
            .args(args)
6538
            .output()
6539
            .unwrap()
6540
    };
6541
    let git = |args: &[&str]| {
6542
        let out = run(args);
6543
        assert!(
6544
            out.status.success(),
6545
            "git {args:?}: {}",
6546
            String::from_utf8_lossy(&out.stderr)
6547
        );
6548
    };
6549
    git(&["init", "-q", "-b", "main"]);
6550
    write(&g, "c/x.txt", b"x\n");
6551
    write(&g, "keep.txt", b"k\n");
6552
    git(&["add", "."]);
6553
    git(&["commit", "-qm", "base"]);
6554
    // One line renames the file within c; the other moves it out of c,
6555
    // which goes.
6556
    git(&["checkout", "-qb", "side"]);
6557
    git(&["mv", "c/x.txt", "c/y.txt"]);
6558
    git(&["commit", "-qm", "rename within c"]);
6559
    git(&["checkout", "-q", "main"]);
6560
    fs::create_dir_all(g.join("n")).unwrap();
6561
    git(&["mv", "c/x.txt", "n/x.txt"]);
6562
    git(&["commit", "-qm", "move out of c"]);
6563
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6564
    let _ = run(&["merge", "-q", "side"]);
6565
    let _ = run(&[
6566
        "rm",
6567
        "-q",
6568
        "--cached",
6569
        "--ignore-unmatch",
6570
        "c/y.txt",
6571
        "c/x.txt",
6572
    ]);
6573
    let _ = std::fs::remove_dir_all(g.join("c"));
6574
    write(&g, "n/x.txt", b"x\n");
6575
    git(&["add", "-A"]);
6576
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6577
6578
    let repo = Repo::init(&root.join("o")).unwrap();
6579
    repo.import_git(&g, "main").unwrap();
6580
    let v = repo.verify_git_import(&g, "main").unwrap();
6581
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6582
    let st = repo
6583
        .load_state_history(&repo.bookmark_heads().unwrap())
6584
        .unwrap();
6585
    let view = st.tree().view();
6586
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6587
    assert!(view.entries.contains_key("n/x.txt"));
6588
}
6589
6590
/// oxygen#30, orphans: a file added on one line into a directory the other
6591
/// line removed is placed where the tree cannot show it; Git's merge keeps
6592
/// the file, and the import's merge leaves exactly one of it.
6593
#[test]
6594
fn git_import_merge_leaves_no_orphan_behind() {
6595
    hermetic();
6596
    if std::process::Command::new("git")
6597
        .arg("--version")
6598
        .output()
6599
        .is_err()
6600
    {
6601
        eprintln!("git not installed; skipping");
6602
        return;
6603
    }
6604
    let dir = tempfile::tempdir().unwrap();
6605
    let root = dir.path();
6606
    let g = root.join("src.git");
6607
    fs::create_dir_all(&g).unwrap();
6608
    let git = |args: &[&str]| {
6609
        let out = std::process::Command::new("git")
6610
            .arg("-C")
6611
            .arg(&g)
6612
            .args([
6613
                "-c",
6614
                "user.name=Grace",
6615
                "-c",
6616
                "[email protected]",
6617
                "-c",
6618
                "commit.gpgsign=false",
6619
            ])
6620
            .args(args)
6621
            .output()
6622
            .unwrap();
6623
        assert!(
6624
            out.status.success(),
6625
            "git {args:?}: {}",
6626
            String::from_utf8_lossy(&out.stderr)
6627
        );
6628
    };
6629
    git(&["init", "-q", "-b", "main"]);
6630
    write(&g, "d/f.txt", b"f\n");
6631
    write(&g, "keep.txt", b"k\n");
6632
    git(&["add", "."]);
6633
    git(&["commit", "-qm", "base"]);
6634
    git(&["checkout", "-qb", "side"]);
6635
    write(&g, "d/new.txt", b"new\n");
6636
    git(&["add", "."]);
6637
    git(&["commit", "-qm", "add into d"]);
6638
    git(&["checkout", "-q", "main"]);
6639
    git(&["rm", "-q", "d/f.txt"]);
6640
    git(&["commit", "-qm", "d goes"]);
6641
    git(&["merge", "-q", "--no-edit", "side"]);
6642
6643
    let repo = Repo::init(&root.join("o")).unwrap();
6644
    repo.import_git(&g, "main").unwrap();
6645
    let v = repo.verify_git_import(&g, "main").unwrap();
6646
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6647
    let st = repo
6648
        .load_state_history(&repo.bookmark_heads().unwrap())
6649
        .unwrap();
6650
    let view = st.tree().view();
6651
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6652
    assert!(view.entries.contains_key("d/new.txt"));
6653
}
d77e1702 Andy McCall ↶ 6654
6655
/// fsck checks a change's text as the blobs it is stored in, without
6656
/// decoding it: a missing text blob is an error named for the change.
6657
#[test]
6658
fn fsck_names_a_missing_text_blob() {
6659
    hermetic();
6660
    let dir = tempfile::tempdir().unwrap();
6661
    let root = dir.path();
6662
    let repo = Repo::init(root).unwrap();
6663
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6664
    write(root, "big.txt", big.as_bytes());
6665
    let h = repo.commit("big", &[]).unwrap();
6666
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6667
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6668
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6669
        panic!("a stored text")
6670
    };
64818938 Andy McCall ↶ 6671
    repo.store().remove_loose_for_test(&b).unwrap();
d77e1702 Andy McCall ↶ 6672
    let rep = repo.fsck().unwrap();
6673
    assert!(rep.errors() > 0);
6674
    assert!(
6675
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6676
        "{:?}",
6677
        rep.problems
6678
    );
6679
}
a07f60a3 Andy McCall ↶ 6680
6681
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6682
/// reached with that remote's token and CA (a private subrepo then clones
6683
/// for anyone who can read the parent); another hub gets none of them.
6684
#[test]
6685
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6686
    hermetic();
6687
    let dir = tempfile::tempdir().unwrap();
6688
    let mut repo = Repo::init(dir.path()).unwrap();
6689
    repo.config
6690
        .set(
6691
            "remote.origin.url",
6692
            "https://Hub.example:7343/doomsdayone/metalgear",
6693
        )
6694
        .unwrap();
6695
    repo.config.set("remote.origin.token", "secret").unwrap();
6696
    repo.config
6697
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6698
        .unwrap();
6699
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6700
    assert_eq!(same.token.as_deref(), Some("secret"));
6701
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6702
    for other in [
6703
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6704
        "https://hub.example/doomsdayone/rstar-api",
6705
        "http://hub.example:7343/doomsdayone/rstar-api",
6706
    ] {
6707
        let o = repo.credentials_for(other);
6708
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6709
    }
6710
}
ce14f0d6 Andy McCall ↶ 6711
ff1f62fe Andy McCall ↶ 6712
/// oxygen#47: a remote with no token of its own uses the user's credential
6713
/// store for its hub, and a nested checkout finds its parent's remote
6714
/// token there instead of keeping a copy.
ce14f0d6 Andy McCall ↶ 6715
#[test]
ff1f62fe Andy McCall ↶ 6716
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
6717
    hermetic();
6718
    let home = tempfile::tempdir().unwrap();
6719
    let dir = tempfile::tempdir().unwrap();
6720
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
6721
    parent
6722
        .config
6723
        .set("remote.origin.url", "https://hub.example/o/parent")
6724
        .unwrap();
6725
    parent.save_config().unwrap();
6726
    assert_eq!(parent.remote_options("origin").token, None);
6727
    crate::credentials::Credentials::at(home.path())
6728
        .save("https://hub.example", "stored", Some("andy"), None)
6729
        .unwrap();
6730
    assert_eq!(
6731
        parent.remote_options("origin").token.as_deref(),
6732
        Some("stored")
6733
    );
6734
6735
    let empty_home = tempfile::tempdir().unwrap();
6736
    let nested = dir.path().join("deps").join("child");
6737
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
6738
    child
6739
        .config
6740
        .set("remote.origin.url", "https://hub.example/o/child")
6741
        .unwrap();
6742
    child.save_config().unwrap();
6743
    assert_eq!(child.remote_options("origin").token, None);
6744
    parent
6745
        .config
6746
        .set("remote.origin.token", "checkout")
6747
        .unwrap();
6748
    parent.save_config().unwrap();
6749
    assert_eq!(
6750
        child.remote_options("origin").token.as_deref(),
6751
        Some("checkout")
6752
    );
6753
    // Another hub's checkout token is not borrowed.
6754
    child
6755
        .config
6756
        .set("remote.origin.url", "https://other.example/o/child")
6757
        .unwrap();
6758
    assert_eq!(child.remote_options("origin").token, None);
6759
}
6760
6761
#[test]
ce14f0d6 Andy McCall ↶ 6762
fn the_metadata_cache_survives_a_torn_tail() {
6763
    hermetic();
6764
    let dir = tempfile::tempdir().unwrap();
6765
    let root = dir.path();
6766
    let repo = Repo::init(root).unwrap();
6767
    write(root, "a.txt", b"1\n");
6768
    let h = repo.commit("first", &[]).unwrap();
6769
    let meta = repo.store().get_change_meta(&h).unwrap();
6770
    let cache = repo.store().dir().join("metas");
6771
    let len = fs::metadata(&cache).unwrap().len();
6772
    assert!(len > 0, "a change read is cached");
6773
    // A torn record at the end: the cache reads up to it and cuts it off.
6774
    fs::OpenOptions::new()
6775
        .append(true)
6776
        .open(&cache)
6777
        .unwrap()
6778
        .write_all(&[7; 20])
6779
        .unwrap();
6780
    let again = Repo::open(root).unwrap();
6781
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
6782
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
6783
}
f9466021 Andy McCall ↶ 6784
6785
#[test]
6786
fn a_manifest_that_does_not_check_reads_as_none() {
6787
    hermetic();
6788
    let dir = tempfile::tempdir().unwrap();
6789
    let root = dir.path();
6790
    let repo = Repo::init(root).unwrap();
6791
    write(root, "a.txt", b"1\n");
6792
    repo.commit("first", &[]).unwrap();
6793
    let path = repo.manifest_path();
6794
    let mut bytes = fs::read(&path).unwrap();
6795
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
6796
    let last = bytes.len() - 1;
6797
    bytes[last] ^= 1;
6798
    fs::write(&path, &bytes).unwrap();
6799
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
6800
    // The next status reads the files and writes it again.
6801
    let again = Repo::open(root).unwrap();
6802
    assert!(!again.snapshot("status").unwrap().changed);
6803
    assert!(again.read_manifest().unwrap().is_some());
6804
}
6805
6806
#[test]
6807
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
6808
    hermetic();
6809
    let dir = tempfile::tempdir().unwrap();
6810
    let root = dir.path();
6811
    let repo = Repo::init(root).unwrap();
6812
    write(root, "a.txt", b"1\n");
6813
    write(root, "b.txt", b"2\n");
6814
    // b.txt outside the racy window, so snapshots take it as unchanged.
6815
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6816
    fs::File::options()
6817
        .write(true)
6818
        .open(root.join("b.txt"))
6819
        .unwrap()
6820
        .set_modified(old)
6821
        .unwrap();
6822
    repo.commit("first", &[]).unwrap();
6823
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
6824
    repo.snapshot_status("status").unwrap();
6825
    write(root, "a.txt", b"1\n2\n");
6826
    repo.commit("second", &[]).unwrap();
6827
    assert!(
6828
        repo.clean_by_manifest().unwrap(),
6829
        "after a commit of one file"
6830
    );
6831
    // Edited, seen by a status, edited again, then committed: the status
6832
    // left the first edit's stat, which the commit must not keep.
6833
    write(root, "a.txt", b"1\n2\n3\n");
6834
    repo.snapshot_status("status").unwrap();
6835
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
6836
    repo.commit("third", &[]).unwrap();
6837
    assert!(
6838
        repo.clean_by_manifest().unwrap(),
6839
        "after an edit a status saw"
6840
    );
6841
}
e266b7d4 Andy McCall ↶ 6842
6843
#[test]
6844
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
6845
    hermetic();
6846
    let dir = tempfile::tempdir().unwrap();
6847
    let root = dir.path();
6848
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6849
    write(root, "a.txt", b"1\n2\n");
6850
    let a = repo.commit("A", &[]).unwrap();
6851
    repo.bookmark_create("develop", Some(&[a])).unwrap();
6852
    write(root, "a.txt", b"1\nX\n");
6853
    let c = repo.commit("C: 2 to X", &[]).unwrap();
6854
    repo.bookmark_switch("develop", false).unwrap();
6855
    write(root, "a.txt", b"1\nY\n");
6856
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
6857
    repo.bookmark_switch("main", false).unwrap();
6858
6859
    let err = repo.rebase(&c, &[d]).unwrap_err();
6860
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
6861
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
6862
    assert!(r.changed && r.checked_out);
6863
    let snap = repo.snapshot_status("status").unwrap();
6864
    assert!(
6865
        snap.base_snapshot.is_conflicted(),
6866
        "the conflict is in the working copy"
6867
    );
6868
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
6869
    assert!(text.contains('X') && text.contains('Y'), "{text}");
6870
6871
    write(root, "a.txt", b"1\nXY\n");
6872
    repo.commit("Resolve", &[]).unwrap();
6873
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
6874
    assert!(st.contains(&c) && st.contains(&d));
6875
    let files = st.materialize().files;
6876
    assert!(!files["a.txt"].is_conflicted());
6877
    assert!(
6878
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
6879
    );
6880
6881
    // A change the current bookmark does not hold is refused.
6882
    repo.bookmark_switch("develop", false).unwrap();
6883
    write(root, "b.txt", b"b\n");
6884
    let e = repo.commit("E", &[]).unwrap();
6885
    repo.bookmark_switch("main", false).unwrap();
6886
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
6887
    assert!(
6888
        err.to_string().contains("not on the current bookmark"),
6889
        "{err}"
6890
    );
6891
}
d4dbab97 Andy McCall ↶ 6892
6893
#[test]
6894
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
6895
    hermetic();
6896
    let dir = tempfile::tempdir().unwrap();
6897
    let root = dir.path();
6898
    let repo = Repo::init(root).unwrap();
6899
    write(root, "a.txt", b"a\n");
6900
    write(root, "kept.log", b"tracked\n");
6901
    repo.commit("first", &[]).unwrap();
6902
    write(root, "build.log", b"made\n");
6903
    let snap = repo.snapshot_status("status").unwrap();
6904
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
6905
    // A rule written afterwards leaves the added file out again, while the
6906
    // committed one stays tracked.
6907
    write(root, ".gitignore", b"*.log\n");
6908
    let snap = repo.snapshot_status("status").unwrap();
6909
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
6910
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
6911
    write(root, "kept.log", b"tracked, edited\n");
6912
    let snap = repo.snapshot_status("status").unwrap();
6913
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
6914
}
fd280228 Andy McCall ↶ 6915
6916
#[test]
6917
fn shed_graphs_come_back_the_same() {
6918
    hermetic();
6919
    let dir = tempfile::tempdir().unwrap();
6920
    let root = dir.path();
6921
    let repo = Repo::init(root).unwrap();
6922
    write(root, "a.txt", b"1\n2\n3\n");
6923
    write(root, "b.txt", b"x\n");
6924
    repo.commit("first", &[]).unwrap();
6925
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
6926
    repo.commit("second", &[]).unwrap();
6927
    let heads = repo.bookmark_heads().unwrap();
6928
    let mut st = repo.load_state_history(&heads).unwrap();
6929
    let view = st.tree().view();
6930
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
6931
        .iter()
6932
        .map(|p| view.entries[*p].node)
6933
        .collect();
6934
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6935
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6936
    assert_eq!(st.built_count(), 2);
6937
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
6938
    assert_eq!((shed, st.built_count()), (2, 0));
6939
    // A later change applies on top of the shed history.
6940
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
6941
    let h3 = repo.commit("third", &[]).unwrap();
6942
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
6943
    st.add_known(h3, skeleton, texts);
6944
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6945
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6946
    assert_eq!(after[1], before[1]);
6947
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
6948
}
360aa74a Andy McCall ↶ 6949
6950
#[test]
6951
fn many_edited_files_diff_in_parallel() {
6952
    // Enough edited files that the builder diffs them in parallel; the
6953
    // commit must hold exactly what is on disk, and a second snapshot
6954
    // must find nothing left to commit.
6955
    hermetic();
6956
    let dir = tempfile::tempdir().unwrap();
6957
    let root = dir.path();
6958
    let repo = Repo::init(root).unwrap();
6959
    let text = |i: usize, round: usize| {
6960
        let mut s = String::new();
6961
        for line in 0..50 {
6962
            if round > 0 && line % 7 == i % 7 {
6963
                s.push_str(&format!("edited {round} {i} {line}\n"));
6964
            } else {
6965
                s.push_str(&format!("file {i} line {line}\n"));
6966
            }
6967
        }
6968
        if round > 0 && i.is_multiple_of(3) {
6969
            s.push_str("appended\n");
6970
        }
6971
        s
6972
    };
6973
    for i in 0..40 {
6974
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
6975
    }
6976
    repo.commit("first", &[]).unwrap();
6977
    for i in 0..40 {
6978
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
6979
    }
6980
    let h = repo.commit("edit every file", &[]).unwrap();
6981
    let snap = repo.load_state(&[h]).unwrap().materialize();
6982
    for i in 0..40 {
6983
        let want = text(i, 1);
6984
        assert!(
6985
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
6986
            "d/f{i}.txt as committed"
6987
        );
6988
    }
6989
    assert!(
6990
        repo.commit("nothing", &[]).is_err(),
6991
        "nothing left to commit"
6992
    );
6993
}
b35df36b Andy McCall ↶ 6994
6995
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
6996
/// is known (fetch printed "up to date" while main was behind), a change
6997
/// only fetched resolves and says where it is, and a checkout whose only
6998
/// remote is not `origin` uses that one.
6999
#[test]
7000
fn a_fetched_change_shows_as_behind_and_resolves() {
7001
    hermetic();
7002
    let dir = tempfile::tempdir().unwrap();
7003
    let root = dir.path();
7004
    let origin = Repo::init(&root.join("origin")).unwrap();
7005
    drop(origin);
7006
    let url = root.join("origin").to_string_lossy().to_string();
7007
    let a = Repo::clone(&url, &root.join("a"))
7008
        .unwrap()
7009
        .with_home(root.join("home-a"));
7010
    write(&root.join("a"), "f.txt", b"one\n");
7011
    a.commit("one", &[]).unwrap();
7012
    a.push("origin", false).unwrap();
7013
    let b = Repo::clone(&url, &root.join("b"))
7014
        .unwrap()
7015
        .with_home(root.join("home-b"));
7016
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7017
7018
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7019
    let h2 = a.commit("two", &[]).unwrap();
7020
    a.push("origin", false).unwrap();
7021
    b.fetch("origin").unwrap();
7022
    // Fetched, not pulled: one behind, the change found and placed.
7023
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7024
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7025
    assert_eq!(
7026
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7027
            .unwrap(),
7028
        h2
7029
    );
7030
    assert_eq!(
7031
        b.remote_only_location(&h2).unwrap().as_deref(),
7032
        Some("origin/main")
7033
    );
7034
    // Fetching again changes nothing: still behind, which is what the
7035
    // CLI now says rather than "up to date".
7036
    b.fetch("origin").unwrap();
7037
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7038
    b.pull("origin").unwrap();
7039
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7040
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7041
7042
    // One remote, not called origin: it is the default.
7043
    let mut c = Repo::init(&root.join("c")).unwrap();
7044
    assert_eq!(c.default_remote(), "origin");
7045
    c.config.set("remote.earth.url", &url).unwrap();
7046
    assert_eq!(c.default_remote(), "earth");
7047
    c.config.set("remote.origin.url", &url).unwrap();
7048
    assert_eq!(c.default_remote(), "origin");
7049
}
827281ee Andy McCall ↶ 7050
7051
/// oxygen#57: a clone from a relative local path records the remote as an
7052
/// absolute path, so fetch still finds it from inside the clone.
7053
#[test]
7054
fn a_clone_from_a_relative_path_records_it_absolute() {
7055
    hermetic();
7056
    let dir = tempfile::tempdir().unwrap();
7057
    let root = dir.path();
7058
    Repo::init(&root.join("origin")).unwrap();
7059
    let rel = crate::protocol::stored_url("relative/repo");
7060
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7061
    assert_eq!(
7062
        crate::protocol::stored_url("https://hub.example/o/n"),
7063
        "https://hub.example/o/n"
7064
    );
7065
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8d803563 Andy McCall ↶ 7066
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7067
    // A bucket is kept as written: it is not a path.
7068
    assert_eq!(
7069
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7070
        "s3://bucket/prefix?profile=p"
7071
    );
827281ee Andy McCall ↶ 7072
    let url = root.join("origin").to_string_lossy().to_string();
7073
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7074
    assert_eq!(b.config.remotes["origin"], url);
7075
    b.fetch("origin").unwrap();
7076
}
a46f3e4f Andy McCall ↶ 7077
7078
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7079
/// and gets its subrepos at their pins from this workspace's copies, with
7080
/// their remotes pointing where the subrepos come from.
7081
#[test]
7082
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7083
    hermetic();
7084
    let dir = tempfile::tempdir().unwrap();
7085
    let root = dir.path();
7086
    Repo::init(&root.join("lib-origin")).unwrap();
7087
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7088
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7089
        .unwrap()
7090
        .with_home(root.join("home"));
7091
    write(&root.join("lib"), "lib.txt", b"v1\n");
7092
    let l1 = lib.commit("lib v1", &[]).unwrap();
7093
    assert!(lib.push("origin", false).unwrap()[0].ok);
7094
7095
    let app_dir = root.join("app");
7096
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7097
    write(&app_dir, "main.txt", b"app\n");
7098
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7099
    app.commit("app with lib", &[]).unwrap();
7100
    // A second bookmark, and the main workspace on another.
7101
    app.bookmark_create("develop", None).unwrap();
7102
    app.bookmark_create("feature", None).unwrap();
7103
    let mut app = app;
7104
    app.bookmark_switch("feature", false).unwrap();
7105
    assert_eq!(app.config.bookmark, "feature");
7106
7107
    // The library's origin goes away: the subrepo must come from here.
7108
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7109
    let heads = app.resolve_heads("develop").unwrap();
7110
    let ws = app
7111
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7112
        .unwrap();
7113
    assert_eq!(
7114
        ws.config.bookmark, "develop",
7115
        "the new workspace is on develop"
7116
    );
7117
    assert_eq!(
7118
        app.config.bookmark, "feature",
7119
        "and this one stays on its own"
7120
    );
7121
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7122
    assert_eq!(
7123
        sub.config.remotes["origin"], lib_url,
7124
        "its origin is the subrepo's URL"
7125
    );
7126
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7127
    assert_eq!(
7128
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7129
        b"v1\n"
7130
    );
7131
}
47ce8b8e Andy McCall ↶ 7132
7133
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7134
/// operators and the predicates, over a small graph with two heads and
7135
/// a rename.
7136
#[test]
7137
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7138
    hermetic();
7139
    let dir = tempfile::tempdir().unwrap();
7140
    let root = dir.path();
7141
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7142
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7143
        .unwrap();
7144
    write(root, "src/a.rs", b"one\n");
7145
    let a = repo.commit("first: add a", &[]).unwrap();
7146
    write(root, "src/a.rs", b"one\ntwo\n");
7147
    let b = repo.commit("second: grow a", &[]).unwrap();
7148
    // A second head, independent of b: a new file on top of a.
7149
    repo.checkout(&[a], false, "checkout a").unwrap();
7150
    write(root, "docs/notes.md", b"notes\n");
7151
    let c = repo.commit("third: notes", &[]).unwrap();
7152
    // Back to both heads, then rename a.rs: the node keeps its identity.
7153
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7154
        .unwrap();
7155
    fs::remove_file(root.join("src/a.rs")).unwrap();
7156
    write(root, "src/z.rs", b"one\ntwo\n");
7157
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7158
    let wc = repo.working_copy().unwrap().0;
7159
    // A saved revset is checked when set.
7160
    repo.set_user_config("revset.mine", "author(me) & ::main")
7161
        .unwrap();
7162
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7163
    let set = |src: &str| -> Vec<ChangeHash> {
7164
        let mut v = repo.revset(src).unwrap().hashes;
7165
        v.sort();
7166
        v
7167
    };
7168
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7169
        let mut v = hs.to_vec();
7170
        v.sort();
7171
        v
7172
    };
7173
7174
    // Changes commute: a new file depends on nothing and the rename on the
7175
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7176
    // copy on the three heads b, c, d.
7177
    let heads = sorted(&repo.bookmark_heads().unwrap());
7178
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7179
    assert!(heads.contains(&d) && heads.contains(&c));
7180
    // Symbols and closures.
7181
    assert_eq!(set("main"), heads);
7182
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7183
    assert_eq!(set("@"), vec![wc]);
7184
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7185
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7186
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7187
    assert_eq!(
7188
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7189
        sorted(&[a, b])
7190
    );
7191
    // Ranges: what main has beyond b, and `..` forms.
7192
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7193
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7194
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7195
    // Operators and precedence: ~ binds tighter than &, & than |.
7196
    assert_eq!(
7197
        set(&format!("::main ~ #{}", d.short(12))),
7198
        sorted(&[a, b, c])
7199
    );
7200
    assert_eq!(
7201
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7202
        sorted(&[b, c])
7203
    );
7204
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7205
    // Relations.
7206
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7207
    head_deps.sort();
7208
    head_deps.dedup();
7209
    assert_eq!(set("deps(main)"), head_deps);
7210
    let on_a: Vec<ChangeHash> = [b, c, d]
7211
        .into_iter()
7212
        .filter(|h| meta(h).deps.contains(&a))
7213
        .collect();
7214
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7215
    assert_eq!(set("heads(::main)"), heads);
7216
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7217
    assert_eq!(
7218
        set(&format!(
7219
            "heads(#{} | #{} | #{})",
7220
            a.short(12),
7221
            b.short(12),
7222
            c.short(12)
7223
        )),
7224
        sorted(&[b, c])
7225
    );
7226
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7227
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7228
    assert_eq!(set("none()"), vec![]);
7229
    // Predicates: author by name, email, key prefix and `me`.
7230
    let key = repo.config.author_key.unwrap();
7231
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7232
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7233
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7234
    assert_eq!(set("author(me) & ::main").len(), 4);
7235
    assert_eq!(set("author(nobody)"), vec![]);
7236
    assert_eq!(set("description(notes)"), vec![c]);
7237
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7238
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7239
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7240
    // touches follows the node through the rename, in the current state.
7241
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7242
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7243
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7244
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7245
    // Newest first in the result order.
7246
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7247
    // The saved revset, and errors that say what is wrong.
7248
    assert_eq!(set("mine()").len(), 4);
7249
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7250
    assert!(e.contains("unknown function nosuch()"), "{e}");
7251
    let e = repo.revset("main &").unwrap_err().to_string();
7252
    assert!(e.contains("at character"), "{e}");
7253
    let e = repo.revset("zzzz").unwrap_err().to_string();
7254
    assert!(e.contains("no change matches"), "{e}");
7255
    let e = repo
7256
        .revset_with_budget("::main", std::time::Duration::ZERO)
7257
        .unwrap_err()
7258
        .to_string();
7259
    assert!(e.contains("budget"), "{e}");
7260
    // The log entries carry the bookmark's heads and the working copy.
7261
    let entries = repo.log_revset("::@").unwrap();
7262
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
2c9ddac3 Andy McCall ↶ 7263
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7264
    // push); then a signed change, a tag, and a revocation.
7265
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7266
    assert_eq!(set("signed_by(me)"), vec![]);
7267
    repo.sign_change(&d).unwrap();
7268
    assert_eq!(set("signed_by(me)"), vec![d]);
7269
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7270
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7271
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7272
    assert_eq!(set("delegated()"), vec![]);
7273
    assert_eq!(set("revoked()"), vec![]);
7274
    assert_eq!(set("attested(tag)"), vec![]);
7275
    repo.tag_create("v1", &[b], "first").unwrap();
7276
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7277
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7278
    assert_eq!(set("attested(receipt)"), vec![]);
7279
    assert_eq!(set("built(test)"), vec![]);
7280
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7281
    assert!(e.contains("tag, receipt or ref"), "{e}");
7282
    repo.revoke_identity(&key, "test").unwrap();
7283
    assert_eq!(set("revoked()"), vec![d]);
7284
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
543bbf64 Andy McCall ↶ 7285
    // independent(X, IN): what could ship without X. c and d neither
7286
    // depend on b nor are depended on by it; a is below, the working copy
7287
    // above.
7288
    assert_eq!(
7289
        set(&format!("independent(#{}, ::@)", b.short(12))),
7290
        sorted(&[c, d])
7291
    );
7292
    assert_eq!(
7293
        set(&format!("independent(#{}, ::main)", a.short(12))),
7294
        vec![c]
7295
    );
7296
    // conflicts(S): nothing conflicts yet; then two edits of one line.
7297
    assert_eq!(set("conflicts()"), vec![]);
7298
    assert_eq!(set("conflicts(main)"), vec![]);
7299
    // (The saved revset above edited the user config under the root:
7300
    // discard it.)
7301
    repo.checkout(&[a], true, "checkout a").unwrap();
7302
    write(root, "src/a.rs", b"one\nTWO\n");
7303
    let e = repo
7304
        .commit("fifth: the other edit of line two", &[])
7305
        .unwrap();
7306
    repo.checkout(&repo.bookmark_heads().unwrap(), true, "checkout main")
7307
        .unwrap();
7308
    let conflicted = repo.revset("conflicts()").unwrap().hashes;
7309
    assert!(
7310
        conflicted.contains(&e) && conflicted.contains(&b),
7311
        "{conflicted:?} should hold b and e"
7312
    );
7313
    assert!(!conflicted.contains(&c));
7314
    assert_eq!(set("conflicts() & author(nobody)"), vec![]);
47ce8b8e Andy McCall ↶ 7315
}
614f55e1 Andy McCall ↶ 7316
7317
#[test]
7318
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7319
    let dir = tempfile::tempdir().unwrap();
7320
    let root = dir.path();
7321
    let home = root.join("home");
7322
    // Ada's identity lives in the user file; repository `a` pins the same
7323
    // key in its own file, repository `b` names none.
7324
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7325
    let (key, _) = a
7326
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7327
        .unwrap();
7328
    a.config.set("author.key", &key.to_hex()).unwrap();
7329
    a.save_config().unwrap();
7330
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7331
    let r = a
7332
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7333
        .unwrap();
7334
    assert_eq!(
7335
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7336
        r.new.to_hex(),
7337
        "the user file follows"
7338
    );
7339
    assert_eq!(
7340
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7341
        r.new.to_hex(),
7342
        "the pinning repository follows"
7343
    );
7344
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7345
    assert_eq!(
7346
        b.config.author_key,
7347
        Some(r.new),
7348
        "a checkout without a pin follows the user file"
7349
    );
7350
    // A repository-scoped identity leaves the user file alone.
7351
    let other_home = root.join("home2");
7352
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7353
    let (ck, _) = c
7354
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7355
        .unwrap();
7356
    assert!(!other_home.join("config.toml").exists());
7357
    let r2 = c.rotate_identity().unwrap();
7358
    assert_ne!(r2.new, ck);
7359
    assert_eq!(
7360
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7361
        r2.new.to_hex()
7362
    );
7363
    assert!(
7364
        !other_home.join("config.toml").exists(),
7365
        "a repository-scoped identity stays repository-scoped"
7366
    );
7367
    // Several delegates in one rotation; a repeat is refused.
7368
    let (d1, d2) = (
7369
        SecretKey::generate().identity("D1", "d1@x", 1),
7370
        SecretKey::generate().identity("D2", "d2@x", 1),
7371
    );
7372
    let r3 = c
7373
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7374
        .unwrap();
7375
    assert_eq!(r3.identity.delegates.len(), 2);
7376
    assert!(c
7377
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7378
        .is_err());
7379
}
33be2409 Andy McCall ↶ 7380
7381
/// Two unrelated histories that both add the same file, joined by two
7382
/// independent merges on two branches, then those branches merged: Git
7383
/// merges identical additions cleanly, and the import must too (#71,
7384
/// found in VS Code's history).
7385
#[test]
7386
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7387
    // Batches of one: every merge renders apart from the state, where a
7388
    // file whose graph the state had built came out empty (#71).
7389
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7390
    hermetic();
7391
    if std::process::Command::new("git")
7392
        .arg("--version")
7393
        .output()
7394
        .is_err()
7395
    {
7396
        eprintln!("git not installed; skipping");
7397
        return;
7398
    }
7399
    let dir = tempfile::tempdir().unwrap();
7400
    let root = dir.path();
7401
    let g = root.join("src.git");
7402
    fs::create_dir_all(&g).unwrap();
7403
    let git = |args: &[&str]| -> String {
7404
        let out = std::process::Command::new("git")
7405
            .arg("-C")
7406
            .arg(&g)
7407
            .args([
7408
                "-c",
7409
                "user.name=Grace",
7410
                "-c",
7411
                "[email protected]",
7412
                "-c",
7413
                "commit.gpgsign=false",
7414
            ])
7415
            .args(args)
7416
            .output()
7417
            .unwrap();
7418
        assert!(
7419
            out.status.success(),
7420
            "git {args:?}: {}",
7421
            String::from_utf8_lossy(&out.stderr)
7422
        );
7423
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7424
    };
7425
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7426
    // History A: main.
7427
    git(&["init", "-q", "-b", "main"]);
7428
    write(&g, "gulpfile.js", text);
7429
    write(&g, "a.txt", b"a\n");
7430
    git(&["add", "."]);
7431
    git(&["commit", "-q", "-m", "A root"]);
7432
    // History B: an unrelated root adding the same file, identical.
7433
    git(&["checkout", "-q", "--orphan", "fork"]);
7434
    git(&["rm", "-q", "-r", "--cached", "."]);
7435
    for f in ["gulpfile.js", "a.txt"] {
7436
        let _ = fs::remove_file(g.join(f));
7437
    }
7438
    write(&g, "gulpfile.js", text);
7439
    write(&g, "b.txt", b"b\n");
7440
    git(&["add", "."]);
7441
    git(&["commit", "-q", "-m", "B root"]);
7442
    // Two branches from main, each joining B on its own.
7443
    git(&["checkout", "-q", "-b", "one", "main"]);
7444
    git(&[
7445
        "merge",
7446
        "-q",
7447
        "--no-ff",
7448
        "--allow-unrelated-histories",
7449
        "-m",
7450
        "join on one",
7451
        "fork",
7452
    ]);
7453
    git(&["checkout", "-q", "-b", "two", "main"]);
7454
    write(&g, "a.txt", b"a\ntwo\n");
7455
    git(&["commit", "-q", "-am", "work on two"]);
7456
    git(&[
7457
        "merge",
7458
        "-q",
7459
        "--no-ff",
7460
        "--allow-unrelated-histories",
7461
        "-m",
7462
        "join on two",
7463
        "fork",
7464
    ]);
7465
    // Then the two joins meet, and the file is reformatted after.
7466
    git(&["checkout", "-q", "main"]);
7467
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7468
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7469
    write(
7470
        &g,
7471
        "gulpfile.js",
7472
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7473
    );
7474
    git(&["commit", "-q", "-am", "after"]);
7475
7476
    let dest = root.join("dest");
7477
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7478
    repo.import_git(&g, "main").unwrap();
7479
    let v = repo.verify_git_import(&g, "main").unwrap();
7480
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7481
    assert_eq!(
7482
        fs::read(dest.join("gulpfile.js")).unwrap(),
7483
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7484
    );
7485
}
7486
7487
/// As above, but the two joins keep different copies (each branch had a
7488
/// different version when it joined), and later work edits each copy:
7489
/// the shape of VS Code's c67ef57cda90 (#71).
7490
#[test]
7491
fn git_import_joins_where_each_join_kept_a_different_copy() {
7492
    // Batches of one: every merge renders apart from the state, where a
7493
    // file whose graph the state had built came out empty (#71).
7494
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7495
    hermetic();
7496
    if std::process::Command::new("git")
7497
        .arg("--version")
7498
        .output()
7499
        .is_err()
7500
    {
7501
        eprintln!("git not installed; skipping");
7502
        return;
7503
    }
7504
    let dir = tempfile::tempdir().unwrap();
7505
    let root = dir.path();
7506
    let g = root.join("src.git");
7507
    fs::create_dir_all(&g).unwrap();
7508
    let run = |args: &[&str]| {
7509
        std::process::Command::new("git")
7510
            .arg("-C")
7511
            .arg(&g)
7512
            .args([
7513
                "-c",
7514
                "user.name=Grace",
7515
                "-c",
7516
                "[email protected]",
7517
                "-c",
7518
                "commit.gpgsign=false",
7519
            ])
7520
            .args(args)
7521
            .output()
7522
            .unwrap()
7523
    };
7524
    let git = |args: &[&str]| -> String {
7525
        let out = run(args);
7526
        assert!(
7527
            out.status.success(),
7528
            "git {args:?}: {}",
7529
            String::from_utf8_lossy(&out.stderr)
7530
        );
7531
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7532
    };
7533
    git(&["init", "-q", "-b", "main"]);
7534
    write(
7535
        &g,
7536
        "gulpfile.js",
7537
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7538
    );
7539
    git(&["add", "."]);
7540
    git(&["commit", "-q", "-m", "A root"]);
7541
    write(
7542
        &g,
7543
        "gulpfile.js",
7544
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7545
    );
7546
    git(&["commit", "-q", "-am", "whitespace"]);
7547
    git(&["checkout", "-q", "--orphan", "fork"]);
7548
    git(&["rm", "-q", "-r", "--cached", "."]);
7549
    let _ = fs::remove_file(g.join("gulpfile.js"));
7550
    write(
7551
        &g,
7552
        "gulpfile.js",
7553
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7554
    );
7555
    git(&["add", "."]);
7556
    git(&["commit", "-q", "-m", "B root"]);
7557
    // Branch one joins B keeping main's copy; branch two keeps B's.
7558
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7559
        git(&["checkout", "-q", "-b", branch, "main"]);
7560
        let _ = run(&[
7561
            "merge",
7562
            "-q",
7563
            "--no-ff",
7564
            "--allow-unrelated-histories",
7565
            "-m",
7566
            "join",
7567
            "fork",
7568
        ]);
7569
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7570
        git(&["add", "gulpfile.js"]);
7571
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7572
    }
7573
    // Each branch then edits its copy.
7574
    git(&["checkout", "-q", "one"]);
7575
    write(
7576
        &g,
7577
        "gulpfile.js",
7578
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7579
    );
7580
    git(&["commit", "-q", "-am", "tslint on one"]);
7581
    git(&["checkout", "-q", "two"]);
7582
    write(
7583
        &g,
7584
        "gulpfile.js",
7585
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7586
    );
7587
    write(&g, "extra.txt", b"x\n");
7588
    write(&g, "more.txt", b"m\n");
7589
    git(&["add", "."]);
7590
    git(&["commit", "-q", "-am", "fmt on two"]);
7591
    // They meet: resolved by hand.
7592
    git(&["checkout", "-q", "one"]);
7593
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7594
    write(
7595
        &g,
7596
        "gulpfile.js",
7597
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7598
    );
7599
    git(&["add", "gulpfile.js"]);
7600
    git(&["commit", "-q", "-m", "merge two into one"]);
7601
7602
    let dest = root.join("dest");
7603
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7604
    repo.import_git(&g, "one").unwrap();
7605
    let v = repo.verify_git_import(&g, "one").unwrap();
7606
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7607
}
dd21fd82 Andy McCall ↶ 7608
7609
/// oxygen#68: on a store that is not this disk's directory, the operation
7610
/// head is the store's reference record, moved by compare-and-swap. Two
7611
/// handles recording from the same head both get through, merged; a swap
7612
/// from a stale version is refused; a second repository cannot start on a
7613
/// store that already holds one.
7614
#[test]
7615
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
7616
    use crate::strata::{MemoryStore, Store as _};
7617
    let backend = std::sync::Arc::new(MemoryStore::new());
7618
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
7619
    let dir = tempfile::tempdir().unwrap();
7620
    let a = Repo::init(dir.path()).unwrap();
7621
    assert!(
7622
        !dir.path().join(".oxy/ops/head").exists(),
7623
        "the head is not a file"
7624
    );
7625
    let (h0, op0) = a.head_op().unwrap();
7626
    let record = backend
7627
        .read_ref(HEAD_RECORD)
7628
        .unwrap()
7629
        .expect("the head is the store's record");
7630
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
7631
7632
    let b = Repo::open(dir.path()).unwrap();
7633
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
7634
    let mut va = op0.view.clone();
7635
    va.bookmarks.insert("from-a".into(), state);
7636
    let mut vb = op0.view.clone();
7637
    vb.bookmarks.insert("from-b".into(), state);
7638
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
7639
    assert_eq!(b.head_ref().unwrap(), rb);
7640
    // a recorded from h0 too: the head moved, so the two are merged.
7641
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
7642
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
7643
    assert_eq!(head, ra);
7644
    assert!(
7645
        op.command.ends_with("(merged with a concurrent operation)"),
7646
        "{}",
7647
        op.command
7648
    );
7649
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
7650
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
7651
7652
    // A swap from a version that is no longer current moves nothing.
7653
    let (h, v) = a.read_head().unwrap();
7654
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
7655
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
7656
    assert_eq!(a.head_ref().unwrap(), rb);
7657
7658
    let other = tempfile::tempdir().unwrap();
7659
    let err = Repo::init(other.path())
7660
        .err()
7661
        .expect("the store already holds a log")
7662
        .to_string();
7663
    assert!(
7664
        err.contains("already holds a repository's operation log"),
7665
        "{err}"
7666
    );
7667
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
7668
}
d069701a Andy McCall ↶ 7669
7670
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
7671
/// objects and operation head there, with `.oxy/cache` in front: it works
7672
/// as one on disk does, reopens, and survives losing its cache.
7673
#[test]
7674
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
7675
    hermetic();
7676
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
7677
        return;
7678
    }
7679
    let dir = tempfile::tempdir().unwrap();
7680
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
7681
    let url = format!("dir://{}", bucket.display());
7682
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
7683
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
7684
    write(&root, "a.txt", b"one\n");
7685
    let h1 = repo.commit("First", &[]).unwrap();
7686
    write(&root, "a.txt", b"one\ntwo\n");
7687
    let h2 = repo.commit("Second", &[]).unwrap();
7688
    assert!(
7689
        !root.join(".oxy/ops/head").exists(),
7690
        "the head is in the store"
7691
    );
7692
    assert!(bucket.join("ops/head").is_file());
7693
    assert!(root.join(".oxy/cache").is_dir());
7694
    drop(repo);
7695
7696
    // Reopened, and again with no cache at all: everything comes from the store.
7697
    for drop_cache in [false, true] {
7698
        if drop_cache {
7699
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
7700
        }
7701
        let repo = Repo::open(&root).unwrap();
7702
        let log: Vec<String> = repo
7703
            .op_log()
7704
            .unwrap()
7705
            .into_iter()
7706
            .map(|(_, op)| op.command)
7707
            .collect();
7708
        assert!(log.len() >= 3, "{log:?}");
7709
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
7710
        let heads = repo
7711
            .store()
7712
            .get_state(&repo.view().unwrap().bookmarks["main"])
7713
            .unwrap()
7714
            .heads;
7715
        assert_eq!(heads, vec![h2]);
7716
        assert_eq!(
7717
            repo.load_state(&heads).unwrap().materialize().files.len(),
7718
            1
7719
        );
7720
    }
7721
7722
    // A second repository cannot start on the same store.
7723
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
7724
        .err()
7725
        .unwrap()
7726
        .to_string();
7727
    assert!(
7728
        err.contains("already holds a repository's operation log"),
7729
        "{err}"
7730
    );
7731
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
7732
        .err()
7733
        .unwrap()
7734
        .to_string();
7735
    assert!(err.contains("cannot open that kind of store"), "{err}");
7736
}
80677b7a Andy McCall ↶ 7737
7738
/// oxygen#75: the prompt's quick check agrees with status in a repository
7739
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
7740
/// another state, clean again once that pin is committed. (It compared the
7741
/// subrepo's directory as if it were a file, so it was always dirty.)
7742
#[test]
7743
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
7744
    hermetic();
7745
    let dir = tempfile::tempdir().unwrap();
7746
    let root = dir.path();
7747
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7748
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7749
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7750
        .unwrap()
7751
        .with_home(root.join("home"));
7752
    write(&root.join("lib"), "lib.txt", b"v1\n");
7753
    lib.commit("lib v1", &[]).unwrap();
7754
    assert!(lib.push("origin", false).unwrap()[0].ok);
7755
    let app_dir = root.join("app");
7756
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7757
    write(&app_dir, "main.txt", b"app\n");
7758
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7759
    app.commit("app with lib", &[]).unwrap();
7760
    // Out of the racy window, so the stat-only path decides.
7761
    std::thread::sleep(std::time::Duration::from_millis(2100));
7762
    let reopen = || Repo::open(&app_dir).unwrap();
7763
    assert_eq!(
7764
        reopen().quick_dirty().unwrap(),
7765
        Some(false),
7766
        "clean, as status says"
7767
    );
7768
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
7769
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
7770
    nested.commit("lib v2", &[]).unwrap();
7771
    assert_eq!(
7772
        reopen().quick_dirty().unwrap(),
7773
        Some(true),
7774
        "the subrepo moved"
7775
    );
7776
    reopen().commit("pin lib v2", &[]).unwrap();
7777
    std::thread::sleep(std::time::Duration::from_millis(2100));
7778
    assert_eq!(
7779
        reopen().quick_dirty().unwrap(),
7780
        Some(false),
7781
        "the new pin is committed"
7782
    );
7783
}
7993d465 Andy McCall ↶ 7784
7785
#[test]
7786
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
7787
    // oxygen#72: a .oxymodules section with no subrepo behind it.
7788
    hermetic();
7789
    let dir = tempfile::tempdir().unwrap();
7790
    let root = dir.path();
7791
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7792
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7793
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7794
        .unwrap()
7795
        .with_home(root.join("home"));
7796
    write(&root.join("lib"), "lib.txt", b"v1\n");
7797
    lib.commit("lib v1", &[]).unwrap();
7798
    assert!(lib.push("origin", false).unwrap()[0].ok);
7799
    let app_dir = root.join("app");
7800
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7801
    write(
7802
        &app_dir,
7803
        ".oxymodules",
7804
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
7805
    );
7806
    let unpinned = app.unpinned_modules().unwrap();
7807
    assert_eq!(unpinned.len(), 1);
7808
    assert_eq!(unpinned[0].0, "libs/lib");
7809
    assert_eq!(unpinned[0].1.url, lib_url);
7810
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
7811
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7812
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
7813
}
bf3a6781 Andy McCall ↶ 7814
7815
#[test]
7816
fn the_bookmark_revset_function_names_only_bookmarks() {
7817
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
7818
    hermetic();
7819
    let dir = tempfile::tempdir().unwrap();
7820
    let repo = Repo::init(dir.path()).unwrap();
7821
    write(dir.path(), "a.txt", b"a\n");
7822
    let a = repo.commit("A", &[]).unwrap();
7823
    write(dir.path(), "b.txt", b"b\n");
7824
    let b = repo.commit("B", &[]).unwrap();
7825
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
7826
    heads.sort();
7827
    let mut want = repo.bookmark_heads().unwrap();
7828
    want.sort();
7829
    assert_eq!(heads, want);
7830
    assert!(heads.contains(&b));
7831
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
7832
    // A change prefix is a symbol, not a bookmark.
7833
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
7834
    assert!(repo.revset(&prefix).is_ok());
7835
    let e = repo
7836
        .revset(&format!("bookmark({prefix})"))
7837
        .unwrap_err()
7838
        .to_string();
7839
    assert!(e.contains("no such bookmark"), "{e}");
7840
}
72484195 Andy McCall ↶ 7841
7842
#[test]
7843
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
7844
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
7845
    // pinning the subrepo, and the nested repository on disk at that pin.
7846
    hermetic();
7847
    let dir = tempfile::tempdir().unwrap();
7848
    let root = dir.path();
7849
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7850
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7851
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7852
        .unwrap()
7853
        .with_home(root.join("home"));
7854
    write(&root.join("lib"), "lib.txt", b"v1\n");
7855
    lib.commit("lib v1", &[]).unwrap();
7856
    assert!(lib.push("origin", false).unwrap()[0].ok);
7857
    let app_dir = root.join("app");
7858
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7859
    write(&app_dir, "main.txt", b"app\n");
7860
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7861
    // The stale state: registered in .oxymodules, never pinned.
7862
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
7863
    app.commit("initial", &[]).unwrap();
7864
    let stale = app.bookmark_heads().unwrap();
7865
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
7866
    app.commit("pin lib", &[]).unwrap();
7867
    let newer = app.bookmark_heads().unwrap();
7868
    app.checkout(&stale, false, "test").unwrap();
7869
    write(&app_dir, "notes.txt", b"mine\n");
7870
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
7871
    assert_eq!(carried, vec!["notes.txt".to_string()]);
7872
    assert!(app_dir.join("notes.txt").exists());
7873
}
7874
7875
#[test]
7876
fn a_bookmark_only_behind_its_remote_catches_up() {
7877
    // oxygen#74: switch takes the remote's state rather than a stale one.
7878
    hermetic();
7879
    let dir = tempfile::tempdir().unwrap();
7880
    let root = dir.path();
7881
    let _origin = Repo::init(&root.join("origin")).unwrap();
7882
    let url = root.join("origin").to_string_lossy().to_string();
7883
    let one = Repo::clone(&url, &root.join("one"))
7884
        .unwrap()
7885
        .with_home(root.join("home"));
7886
    write(&root.join("one"), "a.txt", b"a\n");
7887
    one.commit("A", &[]).unwrap();
7888
    assert!(one.push("origin", false).unwrap()[0].ok);
7889
    let two = Repo::clone(&url, &root.join("two"))
7890
        .unwrap()
7891
        .with_home(root.join("home"));
7892
    write(&root.join("two"), "b.txt", b"b\n");
7893
    two.commit("B", &[]).unwrap();
7894
    assert!(two.push("origin", false).unwrap()[0].ok);
7895
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
7896
    one.fetch("origin").unwrap();
7897
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
7898
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
7899
    // Local work the remote lacks: left alone.
7900
    write(&root.join("one"), "c.txt", b"c\n");
7901
    one.commit("C", &[]).unwrap();
7902
    write(&root.join("two"), "d.txt", b"d\n");
7903
    two.commit("D", &[]).unwrap();
7904
    assert!(two.push("origin", false).unwrap()[0].ok);
7905
    one.fetch("origin").unwrap();
7906
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
7907
}
42ccf504 Andy McCall ↶ 7908
7909
#[test]
7910
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
7911
    // oxygen#83: remotes earth and gcs, origin removed.
7912
    hermetic();
7913
    let dir = tempfile::tempdir().unwrap();
7914
    let root = dir.path();
7915
    let _up = Repo::init(&root.join("up")).unwrap();
7916
    let url = root.join("up").to_string_lossy().to_string();
7917
    let other = Repo::clone(&url, &root.join("other"))
7918
        .unwrap()
7919
        .with_home(root.join("home"));
7920
    write(&root.join("other"), "a.txt", b"a\n");
7921
    other.commit("a", &[]).unwrap();
7922
    assert!(other.push("origin", false).unwrap()[0].ok);
7923
    let mut one = Repo::clone(&url, &root.join("one"))
7924
        .unwrap()
7925
        .with_home(root.join("home"));
7926
    one.config.set("remote.earth.url", &url).unwrap();
7927
    one.config.set("remote.gcs.url", &url).unwrap();
7928
    one.config.set("remote.origin.url", "").unwrap();
7929
    one.save_config().unwrap();
7930
    write(&root.join("other"), "b.txt", b"b\n");
7931
    other.commit("b", &[]).unwrap();
7932
    assert!(other.push("origin", false).unwrap()[0].ok);
7933
    one.fetch("earth").unwrap();
7934
    let b = one
7935
        .bookmarks()
7936
        .unwrap()
7937
        .into_iter()
7938
        .find(|b| b.name == "main")
7939
        .unwrap();
7940
    assert_eq!(
7941
        (b.remote.as_deref(), b.behind),
7942
        (Some("earth"), Some(1)),
7943
        "a stale origin copy is not used"
7944
    );
7945
    assert_eq!(
7946
        one.default_remote(),
7947
        "origin",
7948
        "no default chosen among several"
7949
    );
7950
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
7951
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
7952
    one.config.set("core.remote", "earth").unwrap();
7953
    assert_eq!(one.default_remote(), "earth");
7954
}
cbe8499a Andy McCall ↶ 7955
7956
#[test]
7957
fn a_missing_author_identity_says_how_to_fix_it() {
7958
    // oxygen#82: an agent home's author.key naming an identity the
7959
    // repository does not hold.
7960
    hermetic();
7961
    let dir = tempfile::tempdir().unwrap();
7962
    let mut repo = Repo::init(dir.path()).unwrap();
7963
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
7964
    repo.config.set("author.key", &missing.to_hex()).unwrap();
7965
    let e = repo.identity(&missing).unwrap_err().to_string();
7966
    assert!(
7967
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
7968
        "{e}"
7969
    );
7970
    assert!(e.contains("this repository's config"), "{e}");
7971
}
f6dccc45 Andy McCall ↶ 7972
7973
#[test]
7974
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
7975
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
7976
    // the working copy, a pull with nothing new left it there, and status
7977
    // said "clean".
7978
    hermetic();
7979
    let dir = tempfile::tempdir().unwrap();
7980
    let root = dir.path();
7981
    let _up = Repo::init(&root.join("up")).unwrap();
7982
    let url = root.join("up").to_string_lossy().to_string();
7983
    let other = Repo::clone(&url, &root.join("other"))
7984
        .unwrap()
7985
        .with_home(root.join("home"));
7986
    write(&root.join("other"), "a.txt", b"a\n");
7987
    other.commit("a", &[]).unwrap();
7988
    assert!(other.push("origin", false).unwrap()[0].ok);
7989
    let one = Repo::clone(&url, &root.join("one"))
7990
        .unwrap()
7991
        .with_home(root.join("home"));
7992
    write(&root.join("other"), "b.txt", b"b\n");
7993
    other.commit("b", &[]).unwrap();
7994
    assert!(other.push("origin", false).unwrap()[0].ok);
7995
    one.fetch("origin").unwrap();
7996
    // The bookmark moves; the working copy does not.
7997
    let theirs = one.resolve_heads("origin/main").unwrap();
7998
    one.bookmark_set("main", &theirs).unwrap();
7999
    assert!(!root.join("one/b.txt").exists());
8000
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8001
    let r = one.pull("origin").unwrap();
8002
    assert!(
8003
        !r.changed && r.checked_out,
8004
        "nothing new, but the working copy caught up"
8005
    );
8006
    assert!(root.join("one/b.txt").exists());
8007
    assert_eq!(one.working_copy_behind().unwrap(), None);
8008
}
170bb436 Andy McCall ↶ 8009
8010
#[test]
8011
fn touched_nodes_cache_answers_as_the_changes_do() {
8012
    hermetic();
8013
    let dir = tempfile::tempdir().unwrap();
8014
    let repo = Repo::init(dir.path()).unwrap();
8015
    write(dir.path(), "a.txt", b"one\n");
8016
    write(dir.path(), "b.txt", b"x\n");
8017
    repo.snapshot("t").unwrap();
8018
    let c1 = repo.commit("first", &[]).unwrap();
8019
    write(dir.path(), "b.txt", b"y\n");
8020
    repo.snapshot("t").unwrap();
8021
    repo.commit("b only", &[]).unwrap();
8022
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8023
    write(dir.path(), "c.txt", b"one\ntwo\n");
8024
    repo.snapshot("t").unwrap();
8025
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8026
    // Uncommitted work, so the working copy touches a file too.
8027
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8028
    repo.snapshot("t").unwrap();
8029
8030
    let path = dir.path().join(".oxy/index/touched");
8031
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8032
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8033
    assert!(path.exists(), "the first query writes the cache");
8034
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8035
    assert_eq!(cold, warm, "the cache answers as the changes do");
8036
    let (wc, _) = repo.working_copy().unwrap();
8037
    assert_eq!(
8038
        cold,
8039
        vec![wc, c3, c1],
8040
        "renames followed, the working copy included"
8041
    );
8042
8043
    // Working-copy changes are not kept: they are replaced by every snapshot.
8044
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8045
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8046
    assert!(cached.contains(&c1) && cached.contains(&c3));
8047
8048
    // A damaged cache is ignored, not trusted.
8049
    let mut bytes = fs::read(&path).unwrap();
8050
    let last = bytes.len() - 40;
8051
    bytes[last] ^= 1;
8052
    fs::write(&path, &bytes).unwrap();
8053
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8054
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8055
    assert_eq!(hashes(touches), vec![c3, c1]);
8056
}
e8e6e0ca Andy McCall ↶ 8057
8058
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8059
/// file back where it was leave two placements at one place, which the
8060
/// tree shows as one file. Removing it, and then its directory, retires
8061
/// both, so no copy is left under a directory that is gone.
8062
#[test]
8063
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8064
    hermetic();
8065
    if std::process::Command::new("git")
8066
        .arg("--version")
8067
        .output()
8068
        .is_err()
8069
    {
8070
        eprintln!("git not installed; skipping");
8071
        return;
8072
    }
8073
    let dir = tempfile::tempdir().unwrap();
8074
    let root = dir.path();
8075
    let g = root.join("src.git");
8076
    fs::create_dir_all(&g).unwrap();
8077
    let git = |args: &[&str]| {
8078
        let out = std::process::Command::new("git")
8079
            .arg("-C")
8080
            .arg(&g)
8081
            .args([
8082
                "-c",
8083
                "user.name=Grace",
8084
                "-c",
8085
                "[email protected]",
8086
                "-c",
8087
                "commit.gpgsign=false",
8088
            ])
8089
            .args(args)
8090
            .output()
8091
            .unwrap();
8092
        assert!(
8093
            out.status.success(),
8094
            "git {args:?}: {}",
8095
            String::from_utf8_lossy(&out.stderr)
8096
        );
8097
    };
8098
    git(&["init", "-q", "-b", "main"]);
8099
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8100
    write(&g, "keep.txt", b"k\n");
8101
    git(&["add", "."]);
8102
    git(&["commit", "-qm", "base"]);
8103
    fs::create_dir_all(g.join("d/sub")).unwrap();
8104
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8105
    git(&["commit", "-qm", "into sub"]);
8106
    git(&["checkout", "-qb", "side"]);
8107
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8108
    git(&["commit", "-qm", "back, on side"]);
8109
    git(&["checkout", "-q", "main"]);
8110
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8111
    git(&["commit", "-qm", "back, on main"]);
8112
    git(&["merge", "-q", "--no-edit", "side"]);
8113
    git(&["rm", "-rq", "d"]);
8114
    git(&["commit", "-qm", "d goes"]);
8115
8116
    let repo = Repo::init(&root.join("o")).unwrap();
8117
    repo.import_git(&g, "main").unwrap();
8118
    let v = repo.verify_git_import(&g, "main").unwrap();
8119
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8120
    let st = repo
8121
        .load_state_history(&repo.bookmark_heads().unwrap())
8122
        .unwrap();
8123
    let view = st.tree().view();
8124
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8125
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8126
}
5552e69c Andy McCall ↶ 8127
8128
/// oxygen#94: a state index's file histories are read, and checked by
8129
/// their own hashes, only when a file is built. One found damaged is an
8130
/// error that says so, the index is removed, and the next read rebuilds it.
8131
#[test]
8132
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8133
    hermetic();
8134
    let dir = tempfile::tempdir().unwrap();
8135
    let repo = Repo::init(dir.path()).unwrap();
8136
    for i in 0..6 {
8137
        write(
8138
            dir.path(),
8139
            &format!("f{i}.txt"),
8140
            format!("one {i}\n").as_bytes(),
8141
        );
8142
    }
8143
    repo.snapshot("t").unwrap();
8144
    repo.commit("first", &[]).unwrap();
8145
    for i in 0..6 {
8146
        write(
8147
            dir.path(),
8148
            &format!("f{i}.txt"),
8149
            format!("one {i}\ntwo\n").as_bytes(),
8150
        );
8151
    }
8152
    repo.snapshot("t").unwrap();
8153
    repo.commit("second", &[]).unwrap();
8154
    let want: Vec<Vec<u8>> = (0..6)
8155
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8156
        .collect();
8157
    // The index of the working copy's base, holding every file's history
8158
    // (a few changes behind, an index is replayed onto, not rewritten).
8159
    let (_, wc) = repo.working_copy().unwrap();
8160
    let base = repo.load_state_history(&wc.deps).unwrap();
8161
    repo.write_state_index(&wc.deps, &base);
8162
    for (i, w) in want.iter().enumerate() {
8163
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8164
    }
8165
    let index = repo.state_indexes();
8166
    assert!(!index.is_empty(), "a state index was written");
8167
    // The histories are last in the file: damage the last of them.
8168
    let mut bytes = fs::read(&index[0]).unwrap();
8169
    let last = bytes.len() - 1;
8170
    bytes[last] ^= 0x40;
8171
    fs::write(&index[0], &bytes).unwrap();
8172
8173
    let reads: Vec<_> = (0..6)
8174
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8175
        .collect();
8176
    let damaged: Vec<String> = reads
8177
        .iter()
8178
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8179
        .collect();
8180
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8181
    assert!(
8182
        damaged[0].contains("state index was damaged")
8183
            && damaged[0].contains("run the command again"),
8184
        "{}",
8185
        damaged[0]
8186
    );
8187
    // Every file reads right again, from an index rebuilt from history.
8188
    for (i, w) in want.iter().enumerate() {
8189
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8190
    }
8191
}
cb8b8082 Andy McCall ↶ 8192
8193
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8194
/// objects alone and in dependency order, and the last moves the bookmark.
8195
/// The remote ends with every change and the same state, and says how each
8196
/// part went.
8197
#[test]
8198
fn a_long_push_goes_in_parts() {
8199
    hermetic();
8200
    let dir = tempfile::tempdir().unwrap();
8201
    let root = dir.path();
8202
    let origin = root.join("origin");
8203
    Repo::init_bare_unbound(&origin).unwrap();
8204
    let main = root.join("main");
8205
    let mut repo = Repo::init(&main).unwrap();
8206
    repo.config
8207
        .set("remote.origin.url", &origin.to_string_lossy())
8208
        .unwrap();
8209
    // One byte: every change is a part of its own.
8210
    repo.config.set("push.batch-bytes", "1").unwrap();
8211
    repo.save_config().unwrap();
8212
    for i in 0..6 {
8213
        write(
8214
            &main,
8215
            &format!("f{i}.txt"),
8216
            format!("file {i}\n").as_bytes(),
8217
        );
8218
        repo.commit(&format!("c{i}"), &[]).unwrap();
8219
    }
8220
    let mut parts = Vec::new();
8221
    let results = repo
8222
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8223
        .unwrap();
8224
    assert!(
8225
        results.iter().any(|r| r.ok && r.name == "main"),
8226
        "{results:?}"
8227
    );
8228
    assert_eq!(parts.len(), 6, "{parts:?}");
8229
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8230
8231
    let remote = Repo::open(&origin).unwrap();
8232
    let heads = repo.bookmark_heads().unwrap();
8233
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8234
    assert_eq!(
8235
        remote.log_state(&heads).unwrap().len(),
8236
        repo.log_state(&heads).unwrap().len()
8237
    );
8238
    // A push of objects alone reports how it went, as `objects`.
8239
    let got = remote
8240
        .receive_push(Bundle::default(), vec![], None, vec![])
8241
        .unwrap();
8242
    assert_eq!(got.len(), 1);
8243
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8244
}
d6e0d5b8 Andy McCall ↶ 8245
8246
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8247
/// own commits (Git author email = its email, any case) with its key, and
8248
/// leaves anyone else's with the zero key; the history verifies as before.
8249
#[test]
8250
fn git_import_claims_your_own_commits() {
8251
    hermetic();
8252
    if std::process::Command::new("git")
8253
        .arg("--version")
8254
        .output()
8255
        .is_err()
8256
    {
8257
        eprintln!("git not installed; skipping");
8258
        return;
8259
    }
8260
    let dir = tempfile::tempdir().unwrap();
8261
    let root = dir.path();
8262
    let g = root.join("src.git");
8263
    fs::create_dir_all(&g).unwrap();
8264
    let git = |who: &str, args: &[&str]| {
8265
        let (name, email) = who.split_once(' ').unwrap();
8266
        let out = std::process::Command::new("git")
8267
            .arg("-C")
8268
            .arg(&g)
8269
            .args([
8270
                "-c",
8271
                &format!("user.name={name}"),
8272
                "-c",
8273
                &format!("user.email={email}"),
8274
                "-c",
8275
                "commit.gpgsign=false",
8276
            ])
8277
            .args(args)
8278
            .output()
8279
            .unwrap();
8280
        assert!(
8281
            out.status.success(),
8282
            "git {args:?}: {}",
8283
            String::from_utf8_lossy(&out.stderr)
8284
        );
8285
    };
8286
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8287
    write(&g, "a.txt", b"a\n");
8288
    git("Grace [email protected]", &["add", "."]);
8289
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8290
    write(&g, "b.txt", b"b\n");
8291
    git("Ada [email protected]", &["add", "."]);
8292
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8293
8294
    let mut repo = Repo::init(&root.join("o")).unwrap();
8295
    let (key, _) = repo
8296
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8297
        .unwrap();
8298
    repo.config.set("git.claim", "true").unwrap();
8299
    repo.save_config().unwrap();
8300
    let repo = Repo::open(&root.join("o")).unwrap();
8301
    repo.import_git(&g, "main").unwrap();
8302
    let v = repo.verify_git_import(&g, "main").unwrap();
8303
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8304
    let heads = repo.bookmark_heads().unwrap();
8305
    let by_message: std::collections::HashMap<String, KeyId> = repo
8306
        .log_state(&heads)
8307
        .unwrap()
8308
        .into_iter()
8309
        .map(|e| {
8310
            (
8311
                e.change.message.lines().next().unwrap_or("").to_string(),
8312
                e.change.author,
8313
            )
8314
        })
8315
        .collect();
8316
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8317
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8318
}