OXYGENHUB
◆ bare-hashes oxygen / crates / oxy-core / src / repo / tests.rs
320.1 KiB · Rust · last changed A full change hash resolves without its # 24 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,
9b723f69 Andy McCall ↶ 440
            removed_paths: vec!["bin.dat".into()],
75167672 Andy McCall 441
            conflicted: false,
d3cd7ef9 Andy McCall ↶ 442
            notes: vec![],
443
            lacks: 1,
75167672 Andy McCall 444
        }
445
    );
98286406 Andy McCall ↶ 446
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
447
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
448
    assert!(!root.join("bin.dat").exists());
449
    let (_, wc) = repo.working_copy().unwrap();
450
    assert_eq!(wc.deps, vec![h1]);
75167672 Andy McCall 451
    assert!(
452
        !repo.snapshot("status").unwrap().changed,
453
        "checkout leaves a clean working copy"
454
    );
98286406 Andy McCall ↶ 455
    // The bookmark still points at h2.
456
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
457
458
    // Dirty working copy refuses without --discard.
459
    write(root, "a.txt", b"dirty\n");
460
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
75167672 Andy McCall 461
    let r = repo
462
        .checkout(&[h2], true, "oxy checkout --discard")
463
        .unwrap();
98286406 Andy McCall ↶ 464
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
465
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
466
    assert!(!root.join("sub").exists(), "empty directories are pruned");
467
    assert_eq!(r.removed, 1);
468
    assert!(!repo.snapshot("status").unwrap().changed);
469
470
    // Refuses to write through a symlinked directory.
471
    #[cfg(unix)]
472
    {
473
        fs::remove_dir_all(root.join("sub")).ok();
474
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
475
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
476
    }
477
}
478
479
#[test]
480
fn large_files_are_chunked_and_read_back() {
481
    hermetic();
482
    let dir = tempfile::tempdir().unwrap();
483
    let repo = Repo::init(dir.path()).unwrap();
484
    let mut big = vec![0u8; 700 * 1024];
485
    for (i, b) in big.iter_mut().enumerate() {
486
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
487
    }
488
    let r = repo.store_blob(&big).unwrap();
489
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
490
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
491
    assert_eq!(repo.read_blob(&r).unwrap(), big);
492
    assert_eq!(Repo::blob_ref(&big), r);
493
}
494
495
#[test]
496
fn clone_push_pull_with_seals_and_attestations() {
497
    hermetic();
498
    let dir = tempfile::tempdir().unwrap();
499
    let root = dir.path();
500
    let origin_path = root.join("origin");
501
    let origin = Repo::init(&origin_path).unwrap();
502
    let origin_url = origin_path.to_string_lossy().to_string();
503
504
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
75167672 Andy McCall 505
    let mut a = Repo::clone(&origin_url, &root.join("a"))
506
        .unwrap()
507
        .with_home(root.join("home-a"));
98286406 Andy McCall ↶ 508
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
75167672 Andy McCall 509
    let (key_a, _) = a
510
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
511
        .unwrap();
98286406 Andy McCall ↶ 512
    write(&root.join("a"), "f.txt", b"a\n");
513
    let h1 = a.commit("first", &[]).unwrap();
514
    let results = a.push("origin", false).unwrap();
515
    assert!(results[0].ok, "{}", results[0].reason);
516
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
517
    // The change was sealed at push and the reference attested.
75167672 Andy McCall 518
    assert!(
519
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
520
    );
521
    assert_eq!(
522
        origin.verify_change(&h1).unwrap(),
523
        SignatureStatus::Unsigned
524
    );
f8c69576 Andy McCall ↶ 525
    let serial_of = |att: &SignedAttest| match att.attest.body {
526
        AttestBody::Ref { serial, .. } => serial,
527
        _ => unreachable!(),
528
    };
98286406 Andy McCall ↶ 529
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 530
    // A bookmark new to the remote starts at the clock (past any deleted
531
    // namesake's serial); later updates count up from there.
532
    let first = serial_of(&att);
533
    assert!(first > 1_000_000_000_000, "{first}");
98286406 Andy McCall ↶ 534
    let again = a.push("origin", false).unwrap();
535
    assert!(again[0].ok && again[0].reason.contains("up to date"));
536
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 537
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
98286406 Andy McCall ↶ 538
539
    // B clones and sees the file and the seal.
540
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
541
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
542
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
75167672 Andy McCall 543
    assert!(matches!(
544
        b.authenticate_change(&h1).unwrap(),
545
        SignatureStatus::Valid { sealed: true, .. }
546
    ));
98286406 Andy McCall ↶ 547
548
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
549
    write(&root.join("b"), "f.txt", b"a\nb\n");
550
    let h2 = b.commit("second", &[]).unwrap();
551
    assert!(b.push("origin", false).unwrap()[0].ok);
552
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
553
554
    // A commits an independent change; push is refused until A pulls.
555
    write(&root.join("a"), "g.txt", b"g\n");
556
    let h3 = a.commit("third", &[]).unwrap();
557
    assert!(a.push("origin", false).is_err());
558
    let pr = a.pull("origin").unwrap();
559
    assert!(pr.changed && pr.checked_out);
560
    let mut want = vec![h2, h3];
561
    want.sort();
562
    assert_eq!(pr.heads, want);
563
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
564
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
565
    let results = a.push("origin", false).unwrap();
566
    assert!(results[0].ok, "{}", results[0].reason);
567
    let mut origin_heads = origin.bookmark_heads().unwrap();
568
    origin_heads.sort();
569
    assert_eq!(origin_heads, want);
570
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 571
    assert_eq!(serial_of(&att), first + 1);
98286406 Andy McCall ↶ 572
573
    // B pulls and ends up identical.
574
    let pr = b.pull("origin").unwrap();
575
    assert_eq!(pr.heads, want);
576
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
577
    assert!(!b.snapshot("status").unwrap().changed);
578
579
    // Concurrent edits of the same line: the union is a reified conflict.
580
    write(&root.join("a"), "f.txt", b"a\nA\n");
581
    a.commit("a-edit", &[]).unwrap();
582
    a.push("origin", false).unwrap();
583
    write(&root.join("b"), "f.txt", b"a\nB\n");
584
    b.commit("b-edit", &[]).unwrap();
585
    let pr = b.pull("origin").unwrap();
586
    assert!(pr.changed && pr.checked_out);
587
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
588
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
589
    write(&root.join("b"), "f.txt", b"a\nAB\n");
590
    let hr = b.commit("resolve", &[]).unwrap();
75167672 Andy McCall 591
    assert_eq!(
592
        b.store().get_change(&hr).unwrap().kind,
593
        ChangeKind::Resolution
594
    );
98286406 Andy McCall ↶ 595
    assert!(b.push("origin", false).unwrap()[0].ok);
596
    a.pull("origin").unwrap();
597
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
598
    // The resolution depends on the conflicting edits, but nothing depends
599
    // on "third" (it only added g.txt), so it stays a head beside it.
600
    let mut want = vec![hr, h3];
601
    want.sort();
602
    assert_eq!(a.bookmark_heads().unwrap(), want);
603
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
604
}
605
606
#[test]
607
fn receive_push_rejects_bad_updates() {
608
    hermetic();
609
    let dir = tempfile::tempdir().unwrap();
610
    let root = dir.path();
611
    let origin = Repo::init(&root.join("origin")).unwrap();
612
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 613
    let mut a = Repo::clone(&url, &root.join("a"))
614
        .unwrap()
615
        .with_home(root.join("home"));
616
    let (key, _) = a
617
        .create_identity("Ada", "a@b", IdentityScope::Repo)
618
        .unwrap();
98286406 Andy McCall ↶ 619
    write(&root.join("a"), "f.txt", b"x\n");
620
    let h1 = a.commit("one", &[]).unwrap();
621
    assert!(a.push("origin", false).unwrap()[0].ok);
622
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
75167672 Andy McCall 623
    let s1 = origin
624
        .store()
625
        .put_state(&StateObject::new(vec![h1]))
626
        .unwrap();
98286406 Andy McCall ↶ 627
628
    // Missing head.
75167672 Andy McCall 629
    let ghost = origin
630
        .store()
631
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
632
        .unwrap();
633
    let r = origin
634
        .receive_push(
635
            Bundle::default(),
636
            vec![RefUpdate {
637
                name: "main".into(),
638
                old_state: s1,
639
                new_state: ghost,
640
                force: false,
641
                attestation: None,
642
            }],
643
            None,
644
            vec![],
645
        )
646
        .unwrap();
647
    assert!(
648
        !r[0].ok && r[0].reason.contains("missing"),
649
        "{}",
650
        r[0].reason
651
    );
98286406 Andy McCall ↶ 652
653
    // Stale old_state.
75167672 Andy McCall 654
    let r = origin
655
        .receive_push(
656
            Bundle::default(),
657
            vec![RefUpdate {
658
                name: "main".into(),
659
                old_state: empty,
660
                new_state: s1,
661
                force: false,
662
                attestation: None,
663
            }],
664
            None,
665
            vec![],
666
        )
667
        .unwrap();
98286406 Andy McCall ↶ 668
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
669
670
    // Non-fast-forward without force is refused; with force it passes.
75167672 Andy McCall 671
    let r = origin
672
        .receive_push(
673
            Bundle::default(),
674
            vec![RefUpdate {
675
                name: "main".into(),
676
                old_state: s1,
677
                new_state: empty,
678
                force: false,
679
                attestation: None,
680
            }],
681
            None,
682
            vec![],
683
        )
684
        .unwrap();
685
    assert!(
686
        !r[0].ok && r[0].reason.contains("fast-forward"),
687
        "{}",
688
        r[0].reason
689
    );
690
    let r = origin
691
        .receive_push(
692
            Bundle::default(),
693
            vec![RefUpdate {
694
                name: "main".into(),
695
                old_state: s1,
696
                new_state: empty,
697
                force: true,
698
                attestation: None,
699
            }],
700
            None,
701
            vec![],
702
        )
703
        .unwrap();
98286406 Andy McCall ↶ 704
    assert!(r[0].ok);
705
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
706
707
    // Attestation with a stale serial is a rollback and is refused.
75167672 Andy McCall 708
    let sa = a
709
        .sign_attest(&Attest {
710
            repo: a.id().unwrap(),
711
            hlc: Hlc::now(),
712
            body: AttestBody::Ref {
713
                name: "main".into(),
714
                old_state: empty,
715
                new_state: s1,
716
                serial: 1,
717
            },
718
        })
719
        .unwrap();
720
    let r = origin
721
        .receive_push(
722
            Bundle::default(),
723
            vec![RefUpdate {
724
                name: "main".into(),
725
                old_state: empty,
726
                new_state: s1,
727
                force: false,
728
                attestation: Some(sa.clone()),
729
            }],
730
            None,
731
            vec![],
732
        )
733
        .unwrap();
734
    assert!(
735
        !r[0].ok && r[0].reason.contains("serial"),
736
        "{}",
737
        r[0].reason
738
    );
98286406 Andy McCall ↶ 739
    // An attestation for a different update is refused too.
75167672 Andy McCall 740
    let sa2 = a
741
        .sign_attest(&Attest {
742
            repo: a.id().unwrap(),
743
            hlc: Hlc::now(),
744
            body: AttestBody::Ref {
745
                name: "main".into(),
746
                old_state: s1,
747
                new_state: empty,
748
                serial: 5,
749
            },
750
        })
751
        .unwrap();
752
    let r = origin
753
        .receive_push(
754
            Bundle::default(),
755
            vec![RefUpdate {
756
                name: "main".into(),
757
                old_state: empty,
758
                new_state: s1,
759
                force: false,
760
                attestation: Some(sa2),
761
            }],
762
            None,
763
            vec![],
764
        )
765
        .unwrap();
766
    assert!(
767
        !r[0].ok && r[0].reason.contains("describe"),
768
        "{}",
769
        r[0].reason
770
    );
98286406 Andy McCall ↶ 771
    let _ = key;
772
}
773
774
#[test]
775
fn user_config_supplies_defaults_and_clones_sign() {
776
    hermetic();
777
    let dir = tempfile::tempdir().unwrap();
778
    let root = dir.path();
779
    let home = root.join("home");
780
    let origin = Repo::init(&root.join("origin")).unwrap();
781
    let url = root.join("origin").to_string_lossy().to_string();
782
783
    // Identity at user scope: the repository file stays free of author keys.
784
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
75167672 Andy McCall 785
    let (key, _) = a
786
        .create_identity("Ada", "[email protected]", IdentityScope::User)
787
        .unwrap();
98286406 Andy McCall ↶ 788
    assert!(!a.config.repo_layer().contains_key("author.key"));
789
    assert_eq!(a.config.author_key, Some(key));
790
    assert!(home.join("config.toml").exists());
791
    a.set_user_config("core.sign", "change").unwrap();
792
    assert!(a.config.sign_changes);
793
794
    // Repository settings override user settings and are the only ones saved.
795
    a.config.set("core.sign", "seal").unwrap();
796
    a.save_config().unwrap();
797
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
798
    assert!(!again.config.sign_changes);
799
    assert_eq!(again.config.author_key, Some(key));
75167672 Andy McCall 800
    assert_eq!(
801
        read_config_file(&root.join("a/.oxy/config"))
802
            .unwrap()
803
            .get("core.sign")
804
            .map(String::as_str),
805
        Some("seal")
806
    );
98286406 Andy McCall ↶ 807
808
    // A fresh clone made by this user signs with the user-level identity,
809
    // even though the clone's store has never seen the identity object.
810
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
811
    assert!(b.config.sign_changes);
812
    write(&root.join("b"), "f.txt", b"f\n");
813
    let h = b.commit("signed from a clone", &[]).unwrap();
75167672 Andy McCall 814
    assert!(
815
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
816
    );
98286406 Andy McCall ↶ 817
    assert!(b.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 818
    assert!(matches!(
819
        origin.verify_change(&h).unwrap(),
820
        SignatureStatus::Valid { .. }
821
    ));
98286406 Andy McCall ↶ 822
}
823
824
#[test]
825
fn format1_repositories_are_migrated_on_open() {
826
    hermetic();
827
    use crate::oplog::{Format1Op, Format1View};
828
    let dir = tempfile::tempdir().unwrap();
829
    let root = dir.path();
830
    let repo = Repo::init(root).unwrap();
831
    write(root, "a.txt", b"a\n");
832
    let h1 = repo.commit("one", &[]).unwrap();
833
    let (wc_hash, _) = repo.working_copy().unwrap();
834
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
835
    let mut v1 = Format1View::default();
836
    v1.bookmarks.insert("main".into(), vec![]);
837
    v1.workspaces.insert(repo.workspace(), wc_hash);
75167672 Andy McCall 838
    let init = Format1Op {
839
        parents: vec![],
840
        hlc: Hlc::default(),
841
        command: "oxy init".into(),
842
        view: v1.clone(),
843
    };
98286406 Andy McCall ↶ 844
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
845
    v1.bookmarks.insert("main".into(), vec![h1]);
75167672 Andy McCall 846
    let commit = Format1Op {
847
        parents: vec![init_ref],
848
        hlc: Hlc::default(),
849
        command: "oxy commit".into(),
850
        view: v1,
851
    };
98286406 Andy McCall ↶ 852
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
853
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
854
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
855
    drop(repo);
856
857
    let repo = Repo::open(root).unwrap();
75167672 Andy McCall 858
    assert_eq!(
859
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
860
        FORMAT_LINE
861
    );
98286406 Andy McCall ↶ 862
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
863
    let ops = repo.op_log().unwrap();
75167672 Andy McCall 864
    assert_eq!(
865
        ops.iter()
866
            .map(|(_, o)| o.command.as_str())
867
            .collect::<Vec<_>>(),
868
        ["oxy commit", "oxy init"]
869
    );
98286406 Andy McCall ↶ 870
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
871
    assert!(!repo.snapshot("status").unwrap().changed);
872
    // Reopening again is a no-op.
873
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
874
}
875
876
#[test]
877
fn undo_skips_snapshot_operations() {
878
    hermetic();
879
    let dir = tempfile::tempdir().unwrap();
880
    let root = dir.path();
881
    let repo = Repo::init(root).unwrap();
882
    write(root, "a.txt", b"a\n");
883
    let h1 = repo.commit("a", &[]).unwrap();
884
    // A later command snapshots new edits on top of the commit.
885
    write(root, "b.txt", b"b\n");
886
    let s = repo.snapshot("oxy status").unwrap();
887
    assert!(s.changed);
888
    assert!(repo.head_op().unwrap().1.is_snapshot());
889
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
890
    // Undo must undo the commit, not the snapshot.
891
    repo.undo().unwrap();
892
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
893
    let s = repo.snapshot("oxy status").unwrap();
894
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
75167672 Andy McCall 895
    assert_eq!(
896
        paths,
897
        ["a.txt", "b.txt"],
898
        "both files are back in the working copy"
899
    );
98286406 Andy McCall ↶ 900
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
901
    // Only snapshots remain above `init`, so there is nothing left to undo.
902
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
903
    assert!(repo.undo().is_err());
904
}
905
906
#[test]
907
fn independent_changes_commute_and_make_multiple_heads() {
908
    hermetic();
909
    let dir = tempfile::tempdir().unwrap();
910
    let root = dir.path();
911
    let repo = Repo::init(root).unwrap();
912
    write(root, "a.txt", b"a\n");
913
    let h1 = repo.commit("a", &[]).unwrap();
914
    write(root, "b.txt", b"b\n");
915
    let h2 = repo.commit("b", &[]).unwrap();
916
    let c2 = repo.store().get_change(&h2).unwrap();
917
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
918
    let mut heads = repo.bookmark_heads().unwrap();
919
    heads.sort();
920
    let mut want = vec![h1, h2];
921
    want.sort();
922
    assert_eq!(heads, want);
923
    // Editing a.txt depends on h1 only.
924
    write(root, "a.txt", b"a\na2\n");
925
    let h3 = repo.commit("a2", &[]).unwrap();
926
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
927
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
928
    assert_eq!(heads, [h2, h3].into_iter().collect());
929
    // Explicit dependency.
930
    write(root, "c.txt", b"c\n");
931
    let h4 = repo.commit("c", &[h2]).unwrap();
932
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
933
}
934
935
#[test]
936
fn mode_change_and_text_binary_switch() {
937
    hermetic();
938
    let dir = tempfile::tempdir().unwrap();
939
    let root = dir.path();
940
    let repo = Repo::init(root).unwrap();
941
    write(root, "run.sh", b"#!/bin/sh\n");
942
    repo.commit("add script", &[]).unwrap();
943
    #[cfg(unix)]
944
    {
945
        use std::os::unix::fs::PermissionsExt;
946
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
947
        let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 948
        assert_eq!(
949
            statuses(&s),
950
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
951
        );
98286406 Andy McCall ↶ 952
        let h = repo.commit("exec", &[]).unwrap();
953
        let snap = repo.load_state(&[h]).unwrap().materialize();
954
        assert!(snap.files["run.sh"].mode.exec);
955
    }
956
    // Text → binary → text.
957
    write(root, "run.sh", b"\0binary");
958
    let h = repo.commit("binary", &[]).unwrap();
959
    let snap = repo.load_state(&[h]).unwrap().materialize();
960
    assert!(snap.files["run.sh"].mode.opaque);
961
    write(root, "run.sh", b"text again\n");
962
    let h = repo.commit("text", &[]).unwrap();
963
    let snap = repo.load_state(&[h]).unwrap().materialize();
964
    assert!(!snap.files["run.sh"].mode.opaque);
75167672 Andy McCall 965
    assert!(
966
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
967
    );
98286406 Andy McCall ↶ 968
    assert!(!snap.is_conflicted());
969
}
83e0677b Andy McCall ↶ 970
6eae06b6 Andy McCall ↶ 971
/// oxygen#87: a binary file given new contents and the executable bit in
972
/// one commit kept the contents and lost the bit.
973
#[cfg(unix)]
974
#[test]
975
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
976
    use std::os::unix::fs::PermissionsExt;
977
    hermetic();
978
    let dir = tempfile::tempdir().unwrap();
979
    let root = dir.path();
980
    let repo = Repo::init(root).unwrap();
981
    write(root, "tool.exe", b"MZ\0one");
982
    repo.commit("add", &[]).unwrap();
983
    write(root, "tool.exe", b"MZ\0two");
984
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
985
    let h = repo.commit("update and +x", &[]).unwrap();
986
    let snap = repo.load_state(&[h]).unwrap().materialize();
987
    let f = &snap.files["tool.exe"];
988
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
989
    assert!(
990
        repo.snapshot("status").unwrap().statuses.is_empty(),
991
        "nothing left to commit"
992
    );
993
}
994
83e0677b Andy McCall ↶ 995
#[test]
996
fn trust_policy_governs_pushes_and_fetches() {
997
    hermetic();
998
    let dir = tempfile::tempdir().unwrap();
999
    let root = dir.path();
1000
    let origin = Repo::init(&root.join("origin")).unwrap();
1001
    let url = root.join("origin").to_string_lossy().to_string();
1002
1003
    // A is the root. Before the policy, an unsigned push from B is fine.
75167672 Andy McCall 1004
    let mut a = Repo::clone(&url, &root.join("a"))
1005
        .unwrap()
1006
        .with_home(root.join("home-a"));
1007
    let (key_a, _) = a
1008
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1009
        .unwrap();
1010
    let mut b = Repo::clone(&url, &root.join("b"))
1011
        .unwrap()
1012
        .with_home(root.join("home-b"));
83e0677b Andy McCall ↶ 1013
    write(&root.join("b"), "b.txt", b"b\n");
1014
    b.commit("unsigned before policy", &[]).unwrap();
1015
    assert!(b.push("origin", false).unwrap()[0].ok);
1016
1017
    // A creates the policy and pushes it; origin now enforces it.
1018
    write(&root.join("a"), "a.txt", b"a\n");
1019
    a.commit("a", &[]).unwrap();
1020
    let sp = a.policy_init().unwrap();
1021
    assert_eq!(sp.policy.serial, 1);
1022
    a.pull("origin").unwrap();
1023
    let results = a.push("origin", false).unwrap();
1024
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1025
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1026
1027
    // B pulls the policy. Without an identity B cannot push at all.
1028
    b.pull("origin").unwrap();
75167672 Andy McCall 1029
    assert!(
1030
        b.current_policy().unwrap().is_some(),
1031
        "the policy arrived with the fetch"
1032
    );
83e0677b Andy McCall ↶ 1033
    assert!(b.push("origin", false).is_err());
1034
    // With an identity the policy does not list, the push is rejected by origin.
75167672 Andy McCall 1035
    let (key_b, id_b) = b
1036
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1037
        .unwrap();
83e0677b Andy McCall ↶ 1038
    write(&root.join("b"), "b.txt", b"b2\n");
1039
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1040
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1041
    let r = b.push("origin", false).unwrap();
75167672 Andy McCall 1042
    assert!(
1043
        !r[0].ok && r[0].reason.contains("may not update"),
1044
        "{:?}",
1045
        r
1046
    );
83e0677b Andy McCall ↶ 1047
1048
    // A grants B (identity handed over as a file) and publishes the policy.
1049
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1050
    assert_eq!(sp.policy.serial, 2);
1051
    let r = a.push("origin", false).unwrap();
1052
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1053
    // B must fetch the new policy before pushing.
75167672 Andy McCall 1054
    assert!(b
1055
        .push("origin", false)
1056
        .unwrap_or_else(|e| vec![RefResult {
1057
            name: "main".into(),
1058
            ok: false,
1059
            reason: e.to_string()
1060
        }])
1061
        .iter()
1062
        .all(|x| !x.ok));
83e0677b Andy McCall ↶ 1063
    b.pull("origin").unwrap();
1064
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1065
    let r = b.push("origin", false).unwrap();
1066
    assert!(r[0].ok, "{:?}", r);
1067
    // Origin verified B's change under the policy.
1068
    let heads = origin.bookmark_heads().unwrap();
1069
    for h in &heads {
1070
        let c = origin.store().get_change(h).unwrap();
1071
        if c.author == key_b {
75167672 Andy McCall 1072
            origin
1073
                .change_allowed(
1074
                    h,
1075
                    &origin.current_policy().unwrap().unwrap().1.policy,
1076
                    "main",
1077
                )
1078
                .unwrap();
83e0677b Andy McCall ↶ 1079
        }
1080
    }
1081
1082
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1083
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1084
    forged.serial = 3;
1085
    forged.roots = vec![key_b];
1086
    let fh = forged.hash();
1087
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 1088
    let forged = SignedPolicy {
1089
        policy: forged,
1090
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1091
    };
1092
    let r = origin
1093
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1094
        .unwrap();
83e0677b Andy McCall ↶ 1095
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1096
    let stale = a.current_policy().unwrap().unwrap().1;
1097
    let mut old = stale.clone();
1098
    old.policy.serial = 1;
75167672 Andy McCall 1099
    let r = origin
1100
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1101
        .unwrap();
83e0677b Andy McCall ↶ 1102
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1103
1104
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1105
    a.pull("origin").unwrap();
1106
    a.policy_revoke(&key_b).unwrap();
1107
    let r = a.push("origin", false).unwrap();
1108
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1109
    b.pull("origin").unwrap();
1110
    write(&root.join("b"), "b.txt", b"b3\n");
1111
    b.commit("b3", &[]).unwrap();
1112
    let r = b.push("origin", false).unwrap();
1113
    assert!(!r[0].ok, "{:?}", r);
1114
1115
    // A clone by a third party receives and verifies everything.
75167672 Andy McCall 1116
    let c = Repo::clone(&url, &root.join("c"))
1117
        .unwrap()
1118
        .with_home(root.join("home-c"));
83e0677b Andy McCall ↶ 1119
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
75167672 Andy McCall 1120
    assert!(c
1121
        .current_policy()
1122
        .unwrap()
1123
        .unwrap()
1124
        .1
1125
        .policy
1126
        .roots
1127
        .contains(&key_a));
83e0677b Andy McCall ↶ 1128
    assert!(!c.snapshot("status").unwrap().changed);
1129
}
d02e545d Andy McCall ↶ 1130
9ae4d15a Andy McCall ↶ 1131
/// oxygen#66: a gc says what it is doing, phase by phase.
d02e545d Andy McCall ↶ 1132
#[test]
9ae4d15a Andy McCall ↶ 1133
fn gc_reports_its_phases() {
1134
    hermetic();
1135
    let dir = tempfile::tempdir().unwrap();
1136
    let repo = Repo::init(dir.path()).unwrap();
1137
    for i in 0..3 {
1138
        write(
1139
            dir.path(),
1140
            &format!("f{i}.txt"),
1141
            format!("{i}\n").as_bytes(),
1142
        );
1143
        repo.commit(&format!("c{i}"), &[]).unwrap();
1144
    }
1145
    let mut phases = Vec::new();
1146
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1147
        .unwrap();
1148
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1149
    assert!(
1150
        phases.iter().any(|p| p.starts_with("pruning")),
1151
        "{phases:?}"
1152
    );
1153
    assert!(
1154
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1155
        "{phases:?}"
1156
    );
1157
    assert!(
1158
        phases
1159
            .iter()
1160
            .any(|p| p.starts_with("writing the index of ")),
1161
        "{phases:?}"
1162
    );
1163
}
1164
1165
#[test]
d02e545d Andy McCall ↶ 1166
fn gc_packs_objects_and_history_still_works() {
1167
    hermetic();
1168
    let dir = tempfile::tempdir().unwrap();
1169
    let root = dir.path();
1170
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1171
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1172
        .unwrap();
d02e545d Andy McCall ↶ 1173
    repo.set_user_config("core.sign", "change").unwrap();
1174
    write(root, "a.txt", b"one\n");
1175
    let h1 = repo.commit("one", &[]).unwrap();
1176
    write(root, "a.txt", b"two\n");
1177
    write(root, "big.bin", &vec![0u8; 100_000]);
1178
    let h2 = repo.commit("two", &[]).unwrap();
ba160f60 Andy McCall ↶ 1179
    // Several snapshots leave superseded working-copy versions behind.
1180
    for i in 0..5 {
1181
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1182
        repo.snapshot("status").unwrap();
1183
    }
1184
    write(root, "a.txt", b"two\n");
1185
    repo.snapshot("status").unwrap();
d02e545d Andy McCall ↶ 1186
    let before = repo.store().list().unwrap();
1187
    assert!(repo.store().loose_count().unwrap() > 0);
ba160f60 Andy McCall ↶ 1188
1189
    // With the default retention every operation's view is a root: nothing prunes.
1190
    let r = repo.gc(true).unwrap();
1191
    assert_eq!(r.packed.objects, before.len());
1192
    assert_eq!(r.pruned.objects, 0);
d02e545d Andy McCall ↶ 1193
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1194
    assert_eq!(repo.store().list().unwrap(), before);
ba160f60 Andy McCall ↶ 1195
1196
    // With zero retention only the current view is a root: superseded
1197
    // working copies go, everything reachable stays.
1198
    repo.config.set("core.op-retention", "0").unwrap();
1199
    repo.save_config().unwrap();
21b2aec2 Andy McCall ↶ 1200
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
ba160f60 Andy McCall ↶ 1201
    let r = repo.gc(true).unwrap();
1202
    assert!(r.pruned.objects >= 5, "{r:?}");
1203
    let after = repo.store().list().unwrap();
1204
    assert!(after.len() < before.len());
1205
    assert!(after.contains(&h1) && after.contains(&h2));
1206
    for (_, op) in repo.op_log().unwrap() {
1207
        assert!(!op.command.is_empty(), "operation objects are all kept");
1208
    }
1209
    // Everything still works from the pruned, packed store.
d02e545d Andy McCall ↶ 1210
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
75167672 Andy McCall 1211
    assert!(matches!(
1212
        repo.verify_change(&h2).unwrap(),
1213
        SignatureStatus::Valid { .. }
1214
    ));
d02e545d Andy McCall ↶ 1215
    assert_eq!(repo.log().unwrap().len(), 3);
1216
    repo.checkout(&[h1], false, "checkout").unwrap();
1217
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1218
    repo.checkout(&[h2], false, "checkout").unwrap();
1219
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1220
    assert!(!repo.snapshot("status").unwrap().changed);
ba160f60 Andy McCall ↶ 1221
    // Grace period defers pruning of young garbage.
d02e545d Andy McCall ↶ 1222
    write(root, "a.txt", b"three\n");
1223
    repo.commit("three", &[]).unwrap();
ba160f60 Andy McCall ↶ 1224
    let r = repo.gc(false).unwrap();
1225
    assert_eq!(r.pruned.objects, 0);
1226
    assert!(r.pruned.deferred > 0);
1227
    let r = repo.gc(true).unwrap();
1228
    assert!(r.pruned.objects > 0);
1229
    assert_eq!(repo.log().unwrap().len(), 4);
21b2aec2 Andy McCall ↶ 1230
    // Restoring the default retention makes the old views roots again; the
1231
    // working copies they name were pruned, which gc tolerates.
1232
    repo.config.set("core.op-retention", "90").unwrap();
1233
    repo.save_config().unwrap();
1234
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1235
    let r = repo.gc(false).unwrap();
1236
    assert_eq!(r.pruned.objects, 0);
1237
    assert_eq!(repo.log().unwrap().len(), 4);
d02e545d Andy McCall ↶ 1238
}
614541c3 Andy McCall ↶ 1239
1240
#[test]
1241
fn describe_amend_abandon_heads() {
1242
    hermetic();
1243
    let dir = tempfile::tempdir().unwrap();
1244
    let root = dir.path();
1245
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1246
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1247
        .unwrap();
614541c3 Andy McCall ↶ 1248
    repo.set_user_config("core.sign", "change").unwrap();
1249
    write(root, "a.txt", b"one\n");
1250
    let h1 = repo.commit("first", &[]).unwrap();
1251
    write(root, "a.txt", b"one\ntwo\n");
1252
    let h2 = repo.commit("secnod", &[]).unwrap();
1253
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1254
1255
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1256
    let h2b = repo.describe(&h2, "second").unwrap();
1257
    assert_ne!(h2b, h2);
1258
    let c = repo.store().get_change(&h2b).unwrap();
75167672 Andy McCall 1259
    assert_eq!(
1260
        (c.change_id, c.message.as_str(), c.deps.clone()),
1261
        (id2, "second", vec![h1])
1262
    );
614541c3 Andy McCall ↶ 1263
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
75167672 Andy McCall 1264
    assert!(matches!(
1265
        repo.verify_change(&h2b).unwrap(),
1266
        SignatureStatus::Valid { .. }
1267
    ));
614541c3 Andy McCall ↶ 1268
    let s = repo.snapshot("status").unwrap();
1269
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
75167672 Andy McCall 1270
    assert_eq!(
1271
        repo.resolve_change(&id2.short(8)).unwrap(),
1272
        h2b,
1273
        "the old object is no longer reachable from the log"
1274
    );
c07e0e7d Andy McCall ↶ 1275
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1276
    let h1b = repo.describe(&h1, "first, described").unwrap();
1277
    assert_ne!(h1b, h1);
1278
    let heads = repo.bookmark_heads().unwrap();
1279
    assert_eq!(heads.len(), 1);
1280
    let top = repo.store().get_change(&heads[0]).unwrap();
1281
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
75167672 Andy McCall 1282
    assert!(
1283
        matches!(
1284
            repo.verify_change(&heads[0]).unwrap(),
1285
            SignatureStatus::Valid { .. }
1286
        ),
1287
        "rewritten own change is re-signed"
1288
    );
c07e0e7d Andy McCall ↶ 1289
    let (_, wc) = repo.working_copy().unwrap();
75167672 Andy McCall 1290
    assert_eq!(
1291
        wc.deps,
1292
        vec![heads[0]],
1293
        "the working copy follows the rewrite"
1294
    );
c07e0e7d Andy McCall ↶ 1295
    assert!(!repo.snapshot("status").unwrap().changed);
1296
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 1297
    assert!(
1298
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1299
    );
614541c3 Andy McCall ↶ 1300
1301
    // amend: fold an edit into the head; the result is one change from h1.
1302
    write(root, "a.txt", b"one\ntwo\nthree\n");
1303
    write(root, "b.txt", b"b\n");
1304
    let h2c = repo.amend(None).unwrap();
1305
    let c = repo.store().get_change(&h2c).unwrap();
1306
    assert_eq!(c.change_id, id2);
1307
    assert_eq!(c.message, "second");
1308
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
75167672 Andy McCall 1309
    assert_eq!(
1310
        repo.log().unwrap().len(),
1311
        3,
1312
        "working copy, amended head, first"
1313
    );
614541c3 Andy McCall ↶ 1314
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
75167672 Andy McCall 1315
    assert!(
1316
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1317
    );
614541c3 Andy McCall ↶ 1318
    assert!(snap.files.contains_key("b.txt"));
1319
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 1320
    assert!(
1321
        repo.amend(None).is_err(),
1322
        "clean working copy and no message"
1323
    );
614541c3 Andy McCall ↶ 1324
    let h2d = repo.amend(Some("second, amended")).unwrap();
75167672 Andy McCall 1325
    assert_eq!(
1326
        repo.store().get_change(&h2d).unwrap().message,
1327
        "second, amended"
1328
    );
614541c3 Andy McCall ↶ 1329
1330
    // abandon: the head goes, its content stays as uncommitted work.
1331
    repo.abandon(&h2d).unwrap();
75167672 Andy McCall 1332
    assert_eq!(
1333
        repo.bookmark_heads().unwrap(),
1334
        vec![h1b],
1335
        "the described first change is the head again"
1336
    );
614541c3 Andy McCall ↶ 1337
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 1338
    let paths: Vec<_> = s
1339
        .statuses
1340
        .iter()
1341
        .map(|p| (p.path.as_str(), p.status))
1342
        .collect();
1343
    assert_eq!(
1344
        paths,
1345
        vec![
1346
            ("a.txt", ChangeStatus::Modified),
1347
            ("b.txt", ChangeStatus::Added)
1348
        ]
1349
    );
614541c3 Andy McCall ↶ 1350
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1351
    let h3 = repo.commit("recommitted", &[]).unwrap();
1352
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1353
    // undo brings the abandoned head back.
1354
    repo.undo().unwrap();
1355
    repo.undo().unwrap();
1356
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
c07e0e7d Andy McCall ↶ 1357
6706bdcf Andy McCall ↶ 1358
    // Abandoning a non-head whose dependent references its atoms reifies
1359
    // the references (here: a.txt vanishes with it, so the dependent's edit
1360
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
c07e0e7d Andy McCall ↶ 1361
    let base = repo.bookmark_heads().unwrap()[0];
1362
    let base_change = repo.store().get_change(&base).unwrap();
1363
    let h1_now = base_change.deps[0];
6706bdcf Andy McCall ↶ 1364
    let notes = repo.abandon(&h1_now).unwrap();
75167672 Andy McCall 1365
    assert!(
1366
        !notes.is_empty(),
1367
        "the dependent's edit of a.txt was reified"
1368
    );
6706bdcf Andy McCall ↶ 1369
    let heads = repo.bookmark_heads().unwrap();
1370
    let after = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 1371
    assert!(
1372
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1373
        "{:?}",
1374
        after.files.keys()
1375
    );
6706bdcf Andy McCall ↶ 1376
    repo.undo().unwrap();
1377
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
c07e0e7d Andy McCall ↶ 1378
    write(root, "c.txt", b"c\n");
1379
    let hc = repo.commit("c", &[]).unwrap();
1380
    write(root, "d.txt", b"d\n");
1381
    let hd = repo.commit("d", &[hc]).unwrap();
1382
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1383
    repo.abandon(&hc).unwrap();
1384
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1385
    assert!(!heads.contains(&hc));
75167672 Andy McCall 1386
    let d_now = heads
1387
        .iter()
1388
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1389
        .copied()
1390
        .unwrap();
1391
    assert!(
1392
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1393
        "d inherited c's (empty) dependencies"
1394
    );
c07e0e7d Andy McCall ↶ 1395
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 1396
    assert_eq!(
1397
        s.statuses
1398
            .iter()
1399
            .map(|p| p.path.as_str())
1400
            .collect::<Vec<_>>(),
1401
        vec!["c.txt"],
1402
        "c's content is now uncommitted work"
1403
    );
614541c3 Andy McCall ↶ 1404
}
79ab8528 Andy McCall ↶ 1405
1406
#[test]
1407
fn git_export_mirrors_history() {
1408
    hermetic();
75167672 Andy McCall 1409
    if std::process::Command::new("git")
1410
        .arg("--version")
1411
        .output()
1412
        .is_err()
1413
    {
79ab8528 Andy McCall ↶ 1414
        eprintln!("git not installed; skipping");
1415
        return;
1416
    }
1417
    let dir = tempfile::tempdir().unwrap();
1418
    let root = dir.path();
75167672 Andy McCall 1419
    let mut repo = Repo::init(&root.join("r"))
1420
        .unwrap()
1421
        .with_home(root.join("home"));
1422
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1423
        .unwrap();
79ab8528 Andy McCall ↶ 1424
    let r = root.join("r");
1425
    write(&r, "README.md", b"hello\n");
1426
    write(&r, "src/main.rs", b"fn main() {}\n");
1427
    let h1 = repo.commit("first", &[]).unwrap();
1428
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1429
    write(&r, "logo.png", b"\x89PNG\0\0");
1430
    let h2 = repo.commit("second", &[]).unwrap();
1431
1432
    let git_dir = root.join("mirror.git");
1433
    let rep = repo.git_export(&git_dir).unwrap();
1434
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1435
    let git = |args: &[&str]| -> String {
75167672 Andy McCall 1436
        let out = std::process::Command::new("git")
1437
            .arg("-C")
1438
            .arg(&git_dir)
1439
            .args(args)
1440
            .output()
1441
            .unwrap();
1442
        assert!(
1443
            out.status.success(),
1444
            "{}",
1445
            String::from_utf8_lossy(&out.stderr)
1446
        );
79ab8528 Andy McCall ↶ 1447
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1448
    };
1449
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1450
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1451
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1452
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 1453
    assert!(
1454
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1455
        "{body}"
1456
    );
79ab8528 Andy McCall ↶ 1457
    assert!(body.contains("Change-Id: "), "{body}");
75167672 Andy McCall 1458
    assert_eq!(
1459
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1460
        "Ada Lovelace <[email protected]>"
1461
    );
1462
    assert_eq!(
1463
        git(&["ls-tree", "--name-only", "main"]),
1464
        "README.md\nlogo.png\nsrc"
1465
    );
79ab8528 Andy McCall ↶ 1466
1467
    // Re-export is incremental.
1468
    let rep = repo.git_export(&git_dir).unwrap();
1469
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1470
1471
    // An independent change makes two heads; the next state is one more
1472
    // commit on the linear branch whose tree is the union.
1473
    repo.checkout(&[h1], false, "checkout").unwrap();
1474
    write(&r, "other.txt", b"o\n");
1475
    let h3 = repo.commit("third", &[]).unwrap();
1476
    let rep = repo.git_export(&git_dir).unwrap();
1477
    assert_eq!((rep.exported, rep.heads), (1, 2));
1478
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1479
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1480
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1481
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1482
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
75167672 Andy McCall 1483
    assert_eq!(
1484
        git(&["ls-tree", "--name-only", "main"]),
1485
        "README.md\nlogo.png\nother.txt\nsrc"
1486
    );
79ab8528 Andy McCall ↶ 1487
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 1488
    assert!(
1489
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1490
        "{body}"
1491
    );
79ab8528 Andy McCall ↶ 1492
    // A rewrite is a new state whose one new change is the rewritten one.
1493
    repo.describe(&h3, "third, described").unwrap();
1494
    let rep = repo.git_export(&git_dir).unwrap();
1495
    assert_eq!(rep.exported, 1);
75167672 Andy McCall 1496
    assert_eq!(
1497
        git(&["log", "-1", "--format=%s", "main"]),
1498
        "third, described"
1499
    );
79ab8528 Andy McCall ↶ 1500
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1501
    let _ = h2;
1502
}
c3069537 Andy McCall ↶ 1503
1504
#[test]
1505
fn git_import_reproduces_trees() {
c3d2ef61 Andy McCall ↶ 1506
    git_import_reproduces_trees_with(None);
1507
}
1508
1509
/// The same import with every merge rendered in batches of one file
1510
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1511
#[test]
1512
fn git_import_reproduces_trees_in_batches() {
1513
    git_import_reproduces_trees_with(Some(1));
1514
}
1515
1516
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1517
    crate::repo::git::set_merge_batch_for_tests(batch);
c3069537 Andy McCall ↶ 1518
    hermetic();
75167672 Andy McCall 1519
    if std::process::Command::new("git")
1520
        .arg("--version")
1521
        .output()
1522
        .is_err()
1523
    {
c3069537 Andy McCall ↶ 1524
        eprintln!("git not installed; skipping");
1525
        return;
1526
    }
1527
    let dir = tempfile::tempdir().unwrap();
1528
    let root = dir.path();
1529
    let g = root.join("src.git");
1530
    fs::create_dir_all(&g).unwrap();
1531
    let git = |args: &[&str]| -> String {
1532
        let out = std::process::Command::new("git")
1533
            .arg("-C")
1534
            .arg(&g)
75167672 Andy McCall 1535
            .args([
1536
                "-c",
1537
                "user.name=Grace",
1538
                "-c",
1539
                "[email protected]",
1540
                "-c",
1541
                "commit.gpgsign=false",
1542
            ])
c3069537 Andy McCall ↶ 1543
            .args(args)
1544
            .output()
1545
            .unwrap();
75167672 Andy McCall 1546
        assert!(
1547
            out.status.success(),
1548
            "git {args:?}: {}",
1549
            String::from_utf8_lossy(&out.stderr)
1550
        );
c3069537 Andy McCall ↶ 1551
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1552
    };
1553
    git(&["init", "-q", "-b", "main"]);
1554
    write(&g, "README.md", b"# Hi\n");
1555
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1556
    git(&["add", "."]);
1557
    git(&["commit", "-q", "-m", "initial"]);
1558
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1559
    write(&g, "run.sh", b"#!/bin/sh\n");
1560
    #[cfg(unix)]
1561
    {
1562
        use std::os::unix::fs::PermissionsExt;
1563
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1564
    }
1565
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1566
    git(&["add", "."]);
75167672 Andy McCall 1567
    git(&[
1568
        "commit",
1569
        "-q",
1570
        "-m",
1571
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1572
    ]);
c3069537 Andy McCall ↶ 1573
    // A branch that edits README, merged back with a conflict-free merge.
1574
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1575
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1576
    git(&["commit", "-q", "-am", "readme"]);
1577
    git(&["checkout", "-q", "main"]);
1578
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1579
    // A branch from the initial commit inserting at the same place as
1580
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1581
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1582
    git(&["checkout", "-q", "-b", "clash", &initial]);
1583
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1584
    git(&["commit", "-q", "-am", "clash"]);
1585
    git(&["checkout", "-q", "main"]);
7df9007b Andy McCall ↶ 1586
    // Expected to stop at the conflict, so its status is ignored; the
1587
    // identity is passed as for every other git call here, or a machine
1588
    // without one refuses to start the merge at all.
75167672 Andy McCall 1589
    let _ = std::process::Command::new("git")
1590
        .arg("-C")
1591
        .arg(&g)
7df9007b Andy McCall ↶ 1592
        .args([
1593
            "-c",
1594
            "user.name=Grace",
1595
            "-c",
1596
            "[email protected]",
1597
            "merge",
1598
            "-q",
1599
            "clash",
1600
        ])
75167672 Andy McCall 1601
        .output();
7df9007b Andy McCall ↶ 1602
    assert!(
1603
        g.join(".git/MERGE_HEAD").exists(),
1604
        "the clash merge stopped at its conflict"
1605
    );
75167672 Andy McCall 1606
    write(
1607
        &g,
1608
        "src/lib.rs",
1609
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1610
    );
c3069537 Andy McCall ↶ 1611
    git(&["add", "."]);
1612
    git(&["commit", "-q", "-m", "resolve clash"]);
1613
    git(&["rm", "-q", "logo.png"]);
1614
    git(&["commit", "-q", "-m", "drop logo"]);
6e723b81 Andy McCall ↶ 1615
    // A rename with a small edit is imported as a move of the same node.
1616
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
75167672 Andy McCall 1617
    write(
1618
        &g,
1619
        "src/lib2.rs",
1620
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1621
    );
6e723b81 Andy McCall ↶ 1622
    git(&["add", "."]);
1623
    git(&["commit", "-q", "-m", "rename lib"]);
958fb27d Andy McCall ↶ 1624
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1625
    // run.sh is the same as in the first parent's tree, but the merged
1626
    // change touched it, so the importer must compare it, not skip it.
1627
    git(&["checkout", "-q", "-b", "discarded"]);
1628
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1629
    git(&["commit", "-q", "-am", "discarded edit"]);
1630
    git(&["checkout", "-q", "main"]);
314db9b4 Andy McCall ↶ 1631
    git(&[
1632
        "merge",
1633
        "-q",
1634
        "-s",
1635
        "ours",
1636
        "-m",
1637
        "merge discarded, keeping ours",
1638
        "discarded",
1639
    ]);
c3069537 Andy McCall ↶ 1640
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1641
1642
    let dest = root.join("oxy");
1643
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1644
    let rep = repo.import_git(&g, "main").unwrap();
1645
    assert_eq!(rep.commits, expected_count);
958fb27d Andy McCall ↶ 1646
    assert_eq!(rep.merges, 3);
314db9b4 Andy McCall ↶ 1647
    assert_eq!(
1648
        fs::read(dest.join("run.sh")).unwrap(),
1649
        b"#!/bin/sh\n",
1650
        "the ours merge kept main's run.sh"
1651
    );
958fb27d Andy McCall ↶ 1652
    let v = repo.verify_git_import(&g, "main").unwrap();
1653
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1654
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
c3069537 Andy McCall ↶ 1655
    // The working copy equals the Git tree at main.
75167672 Andy McCall 1656
    assert_eq!(
1657
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1658
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1659
    );
6e723b81 Andy McCall ↶ 1660
    assert!(!dest.join("src/lib.rs").exists());
75167672 Andy McCall 1661
    assert_eq!(
1662
        fs::read(dest.join("README.md")).unwrap(),
1663
        b"# Hi\n\nMore.\n"
1664
    );
c3069537 Andy McCall ↶ 1665
    assert!(!dest.join("logo.png").exists());
1666
    #[cfg(unix)]
1667
    {
1668
        use std::os::unix::fs::PermissionsExt;
75167672 Andy McCall 1669
        assert!(
1670
            fs::metadata(dest.join("run.sh"))
1671
                .unwrap()
1672
                .permissions()
1673
                .mode()
1674
                & 0o111
1675
                != 0
1676
        );
c3069537 Andy McCall ↶ 1677
    }
75167672 Andy McCall 1678
    assert!(
1679
        !repo.snapshot("status").unwrap().changed,
1680
        "clean after import"
1681
    );
c3069537 Andy McCall ↶ 1682
    let heads = repo.bookmark_heads().unwrap();
1683
    let st = repo.load_state(&heads).unwrap();
1684
    assert!(!st.materialize().is_conflicted());
1685
    assert_eq!(st.len(), expected_count);
75167672 Andy McCall 1686
    let tip = repo
1687
        .log()
1688
        .unwrap()
1689
        .into_iter()
1690
        .find(|e| e.change.message.starts_with("rename lib"))
1691
        .unwrap();
6e723b81 Andy McCall ↶ 1692
    let c = repo.store().get_change(&tip.hash).unwrap();
75167672 Andy McCall 1693
    assert!(
1694
        c.tree_ops
1695
            .iter()
1696
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1697
        "{:?}",
1698
        c.tree_ops
1699
    );
1700
    assert!(!c
1701
        .tree_ops
1702
        .iter()
1703
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
c3069537 Andy McCall ↶ 1704
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1705
    let log = repo.log().unwrap();
75167672 Andy McCall 1706
    let second = log
1707
        .iter()
1708
        .find(|e| e.change.message.starts_with("second"))
1709
        .unwrap();
1710
    assert_eq!(
1711
        second.change.change_id,
1712
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1713
    );
1714
    assert!(second
1715
        .change
1716
        .message
1717
        .contains("Git-Author: Grace <[email protected]>"));
1718
    let resolve = log
1719
        .iter()
1720
        .find(|e| e.change.message.starts_with("resolve clash"))
1721
        .unwrap();
1722
    assert_eq!(
1723
        resolve.change.kind,
1724
        ChangeKind::Resolution,
1725
        "a conflicting Git merge becomes a resolution"
1726
    );
c3069537 Andy McCall ↶ 1727
    // Re-importing into another fresh repository gives the same ChangeIds.
75167672 Andy McCall 1728
    let repo2 = Repo::init(&root.join("oxy2"))
1729
        .unwrap()
1730
        .with_home(root.join("home"));
c3069537 Andy McCall ↶ 1731
    repo2.import_git(&g, "main").unwrap();
dfb23a3a Andy McCall ↶ 1732
    // New nodes' identifiers derive from the commit (spec §23), so the
1733
    // re-import is not just the same ChangeIds but the same changes.
1734
    assert_eq!(
1735
        repo2.bookmark_heads().unwrap(),
1736
        repo.bookmark_heads().unwrap()
1737
    );
75167672 Andy McCall 1738
    let ids: BTreeSet<ChangeId> = repo
1739
        .log()
1740
        .unwrap()
1741
        .iter()
1742
        .filter(|e| !e.is_working_copy)
1743
        .map(|e| e.change.change_id)
1744
        .collect();
1745
    let ids2: BTreeSet<ChangeId> = repo2
1746
        .log()
1747
        .unwrap()
1748
        .iter()
1749
        .filter(|e| !e.is_working_copy)
1750
        .map(|e| e.change.change_id)
1751
        .collect();
c3069537 Andy McCall ↶ 1752
    assert_eq!(ids, ids2);
1753
    // Round trip back out to Git reproduces the tip tree.
1754
    let mirror = root.join("mirror.git");
1755
    repo.git_export(&mirror).unwrap();
75167672 Andy McCall 1756
    let out = std::process::Command::new("git")
1757
        .arg("-C")
1758
        .arg(&mirror)
1759
        .args(["show", "main:src/lib2.rs"])
1760
        .output()
1761
        .unwrap();
1762
    assert_eq!(
1763
        String::from_utf8_lossy(&out.stdout),
1764
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1765
    );
1766
    let out = std::process::Command::new("git")
1767
        .arg("-C")
1768
        .arg(&mirror)
1769
        .args(["show", "main:src/lib.rs"])
1770
        .output()
1771
        .unwrap();
1772
    assert!(
1773
        !out.status.success(),
1774
        "the old path is gone from the export"
1775
    );
c3069537 Andy McCall ↶ 1776
}
252e8cb2 Andy McCall ↶ 1777
1778
#[test]
1779
fn checkpoints_accelerate_loading_and_stay_correct() {
1780
    hermetic();
1781
    let dir = tempfile::tempdir().unwrap();
1782
    let root = dir.path();
1783
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1784
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1785
    repo.save_config().unwrap();
1786
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1787
    let mut hashes = Vec::new();
1788
    for i in 0..12 {
75167672 Andy McCall 1789
        write(
1790
            root,
1791
            "a.txt",
1792
            format!(
1793
                "{}\n",
1794
                (0..=i)
1795
                    .map(|k| k.to_string())
1796
                    .collect::<Vec<_>>()
1797
                    .join("\n")
1798
            )
1799
            .as_bytes(),
1800
        );
252e8cb2 Andy McCall ↶ 1801
        write(root, &format!("f{i}.txt"), b"x\n");
1802
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1803
    }
75167672 Andy McCall 1804
    let (_, cp) = repo
1805
        .latest_checkpoint("main")
1806
        .unwrap()
1807
        .expect("automatic checkpoint");
252e8cb2 Andy McCall ↶ 1808
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1809
    // Loading through the checkpoint equals loading everything.
1810
    let heads = repo.bookmark_heads().unwrap();
1811
    let fast = repo.load_state(&heads).unwrap();
1812
    let full = repo.load_state_full(&heads).unwrap();
1813
    assert_eq!(fast.len(), full.len());
1814
    assert_eq!(fast.heads(), full.heads());
1815
    let (a, b) = (fast.materialize(), full.materialize());
75167672 Andy McCall 1816
    assert_eq!(
1817
        a.files.keys().collect::<Vec<_>>(),
1818
        b.files.keys().collect::<Vec<_>>()
1819
    );
252e8cb2 Andy McCall ↶ 1820
    for (p, f) in &a.files {
1821
        assert_eq!(f.content, b.files[p].content, "{p}");
1822
    }
1823
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1824
    // A head set that does not contain the checkpoint's heads falls back.
75167672 Andy McCall 1825
    assert!(repo
1826
        .load_state_checkpointed(&[hashes[0]])
1827
        .unwrap()
1828
        .is_none());
252e8cb2 Andy McCall ↶ 1829
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1830
    // Everything else keeps working on top of the checkpoint.
1831
    assert!(!repo.snapshot("status").unwrap().changed);
1832
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1833
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1834
    let (r, n, bytes) = repo.checkpoint().unwrap();
1835
    assert!(n >= 12 && bytes > 0);
1836
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1837
    write(root, "a.txt", b"after\n");
1838
    let h_after = repo.commit("after", &[]).unwrap();
1839
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1840
    assert!(st.contains(&h_after));
75167672 Andy McCall 1841
    assert!(
1842
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1843
    );
252e8cb2 Andy McCall ↶ 1844
    assert_eq!(repo.log().unwrap().len(), 14);
1845
    // Checkpoints survive gc.
1846
    repo.gc(true).unwrap();
1847
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
75167672 Andy McCall 1848
    assert!(repo
1849
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1850
        .unwrap()
1851
        .is_some());
252e8cb2 Andy McCall ↶ 1852
}
135212de Andy McCall ↶ 1853
1854
#[test]
1855
fn quick_status_for_prompts() {
1856
    hermetic();
1857
    let dir = tempfile::tempdir().unwrap();
1858
    let root = dir.path();
1859
    let origin = Repo::init(&root.join("origin")).unwrap();
1860
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 1861
    let a = Repo::clone(&url, &root.join("a"))
1862
        .unwrap()
1863
        .with_home(root.join("home"));
135212de Andy McCall ↶ 1864
    let ops_before = a.op_log().unwrap().len();
1865
    let info = a.quick_status().unwrap();
75167672 Andy McCall 1866
    assert_eq!(
1867
        (
1868
            info.bookmark.as_str(),
1869
            info.heads,
1870
            info.dirty,
1871
            info.conflicted,
1872
            info.ahead,
1873
            info.behind
1874
        ),
1875
        ("main", 0, false, false, Some(0), Some(0))
1876
    );
135212de Andy McCall ↶ 1877
    write(&root.join("a"), "f.txt", b"f\n");
1878
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
75167672 Andy McCall 1879
    assert_eq!(
1880
        a.op_log().unwrap().len(),
1881
        ops_before,
1882
        "quick_status records nothing"
1883
    );
135212de Andy McCall ↶ 1884
    // A snapshotted but uncommitted change is still dirty.
1885
    a.snapshot("status").unwrap();
1886
    assert!(a.quick_status().unwrap().dirty);
1887
    a.commit("f", &[]).unwrap();
1888
    let info = a.quick_status().unwrap();
1889
    assert!(!info.dirty, "clean right after a commit");
1890
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
75167672 Andy McCall 1891
    assert_eq!(
1892
        info.format("%b %c%d%x%A%D"),
1893
        format!("main {}+1", info.change_id)
1894
    );
135212de Andy McCall ↶ 1895
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1896
    // Touching a file without changing it is not dirty; changing content of
1897
    // the same size is.
1898
    let p = root.join("a/f.txt");
1899
    let content = fs::read(&p).unwrap();
1900
    fs::write(&p, &content).unwrap();
1901
    assert!(!a.quick_status().unwrap().dirty);
1902
    fs::write(&p, b"g\n").unwrap();
1903
    assert!(a.quick_status().unwrap().dirty);
1904
    fs::write(&p, b"f\n").unwrap();
1905
    // Push, then a second clone commits and pushes: we are behind.
1906
    assert!(a.push("origin", false).unwrap()[0].ok);
1907
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
75167672 Andy McCall 1908
    let b = Repo::clone(&url, &root.join("b"))
1909
        .unwrap()
1910
        .with_home(root.join("home-b"));
135212de Andy McCall ↶ 1911
    write(&root.join("b"), "g.txt", b"g\n");
1912
    b.commit("g", &[]).unwrap();
1913
    b.push("origin", false).unwrap();
1914
    a.fetch("origin").unwrap();
1915
    let info = a.quick_status().unwrap();
1916
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1917
    assert_eq!(info.format("%A%D"), "-1");
1918
    let _ = origin;
1919
}
b3c5a59a Andy McCall ↶ 1920
1921
#[test]
1922
fn lazy_blobs_are_fetched_on_first_read() {
1923
    hermetic();
1924
    let dir = tempfile::tempdir().unwrap();
1925
    let root = dir.path();
1926
    let origin_dir = root.join("origin");
75167672 Andy McCall 1927
    let origin = Repo::init(&origin_dir)
1928
        .unwrap()
1929
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 1930
    let url = origin_dir.to_string_lossy().to_string();
1931
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1932
    write(&origin_dir, "big.bin", &big);
1933
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1934
    write(&origin_dir, "t.txt", b"t\n");
1935
    let h = origin.commit("blobs", &[]).unwrap();
1936
    let big_ref = Repo::blob_ref(&big);
1937
1938
    // Fetch only (no checkout) with a filter: the big blob stays absent.
75167672 Andy McCall 1939
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1940
        .unwrap()
1941
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 1942
    let a = {
1943
        let mut a = a;
1944
        a.config.set("remote.origin.url", &url).unwrap();
1945
        a.config.set("filter.max-blob", "100K").unwrap();
1946
        a.save_config().unwrap();
1947
        a
1948
    };
1949
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1950
    a.fetch("origin").unwrap();
1951
    assert!(a.store().has(&h));
1952
    assert!(!a.store().has(&big_ref), "withheld");
75167672 Andy McCall 1953
    assert!(
1954
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1955
        "small blob came along"
1956
    );
b3c5a59a Andy McCall ↶ 1957
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1958
1959
    // status and commit do not need it: adopt the state, edit a text file, commit.
1960
    let (op_ref, op) = a.head_op().unwrap();
1961
    let mut view = op.view.clone();
75167672 Andy McCall 1962
    view.bookmarks.insert(
1963
        "main".into(),
1964
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1965
    );
b3c5a59a Andy McCall ↶ 1966
    a.record_op(&[op_ref], "adopt", view).unwrap();
1967
    // Checkout reads the blob lazily, which fetches it.
1968
    a.checkout(&[h], true, "checkout").unwrap();
1969
    assert!(a.store().has(&big_ref), "fetched on first read");
1970
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1971
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1972
    write(&root.join("a"), "t.txt", b"t2\n");
1973
    a.commit("text edit", &[]).unwrap();
1974
1975
    // clone --max-blob records the filter; the checkout fetches lazily.
7421309f Andy McCall ↶ 1976
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
b3c5a59a Andy McCall ↶ 1977
    assert_eq!(b.config.max_blob, Some(1024));
1978
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1979
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1980
    assert!(parse_size("lots").is_err());
1981
}
7421309f Andy McCall ↶ 1982
1983
#[test]
1984
fn sparse_checkout_materializes_only_chosen_paths() {
1985
    hermetic();
1986
    let dir = tempfile::tempdir().unwrap();
1987
    let root = dir.path();
1988
    let origin_dir = root.join("origin");
75167672 Andy McCall 1989
    let origin = Repo::init(&origin_dir)
1990
        .unwrap()
1991
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 1992
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1993
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1994
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1995
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1996
    write(&origin_dir, "docs/logo.png", &logo);
1997
    write(&origin_dir, "README.md", b"# top\n");
1998
    let h1 = origin.commit("tree", &[]).unwrap();
1999
    let url = origin_dir.to_string_lossy().to_string();
2000
75167672 Andy McCall 2001
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2002
        .unwrap()
2003
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 2004
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2005
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2006
    assert!(root.join("a/src/main.rs").exists());
2007
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
75167672 Andy McCall 2008
    assert!(
2009
        !a.store().has(&Repo::blob_ref(&logo)),
2010
        "out-of-scope blob never fetched"
2011
    );
2012
    assert!(
2013
        !a.snapshot("status").unwrap().changed,
2014
        "out-of-scope files are not removals"
2015
    );
05e71ed6 Andy McCall ↶ 2016
    assert!(!a.quick_status().unwrap().dirty);
7421309f Andy McCall ↶ 2017
2018
    // Edits in scope commit normally and keep the rest of the tree intact.
75167672 Andy McCall 2019
    write(
2020
        &root.join("a"),
2021
        "src/lib.rs",
2022
        b"pub fn a() {}\npub fn b() {}\n",
2023
    );
7421309f Andy McCall ↶ 2024
    let h2 = a.commit("edit lib", &[]).unwrap();
2025
    let st = a.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 2026
    assert!(
2027
        st.files.contains_key("docs/guide.md"),
2028
        "the state still has everything"
2029
    );
7421309f Andy McCall ↶ 2030
    assert!(a.push("origin", false).unwrap()[0].ok);
2031
    // Files created outside the scope are ignored by status.
2032
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2033
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2034
2035
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2036
    let mut a = a;
2037
    a.config.set("filter.paths", "src,docs").unwrap();
2038
    a.save_config().unwrap();
75167672 Andy McCall 2039
    let r = a
2040
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2041
        .unwrap();
7421309f Andy McCall ↶ 2042
    assert!(r.written >= 2);
75167672 Andy McCall 2043
    assert_eq!(
2044
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2045
        logo,
2046
        "now fetched lazily"
2047
    );
7421309f Andy McCall ↶ 2048
    assert!(!root.join("a/README.md").exists());
2049
    // Origin sees the change made under a sparse checkout with the full tree intact.
2050
    origin.pull("origin").err();
75167672 Andy McCall 2051
    let full = origin
2052
        .load_state(&origin.bookmark_heads().unwrap())
2053
        .unwrap()
2054
        .materialize();
2055
    assert!(
2056
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2057
    );
7421309f Andy McCall ↶ 2058
    assert!(full.files.contains_key("README.md"));
2059
    let _ = h1;
2060
}
2863456a Andy McCall ↶ 2061
2062
#[test]
2063
fn shallow_clone_and_deepen() {
2064
    hermetic();
2065
    let dir = tempfile::tempdir().unwrap();
2066
    let root = dir.path();
2067
    let origin_dir = root.join("origin");
75167672 Andy McCall 2068
    let origin = Repo::init(&origin_dir)
2069
        .unwrap()
2070
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2071
    let mut hashes = Vec::new();
2072
    for i in 0..8 {
75167672 Andy McCall 2073
        write(
2074
            &origin_dir,
2075
            "a.txt",
2076
            format!(
2077
                "{}\n",
2078
                (0..=i)
2079
                    .map(|k| k.to_string())
2080
                    .collect::<Vec<_>>()
2081
                    .join("\n")
2082
            )
2083
            .as_bytes(),
2084
        );
2863456a Andy McCall ↶ 2085
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2086
    }
2087
    let url = origin_dir.to_string_lossy().to_string();
75167672 Andy McCall 2088
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2089
        .unwrap()
2090
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2091
    assert!(a.is_shallow());
75167672 Andy McCall 2092
    assert_eq!(
2093
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2094
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2095
    );
2096
    assert!(
2097
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2098
        "three levels present"
2099
    );
2863456a Andy McCall ↶ 2100
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2101
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
75167672 Andy McCall 2102
    assert_eq!(
2103
        a.log().unwrap().len(),
2104
        9,
2105
        "the log shows every change from the checkpoint's metadata"
2106
    );
2863456a Andy McCall ↶ 2107
    assert!(!a.snapshot("status").unwrap().changed);
2108
    assert_eq!(a.quick_status().unwrap().heads, 1);
2109
2110
    // Work continues on top of the shallow history and pushes back.
2111
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2112
    let h_new = a.commit("c8", &[]).unwrap();
2113
    assert!(a.push("origin", false).unwrap()[0].ok);
2114
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2115
    // Fetching new work from origin into the shallow clone works too.
2116
    write(&origin_dir, "b.txt", b"b\n");
2117
    origin.pull("origin").err();
2118
    let (_, wc) = origin.working_copy().unwrap();
2119
    let _ = wc;
75167672 Andy McCall 2120
    origin
2121
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2122
        .unwrap();
2863456a Andy McCall ↶ 2123
    write(&origin_dir, "b.txt", b"b\n");
2124
    let h_b = origin.commit("b", &[]).unwrap();
2125
    let pr = a.pull("origin").unwrap();
2126
    assert!(pr.changed);
2127
    assert!(a.store().has(&h_b));
2128
    assert!(root.join("a/b.txt").exists());
2129
2130
    // Deepening fetches older history until the boundary is gone.
2131
    // Every commit also depends on the change that created the file, so two
2132
    // levels below the boundary hold h4, h3, and the root.
2133
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2134
    assert!(a.store().has(&hashes[3]));
2135
    assert!(a.is_shallow());
2136
    a.deepen("origin", 100).unwrap();
2137
    assert!(!a.is_shallow(), "boundary reached the root");
2138
    assert!(a.store().has(&hashes[0]));
75167672 Andy McCall 2139
    assert_eq!(
2140
        a.load_state_full(&a.bookmark_heads().unwrap())
2141
            .unwrap()
2142
            .len(),
2143
        10
2144
    );
2863456a Andy McCall ↶ 2145
}
132b884b Andy McCall ↶ 2146
2147
#[test]
2148
fn tags_are_immutable_named_states_and_travel() {
2149
    hermetic();
2150
    let dir = tempfile::tempdir().unwrap();
2151
    let root = dir.path();
2152
    let origin = Repo::init(&root.join("origin")).unwrap();
2153
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2154
    let mut a = Repo::clone(&url, &root.join("a"))
2155
        .unwrap()
2156
        .with_home(root.join("home-a"));
2157
    let (key_a, _) = a
2158
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2159
        .unwrap();
132b884b Andy McCall ↶ 2160
    write(&root.join("a"), "f.txt", b"1\n");
2161
    let h1 = a.commit("one", &[]).unwrap();
2162
    write(&root.join("a"), "f.txt", b"1\n2\n");
2163
    let h2 = a.commit("two", &[]).unwrap();
2164
2165
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
75167672 Andy McCall 2166
    assert_eq!(
2167
        (t.heads.clone(), t.signer.as_deref()),
2168
        (vec![h1], Some("Ada"))
2169
    );
132b884b Andy McCall ↶ 2170
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2171
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2172
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2173
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2174
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2175
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2176
    assert_eq!(sa.sigs[0].key, key_a);
2177
    // Checkout by tag.
75167672 Andy McCall 2178
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2179
        .unwrap();
132b884b Andy McCall ↶ 2180
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
75167672 Andy McCall 2181
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2182
        .unwrap();
132b884b Andy McCall ↶ 2183
2184
    // Push carries the tag; a second attestation for the name is refused.
2185
    let r = a.push("origin", false).unwrap();
2186
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2187
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
75167672 Andy McCall 2188
    let mut forged = a
2189
        .tag_refs()
2190
        .unwrap()
2191
        .into_iter()
2192
        .find(|t| t.name == "v1")
2193
        .unwrap();
2194
    forged.state = origin
2195
        .store()
2196
        .put_state(&StateObject::new(vec![h2]))
2197
        .unwrap();
132b884b Andy McCall ↶ 2198
    forged.heads = vec![h2];
2199
    forged.attestation = None;
75167672 Andy McCall 2200
    let r = origin
2201
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2202
        .unwrap();
132b884b Andy McCall ↶ 2203
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2204
2205
    // A clone gets the tag; a later tag arrives on fetch.
75167672 Andy McCall 2206
    let b = Repo::clone(&url, &root.join("b"))
2207
        .unwrap()
2208
        .with_home(root.join("home-b"));
132b884b Andy McCall ↶ 2209
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2210
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2211
    a.tag_create("v2", &[h2], "second").unwrap();
2212
    a.push("origin", false).unwrap();
2213
    let rep = b.fetch("origin").unwrap();
2214
    assert_eq!(rep.new_tags, 1);
2215
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2216
2217
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2218
    a.policy_init().unwrap();
2219
    a.push("origin", false).unwrap();
75167672 Andy McCall 2220
    let unattested = crate::protocol::TagRef {
2221
        name: "v3".into(),
2222
        state: origin
2223
            .store()
2224
            .put_state(&StateObject::new(vec![h2]))
2225
            .unwrap(),
2226
        heads: vec![h2],
2227
        attestation: None,
2228
    };
2229
    let r = origin
2230
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2231
        .unwrap();
132b884b Andy McCall ↶ 2232
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2233
    a.tag_create("v3", &[h2], "").unwrap();
2234
    let r = a.push("origin", false).unwrap();
2235
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2236
    assert!(a.gc(true).is_ok());
2237
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2238
}
4e88e774 Andy McCall ↶ 2239
2240
#[test]
2241
fn multiple_workspaces_share_a_repository() {
2242
    hermetic();
2243
    let dir = tempfile::tempdir().unwrap();
2244
    let root = dir.path();
2245
    let main_dir = root.join("main");
2246
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2247
    write(&main_dir, "a.txt", b"a\n");
2248
    let h1 = repo.commit("a", &[]).unwrap();
2249
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2250
2251
    // A second workspace elsewhere, checked out on the bookmark.
2252
    let ws_dir = root.join("ws2");
2253
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2254
    assert!(ws_dir.join(".oxy").is_file());
2255
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2256
    assert_ne!(ws.workspace(), repo.workspace());
2257
    let list = repo.workspaces().unwrap();
2258
    assert_eq!(list.len(), 2);
75167672 Andy McCall 2259
    assert!(list
2260
        .iter()
2261
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
4e88e774 Andy McCall ↶ 2262
    assert!(!ws.snapshot("status").unwrap().changed);
2263
2264
    // Work in the second workspace: its own working copy, shared bookmark.
2265
    write(&ws_dir, "b.txt", b"b\n");
2266
    let s = ws.snapshot("status").unwrap();
2267
    assert_eq!(s.statuses.len(), 1);
75167672 Andy McCall 2268
    assert!(
2269
        !repo.snapshot("status").unwrap().changed,
2270
        "the first workspace is untouched"
2271
    );
4e88e774 Andy McCall ↶ 2272
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2273
    let mut heads = repo.bookmark_heads().unwrap();
2274
    heads.sort();
2275
    let mut want = vec![h1, h2];
2276
    want.sort();
2277
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2278
    assert!(!main_dir.join("b.txt").exists());
75167672 Andy McCall 2279
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2280
        .unwrap();
4e88e774 Andy McCall ↶ 2281
    assert!(main_dir.join("b.txt").exists());
2282
2283
    // Reopening from inside the second workspace finds the shared repository.
2284
    let reopened = Repo::open(&ws_dir).unwrap();
2285
    assert_eq!(reopened.workspace(), ws.workspace());
2286
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2287
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2288
2289
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2290
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2291
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2292
    repo.workspace_forget(&ws.workspace()).unwrap();
2293
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2294
    assert!(ws_dir.join("b.txt").exists());
75167672 Andy McCall 2295
    assert!(
2296
        ws.snapshot("status").is_err(),
2297
        "a forgotten workspace is no longer in the view"
2298
    );
4e88e774 Andy McCall ↶ 2299
6caacfff Andy McCall ↶ 2300
    // The working-copy lock: re-entrant in a thread; a lock whose process
2301
    // is gone is taken over, and a live process's is not, however old.
4e88e774 Andy McCall ↶ 2302
    let lock = repo.lock_snapshot().unwrap();
6caacfff Andy McCall ↶ 2303
    let again = repo.lock_working_copy().unwrap();
2304
    drop(again);
4e88e774 Andy McCall ↶ 2305
    drop(lock);
75167672 Andy McCall 2306
    let lock_path = main_dir
2307
        .join(".oxy/workspaces")
2308
        .join(repo.workspace().to_hex())
2309
        .join("lock");
4e88e774 Andy McCall ↶ 2310
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
6caacfff Andy McCall ↶ 2311
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2312
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2313
    age(&lock_path);
2314
    assert!(
2315
        !super::workspace::lock_is_stale(&lock_path),
2316
        "a live process keeps its lock"
2317
    );
2318
    fs::write(&lock_path, "4294967295").unwrap();
2319
    age(&lock_path);
4e88e774 Andy McCall ↶ 2320
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2321
}
cdb5beba Andy McCall ↶ 2322
2323
#[test]
2324
fn attributes_binary_eol_nocompress_lockable() {
2325
    hermetic();
2326
    let dir = tempfile::tempdir().unwrap();
2327
    let root = dir.path();
2328
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2329
    write(
2330
        root,
2331
        ".oxyattributes",
2332
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2333
    );
cdb5beba Andy McCall ↶ 2334
    write(root, "plain.dat", b"no nul bytes here\n");
2335
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2336
    write(root, "assets/model.bin", b"\0model");
2337
    let h = repo.commit("attrs", &[]).unwrap();
2338
    let snap = repo.load_state(&[h]).unwrap().materialize();
75167672 Andy McCall 2339
    assert!(
2340
        snap.files["plain.dat"].mode.opaque,
2341
        "binary attribute forces opaque without NUL bytes"
2342
    );
2343
    assert!(
2344
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2345
        "stored with LF"
2346
    );
2347
    assert!(
2348
        !repo.snapshot("status").unwrap().changed,
2349
        "CRLF on disk equals LF in the state"
2350
    );
cdb5beba Andy McCall ↶ 2351
    // nocompress chunks pack raw.
2352
    let r = repo.gc(true).unwrap();
2353
    assert!(r.packed.objects > 0);
2354
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2355
    fs::remove_file(root.join("notes.txt")).unwrap();
2356
    repo.checkout(&[h], true, "co").unwrap();
2357
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
75167672 Andy McCall 2358
    assert!(fs::metadata(root.join("assets/model.bin"))
2359
        .unwrap()
2360
        .permissions()
2361
        .readonly());
cdb5beba Andy McCall ↶ 2362
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2363
    repo.lock_path("assets/model.bin").unwrap();
75167672 Andy McCall 2364
    assert!(!fs::metadata(root.join("assets/model.bin"))
2365
        .unwrap()
2366
        .permissions()
2367
        .readonly());
cdb5beba Andy McCall ↶ 2368
    assert!(repo.is_locked("assets/model.bin"));
2369
    write(root, "assets/model.bin", b"\0model2");
2370
    repo.commit("edit model", &[]).unwrap();
2371
    repo.unlock_path("assets/model.bin").unwrap();
75167672 Andy McCall 2372
    assert!(fs::metadata(root.join("assets/model.bin"))
2373
        .unwrap()
2374
        .permissions()
2375
        .readonly());
cdb5beba Andy McCall ↶ 2376
    // A later checkout can still overwrite a read-only lockable file.
2377
    repo.checkout(&[h], true, "co").unwrap();
2378
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2379
}
6d3eefbc Andy McCall ↶ 2380
2381
#[cfg(unix)]
2382
#[test]
2383
fn hooks_can_veto_observe_and_add_dependencies() {
2384
    use std::os::unix::fs::PermissionsExt;
2385
    hermetic();
2386
    let dir = tempfile::tempdir().unwrap();
2387
    let root = dir.path();
2388
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2389
    let hooks = root.join(".oxy/hooks");
2390
    fs::create_dir_all(&hooks).unwrap();
2391
    let hook = |name: &str, body: &str| {
2392
        let p = hooks.join(name);
2393
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2394
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2395
    };
2396
    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");
2397
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2398
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2399
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2400
    write(root, ".oxyignore", b".last-*\n");
2401
    write(root, "a.txt", b"a\n");
2402
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2403
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2404
    let h1 = repo.commit("first", &[]).unwrap();
2405
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
75167672 Andy McCall 2406
    assert!(
2407
        pre.contains("\"event\":\"pre-commit\"")
2408
            && pre.contains("\"path\":\"a.txt\"")
2409
            && pre.contains("\"message\":\"first\""),
2410
        "{pre}"
2411
    );
6d3eefbc Andy McCall ↶ 2412
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2413
    assert!(post.contains(&h1.to_hex()), "{post}");
2414
    repo.checkout(&[h1], false, "co").unwrap();
75167672 Andy McCall 2415
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2416
        .unwrap()
2417
        .contains("post-checkout"));
6d3eefbc Andy McCall ↶ 2418
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2419
    repo.save_config().unwrap();
2420
    let err = repo.push("origin", false).unwrap_err().to_string();
2421
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2422
2423
    // semantic-deps: only when enabled; adds an explicit dependency.
2424
    write(root, "b.txt", b"b\n");
75167672 Andy McCall 2425
    hook(
2426
        "semantic-deps",
2427
        &format!(
2428
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2429
            h1.to_hex()
2430
        ),
2431
    );
6d3eefbc Andy McCall ↶ 2432
    let h2 = repo.commit("b without hook", &[]).unwrap();
75167672 Andy McCall 2433
    assert!(
2434
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2435
        "hook disabled by default"
2436
    );
6d3eefbc Andy McCall ↶ 2437
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2438
    repo.save_config().unwrap();
2439
    write(root, "c.txt", b"c\n");
2440
    let h3 = repo.commit("c with hook", &[]).unwrap();
2441
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2442
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
75167672 Andy McCall 2443
    assert!(
2444
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2445
        "{sem}"
2446
    );
6d3eefbc Andy McCall ↶ 2447
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2448
}
23b217d7 Andy McCall ↶ 2449
2450
#[test]
2451
fn amend_into_older_change_and_split() {
2452
    hermetic();
2453
    let dir = tempfile::tempdir().unwrap();
2454
    let root = dir.path();
2455
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2456
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2457
        .unwrap();
23b217d7 Andy McCall ↶ 2458
    repo.set_user_config("core.sign", "change").unwrap();
2459
    write(root, "a.txt", b"one\ntwo\n");
2460
    let h0 = repo.commit("base", &[]).unwrap();
2461
    write(root, "a.txt", b"one\nTWO\n");
2462
    let h1 = repo.commit("edit two", &[]).unwrap();
2463
    write(root, "a.txt", b"one\nTWO\nthree\n");
2464
    let h2 = repo.commit("add three", &[]).unwrap();
2465
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2466
2467
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2468
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2469
    let h1b = repo.amend_into(&h1, None).unwrap();
2470
    assert_ne!(h1b, h1);
2471
    let c1b = repo.store().get_change(&h1b).unwrap();
2472
    assert_eq!(c1b.change_id, id1);
2473
    assert_eq!(c1b.deps, vec![h0]);
75167672 Andy McCall 2474
    assert!(matches!(
2475
        repo.verify_change(&h1b).unwrap(),
2476
        SignatureStatus::Valid { .. }
2477
    ));
23b217d7 Andy McCall ↶ 2478
    let heads = repo.bookmark_heads().unwrap();
2479
    assert_eq!(heads.len(), 1);
2480
    let top = repo.store().get_change(&heads[0]).unwrap();
2481
    assert_eq!(top.message, "add three");
75167672 Andy McCall 2482
    assert_eq!(
2483
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2484
        [h0, h1b].into_iter().collect(),
2485
        "depends on the file's creator and the rewritten line"
2486
    );
23b217d7 Andy McCall ↶ 2487
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 2488
    assert!(
2489
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2490
    );
2491
    assert!(
2492
        !repo.snapshot("status").unwrap().changed,
2493
        "the working copy is clean after folding"
2494
    );
23b217d7 Andy McCall ↶ 2495
    // Only h1b's own state shows the fix without "three".
2496
    let only = repo.load_state(&[h1b]).unwrap().materialize();
75167672 Andy McCall 2497
    assert!(
2498
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2499
    );
23b217d7 Andy McCall ↶ 2500
    assert_eq!(repo.log().unwrap().len(), 4);
2501
2502
    // An edit to a line introduced by h2 cannot fold into h1.
2503
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2504
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2505
    assert!(err.contains("introduced after"), "{err}");
75167672 Andy McCall 2506
    assert!(
2507
        repo.snapshot("status").unwrap().statuses.len() == 1,
2508
        "nothing was changed by the refusal"
2509
    );
23b217d7 Andy McCall ↶ 2510
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2511
2512
    // Split the head that touches two files.
2513
    write(root, "b.txt", b"b\n");
2514
    write(root, "c.txt", b"c\n");
2515
    let h3 = repo.commit("b and c", &[]).unwrap();
2516
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2517
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2518
    let c_1 = repo.store().get_change(&p1).unwrap();
2519
    let c_2 = repo.store().get_change(&p2).unwrap();
2520
    assert!(c_1.message.contains("part 1: b.txt"));
2521
    assert_eq!(c_2.change_id, id3);
2522
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
75167672 Andy McCall 2523
    assert!(
2524
        heads.contains(&p1) && heads.contains(&p2),
2525
        "independent parts are both heads"
2526
    );
2527
    let snap = repo
2528
        .load_state(&repo.bookmark_heads().unwrap())
2529
        .unwrap()
2530
        .materialize();
23b217d7 Andy McCall ↶ 2531
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2532
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2533
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2534
    assert!(!repo.snapshot("status").unwrap().changed);
2535
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2536
    let _ = h2;
2537
}
28fc23d7 Andy McCall ↶ 2538
2539
#[test]
2540
fn identity_lifecycle() {
2541
    hermetic();
2542
    let dir = tempfile::tempdir().unwrap();
2543
    let root = dir.path();
2544
    let origin = Repo::init(&root.join("origin")).unwrap();
2545
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2546
    let mut a = Repo::clone(&url, &root.join("a"))
2547
        .unwrap()
2548
        .with_home(root.join("home-a"));
28fc23d7 Andy McCall ↶ 2549
    a.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 2550
    let (key_a, _) = a
2551
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2552
        .unwrap();
28fc23d7 Andy McCall ↶ 2553
    write(&root.join("a"), "a.txt", b"a\n");
2554
    let h1 = a.commit("one", &[]).unwrap();
2555
    assert!(a.policy_init().unwrap().applied);
2556
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2557
2558
    // Expiry: an identity that had expired when the change was made does not authenticate it.
75167672 Andy McCall 2559
    let mut e = Repo::init(&root.join("e"))
2560
        .unwrap()
2561
        .with_home(root.join("home-e"));
28fc23d7 Andy McCall ↶ 2562
    e.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 2563
    e.create_identity_with(
2564
        "Eve",
2565
        "[email protected]",
2566
        IdentityScope::User,
2567
        Some(Hlc::now().wall_ms - 1),
2568
    )
2569
    .unwrap();
28fc23d7 Andy McCall ↶ 2570
    write(&root.join("e"), "e.txt", b"e\n");
2571
    let he = e.commit("late", &[]).unwrap();
75167672 Andy McCall 2572
    assert!(
2573
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2574
    );
28fc23d7 Andy McCall ↶ 2575
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
75167672 Andy McCall 2576
    let r = e
2577
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2578
        .unwrap();
28fc23d7 Andy McCall ↶ 2579
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2580
    write(&root.join("e"), "e.txt", b"e2\n");
2581
    let he2 = e.commit("in time", &[]).unwrap();
75167672 Andy McCall 2582
    assert!(
2583
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2584
    );
28fc23d7 Andy McCall ↶ 2585
2586
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2587
    let r = a.rotate_identity().unwrap();
2588
    assert_eq!(r.old, key_a);
2589
    assert_eq!(a.config.author_key, Some(r.new));
2590
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2591
    assert!(r.policy.as_ref().unwrap().applied);
2592
    let (_, sp) = a.current_policy().unwrap().unwrap();
75167672 Andy McCall 2593
    assert_eq!(
2594
        (sp.policy.serial, sp.policy.roots.clone()),
2595
        (2, vec![r.new])
2596
    );
2597
    assert!(
2598
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2599
        "superseded, not revoked"
2600
    );
28fc23d7 Andy McCall ↶ 2601
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
75167672 Andy McCall 2602
    assert!(
2603
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2604
    );
28fc23d7 Andy McCall ↶ 2605
    write(&root.join("a"), "a.txt", b"a2\n");
2606
    let h2 = a.commit("two", &[]).unwrap();
75167672 Andy McCall 2607
    assert!(
2608
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2609
    );
28fc23d7 Andy McCall ↶ 2610
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2611
    let res = a.push("origin", false).unwrap();
2612
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2613
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2614
    let key_a = r.new;
2615
2616
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2617
    // identity object, so Ada's KeyId changes while her keys stay the same.
75167672 Andy McCall 2618
    let mut b = Repo::clone(&url, &root.join("b"))
2619
        .unwrap()
2620
        .with_home(root.join("home-b"));
2621
    let (key_b, id_b) = b
2622
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2623
        .unwrap();
7ba155f2 Andy McCall ↶ 2624
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
28fc23d7 Andy McCall ↶ 2625
    assert_eq!(r.old, key_a);
2626
    let key_a2 = r.new;
75167672 Andy McCall 2627
    assert_eq!(
7ba155f2 Andy McCall ↶ 2628
        a.identity(&key_a2).unwrap().delegates,
2629
        vec![Delegate::full(key_b)]
2630
    );
2631
    assert_eq!(
75167672 Andy McCall 2632
        a.identity(&key_a2).unwrap().ed25519_pk,
2633
        a.identity(&key_a).unwrap().ed25519_pk
7ba155f2 Andy McCall ↶ 2634
    );
2635
    assert!(
2636
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2637
        "already a delegate"
75167672 Andy McCall 2638
    );
28fc23d7 Andy McCall ↶ 2639
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2640
    write(&root.join("a"), "a.txt", b"a3\n");
2641
    let h3 = a.commit("three", &[]).unwrap();
75167672 Andy McCall 2642
    assert!(
2643
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2644
        "the same secret signs under the new KeyId"
2645
    );
28fc23d7 Andy McCall ↶ 2646
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2647
    a.set_user_config("core.sign", "seal").unwrap();
2648
    write(&root.join("a"), "a.txt", b"a4\n");
2649
    let h4 = a.commit("four", &[]).unwrap();
2650
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2651
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 2652
    a.store()
2653
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2654
        .unwrap();
2655
    assert!(
2656
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2657
    );
28fc23d7 Andy McCall ↶ 2658
    a.set_user_config("core.sign", "change").unwrap();
2659
    // Withdrawing the delegation re-issues the identity again.
2660
    let r = a.delegate_remove(&key_b).unwrap();
2661
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2662
    assert!(a.delegate_remove(&key_b).is_err());
2663
    let key_a3 = r.new;
2664
    let res = a.push("origin", false).unwrap();
2665
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2666
2667
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2668
    // both applied under the old threshold of 1. A grant then needs Bob too.
2669
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2670
    assert!(a.policy_root_add(id_b.clone()).is_err());
2671
    assert!(a.policy_set_threshold(3).is_err());
2672
    assert!(a.policy_set_threshold(2).unwrap().applied);
2673
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2674
    b.pull("origin").unwrap();
75167672 Andy McCall 2675
    assert_eq!(
2676
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2677
        2
2678
    );
2679
    let mut c = Repo::init(&root.join("c"))
2680
        .unwrap()
2681
        .with_home(root.join("home-c"));
2682
    let (key_c, id_c) = c
2683
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2684
        .unwrap();
28fc23d7 Andy McCall ↶ 2685
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2686
    let proposal = a.policy_grant(id_c, None).unwrap();
2687
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2688
    assert_eq!(proposal.policy.serial, serial_before + 1);
75167672 Andy McCall 2689
    assert_eq!(
2690
        a.current_policy().unwrap().unwrap().1.policy.serial,
2691
        serial_before,
2692
        "a proposal changes nothing yet"
2693
    );
28fc23d7 Andy McCall ↶ 2694
    // Bob signs the proposal, handed over as a file, and it applies for him.
2695
    let bytes = proposal.signed().encode();
75167672 Andy McCall 2696
    let signed = b
2697
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2698
        .unwrap();
28fc23d7 Andy McCall ↶ 2699
    assert!(signed.applied && signed.sigs.len() == 2);
75167672 Andy McCall 2700
    assert!(b
2701
        .current_policy()
2702
        .unwrap()
2703
        .unwrap()
2704
        .1
2705
        .policy
2706
        .authorizes(&key_c, "main"));
2707
    assert!(
2708
        b.policy_sign(signed.signed()).is_err(),
2709
        "a stale proposal is refused"
2710
    );
28fc23d7 Andy McCall ↶ 2711
    // Bob publishes it and Ada picks it up.
75167672 Andy McCall 2712
    assert!(b
2713
        .push("origin", false)
2714
        .unwrap()
2715
        .iter()
2716
        .any(|x| x.name == "policy" && x.ok));
28fc23d7 Andy McCall ↶ 2717
    a.pull("origin").unwrap();
75167672 Andy McCall 2718
    assert_eq!(
2719
        a.current_policy().unwrap().unwrap().1.policy.serial,
2720
        serial_before + 1
2721
    );
28fc23d7 Andy McCall ↶ 2722
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2723
    assert!(a.policy_revoke(&key_a3).is_err());
75167672 Andy McCall 2724
    let u = a
2725
        .revoke_identity(&key_c, "left the project")
2726
        .unwrap()
2727
        .unwrap();
28fc23d7 Andy McCall ↶ 2728
    assert!(!u.applied);
2729
    assert!(a.is_revoked(&key_c).unwrap());
2730
    assert!(!b.is_revoked(&key_c).unwrap());
2731
    let u = b.policy_sign(u.signed()).unwrap();
2732
    assert!(u.applied && u.policy.is_revoked(&key_c));
2733
    assert!(b.is_revoked(&key_c).unwrap());
2734
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
75167672 Andy McCall 2735
    assert!(
2736
        b.policy_revoke(&key_a3).is_err(),
2737
        "would leave one root for a threshold of 2"
2738
    );
28fc23d7 Andy McCall ↶ 2739
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2740
    let key_c_own = c.config.author_key.unwrap();
75167672 Andy McCall 2741
    assert!(c
2742
        .revoke_identity(&key_c_own, "lost laptop")
2743
        .unwrap()
2744
        .is_none());
28fc23d7 Andy McCall ↶ 2745
    assert!(c.is_revoked(&key_c_own).unwrap());
2746
    assert_eq!(key_c_own, key_c);
2747
}
2748
6e723b81 Andy McCall ↶ 2749
#[test]
2750
fn renames_are_detected_and_tracked_as_moves() {
2751
    hermetic();
2752
    let dir = tempfile::tempdir().unwrap();
2753
    let root = dir.path();
2754
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2755
    write(
2756
        root,
2757
        "src/old.rs",
2758
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2759
    );
6e723b81 Andy McCall ↶ 2760
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2761
    write(root, "tiny.txt", b"x\n");
2762
    let h1 = repo.commit("base", &[]).unwrap();
2763
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2764
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2765
2766
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2767
    // that shares nothing with the removed file.
2768
    fs::remove_file(root.join("src/old.rs")).unwrap();
75167672 Andy McCall 2769
    write(
2770
        root,
2771
        "lib/new.rs",
2772
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2773
    );
6e723b81 Andy McCall ↶ 2774
    fs::remove_file(root.join("img.bin")).unwrap();
2775
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2776
    fs::remove_file(root.join("tiny.txt")).unwrap();
2777
    write(root, "other.txt", b"completely different\n");
2778
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 2779
    let statuses: Vec<(&str, ChangeStatus)> = snap
2780
        .statuses
2781
        .iter()
2782
        .map(|s| (s.path.as_str(), s.status))
2783
        .collect();
6e723b81 Andy McCall ↶ 2784
    assert_eq!(
2785
        statuses,
75167672 Andy McCall 2786
        vec![
2787
            ("assets/img.bin", ChangeStatus::Renamed),
2788
            ("lib/new.rs", ChangeStatus::Renamed),
2789
            ("other.txt", ChangeStatus::Added),
2790
            ("src", ChangeStatus::Removed),
2791
            ("tiny.txt", ChangeStatus::Removed)
2792
        ]
6e723b81 Andy McCall ↶ 2793
    );
2794
    let h2 = repo.commit("move things", &[]).unwrap();
2795
    let c = repo.store().get_change(&h2).unwrap();
75167672 Andy McCall 2796
    let moves: Vec<_> = c
2797
        .tree_ops
2798
        .iter()
2799
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2800
        .collect();
6e723b81 Andy McCall ↶ 2801
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
75167672 Andy McCall 2802
    assert!(c.tree_ops.iter().any(
2803
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2804
    ));
2805
    assert!(c.tree_ops.iter().any(
2806
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2807
    ));
6e723b81 Andy McCall ↶ 2808
    let snap = repo.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 2809
    assert_eq!(
2810
        snap.files["lib/new.rs"].node, node_old,
2811
        "the node survives the rename"
2812
    );
2813
    assert!(
2814
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2815
    );
6e723b81 Andy McCall ↶ 2816
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
75167672 Andy McCall 2817
    assert!(render_change(
2818
        &c,
2819
        &repo.load_state(&[h1]).unwrap(),
2820
        &repo.load_state(&[h1]).unwrap().materialize()
2821
    )
0912a033 Andy McCall ↶ 2822
    .contains("R src/old.rs -> lib/new.rs"));
6e723b81 Andy McCall ↶ 2823
    // A fresh checkout reproduces the tree.
2824
    let other = tempfile::tempdir().unwrap();
2825
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
75167672 Andy McCall 2826
    assert_eq!(
2827
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2828
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2829
    );
6e723b81 Andy McCall ↶ 2830
    assert!(!other.path().join("src").exists());
2831
    assert!(!clone.snapshot("status").unwrap().changed);
2832
    // Similarity is line based, byte weighted.
2833
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2834
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2835
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2836
    assert_eq!(similarity(b"", b"x\n"), 0);
2837
}
2838
30ea9c1e Andy McCall ↶ 2839
#[test]
2840
fn git_fetch_and_push_round_trip() {
2841
    hermetic();
75167672 Andy McCall 2842
    if std::process::Command::new("git")
2843
        .arg("--version")
2844
        .output()
2845
        .is_err()
2846
    {
30ea9c1e Andy McCall ↶ 2847
        eprintln!("git not installed; skipping");
2848
        return;
2849
    }
2850
    let dir = tempfile::tempdir().unwrap();
2851
    let root = dir.path();
2852
    let git_in = |d: &Path, args: &[&str]| -> String {
2853
        let out = std::process::Command::new("git")
2854
            .arg("-C")
2855
            .arg(d)
75167672 Andy McCall 2856
            .args([
2857
                "-c",
2858
                "user.name=Grace",
2859
                "-c",
2860
                "[email protected]",
2861
                "-c",
2862
                "commit.gpgsign=false",
2863
            ])
30ea9c1e Andy McCall ↶ 2864
            .args(args)
2865
            .output()
2866
            .unwrap();
75167672 Andy McCall 2867
        assert!(
2868
            out.status.success(),
2869
            "git {args:?}: {}",
2870
            String::from_utf8_lossy(&out.stderr)
2871
        );
30ea9c1e Andy McCall ↶ 2872
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2873
    };
2874
    // A bare "remote" and a work tree that pushes to it.
2875
    let remote = root.join("remote.git");
2876
    fs::create_dir_all(&remote).unwrap();
2877
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2878
    let work = root.join("work");
75167672 Andy McCall 2879
    git_in(
2880
        root,
2881
        &[
2882
            "clone",
2883
            "-q",
2884
            remote.to_str().unwrap(),
2885
            work.to_str().unwrap(),
2886
        ],
2887
    );
30ea9c1e Andy McCall ↶ 2888
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2889
    write(&work, "README.md", b"# Project\n");
2890
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2891
    git_in(&work, &["add", "."]);
2892
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2893
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2894
    git_in(&work, &["commit", "-q", "-am", "second"]);
2895
    git_in(&work, &["push", "-q", "origin", "main"]);
2896
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2897
2898
    // Fetch into a fresh oxy repository.
2899
    let o = root.join("oxy");
2900
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2901
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2902
        .unwrap();
30ea9c1e Andy McCall ↶ 2903
    let url = remote.to_string_lossy().to_string();
2904
    let r = repo.git_fetch(&url, "main").unwrap();
2905
    assert_eq!((r.commits, r.heads), (2, 1));
75167672 Andy McCall 2906
    assert_eq!(
2907
        fs::read(o.join("src/lib.rs")).unwrap(),
2908
        b"pub fn a() {}\npub fn b() {}\n"
2909
    );
30ea9c1e Andy McCall ↶ 2910
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 2911
    assert_eq!(
2912
        repo.git_fetch(&url, "main").unwrap().commits,
2913
        0,
2914
        "nothing new"
2915
    );
30ea9c1e Andy McCall ↶ 2916
2917
    // An oxy change, pushed back: one commit on top of the Git tip.
75167672 Andy McCall 2918
    write(
2919
        &o,
2920
        "src/lib.rs",
2921
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2922
    );
30ea9c1e Andy McCall ↶ 2923
    write(&o, "NOTES.md", b"from oxy\n");
2924
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2925
    let r = repo.git_push(&url, "main").unwrap();
2926
    assert_eq!(r.exported, 1, "{r:?}");
2927
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
75167672 Andy McCall 2928
    assert_eq!(
2929
        git_in(&work, &["log", "--format=%s", "main"]),
2930
        "add c and notes\nsecond\ninitial"
2931
    );
30ea9c1e Andy McCall ↶ 2932
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2933
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2934
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
75167672 Andy McCall 2935
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2936
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2937
    assert_eq!(
2938
        repo.git_push(&url, "main").unwrap().exported,
2939
        0,
2940
        "already pushed"
2941
    );
30ea9c1e Andy McCall ↶ 2942
2943
    // Git moves on; pushing without fetching is refused, fetching brings
2944
    // the commit in and the working copy follows.
2945
    write(&work, "README.md", b"# Project\n\nMore.\n");
2946
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2947
    git_in(&work, &["push", "-q", "origin", "main"]);
2948
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
75167672 Andy McCall 2949
    assert!(repo
2950
        .git_push(&url, "main")
2951
        .unwrap_err()
2952
        .to_string()
2953
        .contains("fetch"));
30ea9c1e Andy McCall ↶ 2954
    let r = repo.git_fetch(&url, "main").unwrap();
75167672 Andy McCall 2955
    assert_eq!(
2956
        (r.commits, r.heads),
2957
        (1, 2),
2958
        "the Git change and the oxy change commute"
2959
    );
2960
    assert_eq!(
2961
        fs::read(o.join("README.md")).unwrap(),
2962
        b"# Project\n\nMore.\n"
2963
    );
30ea9c1e Andy McCall ↶ 2964
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2965
    assert!(!repo.snapshot("status").unwrap().changed);
2966
    // Another oxy change pushes on top of Git's newest commit.
2967
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2968
    repo.commit("notes again", &[]).unwrap();
2969
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2970
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2971
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
75167672 Andy McCall 2972
    assert_eq!(
2973
        fs::read(work.join("NOTES.md")).unwrap(),
2974
        b"from oxy\nagain\n"
2975
    );
2976
    assert_eq!(
2977
        git_in(&work, &["log", "--format=%s", "main"])
2978
            .lines()
2979
            .count(),
2980
        5
2981
    );
30ea9c1e Andy McCall ↶ 2982
}
2983
2b872d07 Andy McCall ↶ 2984
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2985
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2986
#[test]
2987
#[ignore]
2988
fn bench_one_gibibyte_file() {
2989
    hermetic();
2990
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2991
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2992
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2993
        None => tempfile::tempdir().unwrap(),
2994
    };
2995
    let root = dir.path();
75167672 Andy McCall 2996
    let repo = Repo::init(&root.join("r"))
2997
        .unwrap()
2998
        .with_home(root.join("home"));
2b872d07 Andy McCall ↶ 2999
    let size = 1usize << 30;
3000
    let mut data = vec![0u8; size];
3001
    let mut x = 0x9e3779b97f4a7c15u64;
3002
    for chunk in data.chunks_mut(8) {
3003
        x ^= x << 13;
3004
        x ^= x >> 7;
3005
        x ^= x << 17;
3006
        let b = x.to_le_bytes();
3007
        chunk.copy_from_slice(&b[..chunk.len()]);
3008
    }
3009
    let t = std::time::Instant::now();
3010
    write(&root.join("r"), "big.bin", &data);
3011
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3012
    let t = std::time::Instant::now();
3013
    let h = repo.commit("big", &[]).unwrap();
3014
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3015
    let t = std::time::Instant::now();
3016
    assert!(!repo.snapshot("status").unwrap().changed);
3017
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3018
    let t = std::time::Instant::now();
3019
    let objects = repo.store().list().unwrap().len();
3020
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3021
    let t = std::time::Instant::now();
3022
    let g = repo.gc(true).unwrap();
3023
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3024
    let t = std::time::Instant::now();
3025
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3026
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3027
    let t = std::time::Instant::now();
3028
    let back = fs::read(root.join("c/big.bin")).unwrap();
3029
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3030
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3031
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3032
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
75167672 Andy McCall 3033
    eprintln!(
3034
        "store size: {:.1} MiB for 1 GiB of data",
3035
        store_bytes as f64 / (1024.0 * 1024.0)
3036
    );
2b872d07 Andy McCall ↶ 3037
}
3038
3039
fn walkdir_size(p: &Path) -> u64 {
3040
    let mut total = 0;
3041
    if let Ok(rd) = fs::read_dir(p) {
3042
        for e in rd.flatten() {
3043
            let path = e.path();
3044
            if path.is_dir() {
3045
                total += walkdir_size(&path);
3046
            } else if let Ok(m) = fs::metadata(&path) {
3047
                total += m.len();
3048
            }
3049
        }
3050
    }
3051
    total
3052
}
3053
b7f102fc Andy McCall ↶ 3054
/// An opaque file whose size and mtime match the manifest is not read on
3055
/// the next snapshot: its blob comes from the manifest's stat cache.
3056
#[cfg(unix)]
3057
#[test]
3058
fn stat_cache_skips_reading_unchanged_opaque_files() {
3059
    use std::os::unix::fs::PermissionsExt;
3060
    hermetic();
3061
    let dir = tempfile::tempdir().unwrap();
3062
    let root = dir.path();
3063
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3064
    let mut big = vec![0u8; 300 * 1024];
3065
    for (i, b) in big.iter_mut().enumerate() {
3066
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3067
    }
3068
    big[0] = 0;
3069
    write(root, "big.bin", &big);
3070
    write(root, "a.txt", b"text\n");
3071
    let h1 = repo.commit("base", &[]).unwrap();
3072
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
75167672 Andy McCall 3073
    assert!(
3074
        m.entries["big.bin"].blob.is_some(),
3075
        "opaque files record their blob"
3076
    );
b7f102fc Andy McCall ↶ 3077
    assert!(m.entries["a.txt"].blob.is_none());
3078
    let blob = m.entries["big.bin"].blob.unwrap();
3079
    assert!(repo.store().has(&blob));
3080
3081
    // Files modified within two seconds of the manifest are racy and still
3082
    // read; age the file so the cache applies, then snapshot to record it.
3083
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
75167672 Andy McCall 3084
    fs::File::options()
3085
        .write(true)
3086
        .open(root.join("big.bin"))
3087
        .unwrap()
3088
        .set_modified(old)
3089
        .unwrap();
b7f102fc Andy McCall ↶ 3090
    assert!(!repo.snapshot("status").unwrap().changed);
3091
    // Now the file cannot be read at all; the snapshot succeeds without it.
3092
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3093
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3094
    assert!(
3095
        !snap.changed && snap.statuses.is_empty(),
3096
        "{:?}",
3097
        snap.statuses
3098
    );
b7f102fc Andy McCall ↶ 3099
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3100
    // A real change (new mtime, new content) is seen and committed correctly.
3101
    let mut big2 = big.clone();
3102
    big2[10] ^= 0xff;
3103
    write(root, "big.bin", &big2);
3104
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3105
    assert_eq!(
3106
        snap.statuses
3107
            .iter()
3108
            .map(|s| (s.path.as_str(), s.status))
3109
            .collect::<Vec<_>>(),
3110
        vec![("big.bin", ChangeStatus::Modified)]
3111
    );
b7f102fc Andy McCall ↶ 3112
    let h2 = repo.commit("edit", &[]).unwrap();
3113
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 3114
    assert_eq!(
3115
        files["big.bin"].content,
3116
        FileContent::Opaque {
3117
            blobs: vec![Repo::blob_ref(&big2)]
3118
        }
3119
    );
b7f102fc Andy McCall ↶ 3120
    // Checkout writes a manifest with blobs too, so the next status is cached.
3121
    repo.checkout(&[h1], false, "checkout").unwrap();
3122
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3123
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3124
    assert!(!repo.snapshot("status").unwrap().changed);
3125
}
3126
50a046e4 Andy McCall ↶ 3127
#[test]
3128
fn status_json_lists_conflicts_with_contributors() {
3129
    hermetic();
3130
    let dir = tempfile::tempdir().unwrap();
3131
    let root = dir.path();
3132
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3133
    write(root, "a.txt", b"one\n");
3134
    let h1 = repo.commit("base", &[]).unwrap();
3135
    write(root, "a.txt", b"one\nleft\n");
3136
    let ha = repo.commit("left", &[]).unwrap();
3137
    repo.checkout(&[h1], true, "checkout").unwrap();
3138
    write(root, "a.txt", b"one\nright\n");
3139
    let hb = repo.commit("right", &[]).unwrap();
3140
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3141
    let snap = repo.snapshot("status").unwrap();
3142
    assert!(snap.base_snapshot.is_conflicted());
3143
    let json = repo.status_json(&snap).unwrap();
3144
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3145
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3146
    assert!(json.contains("\"conflicted\":true"), "{json}");
75167672 Andy McCall 3147
    assert!(
3148
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3149
        "{json}"
3150
    );
50a046e4 Andy McCall ↶ 3151
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3152
    assert!(json.contains("\"resolved\":false"), "{json}");
3153
    assert!(json.starts_with('{') && json.ends_with('}'));
3154
    // Resolve and the report says so; a clean copy has no conflicts.
3155
    write(root, "a.txt", b"one\nleft\nright\n");
3156
    let snap = repo.snapshot("status").unwrap();
3157
    let json = repo.status_json(&snap).unwrap();
3158
    assert!(json.contains("\"resolved\":true"), "{json}");
3159
    repo.commit("resolve", &[]).unwrap();
3160
    let snap = repo.snapshot("status").unwrap();
3161
    let json = repo.status_json(&snap).unwrap();
75167672 Andy McCall 3162
    assert!(
3163
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3164
        "{json}"
3165
    );
50a046e4 Andy McCall ↶ 3166
}
3167
9ac1fbe2 Andy McCall ↶ 3168
#[test]
3169
fn ignore_rules_do_not_untrack_files() {
3170
    hermetic();
3171
    let dir = tempfile::tempdir().unwrap();
3172
    let root = dir.path();
3173
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3174
    write(root, "src.c", b"int x;\n");
3175
    write(root, "build/out.o", b"\0obj");
3176
    write(root, "sub/keep.log", b"keep\n");
3177
    write(root, "sub/junk.log", b"junk\n");
3178
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3179
    let snap = repo.snapshot("status").unwrap();
3180
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 3181
    assert_eq!(
3182
        added,
3183
        vec![".oxyignore", "src.c", "sub/keep.log"],
3184
        "anchored, glob, and negated rules"
3185
    );
9ac1fbe2 Andy McCall ↶ 3186
    let h1 = repo.commit("base", &[]).unwrap();
3187
    // Ignoring a tracked file changes nothing about it.
3188
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3189
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3190
    assert_eq!(
3191
        snap.statuses
3192
            .iter()
3193
            .map(|s| s.path.as_str())
3194
            .collect::<Vec<_>>(),
3195
        vec![".oxyignore"]
3196
    );
9ac1fbe2 Andy McCall ↶ 3197
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
75167672 Andy McCall 3198
    assert!(repo
3199
        .load_state(&[h2])
3200
        .unwrap()
3201
        .materialize()
3202
        .files
3203
        .contains_key("src.c"));
9ac1fbe2 Andy McCall ↶ 3204
    // Its edits are still seen, by status and by the prompt.
3205
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3206
    write(root, "src.c", b"int x, y;\n");
3207
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3208
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3209
    assert_eq!(
3210
        snap.statuses
3211
            .iter()
3212
            .map(|s| (s.path.as_str(), s.status))
3213
            .collect::<Vec<_>>(),
3214
        vec![("src.c", ChangeStatus::Modified)]
3215
    );
9ac1fbe2 Andy McCall ↶ 3216
    let h3 = repo.commit("edit src.c", &[]).unwrap();
75167672 Andy McCall 3217
    assert!(
3218
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3219
    );
9ac1fbe2 Andy McCall ↶ 3220
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3221
    fs::remove_file(root.join("src.c")).unwrap();
3222
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3223
    assert_eq!(
3224
        snap.statuses
3225
            .iter()
3226
            .map(|s| (s.path.as_str(), s.status))
3227
            .collect::<Vec<_>>(),
3228
        vec![("src.c", ChangeStatus::Removed)]
3229
    );
9ac1fbe2 Andy McCall ↶ 3230
    repo.checkout(&[h3], true, "checkout").unwrap();
3231
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3232
    assert!(!repo.snapshot("status").unwrap().changed);
3233
    let _ = h1;
3234
}
3235
b837d2b5 Andy McCall ↶ 3236
#[test]
3237
fn split_works_on_non_heads_by_node() {
3238
    hermetic();
3239
    let dir = tempfile::tempdir().unwrap();
3240
    let root = dir.path();
3241
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3242
    write(root, "a.txt", b"one\n");
3243
    write(root, "junk/x.lock", b"lock\n");
3244
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3245
    write(root, "a.txt", b"one\ntwo\n");
3246
    let h2 = repo.commit("more work", &[]).unwrap();
3247
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3248
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3249
    // h1 is not a head: split it by node.
3250
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3251
    assert_ne!(h1b, h1);
75167672 Andy McCall 3252
    assert_eq!(
3253
        repo.store().get_change(&h1b).unwrap().change_id,
3254
        id1,
3255
        "the rest keeps the ChangeId"
3256
    );
b837d2b5 Andy McCall ↶ 3257
    let junk = repo.store().get_change(&hj).unwrap();
75167672 Andy McCall 3258
    assert!(junk.tree_ops.iter().all(
3259
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3260
    ));
b837d2b5 Andy McCall ↶ 3261
    let heads = repo.bookmark_heads().unwrap();
75167672 Andy McCall 3262
    assert!(
3263
        heads.contains(&hj),
3264
        "the split-off part is a head of its own"
3265
    );
b837d2b5 Andy McCall ↶ 3266
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 3267
    assert!(
3268
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3269
        "the dependent was rewritten onto the new hash"
3270
    );
b837d2b5 Andy McCall ↶ 3271
    assert!(snap.files.contains_key("junk/x.lock"));
75167672 Andy McCall 3272
    let h2b = heads
3273
        .iter()
3274
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3275
        .copied()
3276
        .unwrap();
b837d2b5 Andy McCall ↶ 3277
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3278
    assert!(!repo.snapshot("status").unwrap().changed);
3279
    // Abandoning the split-off head removes the junk from history.
3280
    repo.abandon(&hj).unwrap();
3281
    let heads = repo.bookmark_heads().unwrap();
3282
    let snap = repo.load_state(&heads).unwrap().materialize();
3283
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3284
    assert!(snap.files.contains_key("a.txt"));
3285
    // A dependent that touches the split-off paths blocks the split.
3286
    write(root, "junk/y.lock", b"y\n");
3287
    let hb = repo.commit("junk base", &[]).unwrap();
3288
    write(root, "junk/y.lock", b"yy\n");
3289
    write(root, "b.txt", b"b\n");
3290
    repo.commit("touches junk", &[]).unwrap();
3291
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3292
    assert!(err.contains("depends on the split-off paths"), "{err}");
3293
}
3294
7b9809e6 Andy McCall ↶ 3295
#[test]
3296
fn bookmarks_switch_merge_and_push() {
3297
    hermetic();
3298
    let dir = tempfile::tempdir().unwrap();
3299
    let root = dir.path();
3300
    let origin = Repo::init(&root.join("origin")).unwrap();
3301
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3302
    let mut repo = Repo::clone(&url, &root.join("r"))
3303
        .unwrap()
3304
        .with_home(root.join("home"));
7b9809e6 Andy McCall ↶ 3305
    let r = root.join("r");
3306
    write(&r, "a.txt", b"a\n");
3307
    let h_a = repo.commit("a", &[]).unwrap();
3308
    assert!(repo.push("origin", false).unwrap()[0].ok);
3309
3310
    // A bookmark at the working copy's base, then work on it.
3311
    assert!(repo.bookmark_create("bad name..", None).is_err());
3312
    assert!(repo.bookmark_create("-x", None).is_err());
3313
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3314
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3315
    repo.bookmark_switch("feature", false).unwrap();
3316
    assert_eq!(repo.config.bookmark, "feature");
3317
    write(&r, "a.txt", b"a\nb\n");
3318
    write(&r, "b.txt", b"b\n");
3319
    let h_b = repo.commit("b on feature", &[]).unwrap();
75167672 Andy McCall 3320
    assert_eq!(
3321
        repo.bookmark_heads().unwrap(),
3322
        vec![h_b],
3323
        "b edits a.txt, so it depends on a"
3324
    );
3325
    assert_eq!(
3326
        repo.resolve_heads("main").unwrap(),
3327
        vec![h_a],
3328
        "main is untouched"
3329
    );
3330
    assert_eq!(
3331
        repo.resolve_change("feature").unwrap(),
3332
        h_b,
3333
        "a one-head bookmark names its change"
3334
    );
7b9809e6 Andy McCall ↶ 3335
    // Reopening keeps the workspace's bookmark.
3336
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3337
    assert_eq!(reopened.config.bookmark, "feature");
3338
    // Back to main: b.txt goes away; work there.
3339
    repo.bookmark_switch("main", false).unwrap();
3340
    assert!(!r.join("b.txt").exists());
3341
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3342
    write(&r, "c.txt", b"c\n");
3343
    let h_c = repo.commit("c on main", &[]).unwrap();
3344
    let list = repo.bookmarks().unwrap();
75167672 Andy McCall 3345
    assert_eq!(
3346
        list.iter()
3347
            .map(|b| (b.name.as_str(), b.current))
3348
            .collect::<Vec<_>>(),
3349
        vec![("feature", false), ("main", true)]
3350
    );
3351
    assert_eq!(
3352
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3353
        Some(1),
3354
        "c is not on origin yet"
3355
    );
7b9809e6 Andy McCall ↶ 3356
    // Merge feature into main: the union, both heads, no merge change.
3357
    let m = repo.merge("feature").unwrap();
3358
    assert!(m.changed && m.checked_out);
3359
    let mut want = vec![h_b, h_c];
3360
    want.sort();
3361
    assert_eq!(m.heads, want);
3362
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3363
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3364
    assert!(repo.merge("main").is_err());
3365
    // The other bookmark can be pushed by name and appears at origin.
3366
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3367
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3368
    assert!(repo.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 3369
    assert_eq!(
3370
        repo.bookmarks()
3371
            .unwrap()
3372
            .iter()
3373
            .find(|b| b.name == "main")
3374
            .unwrap()
3375
            .ahead,
3376
        Some(0)
3377
    );
7b9809e6 Andy McCall ↶ 3378
    // A second workspace inherits the current bookmark and can switch independently.
3379
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3380
    assert_eq!(ws.config.bookmark, "main");
3381
    let mut ws = ws;
3382
    ws.bookmark_switch("feature", false).unwrap();
75167672 Andy McCall 3383
    assert_eq!(
3384
        Repo::open(&r).unwrap().config.bookmark,
3385
        "main",
3386
        "the first workspace is unaffected"
3387
    );
3388
    assert!(
3389
        repo.bookmark_delete("feature").is_err(),
3390
        "current bookmark of another workspace"
3391
    );
7b9809e6 Andy McCall ↶ 3392
    ws.bookmark_switch("main", false).unwrap();
3393
    // Set and delete.
3394
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3395
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3396
    repo.bookmark_delete("feature").unwrap();
3397
    assert!(repo.resolve_heads("feature").is_err());
3398
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
75167672 Andy McCall 3399
    assert!(
3400
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3401
        "changes of a deleted bookmark remain"
3402
    );
7b9809e6 Andy McCall ↶ 3403
}
3404
4dee277c Andy McCall ↶ 3405
#[test]
3406
fn oxygen_subrepos_pin_follow_and_update() {
3407
    hermetic();
3408
    let dir = tempfile::tempdir().unwrap();
3409
    let root = dir.path();
3410
    // A library repository with two commits, and a bare-ish origin for it.
3411
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3412
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
75167672 Andy McCall 3413
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3414
        .unwrap()
3415
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3416
    write(&root.join("lib"), "lib.txt", b"v1\n");
3417
    let l1 = lib.commit("lib v1", &[]).unwrap();
3418
    assert!(lib.push("origin", false).unwrap()[0].ok);
3419
    let _ = lib_origin;
3420
3421
    // The application (a clone of its own origin) adds it as a subrepo.
3422
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3423
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3424
    let _ = app_origin;
3425
    let app_dir = root.join("app");
75167672 Andy McCall 3426
    let app = Repo::clone(&app_url, &app_dir)
3427
        .unwrap()
3428
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3429
    write(&app_dir, "main.txt", b"app\n");
3430
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3431
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3432
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3433
    let snap = app.snapshot("status").unwrap();
3434
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 3435
    assert_eq!(
3436
        paths,
3437
        vec![".oxymodules", "libs/lib", "main.txt"],
3438
        "the nested files are not walked"
3439
    );
4dee277c Andy McCall ↶ 3440
    let a1 = app.commit("app with lib", &[]).unwrap();
3441
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3442
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3443
    assert!(!files.contains_key("libs/lib/lib.txt"));
3444
    assert!(!app.snapshot("status").unwrap().changed);
3445
    let subs = app.subrepos().unwrap();
3446
    assert_eq!(subs.len(), 1);
3447
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3448
3449
    // Advance the nested repository: the parent sees a modified pin.
75167672 Andy McCall 3450
    let nested = Repo::open(&app_dir.join("libs/lib"))
3451
        .unwrap()
3452
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3453
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3454
    let l2 = nested.commit("lib v2", &[]).unwrap();
3455
    assert!(nested.push("origin", false).unwrap()[0].ok);
3456
    let snap = app.snapshot("status").unwrap();
75167672 Andy McCall 3457
    assert_eq!(
3458
        snap.statuses
3459
            .iter()
3460
            .map(|s| (s.path.as_str(), s.status))
3461
            .collect::<Vec<_>>(),
3462
        vec![("libs/lib", ChangeStatus::Modified)]
3463
    );
4dee277c Andy McCall ↶ 3464
    let a2 = app.commit("bump lib", &[]).unwrap();
1a3b6203 Andy McCall ↶ 3465
    // Checking out the older app state brings the nested working copy back
3466
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4dee277c Andy McCall ↶ 3467
    let r = app.checkout(&[a1], false, "checkout").unwrap();
1a3b6203 Andy McCall ↶ 3468
    assert!(
3469
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3470
        "{:?}",
3471
        r.notes
3472
    );
4dee277c Andy McCall ↶ 3473
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
1a3b6203 Andy McCall ↶ 3474
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3475
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3476
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4dee277c Andy McCall ↶ 3477
    assert!(!app.snapshot("status").unwrap().changed);
3478
    // A dirty nested repository is left alone and reported.
3479
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3480
    let r = app.checkout(&[a2], false, "checkout").unwrap();
75167672 Andy McCall 3481
    assert!(
3482
        r.notes.iter().any(|n| n.contains("uncommitted")),
3483
        "{:?}",
3484
        r.notes
3485
    );
4dee277c Andy McCall ↶ 3486
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3487
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3488
    let r = app.submodule_update(false, &[]).unwrap();
3489
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3490
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3491
    let _ = l2;
3492
3493
    // A fresh clone of the app has the pin but no nested repository until update --init.
3494
    assert!(app.push("origin", false).unwrap()[0].ok);
3495
    let clone_dir = root.join("app-clone");
75167672 Andy McCall 3496
    let clone = Repo::clone(&app_url, &clone_dir)
3497
        .unwrap()
3498
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3499
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
75167672 Andy McCall 3500
    assert_eq!(
3501
        clone.submodule_update(false, &[]).unwrap(),
3502
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3503
    );
3504
    assert_eq!(
3505
        clone.submodule_update(true, &[]).unwrap(),
3506
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3507
    );
3508
    assert_eq!(
3509
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3510
        b"v2\n"
3511
    );
4dee277c Andy McCall ↶ 3512
    assert!(!clone.snapshot("status").unwrap().changed);
3513
    // Removing the subrepo leaves the directory and drops the node.
3514
    clone.submodule_remove("libs/lib").unwrap();
3515
    let snap = clone.snapshot("status").unwrap();
75167672 Andy McCall 3516
    assert!(
3517
        snap.statuses
3518
            .iter()
3519
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3520
        "{:?}",
3521
        snap.statuses
3522
    );
4dee277c Andy McCall ↶ 3523
    let c = clone.commit("drop lib", &[]).unwrap();
75167672 Andy McCall 3524
    assert!(!clone
3525
        .load_state(&[c])
3526
        .unwrap()
3527
        .materialize()
3528
        .files
3529
        .contains_key("libs/lib"));
4dee277c Andy McCall ↶ 3530
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
75167672 Andy McCall 3531
    assert!(
3532
        !clone.snapshot("status").unwrap().changed,
3533
        "an unregistered nested repository is ignored"
3534
    );
4dee277c Andy McCall ↶ 3535
}
3536
3537
#[test]
3538
fn git_submodules_import_and_export_as_gitlinks() {
3539
    hermetic();
75167672 Andy McCall 3540
    if std::process::Command::new("git")
3541
        .arg("--version")
3542
        .output()
3543
        .is_err()
3544
    {
4dee277c Andy McCall ↶ 3545
        eprintln!("git not installed; skipping");
3546
        return;
3547
    }
3548
    let dir = tempfile::tempdir().unwrap();
3549
    let root = dir.path();
3550
    let git_in = |d: &Path, args: &[&str]| -> String {
3551
        let out = std::process::Command::new("git")
3552
            .arg("-C")
3553
            .arg(d)
75167672 Andy McCall 3554
            .args([
3555
                "-c",
3556
                "user.name=Grace",
3557
                "-c",
3558
                "[email protected]",
3559
                "-c",
3560
                "commit.gpgsign=false",
3561
                "-c",
3562
                "protocol.file.allow=always",
3563
            ])
4dee277c Andy McCall ↶ 3564
            .args(args)
3565
            .output()
3566
            .unwrap();
75167672 Andy McCall 3567
        assert!(
3568
            out.status.success(),
3569
            "git {args:?}: {}",
3570
            String::from_utf8_lossy(&out.stderr)
3571
        );
4dee277c Andy McCall ↶ 3572
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3573
    };
3574
    let sub = root.join("sub");
3575
    fs::create_dir_all(&sub).unwrap();
3576
    git_in(&sub, &["init", "-q", "-b", "main"]);
3577
    write(&sub, "s.txt", b"sub\n");
3578
    git_in(&sub, &["add", "."]);
3579
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3580
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3581
    let g = root.join("main.git");
3582
    fs::create_dir_all(&g).unwrap();
3583
    git_in(&g, &["init", "-q", "-b", "main"]);
3584
    write(&g, "README.md", b"# app\n");
3585
    git_in(&g, &["add", "."]);
3586
    git_in(&g, &["commit", "-q", "-m", "initial"]);
75167672 Andy McCall 3587
    git_in(
3588
        &g,
3589
        &[
3590
            "submodule",
3591
            "add",
3592
            "-q",
3593
            sub.to_str().unwrap(),
3594
            "vendor/sub",
3595
        ],
3596
    );
4dee277c Andy McCall ↶ 3597
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3598
3599
    let dest = root.join("oxy");
3600
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3601
    let rep = repo.import_git(&g, "main").unwrap();
3602
    assert_eq!((rep.commits, rep.submodules), (2, 1));
75167672 Andy McCall 3603
    let files = repo
3604
        .load_state(&repo.bookmark_heads().unwrap())
3605
        .unwrap()
3606
        .materialize()
3607
        .files;
4dee277c Andy McCall ↶ 3608
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
75167672 Andy McCall 3609
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3610
        panic!()
3611
    };
3612
    assert_eq!(
3613
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3614
        crate::subrepo::Pin::Git {
3615
            sha: sub_sha.clone(),
3616
            branch: "HEAD".into()
3617
        }
3618
    );
3619
    let modules =
3620
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4dee277c Andy McCall ↶ 3621
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3622
    assert!(modules.entries["vendor/sub"].git);
75167672 Andy McCall 3623
    assert!(
3624
        files.contains_key(".gitmodules"),
3625
        "the Git file is kept for round trips"
3626
    );
3627
    assert!(
3628
        !dest.join("vendor/sub/.git").exists(),
3629
        "not cloned until update --init"
3630
    );
4dee277c Andy McCall ↶ 3631
    assert!(!repo.snapshot("status").unwrap().changed);
3632
    // update --init clones it at the pinned commit; status is unchanged.
75167672 Andy McCall 3633
    assert_eq!(
3634
        repo.submodule_update(true, &[]).unwrap(),
3635
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3636
    );
3637
    assert_eq!(
3638
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3639
        sub_sha
3640
    );
4dee277c Andy McCall ↶ 3641
    assert!(!repo.snapshot("status").unwrap().changed);
3642
    // Export writes the gitlink and .gitmodules back.
3643
    let mirror = root.join("mirror.git");
3644
    let rep = repo.git_export(&mirror).unwrap();
3645
    assert_eq!(rep.skipped_subrepos, 0);
3646
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
75167672 Andy McCall 3647
    assert!(
3648
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3649
        "{ls}"
3650
    );
3651
    assert_eq!(
3652
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3653
        ".gitmodules\nREADME.md\nvendor"
3654
    );
4dee277c Andy McCall ↶ 3655
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
75167672 Andy McCall 3656
    assert_eq!(
3657
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3658
        orig_tree,
3659
        "tree round trip"
3660
    );
4dee277c Andy McCall ↶ 3661
}
3662
957fee30 Andy McCall ↶ 3663
#[test]
3664
fn partial_commits_by_path_and_by_hunk() {
3665
    hermetic();
3666
    let dir = tempfile::tempdir().unwrap();
3667
    let root = dir.path();
3668
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3669
    write(root, "a.txt", b"1\n2\n3\n");
3670
    write(root, "b.txt", b"b\n");
3671
    let h0 = repo.commit("base", &[]).unwrap();
3672
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3673
    write(root, "b.txt", b"b\nbb\n");
3674
    write(root, "c.txt", b"c\n");
3675
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
75167672 Andy McCall 3676
    let h1 = repo
3677
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3678
        .unwrap();
957fee30 Andy McCall ↶ 3679
    let c1 = repo.store().get_change(&h1).unwrap();
75167672 Andy McCall 3680
    assert!(
3681
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3682
        "{:?}",
3683
        c1.tree_ops
3684
    );
957fee30 Andy McCall ↶ 3685
    assert_eq!(c1.deps, vec![h0]);
3686
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
75167672 Andy McCall 3687
    assert!(
3688
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3689
    );
957fee30 Andy McCall ↶ 3690
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3691
    assert!(!files.contains_key("c.txt"));
3692
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3693
    assert_eq!(
3694
        snap.statuses
3695
            .iter()
3696
            .map(|s| (s.path.as_str(), s.status))
3697
            .collect::<Vec<_>>(),
3698
        vec![
3699
            ("b.txt", ChangeStatus::Modified),
3700
            ("c.txt", ChangeStatus::Added)
3701
        ]
3702
    );
3703
    assert_eq!(
3704
        fs::read(root.join("b.txt")).unwrap(),
3705
        b"b\nbb\n",
3706
        "disk untouched"
3707
    );
957fee30 Andy McCall ↶ 3708
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3709
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 3710
    let b_hunk = hunks
3711
        .iter()
3712
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3713
        .unwrap()
3714
        .index;
3715
    let h2 = repo
3716
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3717
        .unwrap();
957fee30 Andy McCall ↶ 3718
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 3719
    assert!(
3720
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3721
    );
957fee30 Andy McCall ↶ 3722
    assert!(!files.contains_key("c.txt"));
3723
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3724
    assert_eq!(
3725
        snap.statuses
3726
            .iter()
3727
            .map(|s| s.path.as_str())
3728
            .collect::<Vec<_>>(),
3729
        vec!["c.txt"]
3730
    );
957fee30 Andy McCall ↶ 3731
    // Choosing only the content hunk of a file in a new directory pulls in
3732
    // the directory and file additions it needs.
3733
    write(root, "d/e.txt", b"e\n");
3734
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 3735
    let e_insert = hunks
3736
        .iter()
3737
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3738
        .unwrap()
3739
        .index;
3740
    let h3 = repo
3741
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3742
        .unwrap();
957fee30 Andy McCall ↶ 3743
    let c3 = repo.store().get_change(&h3).unwrap();
3744
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3745
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3746
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
d8c086ca Andy McCall ↶ 3747
    // Choosing a new file's addition hunk brings its content along.
3748
    write(root, "f/g.txt", b"g\n");
3749
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 3750
    let g_add = hunks
3751
        .iter()
3752
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3753
        .unwrap()
3754
        .index;
3755
    let h4 = repo
3756
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3757
        .unwrap();
d8c086ca Andy McCall ↶ 3758
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
75167672 Andy McCall 3759
    assert!(
3760
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3761
    );
3762
    assert!(!repo
3763
        .snapshot("status")
3764
        .unwrap()
3765
        .statuses
3766
        .iter()
3767
        .any(|s| s.path == "f/g.txt"));
957fee30 Andy McCall ↶ 3768
    // Everything left commits normally; the working copy is then clean.
3769
    repo.commit("the rest", &[]).unwrap();
3770
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 3771
    let files = repo
3772
        .load_state(&repo.bookmark_heads().unwrap())
3773
        .unwrap()
3774
        .materialize()
3775
        .files;
957fee30 Andy McCall ↶ 3776
    assert!(files.contains_key("c.txt"));
3777
}
3778
3779
#[test]
3780
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3781
    hermetic();
3782
    let dir = tempfile::tempdir().unwrap();
3783
    let root = dir.path();
3784
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3785
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3786
        .unwrap();
957fee30 Andy McCall ↶ 3787
    write(root, "a.txt", b"one\n");
3788
    let h1 = repo.commit("first", &[]).unwrap();
3789
    write(root, "a.txt", b"one\ntwo\n");
3790
    let h2 = repo.commit("second", &[]).unwrap();
3791
    let b = repo.blame("a.txt").unwrap();
75167672 Andy McCall 3792
    assert_eq!(
3793
        b.iter()
3794
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3795
            .collect::<Vec<_>>(),
3796
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3797
    );
957fee30 Andy McCall ↶ 3798
    assert!(b.iter().all(|l| l.author == "Ada"));
75167672 Andy McCall 3799
    assert_eq!(
3800
        b[0].change_id,
3801
        repo.store().get_change(&h1).unwrap().change_id
3802
    );
957fee30 Andy McCall ↶ 3803
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3804
    repo.commit("rename", &[]).unwrap();
3805
    let b = repo.blame("b.txt").unwrap();
75167672 Andy McCall 3806
    assert_eq!(
3807
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3808
        vec![h1, h2],
3809
        "the node survives the rename"
3810
    );
957fee30 Andy McCall ↶ 3811
    assert!(repo.blame("a.txt").is_err());
3812
}
3813
3814
#[test]
3815
fn bisect_finds_the_first_bad_change() {
3816
    hermetic();
3817
    let dir = tempfile::tempdir().unwrap();
3818
    let root = dir.path();
3819
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3820
    let mut content = String::new();
3821
    let mut hashes = Vec::new();
3822
    for i in 1..=8 {
3823
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3824
        write(root, "f.txt", content.as_bytes());
3825
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3826
    }
3827
    // Each step appends after the previous line, so the chain is linear.
3828
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3829
    repo.bisect_start().unwrap();
75167672 Andy McCall 3830
    assert!(matches!(
3831
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3832
        BisectStep::NeedMarks { good: 1, bad: 0 }
3833
    ));
957fee30 Andy McCall ↶ 3834
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
75167672 Andy McCall 3835
    assert!(
3836
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3837
        "{step:?}"
3838
    );
957fee30 Andy McCall ↶ 3839
    // Automated: bad when the bug line is present.
75167672 Andy McCall 3840
    let step = repo
3841
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3842
        .unwrap();
957fee30 Andy McCall ↶ 3843
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
75167672 Andy McCall 3844
    assert_eq!(
3845
        repo.bisect_status().unwrap(),
3846
        Some(BisectStep::Found { culprit: hashes[4] })
3847
    );
957fee30 Andy McCall ↶ 3848
    repo.bisect_reset().unwrap();
3849
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3850
    assert!(repo.bisect_status().unwrap().is_none());
3851
    assert!(!repo.snapshot("status").unwrap().changed);
3852
    // Manual marks and a skip.
3853
    repo.bisect_start().unwrap();
3854
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3855
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3856
    let mut skipped_once = false;
3857
    let mut guard = 0;
3858
    while let BisectStep::Testing { .. } = step {
3859
        guard += 1;
3860
        assert!(guard < 20);
3861
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3862
        if !skipped_once && text.contains("line 6") {
3863
            // An untestable state away from the boundary: the search routes around it.
3864
            skipped_once = true;
3865
            step = repo.bisect_mark(None, &[]).unwrap();
3866
            continue;
3867
        }
3868
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3869
    }
3870
    assert!(skipped_once);
3871
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3872
    repo.bisect_reset().unwrap();
3873
    // Skipping the culprit itself leaves it among the candidates reported.
3874
    repo.bisect_start().unwrap();
3875
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3876
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3877
    let mut guard = 0;
3878
    while let BisectStep::Testing { heads, .. } = &step {
3879
        guard += 1;
3880
        assert!(guard < 20);
3881
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 3882
        let is_culprit_state =
3883
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3884
        step = if is_culprit_state {
3885
            repo.bisect_mark(None, &[]).unwrap()
3886
        } else {
3887
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3888
        };
957fee30 Andy McCall ↶ 3889
    }
3890
    match step {
75167672 Andy McCall 3891
        BisectStep::Inconclusive { candidates } => assert!(
3892
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3893
            "{candidates:?}"
3894
        ),
957fee30 Andy McCall ↶ 3895
        other => panic!("{other:?}"),
3896
    }
3897
    repo.bisect_reset().unwrap();
3898
}
3899
728da0f9 Andy McCall ↶ 3900
#[test]
3901
fn squash_folds_a_change_into_its_dependency() {
3902
    hermetic();
3903
    let dir = tempfile::tempdir().unwrap();
3904
    let root = dir.path();
3905
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3906
    write(root, "a.txt", b"1\n");
3907
    let a = repo.commit("A", &[]).unwrap();
3908
    write(root, "a.txt", b"1\n2\n");
3909
    let c = repo.commit("C", &[]).unwrap();
3910
    write(root, "a.txt", b"1\n2\n3\n");
3911
    let e = repo.commit("E", &[]).unwrap();
3912
    write(root, "b.txt", b"b\n");
3913
    let b = repo.commit("B", &[]).unwrap();
3914
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3915
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3916
    // E depends on C which A lacks: refused, naming it.
3917
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3918
    assert!(err.contains(&c.short(12)), "{err}");
3919
    // C into A: A' has both, C is gone, E follows and still reads the same.
3920
    let a2 = repo.squash(&c, &a).unwrap();
3921
    let a2c = repo.store().get_change(&a2).unwrap();
3922
    assert_eq!(a2c.change_id, id_a);
3923
    assert!(a2c.deps.is_empty());
3924
    let heads = repo.bookmark_heads().unwrap();
3925
    let st = repo.load_state(&heads).unwrap();
3926
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
75167672 Andy McCall 3927
    let e2 = st
3928
        .changes()
3929
        .find(|(_, m)| m.change_id == id_e)
3930
        .map(|(h, _)| *h)
3931
        .unwrap();
3932
    assert_eq!(
3933
        repo.store().get_change(&e2).unwrap().deps,
3934
        vec![a2],
3935
        "E now depends on A' alone"
3936
    );
728da0f9 Andy McCall ↶ 3937
    let files = st.materialize().files;
75167672 Andy McCall 3938
    assert!(
3939
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3940
    );
728da0f9 Andy McCall ↶ 3941
    assert!(files.contains_key("b.txt"));
3942
    assert!(st.contains(&b));
3943
    assert!(!repo.snapshot("status").unwrap().changed);
3944
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3945
    // Undo restores the three original changes.
3946
    repo.undo().unwrap();
3947
    repo.undo().unwrap();
3948
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3949
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3950
}
3951
3952
#[test]
3953
fn rebase_re_expresses_a_change_against_another_base() {
3954
    hermetic();
3955
    let dir = tempfile::tempdir().unwrap();
3956
    let root = dir.path();
3957
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3958
    write(root, "a.txt", b"1\n2\n");
3959
    let a = repo.commit("A", &[]).unwrap();
3960
    write(root, "a.txt", b"1\n2\n3\n");
3961
    let c = repo.commit("C: append 3", &[]).unwrap();
3962
    write(root, "a.txt", b"1\n2\n3\n4\n");
3963
    let e = repo.commit("E: append 4", &[]).unwrap();
3964
    // A different base: A plus a change that prepends a line.
3965
    repo.checkout(&[a], true, "checkout").unwrap();
3966
    write(root, "a.txt", b"0\n1\n2\n");
3967
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3968
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3969
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3970
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3971
    let c2 = repo.rebase(&c, &[d]).unwrap();
3972
    let c2c = repo.store().get_change(&c2).unwrap();
3973
    assert_eq!(c2c.change_id, id_c);
3974
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3975
    let heads = repo.bookmark_heads().unwrap();
3976
    let st = repo.load_state(&heads).unwrap();
3977
    assert!(!st.contains(&c) && st.contains(&d));
75167672 Andy McCall 3978
    let e2 = st
3979
        .changes()
3980
        .find(|(_, m)| m.change_id == id_e)
3981
        .map(|(h, _)| *h)
3982
        .unwrap();
728da0f9 Andy McCall ↶ 3983
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
75167672 Andy McCall 3984
    assert!(
3985
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3986
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3987
    );
728da0f9 Andy McCall ↶ 3988
    let files = st.materialize().files;
75167672 Andy McCall 3989
    assert!(
3990
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3991
        "{:?}",
3992
        files["a.txt"].content
3993
    );
728da0f9 Andy McCall ↶ 3994
    assert!(!files["a.txt"].is_conflicted());
3995
    // Rebasing onto a state that already contains the change is refused.
3996
    assert!(repo.rebase(&c2, &[c2]).is_err());
3997
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
75167672 Andy McCall 3998
    assert!(
3999
        err.contains("lacks dependencies"),
4000
        "E needs C, which D's state does not have: {err}"
4001
    );
728da0f9 Andy McCall ↶ 4002
}
4003
c792033a Andy McCall ↶ 4004
#[test]
4005
fn unsigned_tags_keep_their_message() {
4006
    hermetic();
4007
    let dir = tempfile::tempdir().unwrap();
4008
    let root = dir.path();
4009
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4010
    write(root, "a.txt", b"a\n");
4011
    repo.commit("a", &[]).unwrap();
4012
    assert!(repo.secret_key().unwrap().is_none());
75167672 Andy McCall 4013
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4014
        .unwrap();
c792033a Andy McCall ↶ 4015
    let tags = repo.tags().unwrap();
75167672 Andy McCall 4016
    assert_eq!(
4017
        (
4018
            tags[0].name.as_str(),
4019
            tags[0].message.as_str(),
4020
            tags[0].signer.as_deref()
4021
        ),
4022
        ("v1", "first release", None)
4023
    );
4024
    assert!(
4025
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4026
        "an unsigned attestation is not advertised"
4027
    );
c792033a Andy McCall ↶ 4028
}
387335ff Andy McCall ↶ 4029
4030
#[test]
4031
fn fsck_passes_a_sound_repository_and_names_each_fault() {
64818938 Andy McCall ↶ 4032
    // Files on disk are what this tests: tampering with them, and the
4033
    // directory store's crash points.
4034
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4035
        return;
4036
    }
387335ff Andy McCall ↶ 4037
    hermetic();
4038
    let dir = tempfile::tempdir().unwrap();
4039
    let root = dir.path();
4040
    let origin_path = root.join("origin");
4041
    let origin = Repo::init(&origin_path).unwrap();
4042
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4043
        .unwrap()
4044
        .with_home(root.join("home-a"));
4045
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4046
        .unwrap();
4047
    write(&root.join("a"), "f.txt", b"one\n");
4048
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4049
    let h1 = a.commit("first", &[]).unwrap();
4050
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4051
    let h2 = a.commit("second", &[]).unwrap();
4052
    a.tag_create("v1", &[h2], "first release").unwrap();
4053
    a.checkpoint().unwrap();
4054
    assert!(a.push("origin", false).unwrap()[0].ok);
4055
4056
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4057
    for repo in [&a, &origin] {
4058
        let rep = repo.fsck().unwrap();
4059
        assert_eq!(rep.problems, vec![], "{rep:?}");
4060
        // The two commits, plus the working copy's change in `a`.
4061
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4062
        assert!(rep.ops > 1 && rep.objects > 5);
4063
    }
4064
    assert!(origin.fsck().unwrap().attestations >= 1);
4065
4066
    // A flipped byte in a stored object is corruption, named by hash.
4067
    let c1 = a.store().path_for(&h1);
4068
    let pristine = fs::read(&c1).unwrap();
4069
    let mut bytes = pristine.clone();
4070
    *bytes.last_mut().unwrap() ^= 1;
4071
    fs::write(&c1, &bytes).unwrap();
4072
    let rep = a.fsck().unwrap();
4073
    assert!(rep.errors() >= 1);
4074
    assert!(
4075
        rep.problems
4076
            .iter()
4077
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4078
        "{rep:?}"
4079
    );
4080
    fs::write(&c1, &pristine).unwrap();
4081
    assert_eq!(a.fsck().unwrap().errors(), 0);
4082
4083
    // A missing change is named with what needed it.
4084
    fs::remove_file(&c1).unwrap();
4085
    let rep = a.fsck().unwrap();
4086
    assert!(
4087
        rep.problems.iter().any(|p| p.severity == Severity::Error
4088
            && p.object == Some(h1)
4089
            && p.what.contains("change missing, needed by change")),
4090
        "{rep:?}"
4091
    );
4092
    fs::write(&c1, &pristine).unwrap();
4093
4094
    // A missing blob is an error in a full clone.
4095
    let c2 = a.store().get_change(&h1).unwrap();
4096
    let blob = c2
4097
        .edits
4098
        .iter()
4099
        .find_map(|e| match e {
4100
            Edit::Replace { new: Some(b), .. } => Some(*b),
4101
            _ => None,
4102
        })
4103
        .expect("the binary file is a blob");
4104
    let bp = a.store().path_for(&blob);
4105
    let blob_bytes = fs::read(&bp).unwrap();
4106
    fs::remove_file(&bp).unwrap();
4107
    let rep = a.fsck().unwrap();
4108
    assert!(
4109
        rep.problems
4110
            .iter()
4111
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4112
        "{rep:?}"
4113
    );
4114
    fs::write(&bp, &blob_bytes).unwrap();
4115
4116
    // A broken op log head is reported, not a crash.
4117
    let head = root.join("a/.oxy/ops/head");
4118
    let saved = fs::read(&head).unwrap();
4119
    fs::write(&head, b"not a hash").unwrap();
4120
    let rep = a.fsck().unwrap();
4121
    assert!(
4122
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4123
        "{rep:?}"
4124
    );
4125
    fs::write(&head, saved).unwrap();
4126
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4127
}
4dcb8c09 Andy McCall ↶ 4128
4129
/// Copy a directory tree (for restoring a pristine repository).
4130
fn copy_tree(from: &Path, to: &Path) {
4131
    fs::create_dir_all(to).unwrap();
4132
    for e in fs::read_dir(from).unwrap() {
4133
        let e = e.unwrap();
4134
        let target = to.join(e.file_name());
4135
        if e.file_type().unwrap().is_dir() {
4136
            copy_tree(&e.path(), &target);
4137
        } else {
4138
            fs::copy(e.path(), &target).unwrap();
4139
        }
4140
    }
4141
}
4142
4143
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4144
/// would, and check that both repositories still open, pass `fsck`, and
4145
/// accept the same operation again.
4146
#[test]
4147
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
64818938 Andy McCall ↶ 4148
    // Files on disk are what this tests: tampering with them, and the
4149
    // directory store's crash points.
4150
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4151
        return;
4152
    }
4dcb8c09 Andy McCall ↶ 4153
    use crate::durable::failpoint;
4154
    hermetic();
4155
    let dir = tempfile::tempdir().unwrap();
4156
    let pristine = dir.path().join("pristine");
4157
    let origin_path = pristine.join("origin");
4158
    Repo::init(&origin_path).unwrap();
4159
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4160
        .unwrap()
4161
        .with_home(dir.path().join("home"));
4162
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4163
        .unwrap();
4164
    write(&pristine.join("a"), "f.txt", b"one\n");
4165
    a.commit("first", &[]).unwrap();
4166
    assert!(a.push("origin", false).unwrap()[0].ok);
4167
    drop(a);
4168
4169
    type Op = fn(&Repo) -> Result<()>;
4170
    let edit_and_commit: Op = |r| {
4171
        write(r.root(), "f.txt", b"one\ntwo\n");
4172
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4173
        r.commit("second", &[]).map(|_| ())
4174
    };
4175
    let push: Op = |r| {
4176
        let res = r.push("origin", false)?;
4177
        if res.iter().all(|x| x.ok) {
4178
            Ok(())
4179
        } else {
4180
            Err(RepoError::Msg(format!("{res:?}")))
4181
        }
4182
    };
4183
4184
    for (name, prepare, op) in [
4185
        ("commit", None, edit_and_commit),
4186
        ("push", Some(edit_and_commit), push),
4187
    ] {
4188
        let mut steps = 0;
4189
        for n in 1.. {
4190
            let run = dir.path().join(format!("{name}-{n}"));
4191
            copy_tree(&pristine, &run);
4192
            // Clones record their remote by path; point it at this copy.
4193
            let open = |p: &Path| {
4194
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4195
                r.config
4196
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4197
                    .unwrap();
4198
                r.save_config().unwrap();
4199
                r
4200
            };
4201
            let a = open(&run.join("a"));
4202
            if let Some(prep) = prepare {
4203
                prep(&a).unwrap();
4204
            }
4205
            failpoint::crash_after(n);
4206
            let outcome = op(&a);
4207
            let crashed = failpoint::disarm();
4208
            drop(a);
4209
            if !crashed {
4210
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4211
                steps = n - 1;
4212
                break;
4213
            }
4214
            assert!(
4215
                outcome.is_err(),
4216
                "{name}: a crash at step {n} was swallowed"
4217
            );
4218
            for repo in ["a", "origin"] {
4219
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4220
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4221
                });
4222
                let rep = r.fsck().unwrap();
4223
                assert_eq!(
4224
                    rep.errors(),
4225
                    0,
4226
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4227
                    rep.problems
4228
                );
4229
            }
4230
            // The interrupted operation can simply be run again.
4231
            let a = open(&run.join("a"));
4232
            // A crash after the commit point leaves the commit done.
4233
            let landed = a
4234
                .bookmark_heads()
4235
                .unwrap()
4236
                .iter()
4237
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4238
            let again = match (name, landed) {
4239
                ("commit", true) => Ok(()),
4240
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4241
                _ => op(&a),
4242
            };
4243
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4244
            assert_eq!(a.fsck().unwrap().errors(), 0);
4245
            fs::remove_dir_all(&run).unwrap();
4246
        }
4247
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4248
    }
4249
}
19555025 Andy McCall ↶ 4250
4251
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4252
/// running at the same time lose nothing: every commit ends up on the
4253
/// bookmark, locally and on the remote, and the repository passes fsck.
4254
#[test]
4255
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4256
    hermetic();
4257
    let dir = tempfile::tempdir().unwrap();
4258
    let root = dir.path();
4259
    let origin = root.join("origin");
4260
    Repo::init_bare_unbound(&origin).unwrap();
4261
    let main = root.join("main");
4262
    let mut repo = Repo::init(&main).unwrap();
4263
    repo.config
4264
        .set("remote.origin.url", &origin.to_string_lossy())
4265
        .unwrap();
4266
    repo.save_config().unwrap();
4267
    write(&main, "seed.txt", b"seed\n");
4268
    repo.commit("seed", &[]).unwrap();
4269
    let second = root.join("second");
4270
    repo.workspace_add(&second, None).unwrap();
4271
    drop(repo);
4272
4273
    const EACH: usize = 15;
4274
    std::thread::scope(|s| {
4275
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4276
            s.spawn(move || {
4277
                let r = Repo::open(&dir).unwrap();
4278
                for i in 0..EACH {
4279
                    write(
4280
                        &dir,
4281
                        &format!("{tag}-{i}.txt"),
4282
                        format!("{tag} {i}\n").as_bytes(),
4283
                    );
4284
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4285
                    if push && i % 5 == 4 {
4286
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4287
                        let _ = r.push("origin", false);
4288
                    }
4289
                }
4290
            });
4291
        }
4292
    });
4293
4294
    let repo = Repo::open(&main).unwrap();
4295
    let heads = repo.bookmark_heads().unwrap();
4296
    let state = repo.load_state(&heads).unwrap();
4297
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4298
    for tag in ["a", "b"] {
4299
        for i in 0..EACH {
4300
            assert!(
4301
                messages.contains(&format!("{tag} {i}")),
4302
                "lost commit {tag} {i}; have {messages:?}"
4303
            );
4304
        }
4305
    }
4306
    let rep = repo.fsck().unwrap();
4307
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4308
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4309
    let hosted = Repo::open(&origin).unwrap();
4310
    let hosted_heads = hosted.bookmark_heads().unwrap();
4311
    assert_eq!(
4312
        hosted.load_state(&hosted_heads).unwrap().len(),
4313
        state.len(),
4314
        "the remote has every commit"
4315
    );
4316
}
4317
4318
/// Two operations recorded from the same parent (what two processes do
4319
/// when they race) are merged: both bookmarks' heads survive, and a
4320
/// change made on one side only is kept.
4321
#[test]
4322
fn operations_from_the_same_parent_are_merged() {
4323
    hermetic();
4324
    let dir = tempfile::tempdir().unwrap();
4325
    let root = dir.path();
4326
    let repo = Repo::init(root).unwrap();
4327
    write(root, "a.txt", b"a\n");
4328
    let a = repo.commit("a", &[]).unwrap();
4329
    write(root, "b.txt", b"b\n");
4330
    let b = repo.commit("b", &[]).unwrap();
4331
    let (x, op) = repo.head_op().unwrap();
4332
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4333
4334
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4335
    let mut one = op.view.clone();
4336
    one.bookmarks.insert("main".into(), state(vec![a]));
4337
    one.bookmarks.insert("topic".into(), state(vec![a]));
4338
    let mut two = op.view.clone();
4339
    two.bookmarks.insert("main".into(), state(vec![b]));
4340
    repo.record_op(&[x], "one", one).unwrap();
4341
    let merged = repo.record_op(&[x], "two", two).unwrap();
4342
4343
    let (head, op) = repo.head_op().unwrap();
4344
    assert_eq!(head, merged);
4345
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4346
    assert!(op.command.contains("merged with a concurrent operation"));
4347
    let mut main = repo
4348
        .store()
4349
        .get_state(&op.view.bookmarks["main"])
4350
        .unwrap()
4351
        .heads;
4352
    main.sort();
4353
    let mut want = vec![a, b];
4354
    want.sort();
4355
    assert_eq!(main, want, "both sides' heads are kept");
4356
    assert!(
4357
        op.view.bookmarks.contains_key("topic"),
4358
        "a one-sided change survives"
4359
    );
4360
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4361
}
3e5772cc Andy McCall ↶ 4362
4363
#[test]
4364
fn failed_requests_come_with_a_next_step() {
4365
    use crate::protocol::hint_for;
4366
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4367
        .unwrap()
4368
        .contains("token"));
4369
    assert!(hint_for("…: HTTP 403: forbidden")
4370
        .unwrap()
4371
        .contains("repo:write"));
4372
    assert!(hint_for("…: HTTP 404: no such repository")
4373
        .unwrap()
4374
        .contains("owner and repository name"));
4375
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4376
        .unwrap()
4377
        .contains("oxyhub-ca.pem"));
4378
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4379
        .unwrap()
4380
        .contains("running"));
4381
    assert!(hint_for("Dns Failed: failed to lookup address information")
4382
        .unwrap()
4383
        .contains("resolve"));
4384
    assert_eq!(hint_for("something else entirely"), None);
4385
}
4386
4387
#[test]
4388
fn doctor_names_problems_and_what_to_do() {
4389
    hermetic();
4390
    let dir = tempfile::tempdir().unwrap();
4391
    let root = dir.path();
4392
    let origin = root.join("origin");
4393
    Repo::init_bare_unbound(&origin).unwrap();
4394
    let mut repo = Repo::init(&root.join("r"))
4395
        .unwrap()
4396
        .with_home(root.join("home"));
4397
    let find = |r: &DoctorReport, area: &str, h: Health| {
4398
        r.checks
4399
            .iter()
4400
            .find(|c| c.area == area && c.health == h)
4401
            .cloned()
4402
    };
4403
4404
    let r = repo.doctor(true);
4405
    assert!(find(&r, "identity", Health::Warn)
4406
        .unwrap()
4407
        .hint
4408
        .unwrap()
4409
        .contains("oxy identity create"));
4410
    assert!(find(&r, "repository", Health::Ok).is_some());
4411
4412
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4413
        .unwrap();
4414
    repo.config.set("author.name", "Ada").unwrap();
4415
    repo.config.set("author.email", "[email protected]").unwrap();
4416
    repo.config
4417
        .set("remote.origin.url", &origin.to_string_lossy())
4418
        .unwrap();
4419
    repo.config
4420
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4421
        .unwrap();
4422
    repo.config.set("remote.down.token", "t").unwrap();
4423
    repo.config
4424
        .set("remote.badca.url", "https://example.invalid/a/b")
4425
        .unwrap();
4426
    repo.config
4427
        .set(
4428
            "remote.badca.ca",
4429
            &root.join("missing.pem").to_string_lossy(),
4430
        )
4431
        .unwrap();
4432
    repo.save_config().unwrap();
4433
4434
    let r = repo.doctor(true);
4435
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4436
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4437
    assert!(find(&r, "remote origin", Health::Ok)
4438
        .unwrap()
4439
        .message
4440
        .contains("first push binds it"));
4441
    let down = find(&r, "remote down", Health::Fail).unwrap();
4442
    assert!(
4443
        down.hint.as_deref().unwrap_or("").contains("running"),
4444
        "{down:?}"
4445
    );
4446
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4447
    assert!(
4448
        badca.hint.unwrap().contains("remote.badca.ca"),
4449
        "the remote's own name is in the hint"
4450
    );
4451
    assert_eq!(r.worst(), Health::Fail);
4452
4453
    // Offline, nothing is contacted.
4454
    let r = repo.doctor(false);
4455
    assert!(find(&r, "remote down", Health::Fail).is_none());
4456
    assert!(find(&r, "remote down", Health::Ok)
4457
        .unwrap()
4458
        .message
4459
        .contains("not contacted"));
4460
}
62794ecc Andy McCall ↶ 4461
4462
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4463
/// after it. Inserting after `b` and then deleting `b`, one commit after
4464
/// the other, must not leave a delete/insert conflict.
4465
#[test]
4466
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4467
    hermetic();
4468
    let dir = tempfile::tempdir().unwrap();
4469
    let root = dir.path();
4470
    let repo = Repo::init(root).unwrap();
4471
    write(root, "f", b"a\nb\nc\n");
4472
    repo.commit("base", &[]).unwrap();
4473
    write(root, "f", b"a\nb\nx\nc\n");
4474
    let insert = repo.commit("insert x after b", &[]).unwrap();
4475
    write(root, "f", b"a\nx\nc\n");
4476
    let delete = repo.commit("delete b", &[]).unwrap();
4477
    assert!(
4478
        repo.store()
4479
            .get_change(&delete)
4480
            .unwrap()
4481
            .deps
4482
            .contains(&insert),
4483
        "the deletion depends on the insertion below the deleted line"
4484
    );
4485
    let heads = repo.bookmark_heads().unwrap();
4486
    assert_eq!(heads, vec![delete]);
4487
    let snap = repo.load_state(&heads).unwrap().materialize();
4488
    assert!(!snap.is_conflicted());
4489
    assert!(
4490
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4491
    );
4492
}
4493
4494
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4495
/// replacement depends on the change that set the blob it replaces.
4496
#[test]
4497
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4498
    hermetic();
4499
    let dir = tempfile::tempdir().unwrap();
4500
    let root = dir.path();
4501
    let repo = Repo::init(root).unwrap();
4502
    write(root, "bin", b"\0A");
4503
    let v1 = repo.commit("v1", &[]).unwrap();
4504
    write(root, "bin", b"\0B");
4505
    let v2 = repo.commit("v2", &[]).unwrap();
4506
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4507
    write(root, "bin", b"\0A");
4508
    let v3 = repo.commit("back to A", &[]).unwrap();
4509
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4510
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4511
    let state = repo.load_state(&[v3]).unwrap();
4512
    let snap = state.materialize();
4513
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4514
        panic!("opaque")
4515
    };
4516
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4517
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4518
}
4519
4520
/// Spec §23: a binary file changed on two branches and merged in Git to
4521
/// one side's version comes back as that version at the merge, and the
4522
/// import verifies commit by commit.
4523
#[test]
4524
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4525
    hermetic();
4526
    if std::process::Command::new("git")
4527
        .arg("--version")
4528
        .output()
4529
        .is_err()
4530
    {
4531
        eprintln!("git not installed; skipping");
4532
        return;
4533
    }
4534
    let dir = tempfile::tempdir().unwrap();
4535
    let root = dir.path();
4536
    let g = root.join("src.git");
4537
    fs::create_dir_all(&g).unwrap();
4538
    let git = |args: &[&str]| -> String {
4539
        let out = std::process::Command::new("git")
4540
            .arg("-C")
4541
            .arg(&g)
4542
            .args([
4543
                "-c",
4544
                "user.name=Grace",
4545
                "-c",
4546
                "[email protected]",
4547
                "-c",
4548
                "commit.gpgsign=false",
4549
            ])
4550
            .args(args)
4551
            .output()
4552
            .unwrap();
4553
        assert!(
4554
            out.status.success(),
4555
            "git {args:?}: {}",
4556
            String::from_utf8_lossy(&out.stderr)
4557
        );
4558
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4559
    };
4560
    git(&["init", "-q", "-b", "main"]);
4561
    write(&g, "logo.bin", b"\0base");
4562
    write(&g, "notes.txt", b"a\nb\nc\n");
4563
    git(&["add", "."]);
4564
    git(&["commit", "-qm", "base"]);
4565
    git(&["checkout", "-qb", "side"]);
4566
    write(&g, "logo.bin", b"\0side");
4567
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4568
    git(&["commit", "-qam", "side"]);
4569
    git(&["checkout", "-q", "main"]);
4570
    write(&g, "logo.bin", b"\0main");
4571
    git(&["commit", "-qam", "main"]);
4572
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4573
    let _ = std::process::Command::new("git")
4574
        .arg("-C")
4575
        .arg(&g)
4576
        .args([
4577
            "-c",
4578
            "user.name=G",
4579
            "-c",
4580
            "user.email=g@e",
4581
            "merge",
4582
            "-q",
4583
            "side",
4584
        ])
4585
        .output();
4586
    write(&g, "logo.bin", b"\0main");
4587
    git(&["add", "."]);
4588
    git(&["commit", "-qm", "merge side"]);
4589
    // Then a revert of the binary to its first version.
4590
    write(&g, "logo.bin", b"\0base");
4591
    git(&["commit", "-qam", "back to base"]);
4592
4593
    let repo = Repo::init(&root.join("o")).unwrap();
4594
    let rep = repo.import_git(&g, "main").unwrap();
4595
    assert_eq!(rep.merges, 1);
4596
    let v = repo.verify_git_import(&g, "main").unwrap();
4597
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4598
    assert_eq!(v.commits, 5);
4599
    let snap = repo
4600
        .load_state(&repo.bookmark_heads().unwrap())
4601
        .unwrap()
4602
        .materialize();
4603
    assert!(!snap.is_conflicted());
4604
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4605
        panic!("opaque")
4606
    };
4607
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4608
}
c863c7a7 Andy McCall ↶ 4609
4610
/// Spec §7.7 on a file system without executable bits or symlinks: the
4611
/// recorded bit is kept, and a symlink checked out as a plain file holding
4612
/// its target is still that symlink.
4613
#[cfg(unix)]
4614
#[test]
4615
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4616
    use crate::portable::Platform;
4617
    use std::os::unix::fs::PermissionsExt;
4618
    hermetic();
4619
    let dir = tempfile::tempdir().unwrap();
4620
    let root = dir.path();
4621
    let repo = Repo::init(root).unwrap();
4622
    write(root, "run.sh", b"#!/bin/sh\n");
4623
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4624
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4625
    repo.commit("script and link", &[]).unwrap();
4626
    drop(repo);
4627
4628
    // What checking out on Windows leaves: no exec bit, the link as a file.
4629
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4630
    fs::remove_file(root.join("link")).unwrap();
4631
    write(root, "link", b"run.sh");
4632
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4633
    let s = win.snapshot("oxy status").unwrap();
4634
    assert!(
4635
        s.statuses.is_empty(),
4636
        "nothing changed on Windows: {:?}",
4637
        statuses(&s)
4638
    );
4639
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4640
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4641
    write(root, "link", b"other");
4642
    let h = win.commit("edit on Windows", &[]).unwrap();
4643
    let snap = win.load_state(&[h]).unwrap().materialize();
4644
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4645
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4646
    // The same working copy read as Linux sees the lost bit and the plain file.
4647
    let linux = Repo::open(root).unwrap();
4648
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4649
}
4650
4651
/// Paths that collide on case-insensitive or Windows file systems are
4652
/// named at checkout there, and by doctor everywhere.
4653
#[test]
4654
fn paths_other_platforms_cannot_hold_are_reported() {
4655
    use crate::portable::Platform;
4656
    hermetic();
4657
    let dir = tempfile::tempdir().unwrap();
4658
    let root = dir.path();
4659
    let repo = Repo::init(root).unwrap();
4660
    write(root, "README.md", b"a\n");
4661
    write(root, "readme.md", b"b\n");
4662
    write(root, "src/aux.c", b"int x;\n");
4663
    let h = repo.commit("unportable", &[]).unwrap();
4664
    let r = repo.doctor(false);
4665
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4666
    assert_eq!(port.health, Health::Warn);
4667
    assert!(
4668
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4669
        "{}",
4670
        port.message
4671
    );
4672
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4673
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4674
    assert!(
4675
        rep.notes
4676
            .iter()
4677
            .any(|n| n.contains("README.md and readme.md")),
4678
        "{:?}",
4679
        rep.notes
4680
    );
4681
    assert!(
4682
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4683
        "macOS allows aux.c"
4684
    );
4685
}
bc489b6c Andy McCall ↶ 4686
4687
#[test]
4688
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4689
    hermetic();
4690
    let dir = tempfile::tempdir().unwrap();
4691
    let repo = Repo::init(dir.path()).unwrap();
4692
    write(dir.path(), "a.txt", b"one\n");
4693
    write(dir.path(), "other.txt", b"x\n");
4694
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4695
    repo.snapshot("t").unwrap();
4696
    let c1 = repo.commit("first", &[]).unwrap();
4697
    write(dir.path(), "other.txt", b"y\n");
4698
    repo.snapshot("t").unwrap();
4699
    repo.commit("other only", &[]).unwrap();
4700
    write(dir.path(), "a.txt", b"one\ntwo\n");
4701
    repo.snapshot("t").unwrap();
4702
    let c3 = repo.commit("second line", &[]).unwrap();
4703
    write(dir.path(), "other.txt", b"z\n");
4704
    repo.snapshot("t").unwrap();
4705
    repo.commit("other again", &[]).unwrap();
4706
4707
    let heads = repo.bookmark_heads().unwrap();
4708
    let state = repo.load_state(&heads).unwrap();
4709
    let full: Vec<ChangeHash> = repo
4710
        .log_for_path_in("a.txt", &heads)
4711
        .unwrap()
4712
        .iter()
4713
        .map(|e| e.hash)
4714
        .collect();
4715
    assert_eq!(
4716
        full,
4717
        vec![c3, c1],
4718
        "newest first, only changes touching the path"
4719
    );
4720
    let newest: Vec<ChangeHash> = repo
4721
        .log_for_path_of(&state, "a.txt", Some(1))
4722
        .unwrap()
4723
        .iter()
4724
        .map(|e| e.hash)
4725
        .collect();
4726
    assert_eq!(newest, vec![c3], "stops at the first");
4727
    assert_eq!(
4728
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4729
        2
4730
    );
4731
    assert!(repo
4732
        .log_for_path_of(&state, "missing.txt", Some(1))
4733
        .is_err());
4734
    assert_eq!(
4735
        repo.log_state(&heads).unwrap().len(),
4736
        repo.log_of(&state).len()
4737
    );
4738
4739
    let tree = state.tree().view();
4740
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4741
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4742
    assert_eq!(
4743
        via_state
4744
            .iter()
4745
            .map(|l| (l.hash, l.text.clone()))
4746
            .collect::<Vec<_>>(),
4747
        via_heads
4748
            .iter()
4749
            .map(|l| (l.hash, l.text.clone()))
4750
            .collect::<Vec<_>>()
4751
    );
4752
    assert_eq!(
4753
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4754
        vec![c1, c3]
4755
    );
4756
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4757
}
696bbf29 Andy McCall ↶ 4758
4759
/// A text file whose stat matches the manifest and whose recorded hash is
4760
/// the base's content is taken from the base without reading it; anything
4761
/// else is read, so no edit is missed (spec §12.3).
4762
#[cfg(unix)]
4763
#[test]
4764
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4765
    use std::os::unix::fs::PermissionsExt;
4766
    hermetic();
4767
    let dir = tempfile::tempdir().unwrap();
4768
    let root = dir.path();
4769
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4770
    write(root, "a.txt", b"one\ntwo\n");
4771
    write(root, "b.txt", b"bee\n");
4772
    repo.commit("base", &[]).unwrap();
4773
    let age = |p: &str| {
4774
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4775
        fs::File::options()
4776
            .write(true)
4777
            .open(root.join(p))
4778
            .unwrap()
4779
            .set_modified(old)
4780
            .unwrap();
4781
    };
4782
    age("a.txt");
4783
    age("b.txt");
4784
    assert!(
4785
        !repo.snapshot("status").unwrap().changed,
4786
        "records the aged stat"
4787
    );
4788
4789
    // Clean and equal to the base: not read at all.
4790
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4791
    let snap = repo.snapshot("status").unwrap();
4792
    assert!(
4793
        !snap.changed && snap.statuses.is_empty(),
4794
        "{:?}",
4795
        snap.statuses
4796
    );
4797
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4798
4799
    // An uncommitted edit that is older than the manifest: stat-clean, but
4800
    // its hash is not the base's, so it is read and stays visible.
4801
    write(root, "b.txt", b"bee edited\n");
4802
    age("b.txt");
4803
    let first = repo.snapshot("status").unwrap();
4804
    assert_eq!(
4805
        statuses(&first),
4806
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4807
    );
4808
    let again = repo.snapshot("status").unwrap();
4809
    assert_eq!(
4810
        statuses(&again),
4811
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4812
        "still seen once stat-clean"
4813
    );
4814
    assert!(!again.changed, "and the working copy hashes the same");
4815
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4816
    assert!(
4817
        repo.snapshot("status").is_err(),
4818
        "an edited file must be read, never taken from the base"
4819
    );
4820
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4821
4822
    // A same-size edit made just now is racy and read.
4823
    write(root, "a.txt", b"one\nTWO\n");
4824
    assert_eq!(
4825
        statuses(&repo.snapshot("status").unwrap()),
4826
        vec![
4827
            ("a.txt".to_string(), ChangeStatus::Modified),
4828
            ("b.txt".to_string(), ChangeStatus::Modified)
4829
        ]
4830
    );
4831
    // Committing makes the edits the base: both are clean and served from it again.
4832
    repo.commit("edits", &[]).unwrap();
4833
    age("a.txt");
4834
    age("b.txt");
4835
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4836
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4837
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4838
    let snap = repo.snapshot("status").unwrap();
4839
    assert!(!snap.changed && snap.statuses.is_empty());
4840
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4841
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4842
}
afaba5f1 Andy McCall ↶ 4843
4844
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4845
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4846
/// file is unchanged, and loading through the checkpoint equals a full load.
4847
#[test]
4848
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4849
    hermetic();
4850
    let dir = tempfile::tempdir().unwrap();
4851
    let root = dir.path();
4852
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4853
    let long: String = (0..300)
4854
        .map(|i| format!("line {i} of a long file\n"))
4855
        .collect();
4856
    write(root, "long.txt", long.as_bytes());
4857
    write(root, "short.txt", b"short\n");
4858
    repo.commit("base", &[]).unwrap();
4859
    let (r1, _, _) = repo.checkpoint().unwrap();
4860
    let cp1 = crate::objects::Checkpoint::decode(
4861
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4862
    )
4863
    .unwrap();
4864
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4865
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4866
4867
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4868
    repo.gc(true).unwrap();
4869
    assert!(repo.store().has(&graphs1[0]));
4870
    let report = repo.fsck().unwrap();
4871
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4872
4873
    // Loading through the checkpoint equals a full load.
4874
    write(root, "short.txt", b"short, edited\n");
4875
    repo.commit("edit the short file", &[]).unwrap();
4876
    let heads = repo.bookmark_heads().unwrap();
4877
    let fast = repo.load_state(&heads).unwrap();
4878
    let full = repo.load_state_full(&heads).unwrap();
4879
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4880
4881
    // The next checkpoint shares the unchanged long file's graph.
4882
    let (r2, _, _) = repo.checkpoint().unwrap();
4883
    let cp2 = crate::objects::Checkpoint::decode(
4884
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
4885
    )
4886
    .unwrap();
4887
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
4888
4889
    // A shallow clone's bundle carries the graph blob with the checkpoint.
4890
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
4891
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
4892
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
4893
4894
    // A version 1 checkpoint written by an older oxy still loads.
4895
    let state = repo.load_state_full(&heads).unwrap();
4896
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
4897
    let cp_old = crate::objects::Checkpoint {
4898
        heads: cp2.heads.clone(),
4899
        count: cp2.count,
4900
        payload: old,
4901
    };
4902
    let r_old = repo
4903
        .store()
4904
        .put(ObjectType::Checkpoint, &cp_old.encode())
4905
        .unwrap();
4906
    repo.install_checkpoint("main", &r_old).unwrap();
4907
    assert_eq!(
4908
        repo.load_state(&heads).unwrap().checkpoint_payload(),
4909
        full.checkpoint_payload()
4910
    );
4911
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4912
4913
    // A lost graph blob fails the load loudly rather than dropping the
4914
    // file, and fsck reports it (a fresh repository, objects still loose).
4915
    let dir2 = tempfile::tempdir().unwrap();
4916
    let root2 = dir2.path();
4917
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
4918
    write(root2, "long.txt", long.as_bytes());
4919
    repo2.commit("base", &[]).unwrap();
4920
    let (r, _, _) = repo2.checkpoint().unwrap();
4921
    let cp = crate::objects::Checkpoint::decode(
4922
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
4923
    )
4924
    .unwrap();
4925
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
64818938 Andy McCall ↶ 4926
    repo2.store().remove_loose_for_test(&graph).unwrap();
afaba5f1 Andy McCall ↶ 4927
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
4928
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
4929
}
e3d071ce Andy McCall ↶ 4930
4931
/// A new repository has not stored the user's identity yet (that happens
4932
/// at the first signed change); looking it up falls back to the key
4933
/// directory, and a file there that does not hash to the key is refused.
4934
#[test]
4935
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
4936
    hermetic();
4937
    let dir = tempfile::tempdir().unwrap();
4938
    let home = dir.path().join("home");
4939
    let mut first = Repo::init(&dir.path().join("a"))
4940
        .unwrap()
4941
        .with_home(home.clone());
4942
    let (key, _) = first
4943
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4944
        .unwrap();
4945
    let fresh = Repo::init(&dir.path().join("b"))
4946
        .unwrap()
4947
        .with_home(home.clone());
4948
    assert!(!fresh.store().has(&key), "nothing stored yet");
4949
    let id = fresh.identity(&key).unwrap();
4950
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
4951
    // A key file that is not this identity is an error, not a wrong answer.
4952
    let keys = fresh.keys_dir.clone();
4953
    let (other, _) = first
4954
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4955
        .unwrap();
4956
    fs::copy(
4957
        keys.join(format!("{}.identity", other.to_hex())),
4958
        keys.join(format!("{}.identity", key.to_hex())),
4959
    )
4960
    .unwrap();
4961
    assert!(fresh
4962
        .identity(&key)
4963
        .unwrap_err()
4964
        .to_string()
4965
        .contains("does not hold identity"));
4966
}
cc7a0056 Andy McCall ↶ 4967
4968
/// Status snapshots (spec §12.3): a text file whose stat matches the
4969
/// manifest, and whose base graph key is the one the manifest recorded it
4970
/// equal to, is neither read nor rendered; any edit, and any change to the
4971
/// file's graph in the base, brings it back.
4972
#[cfg(unix)]
4973
#[test]
4974
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
4975
    use std::os::unix::fs::PermissionsExt;
4976
    hermetic();
4977
    let dir = tempfile::tempdir().unwrap();
4978
    let root = dir.path();
4979
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4980
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
4981
        write(root, p, c.as_bytes());
4982
    }
4983
    repo.commit("base", &[]).unwrap();
4984
    let age = |p: &str| {
4985
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4986
        fs::File::options()
4987
            .write(true)
4988
            .open(root.join(p))
4989
            .unwrap()
4990
            .set_modified(old)
4991
            .unwrap();
4992
    };
4993
    let lock = |p: &str, mode: u32| {
4994
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
4995
    };
4996
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4997
        age(p);
4998
    }
4999
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5000
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5001
    assert!(
5002
        m.entries.values().all(|e| e.graph.is_some()),
5003
        "keys recorded"
5004
    );
5005
5006
    // Unreadable files prove they are not read; the status snapshot does
5007
    // not render them either, and its base lacks their graphs.
5008
    lock("a.txt", 0o000);
5009
    lock("b.txt", 0o000);
5010
    let snap = repo.snapshot_status("status").unwrap();
5011
    assert!(!snap.changed && snap.statuses.is_empty());
5012
    assert_eq!(
5013
        snap.base_snapshot
5014
            .unrendered
5015
            .iter()
5016
            .cloned()
5017
            .collect::<Vec<_>>(),
5018
        vec!["a.txt", "b.txt", "d/c.txt"]
5019
    );
5020
    assert!(!snap.base.is_full());
5021
    assert!(!snap.base_snapshot.is_conflicted());
5022
    // A full snapshot does not read them either, but renders everything.
5023
    let full = repo.snapshot("status").unwrap();
5024
    assert!(full.statuses.is_empty() && full.base.is_full());
5025
    assert!(full.base_snapshot.unrendered.is_empty());
5026
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5027
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5028
5029
    // An edit is seen; the file is rendered, the others still are not.
5030
    write(root, "d/c.txt", b"sea edited\n");
5031
    let snap = repo.snapshot_status("status").unwrap();
5032
    assert_eq!(
5033
        statuses(&snap),
5034
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5035
    );
5036
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5037
    // So is a mode change of an unread file.
5038
    lock("b.txt", 0o100);
5039
    assert_eq!(
5040
        statuses(&repo.snapshot_status("status").unwrap()),
5041
        vec![
5042
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5043
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5044
        ]
5045
    );
5046
    lock("b.txt", 0o000);
5047
5048
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5049
    // stays unread, c.txt is read once and then skipped too.
5050
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5051
        .unwrap();
5052
    age("d/c.txt");
5053
    let snap = repo.snapshot_status("status").unwrap();
5054
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5055
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5056
    lock("d/c.txt", 0o000);
5057
    let snap = repo.snapshot_status("status").unwrap();
5058
    assert!(snap.statuses.is_empty());
5059
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5060
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5061
        lock(p, 0o644);
5062
    }
5063
}
5064
5065
/// Attributes decide how a file compares with the base, so a changed
5066
/// `.oxyattributes` makes every text file be compared again.
5067
#[cfg(unix)]
5068
#[test]
5069
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5070
    hermetic();
5071
    let dir = tempfile::tempdir().unwrap();
5072
    let root = dir.path();
5073
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5074
    write(root, "a.txt", b"crlf\r\n");
5075
    repo.commit("base", &[]).unwrap();
5076
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5077
    fs::File::options()
5078
        .write(true)
5079
        .open(root.join("a.txt"))
5080
        .unwrap()
5081
        .set_modified(old)
5082
        .unwrap();
5083
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5084
    assert!(repo
5085
        .snapshot_status("status")
5086
        .unwrap()
5087
        .base_snapshot
5088
        .unrendered
5089
        .contains("a.txt"));
5090
    // With eol=lf, a.txt as stored no longer equals the base.
5091
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5092
    let snap = repo.snapshot_status("status").unwrap();
5093
    assert_eq!(
5094
        statuses(&snap),
5095
        vec![
5096
            (".oxyattributes".to_string(), ChangeStatus::Added),
5097
            ("a.txt".to_string(), ChangeStatus::Modified)
5098
        ]
5099
    );
5100
}
54cd08a1 Andy McCall ↶ 5101
5102
/// Bookmarks with `/` in their names: pushing records their
5103
/// attestations, and checkpoints are kept for them, beside `feature`
5104
/// itself.
5105
#[test]
5106
fn bookmarks_with_slashes_push_and_checkpoint() {
5107
    hermetic();
5108
    let dir = tempfile::tempdir().unwrap();
5109
    let root = dir.path();
5110
    let origin = Repo::init(&root.join("origin")).unwrap();
5111
    let url = root.join("origin").to_string_lossy().to_string();
5112
    let mut repo = Repo::clone(&url, &root.join("r"))
5113
        .unwrap()
5114
        .with_home(root.join("home"));
5115
    // With an identity, pushes carry reference attestations: the case
5116
    // that failed, since the attestation is a file named after the bookmark.
5117
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5118
        .unwrap();
5119
    let r = root.join("r");
5120
    write(&r, "a.txt", b"a\n");
5121
    let h_a = repo.commit("a", &[]).unwrap();
5122
    assert!(repo.push("origin", false).unwrap()[0].ok);
5123
    repo.bookmark_create("feature", None).unwrap();
5124
    repo.bookmark_create("feature/x", None).unwrap();
5125
    repo.bookmark_switch("feature/x", false).unwrap();
5126
    write(&r, "b.txt", b"b\n");
5127
    let h_b = repo.commit("b", &[]).unwrap();
5128
    for name in ["feature", "feature/x"] {
5129
        let res = repo.push_bookmark("origin", name, false).unwrap();
5130
        assert!(res[0].ok, "{name}: {res:?}");
5131
    }
5132
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5133
    assert_eq!(
5134
        origin.resolve_heads("feature/x").unwrap(),
5135
        repo.resolve_heads("feature/x").unwrap()
5136
    );
5137
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5138
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5139
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5140
5141
    // A checkpoint of feature/x is found again when loading its state.
5142
    let (cp, _, _) = repo.checkpoint().unwrap();
5143
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5144
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5145
    let heads = repo.resolve_heads("feature/x").unwrap();
5146
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
f8c69576 Andy McCall ↶ 5147
}
5148
5149
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5150
/// never the remote's own bookmark, and a bookmark created again later is
5151
/// accepted although the deletion's attestation stays the latest.
5152
#[test]
5153
fn bookmarks_are_deleted_on_a_remote() {
5154
    hermetic();
5155
    let dir = tempfile::tempdir().unwrap();
5156
    let root = dir.path();
5157
    let origin = Repo::init(&root.join("origin")).unwrap();
5158
    let url = root.join("origin").to_string_lossy().to_string();
5159
    let mut repo = Repo::clone(&url, &root.join("r"))
5160
        .unwrap()
5161
        .with_home(root.join("home"));
5162
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5163
        .unwrap();
5164
    let r = root.join("r");
5165
    write(&r, "a.txt", b"a\n");
5166
    repo.commit("a", &[]).unwrap();
5167
    assert!(repo.push("origin", false).unwrap()[0].ok);
5168
    repo.bookmark_create("feature/x", None).unwrap();
5169
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5170
    assert!(origin.resolve_heads("feature/x").is_ok());
5171
5172
    let res = repo.push_delete("origin", "feature/x").unwrap();
5173
    assert!(res[0].ok, "{res:?}");
5174
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5175
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5176
    assert!(
5177
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5178
        "the deletion is attested"
5179
    );
5180
    assert!(
5181
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5182
        "the local bookmark stays"
5183
    );
5184
    assert!(!repo
5185
        .view()
5186
        .unwrap()
5187
        .remotes
5188
        .get("origin")
5189
        .is_some_and(|m| m.contains_key("feature/x")));
5190
5191
    // Pushing it again creates it again, past the deletion's serial.
5192
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5193
    assert!(res[0].ok, "{res:?}");
5194
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5195
5196
    // Nothing to delete, and never the remote's own bookmark.
5197
    assert!(repo.push_delete("origin", "nope").is_err());
5198
    let res = repo.push_delete("origin", "main").unwrap();
5199
    assert!(
5200
        !res[0].ok && res[0].reason.contains("default bookmark"),
5201
        "{res:?}"
5202
    );
5203
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
54cd08a1 Andy McCall ↶ 5204
}
61e3bce7 Andy McCall ↶ 5205
5206
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5207
/// when the target has the same versions of the files it touches, and is
5208
/// refused, untouched, when it has others.
5209
#[test]
5210
fn switching_bookmarks_carries_uncommitted_work() {
5211
    hermetic();
5212
    let dir = tempfile::tempdir().unwrap();
5213
    let root = dir.path();
5214
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5215
    write(root, "a.txt", b"a\n");
5216
    write(root, "b.txt", b"b\n");
5217
    write(root, "gone.txt", b"gone\n");
5218
    repo.commit("base", &[]).unwrap();
5219
    repo.bookmark_create("feature", None).unwrap();
5220
    // Started on main, belongs on feature: edit, add, remove.
5221
    write(root, "a.txt", b"a\nmore\n");
5222
    write(root, "new.txt", b"new\n");
5223
    fs::remove_file(root.join("gone.txt")).unwrap();
5224
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5225
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5226
    assert_eq!(repo.config.bookmark, "feature");
5227
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5228
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5229
    assert!(!root.join("gone.txt").exists());
5230
    let snap = repo.snapshot("status").unwrap();
5231
    assert_eq!(
5232
        statuses(&snap),
5233
        vec![
5234
            ("a.txt".to_string(), ChangeStatus::Modified),
5235
            ("gone.txt".to_string(), ChangeStatus::Removed),
5236
            ("new.txt".to_string(), ChangeStatus::Added)
5237
        ]
5238
    );
5239
    repo.commit("the work", &[]).unwrap();
5240
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5241
5242
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5243
    repo.bookmark_switch("main", false).unwrap();
5244
    write(root, "b.txt", b"b on main\n");
5245
    repo.commit("b on main", &[]).unwrap();
5246
    repo.bookmark_switch("feature", false).unwrap();
5247
    write(root, "b.txt", b"b edited\n");
5248
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5249
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5250
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5251
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5252
}
1c2bd9ab Andy McCall ↶ 5253
5254
/// Merging and checking out (feedback 3): a working copy without changes
5255
/// follows a merge whichever state it sat on; a refused checkout names
5256
/// what is in the way; `checkout --carry` takes the work along.
5257
#[test]
5258
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5259
    hermetic();
5260
    let dir = tempfile::tempdir().unwrap();
5261
    let root = dir.path();
5262
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5263
    write(root, "a.txt", b"a\n");
5264
    let h1 = repo.commit("a", &[]).unwrap();
5265
    write(root, "b.txt", b"b\n");
5266
    repo.commit("b", &[]).unwrap();
5267
    repo.bookmark_create("feature", None).unwrap();
5268
    repo.bookmark_switch("feature", false).unwrap();
5269
    write(root, "c.txt", b"c\n");
5270
    repo.commit("c on feature", &[]).unwrap();
5271
    repo.bookmark_switch("main", false).unwrap();
5272
    // The working copy sits on an older state than main's heads.
5273
    repo.checkout(&[h1], false, "checkout").unwrap();
5274
    assert!(!root.join("b.txt").exists());
5275
    let m = repo.merge("feature").unwrap();
5276
    assert!(m.checked_out, "a clean working copy follows the merge");
5277
    for f in ["a.txt", "b.txt", "c.txt"] {
5278
        assert!(root.join(f).exists(), "{f}");
5279
    }
5280
5281
    // A refusal says which paths are in the way and what to do.
5282
    fs::remove_file(root.join("b.txt")).unwrap();
5283
    write(root, "a.txt", b"a edited\n");
5284
    let err = repo
5285
        .checkout(&[h1], false, "checkout")
5286
        .unwrap_err()
5287
        .to_string();
5288
    assert!(
5289
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5290
        "{err}"
5291
    );
fe9586d9 Andy McCall ↶ 5292
    // --carry takes them along: h1 has a.txt as the base has it, and the
5293
    // removed b.txt is already as h1 has it (none), so that is no conflict
5294
    // either (oxygen#100).
1c2bd9ab Andy McCall ↶ 5295
    let (_, carried) = repo
5296
        .checkout_carry(&[h1], "the first change", "checkout")
5297
        .unwrap();
5298
    assert_eq!(carried, vec!["a.txt"]);
5299
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5300
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5301
}
e7ac6c2e Andy McCall ↶ 5302
5303
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5304
/// user identity not stored in a new repository yet is fine while its
5305
/// secret key is there; an added subrepo is listed as not committed yet.
5306
#[test]
5307
fn a_new_repository_is_healthy_before_its_first_commit() {
5308
    hermetic();
5309
    let dir = tempfile::tempdir().unwrap();
5310
    let root = dir.path();
5311
    let home = root.join("home");
5312
    let mut first = Repo::init(&root.join("first"))
5313
        .unwrap()
5314
        .with_home(home.clone());
5315
    let (key, _) = first
5316
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5317
        .unwrap();
5318
    let repo = Repo::init(&root.join("second"))
5319
        .unwrap()
5320
        .with_home(home.clone());
5321
    // Only the secret key: no identity object anywhere this repository sees.
5322
    let keys = repo.keys_dir.clone();
5323
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5324
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5325
    let r = repo.doctor(true);
5326
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5327
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5328
    assert!(id.message.contains("first signed change"), "{}", id.message);
5329
5330
    // A subrepo added and not committed yet is listed, pinned where it is.
5331
    let lib = root.join("lib");
5332
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5333
    write(&lib, "x.txt", b"x\n");
5334
    l.commit("x", &[]).unwrap();
5335
    let second = root.join("second");
5336
    write(&second, "a.txt", b"a\n");
5337
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5338
        .unwrap();
5339
    let subs = repo.subrepos().unwrap();
5340
    assert_eq!(subs.len(), 1);
5341
    assert_eq!(
5342
        (subs[0].path.as_str(), subs[0].committed),
5343
        ("deps/lib", false)
5344
    );
5345
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5346
    repo.commit("add lib", &[]).unwrap();
5347
    let subs = repo.subrepos().unwrap();
5348
    assert!(subs[0].committed, "committed now");
5349
}
8ab265dc Andy McCall ↶ 5350
5351
/// Commit, diff, hunks and discard use the partial snapshot: a file
5352
/// unchanged since the manifest is neither read nor rendered, and showing
5353
/// a change renders only what it edits, the same as from a full base.
5354
#[cfg(unix)]
5355
#[test]
5356
fn commits_and_diffs_leave_unchanged_files_alone() {
5357
    use std::os::unix::fs::PermissionsExt;
5358
    hermetic();
5359
    let dir = tempfile::tempdir().unwrap();
5360
    let root = dir.path();
5361
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5362
    write(root, "big.txt", b"lots\nof\nlines\n");
5363
    write(root, "a.txt", b"one\ntwo\n");
5364
    repo.commit("base", &[]).unwrap();
5365
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5366
    for f in ["big.txt", "a.txt"] {
5367
        fs::File::options()
5368
            .write(true)
5369
            .open(root.join(f))
5370
            .unwrap()
5371
            .set_modified(old)
5372
            .unwrap();
5373
    }
5374
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5375
    // big.txt cannot be read at all from here on.
5376
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5377
5378
    write(root, "a.txt", b"one\nTWO\nthree\n");
5379
    let diff = repo.diff_files(None).unwrap();
5380
    assert_eq!(
5381
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5382
        ["a.txt"]
5383
    );
5384
    let (_, hunks) = repo.hunks().unwrap();
5385
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5386
    let h = repo.commit("edit a", &[]).unwrap();
5387
5388
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5389
    let c = repo.store().get_change(&h).unwrap();
5390
    let full = repo.load_state(&c.deps).unwrap();
5391
    let want = render_change(&c, &full, &full.materialize());
5392
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5393
    let (base, snap) = repo.change_base(&c).unwrap();
5394
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5395
5396
    // Discarding works the same way.
5397
    write(root, "a.txt", b"scratch\n");
5398
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5399
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5400
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5401
}
f7510b63 Andy McCall ↶ 5402
5403
/// A replace conflict (spec §9.3) is settled by a change that writes one
5404
/// candidate, or new bytes, at the path when the caller names it; a plain
5405
/// snapshot of a checkout never settles it on its own.
5406
#[test]
5407
fn replace_conflicts_are_settled_when_asked() {
5408
    hermetic();
5409
    let dir = tempfile::tempdir().unwrap();
5410
    let root = dir.path();
5411
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5412
    let blob = |n: u8| {
5413
        let mut v = vec![0u8; 64];
5414
        v[1] = n;
5415
        v
5416
    };
5417
    write(root, "img.bin", &blob(1));
5418
    repo.commit("add img", &[]).unwrap();
5419
    repo.bookmark_create("other", None).unwrap();
5420
    write(root, "img.bin", &blob(2));
5421
    repo.commit("img two", &[]).unwrap();
5422
    repo.bookmark_switch("other", false).unwrap();
5423
    write(root, "img.bin", &blob(3));
5424
    repo.commit("img three", &[]).unwrap();
5425
    repo.bookmark_switch("main", false).unwrap();
5426
    repo.merge("other").unwrap();
5427
    let heads = repo.bookmark_heads().unwrap();
5428
    let merged = repo.load_state(&heads).unwrap().materialize();
5429
    assert!(
5430
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5431
        "a replace conflict"
5432
    );
5433
    // A snapshot of the checkout records nothing.
5434
    assert!(repo
5435
        .snapshot("status")
5436
        .unwrap()
5437
        .statuses
5438
        .iter()
5439
        .all(|s| s.path != "img.bin"));
5440
5441
    // Keeping candidate 3 settles it.
5442
    let author = repo.author();
5443
    let edits = [FileEdit {
5444
        path: "img.bin".into(),
5445
        content: Some(blob(3)),
5446
    }];
5447
    let c = repo
5448
        .build_change(&heads, &edits, "keep three", author)
5449
        .unwrap();
5450
    assert_eq!(c.kind, ChangeKind::Resolution);
5451
    let mut st = repo.load_state(&heads).unwrap();
5452
    for d in &c.deps {
5453
        assert!(st.contains(d));
5454
    }
5455
    assert!(
5456
        heads.iter().all(|h| c.deps.contains(h)),
5457
        "depends on both contributors"
5458
    );
5459
    st.add(c).unwrap();
5460
    let after = st.materialize();
5461
    assert!(!after.is_conflicted());
5462
    assert_eq!(
5463
        after.files["img.bin"].content,
5464
        FileContent::Opaque {
5465
            blobs: vec![Repo::blob_ref(&blob(3))]
5466
        }
5467
    );
5468
5469
    // New bytes settle it too.
5470
    let edits = [FileEdit {
5471
        path: "img.bin".into(),
5472
        content: Some(blob(9)),
5473
    }];
5474
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5475
    let mut st = repo.load_state(&heads).unwrap();
5476
    st.add(c).unwrap();
5477
    assert_eq!(
5478
        st.materialize().files["img.bin"].content,
5479
        FileContent::Opaque {
5480
            blobs: vec![Repo::blob_ref(&blob(9))]
5481
        }
5482
    );
5483
}
83d61e80 Andy McCall ↶ 5484
5485
/// The history of a range of lines (spec §27): the changes that wrote
5486
/// or deleted its atoms, or deleted atoms from between them; edits outside
5487
/// the range and changes the range's lines survived are not in it.
5488
#[test]
5489
fn line_ranges_have_exact_histories() {
5490
    hermetic();
5491
    let dir = tempfile::tempdir().unwrap();
5492
    let root = dir.path();
5493
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5494
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5495
    let base = repo.commit("add f", &[]).unwrap();
5496
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5497
    let outside = repo.commit("change the import", &[]).unwrap();
5498
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5499
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5500
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5501
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5502
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5503
    let after = repo.commit("add b after a", &[]).unwrap();
5504
    let heads = repo.bookmark_heads().unwrap();
5505
5506
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5507
    let hist: Vec<ChangeHash> = repo
5508
        .line_history(&heads, "f.rs", 2, 4)
5509
        .unwrap()
5510
        .iter()
5511
        .map(|e| e.hash)
5512
        .collect();
5513
    for (h, what) in [
5514
        (base, "wrote it"),
5515
        (inside, "edited a line"),
5516
        (deleted, "deleted a line from inside"),
5517
    ] {
5518
        assert!(hist.contains(&h), "{what}");
5519
    }
5520
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5521
        assert!(!hist.contains(&h), "{what}");
5522
    }
5523
    assert_eq!(hist[0], deleted, "newest first");
5524
    // One line: only what touched it.
5525
    let one: Vec<ChangeHash> = repo
5526
        .line_history(&heads, "f.rs", 1, 1)
5527
        .unwrap()
5528
        .iter()
5529
        .map(|e| e.hash)
5530
        .collect();
5531
    assert!(one.contains(&outside) && !one.contains(&inside));
5532
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5533
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5534
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5535
}
fc1a466a Andy McCall ↶ 5536
5537
#[test]
5538
fn receipts_are_kept_with_their_state_and_verified() {
5539
    use crate::receipt::{Receipt, SignedReceipt};
5540
    hermetic();
5541
    let dir = tempfile::tempdir().unwrap();
5542
    let root = dir.path();
5543
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5544
    write(root, "a.txt", b"1\n");
5545
    repo.commit("A", &[]).unwrap();
5546
    let heads = repo.bookmark_heads().unwrap();
5547
    let state = repo
5548
        .store()
5549
        .put_state(&StateObject::new(heads.clone()))
5550
        .unwrap();
5551
    let out = repo.store_blob(b"built\n").unwrap();
5552
    let receipt = Receipt {
5553
        job_name: "build".into(),
5554
        pipeline_hash: ObjectRef([1; 32]),
5555
        scope_tree_hash: ObjectRef([2; 32]),
5556
        inputs: vec![],
5557
        environment: ObjectRef([3; 32]),
5558
        outputs: vec![out],
5559
        exit_code: 0,
5560
        duration_ms: 42,
5561
    };
5562
    let sk = SecretKey::generate();
5563
    let runner = sk.identity("earth-1", "runner@earth", 1);
5564
    let sr = SignedReceipt::sign(
5565
        receipt.clone(),
5566
        repo.id().unwrap(),
5567
        state,
5568
        "demo#1",
5569
        &runner,
5570
        &sk,
5571
    );
5572
5573
    let r = repo.add_receipt(&sr).unwrap();
5574
    let found = repo.receipts(&heads).unwrap();
5575
    assert_eq!(found.len(), 1);
5576
    assert_eq!(found[0].attest, r);
5577
    assert_eq!(found[0].signed, sr);
5578
    assert!(found[0].problem.is_none() && !found[0].revoked);
5579
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5580
5581
    // Another repository's receipt, or a forged one, is refused.
5582
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5583
    assert!(repo
5584
        .add_receipt(&elsewhere)
5585
        .unwrap_err()
5586
        .to_string()
5587
        .contains("another repository"));
5588
    let mut forged = sr.clone();
5589
    forged.receipt.exit_code = 1;
5590
    assert!(repo
5591
        .add_receipt(&forged)
5592
        .unwrap_err()
5593
        .to_string()
5594
        .contains("does not verify"));
5595
5596
    // gc keeps the receipt, its runner and its output while the state lives.
5597
    repo.gc(true).unwrap();
5598
    assert_eq!(repo.receipts(&heads).unwrap().len(), 1);
5599
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5600
    assert!(repo.fsck().unwrap().problems.is_empty());
dfb23a3a Andy McCall ↶ 5601
}
5602
5603
#[test]
5604
fn status_leaves_an_unchanged_manifest_alone() {
5605
    hermetic();
5606
    let dir = tempfile::tempdir().unwrap();
5607
    let root = dir.path();
5608
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5609
    write(root, "a.txt", b"1\n");
5610
    write(root, "b.txt", b"2\n");
5611
    repo.commit("A", &[]).unwrap();
5612
    // Files last touched well outside the racy window.
5613
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5614
    for f in ["a.txt", "b.txt"] {
5615
        fs::File::options()
5616
            .write(true)
5617
            .open(root.join(f))
5618
            .unwrap()
5619
            .set_modified(old)
5620
            .unwrap();
5621
    }
5622
    repo.snapshot_status("status").unwrap();
5623
    let path = repo.manifest_path();
5624
    let first = fs::read(&path).unwrap();
5625
    repo.snapshot_status("status").unwrap();
5626
    assert_eq!(
5627
        fs::read(&path).unwrap(),
5628
        first,
5629
        "an unchanged tree does not rewrite the manifest"
5630
    );
5631
    // A change rewrites it.
5632
    write(root, "a.txt", b"1\n2\n");
5633
    repo.snapshot_status("status").unwrap();
5634
    assert_ne!(fs::read(&path).unwrap(), first);
fc1a466a Andy McCall ↶ 5635
}
6f8aeb99 Andy McCall ↶ 5636
5637
#[test]
5638
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5639
    hermetic();
5640
    let dir = tempfile::tempdir().unwrap();
5641
    let root = dir.path();
5642
    let origin_path = root.join("origin");
5643
    Repo::init(&origin_path).unwrap();
5644
    let origin_url = origin_path.to_string_lossy().to_string();
5645
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5646
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5647
    write(&root.join("a"), "big.txt", big.as_bytes());
5648
    write(&root.join("a"), "small.txt", b"small\n");
5649
    let h1 = a.commit("large", &[]).unwrap();
5650
    let (_, body) = a.store().get(&h1).unwrap();
5651
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5652
    assert!(a.push("origin", false).unwrap()[0].ok);
5653
5654
    // A clone reads the text from the blobs that came with the change.
5655
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5656
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5657
    // An edit in the middle of the stored insert is an ordinary change.
5658
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5659
    write(&root.join("b"), "big.txt", edited.as_bytes());
5660
    let h2 = b.commit("edit", &[]).unwrap();
5661
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5662
    assert!(b.push("origin", false).unwrap()[0].ok);
5663
    assert!(a.pull("origin").unwrap().checked_out);
5664
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5665
    assert_eq!(
5666
        a.fsck().unwrap().errors(),
5667
        0,
5668
        "{:?}",
5669
        a.fsck().unwrap().problems
5670
    );
5671
5672
    // With zero retention gc keeps the text blobs of every kept change.
5673
    let mut a = Repo::open(&root.join("a")).unwrap();
5674
    a.config.set("core.op-retention", "0").unwrap();
5675
    a.save_config().unwrap();
5676
    let a = Repo::open(&root.join("a")).unwrap();
5677
    a.gc(true).unwrap();
5678
    let a = Repo::open(&root.join("a")).unwrap();
5679
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5680
    assert_eq!(
5681
        a.fsck().unwrap().errors(),
5682
        0,
5683
        "{:?}",
5684
        a.fsck().unwrap().problems
5685
    );
5686
    // And a clone of the packed repository reads them from its packs.
5687
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5688
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5689
    drop(c);
6caacfff Andy McCall ↶ 5690
}
5691
5692
#[test]
5693
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5694
    hermetic();
5695
    let dir = tempfile::tempdir().unwrap();
5696
    let root = dir.path();
5697
    let repo = Repo::init(root).unwrap();
5698
    write(root, "a.txt", b"a\n");
5699
    let a = repo.commit("a", &[]).unwrap();
5700
    write(root, "b.txt", b"b\n");
5701
    repo.commit("b", &[]).unwrap();
5702
    let (x, op) = repo.head_op().unwrap();
5703
    let ws = *op.view.workspaces.keys().next().unwrap();
5704
    let mut one = op.view.clone();
5705
    one.workspaces.insert(ws, a);
5706
    let mut two = op.view.clone();
5707
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5708
    let first = repo.record_op(&[x], "one", one).unwrap();
5709
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5710
    assert!(
5711
        e.to_string()
5712
            .contains("changed this working copy at the same time"),
5713
        "{e}"
5714
    );
5715
    assert_eq!(
5716
        repo.head_op().unwrap().0,
5717
        first,
5718
        "the second is not recorded"
5719
    );
5720
}
5721
5722
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5723
/// rewrote the working copy recorded the half-written files as edits, and
5724
/// its view replaced the switch's.
5725
#[test]
5726
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5727
    hermetic();
5728
    let dir = tempfile::tempdir().unwrap();
5729
    let root = dir.path().to_path_buf();
5730
    let mut repo = Repo::init(&root).unwrap();
5731
    write(&root, "keep.txt", b"keep\n");
5732
    repo.commit("base", &[]).unwrap();
5733
    repo.bookmark_create("small", None).unwrap();
5734
    for i in 0..300 {
5735
        write(
5736
            &root,
5737
            &format!("many/f{i}.txt"),
5738
            format!("file {i}\n").as_bytes(),
5739
        );
5740
    }
5741
    repo.commit("many", &[]).unwrap();
5742
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5743
    let watcher = {
5744
        let (root, stop) = (root.clone(), stop.clone());
5745
        std::thread::spawn(move || {
5746
            let r = Repo::open(&root).unwrap();
5747
            let mut ran = 0;
5748
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
5749
                if r.snapshot_status("oxy status").is_ok() {
5750
                    ran += 1;
5751
                }
5752
            }
5753
            ran
5754
        })
5755
    };
5756
    for i in 0..20 {
5757
        let to = if i % 2 == 0 { "small" } else { "main" };
5758
        repo.bookmark_switch(to, false).unwrap();
5759
    }
5760
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
5761
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
5762
    // Back on main, clean, with every file where main has it.
5763
    let repo = Repo::open(&root).unwrap();
5764
    let s = repo.snapshot_status("oxy status").unwrap();
5765
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
5766
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
5767
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
5768
    assert!(root.join("many/f299.txt").exists());
1a3b6203 Andy McCall ↶ 5769
}
5770
5771
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
5772
/// put a subrepo that was ahead of its pin back at the pin and moved the
5773
/// subrepo's own bookmark backwards.
5774
#[test]
5775
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
5776
    hermetic();
5777
    let dir = tempfile::tempdir().unwrap();
5778
    let root = dir.path();
5779
    Repo::init(&root.join("lib-origin")).unwrap();
5780
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5781
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
5782
    write(&root.join("lib"), "lib.txt", b"v1\n");
5783
    lib.commit("lib v1", &[]).unwrap();
5784
    assert!(lib.push("origin", false).unwrap()[0].ok);
5785
5786
    let app_dir = root.join("app");
5787
    let mut app = Repo::init(&app_dir).unwrap();
5788
    write(&app_dir, "main.txt", b"app\n");
5789
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5790
    app.commit("app with lib", &[]).unwrap();
5791
    app.bookmark_create("feature", None).unwrap();
5792
5793
    // New work in the subrepo, not yet pinned by the parent.
5794
    let nested_dir = app_dir.join("libs/lib");
5795
    let nested = Repo::open(&nested_dir).unwrap();
5796
    write(&nested_dir, "new.txt", b"new\n");
5797
    let l2 = nested.commit("lib: new file", &[]).unwrap();
5798
    drop(nested);
5799
5800
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
5801
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
5802
    let nested = Repo::open(&nested_dir).unwrap();
5803
    assert!(
5804
        nested.bookmark_heads().unwrap().contains(&l2),
5805
        "its bookmark kept its work"
5806
    );
5807
    assert!(nested_dir.join("new.txt").exists(), "and its files");
5808
    let s = app.snapshot("status").unwrap();
5809
    assert_eq!(
5810
        statuses(&s),
5811
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
5812
    );
6f8aeb99 Andy McCall ↶ 5813
}
7d9dab13 Andy McCall ↶ 5814
5815
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
5816
/// moving `main` to a change this clone had pushed on another bookmark,
5817
/// the first `pull` said "Already up to date" while `main` was behind.
5818
#[test]
5819
fn pull_takes_a_remote_move_to_changes_already_here() {
5820
    hermetic();
5821
    let dir = tempfile::tempdir().unwrap();
5822
    let root = dir.path();
5823
    let origin_path = root.join("origin");
5824
    let origin = Repo::init(&origin_path).unwrap();
5825
    let url = origin_path.to_string_lossy().to_string();
5826
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
5827
    write(&root.join("b"), "base.txt", b"base\n");
5828
    b.commit("base", &[]).unwrap();
5829
    assert!(b.push("origin", false).unwrap()[0].ok);
5830
5831
    // A feature bookmark with one change, pushed.
5832
    b.bookmark_create("feat", None).unwrap();
5833
    b.bookmark_switch("feat", false).unwrap();
5834
    write(&root.join("b"), "x.txt", b"x\n");
5835
    let x = b.commit("x", &[]).unwrap();
5836
    assert!(b.push("origin", false).unwrap()[0].ok);
5837
    b.bookmark_switch("main", false).unwrap();
5838
5839
    // The remote lands it: its main moves to the feature's state.
5840
    let feat = origin
5841
        .store()
5842
        .get_state(&origin.view().unwrap().bookmarks["feat"])
5843
        .unwrap()
5844
        .heads;
5845
    origin.bookmark_set("main", &feat).unwrap();
5846
5847
    let r = b.pull("origin").unwrap();
5848
    assert!(r.changed, "{r:?}");
5849
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
5850
    let main = b
5851
        .bookmarks()
5852
        .unwrap()
5853
        .into_iter()
5854
        .find(|m| m.name == "main")
5855
        .unwrap();
5856
    assert_eq!(main.behind, Some(0), "{main:?}");
5857
}
86e1824f Andy McCall ↶ 5858
14edbaaf Andy McCall ↶ 5859
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
5860
/// to one only the remote has makes a local bookmark from it; a pull moves
5861
/// every local bookmark the remote has too; a clone checks out the remote's
5862
/// default bookmark.
5863
#[test]
5864
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
5865
    hermetic();
5866
    let dir = tempfile::tempdir().unwrap();
5867
    let root = dir.path();
5868
    let origin_path = root.join("origin");
5869
    let mut origin = Repo::init(&origin_path).unwrap();
5870
    let url = origin_path.to_string_lossy().to_string();
5871
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
5872
    write(&root.join("a"), "base.txt", b"base\n");
5873
    a.commit("base", &[]).unwrap();
5874
    assert!(a.push("origin", false).unwrap()[0].ok);
5875
    a.bookmark_create("develop", None).unwrap();
5876
    a.bookmark_switch("develop", false).unwrap();
5877
    write(&root.join("a"), "base.txt", b"base\nd1\n");
5878
    let d1 = a.commit("d1", &[]).unwrap();
5879
    assert!(a.push("origin", false).unwrap()[0].ok);
5880
5881
    // A clone has main only; origin/develop is a name all the same.
5882
    let c_root = root.join("c");
5883
    let mut c = Repo::clone(&url, &c_root).unwrap();
5884
    assert_eq!(c.config.bookmark, "main");
5885
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
5886
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
5887
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
5888
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
5889
5890
    // Switching makes the local bookmark from origin's.
5891
    c.bookmark_switch("develop", false).unwrap();
5892
    assert_eq!(c.config.bookmark, "develop");
5893
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
5894
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
5895
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
5896
    assert!(c.bookmark_switch("nowhere", false).is_err());
5897
5898
    // Both bookmarks move on the remote; one pull takes both.
5899
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
5900
    let d2 = a.commit("d2", &[]).unwrap();
5901
    assert!(a.push("origin", false).unwrap()[0].ok);
5902
    a.bookmark_switch("main", false).unwrap();
5903
    write(&root.join("a"), "m.txt", b"m\n");
5904
    let m = a.commit("m", &[]).unwrap();
5905
    assert!(a.push("origin", false).unwrap()[0].ok);
5906
    let r = c.pull("origin").unwrap();
5907
    assert!(r.changed && r.checked_out, "{r:?}");
5908
    assert_eq!(r.heads, vec![d2]);
5909
    assert_eq!(r.others, vec!["main".to_string()]);
5910
    assert!(c.resolve_heads("main").unwrap().contains(&m));
5911
    assert_eq!(
5912
        fs::read(c_root.join("base.txt")).unwrap(),
5913
        b"base\nd1\nd2\n"
5914
    );
5915
    let again = c.pull("origin").unwrap();
5916
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
5917
5918
    // A clone checks out the remote's default bookmark.
5919
    origin.config.set("workspace.bookmark", "develop").unwrap();
5920
    origin.save_config().unwrap();
5921
    let e = Repo::clone(&url, &root.join("e")).unwrap();
5922
    assert_eq!(e.config.bookmark, "develop");
5923
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
5924
    let reopened = Repo::open(&root.join("e")).unwrap();
5925
    assert_eq!(reopened.config.bookmark, "develop");
5926
    // REMOTE/NAME names the remote's bookmark to switch to.
5927
    let mut e = reopened;
5928
    e.bookmark_switch("origin/main", false).unwrap();
5929
    assert_eq!(e.config.bookmark, "main");
5930
    assert!(e.bookmark_heads().unwrap().contains(&m));
5931
}
5932
98a1620a Andy McCall ↶ 5933
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
5934
/// op restore goes back to an operation, files included, and undo takes
5935
/// the restore back whole; op revert undoes one operation alone; each
5936
/// operation's changes are described from the views.
5937
#[test]
5938
fn operations_can_be_read_restored_and_reverted() {
5939
    hermetic();
5940
    let dir = tempfile::tempdir().unwrap();
5941
    let root = dir.path();
5942
    let repo = Repo::init(root).unwrap();
5943
    write(root, "a.txt", b"a\n");
5944
    let first = repo.commit("first", &[]).unwrap();
5945
    write(root, "a.txt", b"a\nb\n");
5946
    let second = repo.commit("second", &[]).unwrap();
5947
    let at_second = repo.head_op().unwrap().0.to_hex();
5948
    repo.bookmark_create("keep", None).unwrap();
5949
    let created = repo.head_op().unwrap().0.to_hex();
5950
    write(root, "n.txt", b"n\n");
5951
    let third = repo.commit("third", &[]).unwrap();
5952
5953
    // What each operation changed.
5954
    let ops = repo.op_log().unwrap();
5955
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
5956
    assert!(
5957
        changes
5958
            .iter()
5959
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
5960
        "{changes:?}"
5961
    );
5962
    assert!(changes
5963
        .iter()
5964
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
5965
5966
    // Reading at an earlier operation.
5967
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
5968
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
5969
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
5970
    write(root, "z.txt", b"z\n");
5971
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
5972
    fs::remove_file(root.join("z.txt")).unwrap();
5973
    assert!(repo.resolve_op("zz").is_err());
5974
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
5975
5976
    // Restore goes back, files and all; undo takes it back whole.
5977
    repo.op_restore(&at_second, false).unwrap();
5978
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
5979
    assert!(!root.join("n.txt").exists());
5980
    repo.undo().unwrap();
5981
    let mut heads = repo.bookmark_heads().unwrap();
5982
    heads.sort();
5983
    let mut want = vec![second, third];
5984
    want.sort();
5985
    assert_eq!(heads, want);
5986
    assert!(
5987
        root.join("n.txt").exists(),
5988
        "the files came back with the undo"
5989
    );
5990
5991
    // Revert the bookmark's creation alone: the commit after it stays.
5992
    let r = repo.op_revert(&created).unwrap();
5993
    assert_eq!(r.reverted, vec!["keep".to_string()]);
5994
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
5995
    assert!(repo
5996
        .load_state(&repo.bookmark_heads().unwrap())
5997
        .unwrap()
5998
        .contains(&third));
5999
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6000
    let _ = first;
6001
}
6002
36041796 Andy McCall ↶ 6003
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6004
/// from the status cache while every file is as the snapshot left it, and
6005
/// from a snapshot again as soon as one is not.
6006
#[test]
6007
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6008
    hermetic();
6009
    let dir = tempfile::tempdir().unwrap();
6010
    let root = dir.path();
6011
    let repo = Repo::init(root).unwrap();
6012
    write(root, "a.txt", b"a\n");
6013
    write(root, "b.txt", b"b\n");
6014
    repo.commit("base", &[]).unwrap();
6015
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6016
6017
    write(root, "a.txt", b"a\nmore\n");
6018
    assert_eq!(
6019
        repo.status_by_manifest().unwrap(),
6020
        None,
6021
        "no snapshot of the edit yet"
6022
    );
6023
    let snap = repo.snapshot_status("oxy status").unwrap();
6024
    assert_eq!(snap.statuses.len(), 1);
6025
    let cached = repo
6026
        .status_by_manifest()
6027
        .unwrap()
6028
        .expect("answered from the cache");
6029
    assert_eq!(cached.len(), 1);
6030
    assert_eq!(
6031
        (cached[0].path.as_str(), cached[0].status),
6032
        ("a.txt", ChangeStatus::Modified)
6033
    );
6034
6035
    // Any further change sends status back to a snapshot.
6036
    write(root, "a.txt", b"a\nmore\nand more\n");
6037
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6038
    repo.snapshot_status("oxy status").unwrap();
6039
    assert!(repo.status_by_manifest().unwrap().is_some());
6040
    write(root, "new.txt", b"n\n");
6041
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6042
    fs::remove_file(root.join("new.txt")).unwrap();
6043
    assert!(
6044
        repo.status_by_manifest().unwrap().is_some(),
6045
        "back as it was"
6046
    );
6047
    fs::remove_file(root.join("b.txt")).unwrap();
6048
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6049
    write(root, "b.txt", b"b\n");
6050
6051
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6052
    repo.snapshot_status("oxy status").unwrap();
6053
    repo.commit("more", &[]).unwrap();
6054
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6055
}
6056
77445673 Andy McCall ↶ 6057
/// oxygen#41: while the status cache holds, the working copy's diff is
6058
/// rendered from the stored working-copy change, and says exactly what a
6059
/// snapshot's diff says.
6060
#[test]
6061
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6062
    hermetic();
6063
    let dir = tempfile::tempdir().unwrap();
6064
    let root = dir.path();
6065
    let repo = Repo::init(root).unwrap();
6066
    write(root, "a.txt", b"one\ntwo\nthree\n");
6067
    write(root, "gone.txt", b"bye\n");
6068
    repo.commit("base", &[]).unwrap();
6069
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6070
    write(root, "new.txt", b"hello\n");
6071
    fs::remove_file(root.join("gone.txt")).unwrap();
6072
    let snap = repo.snapshot_status("oxy status").unwrap();
6073
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6074
    assert!(
6075
        repo.status_by_manifest().unwrap().is_some(),
6076
        "the cache holds"
6077
    );
6078
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6079
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6080
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6081
}
6082
1ec3f008 Andy McCall ↶ 6083
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6084
/// while none has moved, the check stats the tracked files without listing
6085
/// the tree, and a file added or removed anywhere moves its directory's
6086
/// time, so the tree is listed again.
6087
#[test]
6088
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6089
    hermetic();
6090
    let dir = tempfile::tempdir().unwrap();
6091
    let root = dir.path();
6092
    let repo = Repo::init(root).unwrap();
6093
    write(root, "a.txt", b"a\n");
6094
    write(root, "sub/deep/b.txt", b"b\n");
6095
    repo.commit("base", &[]).unwrap();
6096
    // Out of the racy window: every file and directory a minute old.
6097
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6098
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6099
        fs::File::open(root.join(p))
6100
            .unwrap()
6101
            .set_modified(old)
6102
            .unwrap();
6103
    }
6104
    repo.snapshot_status("oxy status").unwrap();
6105
    repo.write_manifest(false, false).unwrap();
6106
    let m = repo.read_manifest().unwrap().unwrap().2;
6107
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6108
    assert_eq!(
6109
        repo.disk_differs_by_dirs(&m),
6110
        Some(false),
6111
        "no listing needed"
6112
    );
6113
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6114
6115
    // A same-size edit with a new time: found by its stat.
6116
    write(root, "sub/deep/b.txt", b"c\n");
6117
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6118
    write(root, "sub/deep/b.txt", b"b\n");
6119
    fs::File::open(root.join("sub/deep/b.txt"))
6120
        .unwrap()
6121
        .set_modified(old)
6122
        .unwrap();
6123
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6124
6125
    // A new file moves its directory's time: the tree must be listed.
6126
    write(root, "sub/deep/new.txt", b"n\n");
6127
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6128
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6129
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6130
    // A removed one too.
6131
    fs::remove_file(root.join("a.txt")).unwrap();
6132
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6133
}
6134
e226a6cc Andy McCall ↶ 6135
/// oxygen#41: a commit right after a status takes the snapshot the status
6136
/// left (the status cache holds) rather than walking again, and commits
6137
/// exactly what a snapshot would have.
6138
#[test]
6139
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6140
    hermetic();
6141
    let dir = tempfile::tempdir().unwrap();
6142
    let root = dir.path();
6143
    let repo = Repo::init(root).unwrap();
6144
    write(root, "a.txt", b"a\nb\n");
6145
    write(root, ".oxyattributes", b"*.bin binary\n");
6146
    repo.commit("base", &[]).unwrap();
6147
    write(root, "a.txt", b"a\nB\n");
6148
    write(root, "new.txt", b"new\n");
6149
    let snap = repo.snapshot_status("oxy status").unwrap();
6150
    let cached = repo
6151
        .snapshot_from_cache()
6152
        .unwrap()
6153
        .expect("the cache holds");
6154
    assert_eq!(cached.wc_hash, snap.wc_hash);
6155
    assert_eq!(cached.statuses, snap.statuses);
6156
    assert!(
6157
        !cached.attributes.is_empty(),
6158
        "the .oxyattributes file was read"
6159
    );
6160
    let h = repo.commit("edit", &[]).unwrap();
6161
    let c = repo.store().get_change(&h).unwrap();
6162
    assert_eq!(
6163
        c.tree_ops.len() + c.edits.len(),
6164
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6165
    );
6166
    assert_eq!(
6167
        repo.status_by_manifest().unwrap(),
6168
        Some(vec![]),
6169
        "clean after the commit"
6170
    );
6171
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6172
}
6173
0389c3e8 Andy McCall ↶ 6174
/// oxygen#41: a clean check that verified racy entries restamps the
6175
/// manifest, so later checks can trust them, and a same-size rewrite
6176
/// straight afterwards is still found: entries within two seconds of the
6177
/// new time stay racy.
6178
#[test]
6179
fn a_verified_clean_check_restamps_the_manifest_safely() {
6180
    hermetic();
6181
    let dir = tempfile::tempdir().unwrap();
6182
    let root = dir.path();
6183
    let repo = Repo::init(root).unwrap();
6184
    write(root, "a.txt", b"one\n");
6185
    repo.commit("one", &[]).unwrap();
6186
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6187
    assert!(repo.clean_by_manifest().unwrap());
6188
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6189
    assert!(after > before, "restamped");
6190
    write(root, "a.txt", b"two\n");
6191
    assert!(
6192
        !repo.clean_by_manifest().unwrap(),
6193
        "a same-size rewrite is still seen"
6194
    );
6195
}
6196
86e1824f Andy McCall ↶ 6197
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6198
/// stored insert's text blob only when it builds that file's graph, and
6199
/// builds the same graph a full load does.
6200
#[test]
6201
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6202
    hermetic();
6203
    let dir = tempfile::tempdir().unwrap();
6204
    let root = dir.path();
6205
    let repo = Repo::init(root).unwrap();
6206
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6207
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6208
    write(root, "big.txt", big.as_bytes());
6209
    write(root, "other.txt", other.as_bytes());
6210
    let h = repo.commit("two large files", &[]).unwrap();
6211
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6212
    let h2 = repo.commit("append", &[]).unwrap();
6213
6214
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6215
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6216
        FileContent::Text { bytes, .. } => bytes.clone(),
6217
        other => panic!("{other:?}"),
6218
    };
6219
    // Built on demand, every graph renders as the full load's.
6220
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6221
    let big_node = full.files["big.txt"].node;
6222
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6223
    repo.load_all_graphs(&mut hist).unwrap();
6224
    let rendered = hist.materialize();
6225
    for p in ["big.txt", "other.txt"] {
6226
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6227
    }
6228
6229
    // Without other.txt's text blob, history still loads and big.txt still
6230
    // builds: nothing read the other text.
6231
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6232
    assert_eq!(texts.len(), 2);
6233
    let content = |r: &ObjectRef| -> Vec<u8> {
6234
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6235
        blob.chunks
6236
            .iter()
6237
            .flat_map(|c| repo.store().get(c).unwrap().1)
6238
            .collect()
6239
    };
6240
    let other_text = texts
6241
        .iter()
a4fad5b0 Andy McCall ↶ 6242
        .filter_map(|t| match t {
0f93f49c Andy McCall ↶ 6243
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
a4fad5b0 Andy McCall ↶ 6244
            _ => None,
6245
        })
86e1824f Andy McCall ↶ 6246
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6247
        .unwrap();
64818938 Andy McCall ↶ 6248
    repo.store().remove_loose_for_test(&other_text).unwrap();
86e1824f Andy McCall ↶ 6249
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6250
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6251
    assert!(repo
6252
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6253
        .is_err());
6254
}
6255
6256
/// oxygen#35: the first status after a commit read and rendered every
6257
/// file (79 s and more than 14 GB on the Linux tree), because the
6258
/// manifest had no graph keys for files the commit added.
6259
#[test]
6260
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6261
    use std::os::unix::fs::PermissionsExt;
6262
    hermetic();
6263
    let dir = tempfile::tempdir().unwrap();
6264
    let root = dir.path();
6265
    let repo = Repo::init(root).unwrap();
6266
    let files = ["a.txt", "b.txt", "d/c.txt"];
6267
    for p in files {
6268
        write(root, p, format!("{p}\n").as_bytes());
6269
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6270
        fs::File::options()
6271
            .write(true)
6272
            .open(root.join(p))
6273
            .unwrap()
6274
            .set_modified(old)
6275
            .unwrap();
6276
    }
6277
    repo.commit("added", &[]).unwrap();
6278
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6279
    assert!(
6280
        m.entries.values().all(|e| e.graph.is_some()),
6281
        "keys recorded at commit"
6282
    );
6283
    // Unreadable files prove the next status reads none of them.
6284
    for p in files {
6285
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6286
    }
6287
    let snap = repo.snapshot_status("status").unwrap();
6288
    for p in files {
6289
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6290
    }
6291
    assert!(!snap.changed && snap.statuses.is_empty());
6292
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6293
}
c5ce0367 Andy McCall ↶ 6294
6295
/// oxygen#35: a checkout reads, renders and writes only the files whose
6296
/// graphs differ, and renders the rest a batch at a time.
6297
#[test]
6298
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6299
    use std::os::unix::fs::PermissionsExt;
6300
    hermetic();
6301
    let dir = tempfile::tempdir().unwrap();
6302
    let root = dir.path();
6303
    let origin = root.join("origin");
6304
    let mut repo = Repo::init(&origin).unwrap();
6305
    // More files than one batch holds.
6306
    let n = 2100;
6307
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6308
    for i in 0..n {
6309
        let p = format!("f/{i:04}.txt");
6310
        write(&origin, &p, format!("file {i}\n").as_bytes());
6311
        fs::File::options()
6312
            .write(true)
6313
            .open(origin.join(&p))
6314
            .unwrap()
6315
            .set_modified(old)
6316
            .unwrap();
6317
    }
6318
    repo.commit("many", &[]).unwrap();
6319
    repo.bookmark_create("feature", None).unwrap();
6320
    repo.bookmark_switch("feature", false).unwrap();
6321
    write(&origin, "f/0007.txt", b"changed\n");
6322
    repo.commit("one change", &[]).unwrap();
6323
6324
    // Switching back to main must not read the unchanged files.
6325
    for i in 0..n {
6326
        if i != 7 {
6327
            let p = origin.join(format!("f/{i:04}.txt"));
6328
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6329
        }
6330
    }
6331
    let r = repo.bookmark_switch("main", false).unwrap();
6332
    for i in 0..n {
6333
        let p = origin.join(format!("f/{i:04}.txt"));
6334
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6335
    }
6336
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6337
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6338
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6339
6340
    // A clone renders every file, across batches.
6341
    let c = root.join("clone");
6342
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6343
    for i in [0, 2047, 2048, n - 1] {
6344
        assert_eq!(
6345
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6346
            format!("file {i}\n").as_bytes()
6347
        );
6348
    }
6349
    let cloned = Repo::open(&c).unwrap();
6350
    assert!(cloned
6351
        .snapshot_status("status")
6352
        .unwrap()
6353
        .statuses
6354
        .is_empty());
d3cd7ef9 Andy McCall ↶ 6355
}
6356
6357
/// A file written just before the manifest (inside the racy window) is
6358
/// checked by its hash: trusted when equal, caught when edited in place
6359
/// with the same size and time.
6360
#[test]
6361
fn a_racy_manifest_entry_is_checked_by_hash() {
6362
    hermetic();
6363
    let dir = tempfile::tempdir().unwrap();
6364
    let root = dir.path();
6365
    let repo = Repo::init(root).unwrap();
6366
    write(root, "a.txt", b"one\n");
6367
    repo.commit("fresh", &[]).unwrap();
6368
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6369
    let t = fs::metadata(root.join("a.txt"))
6370
        .unwrap()
6371
        .modified()
6372
        .unwrap();
6373
    write(root, "a.txt", b"two\n");
6374
    fs::File::options()
6375
        .write(true)
6376
        .open(root.join("a.txt"))
6377
        .unwrap()
6378
        .set_modified(t)
6379
        .unwrap();
6380
    assert!(
6381
        !repo.clean_by_manifest().unwrap(),
6382
        "same size and time, other bytes"
6383
    );
6384
    assert_eq!(
6385
        statuses(&repo.snapshot_status("status").unwrap()),
6386
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6387
    );
c5ce0367 Andy McCall ↶ 6388
}
2c75672f Andy McCall ↶ 6389
6390
/// A fetch on one machine moves changes as stored, text blobs among the
6391
/// objects; a change whose text blob did not come is refused, not stored.
6392
#[test]
6393
fn a_raw_bundle_without_a_changes_text_is_refused() {
6394
    hermetic();
6395
    let dir = tempfile::tempdir().unwrap();
6396
    let root = dir.path();
6397
    let a = Repo::init(&root.join("a")).unwrap();
6398
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6399
    write(&root.join("a"), "big.txt", big.as_bytes());
6400
    let h = a.commit("big", &[]).unwrap();
6401
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6402
    assert_eq!(bundle.raw_changes.len(), 1);
6403
    assert!(bundle.changes.is_empty());
6404
    let b = Repo::init(&root.join("b")).unwrap();
6405
    let mut without = bundle.clone();
6406
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6407
    let e = b.import_bundle(&without, false).unwrap_err();
6408
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6409
    assert!(!b.store().has(&h));
6410
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6411
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6412
}
a87c7b9d Andy McCall ↶ 6413
6414
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6415
/// again was a second node for one Git path, so a file moved into it on
6416
/// another line, where the first node still stood, ended up in two places.
6417
/// An import now brings the directory back rather than make a new one.
6418
#[test]
6419
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6420
    hermetic();
6421
    if std::process::Command::new("git")
6422
        .arg("--version")
6423
        .output()
6424
        .is_err()
6425
    {
6426
        eprintln!("git not installed; skipping");
6427
        return;
6428
    }
6429
    let dir = tempfile::tempdir().unwrap();
6430
    let root = dir.path();
6431
    let g = root.join("src.git");
6432
    fs::create_dir_all(&g).unwrap();
6433
    let git = |args: &[&str]| -> String {
6434
        let out = std::process::Command::new("git")
6435
            .arg("-C")
6436
            .arg(&g)
6437
            .args([
6438
                "-c",
6439
                "user.name=Grace",
6440
                "-c",
6441
                "[email protected]",
6442
                "-c",
6443
                "commit.gpgsign=false",
6444
            ])
6445
            .args(args)
6446
            .output()
6447
            .unwrap();
6448
        assert!(
6449
            out.status.success(),
6450
            "git {args:?}: {}",
6451
            String::from_utf8_lossy(&out.stderr)
6452
        );
6453
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6454
    };
6455
    git(&["init", "-q", "-b", "main"]);
6456
    write(&g, "d/a.txt", b"a\n");
6457
    write(&g, "c/x.txt", b"x\n");
6458
    git(&["add", "."]);
6459
    git(&["commit", "-qm", "base"]);
6460
    // One line: move x into d while d still stands.
6461
    git(&["checkout", "-qb", "side"]);
6462
    git(&["mv", "c/x.txt", "d/x.txt"]);
6463
    git(&["commit", "-qm", "x into d"]);
6464
    // The other: d goes, comes back, and x moves into it too.
6465
    git(&["checkout", "-q", "main"]);
6466
    git(&["rm", "-q", "d/a.txt"]);
6467
    git(&["commit", "-qm", "d goes"]);
6468
    write(&g, "d/b.txt", b"b\n");
6469
    git(&["add", "."]);
6470
    git(&["commit", "-qm", "d comes back"]);
6471
    git(&["mv", "c/x.txt", "d/x.txt"]);
6472
    git(&["commit", "-qm", "x into d again"]);
6473
    git(&["merge", "-q", "--no-edit", "side"]);
6474
6475
    let repo = Repo::init(&root.join("o")).unwrap();
6476
    repo.import_git(&g, "main").unwrap();
6477
    let v = repo.verify_git_import(&g, "main").unwrap();
6478
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6479
    let st = repo
6480
        .load_state_history(&repo.bookmark_heads().unwrap())
6481
        .unwrap();
6482
    let view = st.tree().view();
6483
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6484
    // The directory is the one the first commit made.
6485
    // Commits made in one second tie on time: find the first by its message.
6486
    let first = repo
6487
        .log()
6488
        .unwrap()
6489
        .into_iter()
6490
        .find(|e| e.change.message.starts_with("base"))
6491
        .unwrap();
6492
    let base = repo
6493
        .load_state_history(&[first.hash])
6494
        .unwrap()
6495
        .tree()
6496
        .view();
6497
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6498
}
6499
6500
/// oxygen#30, the rest: a placement left under a directory another line
6501
/// removed is out of sight, so no diff reaches it; the merge that settles
6502
/// where the file is retires it.
6503
#[test]
6504
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6505
    hermetic();
6506
    if std::process::Command::new("git")
6507
        .arg("--version")
6508
        .output()
6509
        .is_err()
6510
    {
6511
        eprintln!("git not installed; skipping");
6512
        return;
6513
    }
6514
    let dir = tempfile::tempdir().unwrap();
6515
    let root = dir.path();
6516
    let g = root.join("src.git");
6517
    fs::create_dir_all(&g).unwrap();
6518
    let run = |args: &[&str]| {
6519
        std::process::Command::new("git")
6520
            .arg("-C")
6521
            .arg(&g)
6522
            .args([
6523
                "-c",
6524
                "user.name=Grace",
6525
                "-c",
6526
                "[email protected]",
6527
                "-c",
6528
                "commit.gpgsign=false",
6529
            ])
6530
            .args(args)
6531
            .output()
6532
            .unwrap()
6533
    };
6534
    let git = |args: &[&str]| {
6535
        let out = run(args);
6536
        assert!(
6537
            out.status.success(),
6538
            "git {args:?}: {}",
6539
            String::from_utf8_lossy(&out.stderr)
6540
        );
6541
    };
6542
    git(&["init", "-q", "-b", "main"]);
6543
    write(&g, "c/x.txt", b"x\n");
6544
    write(&g, "keep.txt", b"k\n");
6545
    git(&["add", "."]);
6546
    git(&["commit", "-qm", "base"]);
6547
    // One line renames the file within c; the other moves it out of c,
6548
    // which goes.
6549
    git(&["checkout", "-qb", "side"]);
6550
    git(&["mv", "c/x.txt", "c/y.txt"]);
6551
    git(&["commit", "-qm", "rename within c"]);
6552
    git(&["checkout", "-q", "main"]);
6553
    fs::create_dir_all(g.join("n")).unwrap();
6554
    git(&["mv", "c/x.txt", "n/x.txt"]);
6555
    git(&["commit", "-qm", "move out of c"]);
6556
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6557
    let _ = run(&["merge", "-q", "side"]);
6558
    let _ = run(&[
6559
        "rm",
6560
        "-q",
6561
        "--cached",
6562
        "--ignore-unmatch",
6563
        "c/y.txt",
6564
        "c/x.txt",
6565
    ]);
6566
    let _ = std::fs::remove_dir_all(g.join("c"));
6567
    write(&g, "n/x.txt", b"x\n");
6568
    git(&["add", "-A"]);
6569
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6570
6571
    let repo = Repo::init(&root.join("o")).unwrap();
6572
    repo.import_git(&g, "main").unwrap();
6573
    let v = repo.verify_git_import(&g, "main").unwrap();
6574
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6575
    let st = repo
6576
        .load_state_history(&repo.bookmark_heads().unwrap())
6577
        .unwrap();
6578
    let view = st.tree().view();
6579
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6580
    assert!(view.entries.contains_key("n/x.txt"));
6581
}
6582
6583
/// oxygen#30, orphans: a file added on one line into a directory the other
6584
/// line removed is placed where the tree cannot show it; Git's merge keeps
6585
/// the file, and the import's merge leaves exactly one of it.
6586
#[test]
6587
fn git_import_merge_leaves_no_orphan_behind() {
6588
    hermetic();
6589
    if std::process::Command::new("git")
6590
        .arg("--version")
6591
        .output()
6592
        .is_err()
6593
    {
6594
        eprintln!("git not installed; skipping");
6595
        return;
6596
    }
6597
    let dir = tempfile::tempdir().unwrap();
6598
    let root = dir.path();
6599
    let g = root.join("src.git");
6600
    fs::create_dir_all(&g).unwrap();
6601
    let git = |args: &[&str]| {
6602
        let out = std::process::Command::new("git")
6603
            .arg("-C")
6604
            .arg(&g)
6605
            .args([
6606
                "-c",
6607
                "user.name=Grace",
6608
                "-c",
6609
                "[email protected]",
6610
                "-c",
6611
                "commit.gpgsign=false",
6612
            ])
6613
            .args(args)
6614
            .output()
6615
            .unwrap();
6616
        assert!(
6617
            out.status.success(),
6618
            "git {args:?}: {}",
6619
            String::from_utf8_lossy(&out.stderr)
6620
        );
6621
    };
6622
    git(&["init", "-q", "-b", "main"]);
6623
    write(&g, "d/f.txt", b"f\n");
6624
    write(&g, "keep.txt", b"k\n");
6625
    git(&["add", "."]);
6626
    git(&["commit", "-qm", "base"]);
6627
    git(&["checkout", "-qb", "side"]);
6628
    write(&g, "d/new.txt", b"new\n");
6629
    git(&["add", "."]);
6630
    git(&["commit", "-qm", "add into d"]);
6631
    git(&["checkout", "-q", "main"]);
6632
    git(&["rm", "-q", "d/f.txt"]);
6633
    git(&["commit", "-qm", "d goes"]);
6634
    git(&["merge", "-q", "--no-edit", "side"]);
6635
6636
    let repo = Repo::init(&root.join("o")).unwrap();
6637
    repo.import_git(&g, "main").unwrap();
6638
    let v = repo.verify_git_import(&g, "main").unwrap();
6639
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6640
    let st = repo
6641
        .load_state_history(&repo.bookmark_heads().unwrap())
6642
        .unwrap();
6643
    let view = st.tree().view();
6644
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6645
    assert!(view.entries.contains_key("d/new.txt"));
6646
}
d77e1702 Andy McCall ↶ 6647
6648
/// fsck checks a change's text as the blobs it is stored in, without
6649
/// decoding it: a missing text blob is an error named for the change.
6650
#[test]
6651
fn fsck_names_a_missing_text_blob() {
6652
    hermetic();
6653
    let dir = tempfile::tempdir().unwrap();
6654
    let root = dir.path();
6655
    let repo = Repo::init(root).unwrap();
6656
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6657
    write(root, "big.txt", big.as_bytes());
6658
    let h = repo.commit("big", &[]).unwrap();
6659
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6660
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6661
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6662
        panic!("a stored text")
6663
    };
64818938 Andy McCall ↶ 6664
    repo.store().remove_loose_for_test(&b).unwrap();
d77e1702 Andy McCall ↶ 6665
    let rep = repo.fsck().unwrap();
6666
    assert!(rep.errors() > 0);
6667
    assert!(
6668
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6669
        "{:?}",
6670
        rep.problems
6671
    );
6672
}
a07f60a3 Andy McCall ↶ 6673
6674
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6675
/// reached with that remote's token and CA (a private subrepo then clones
6676
/// for anyone who can read the parent); another hub gets none of them.
6677
#[test]
6678
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6679
    hermetic();
6680
    let dir = tempfile::tempdir().unwrap();
6681
    let mut repo = Repo::init(dir.path()).unwrap();
6682
    repo.config
6683
        .set(
6684
            "remote.origin.url",
6685
            "https://Hub.example:7343/doomsdayone/metalgear",
6686
        )
6687
        .unwrap();
6688
    repo.config.set("remote.origin.token", "secret").unwrap();
6689
    repo.config
6690
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6691
        .unwrap();
6692
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6693
    assert_eq!(same.token.as_deref(), Some("secret"));
6694
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6695
    for other in [
6696
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6697
        "https://hub.example/doomsdayone/rstar-api",
6698
        "http://hub.example:7343/doomsdayone/rstar-api",
6699
    ] {
6700
        let o = repo.credentials_for(other);
6701
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6702
    }
6703
}
ce14f0d6 Andy McCall ↶ 6704
ff1f62fe Andy McCall ↶ 6705
/// oxygen#47: a remote with no token of its own uses the user's credential
6706
/// store for its hub, and a nested checkout finds its parent's remote
6707
/// token there instead of keeping a copy.
ce14f0d6 Andy McCall ↶ 6708
#[test]
ff1f62fe Andy McCall ↶ 6709
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
6710
    hermetic();
6711
    let home = tempfile::tempdir().unwrap();
6712
    let dir = tempfile::tempdir().unwrap();
6713
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
6714
    parent
6715
        .config
6716
        .set("remote.origin.url", "https://hub.example/o/parent")
6717
        .unwrap();
6718
    parent.save_config().unwrap();
6719
    assert_eq!(parent.remote_options("origin").token, None);
6720
    crate::credentials::Credentials::at(home.path())
6721
        .save("https://hub.example", "stored", Some("andy"), None)
6722
        .unwrap();
6723
    assert_eq!(
6724
        parent.remote_options("origin").token.as_deref(),
6725
        Some("stored")
6726
    );
6727
6728
    let empty_home = tempfile::tempdir().unwrap();
6729
    let nested = dir.path().join("deps").join("child");
6730
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
6731
    child
6732
        .config
6733
        .set("remote.origin.url", "https://hub.example/o/child")
6734
        .unwrap();
6735
    child.save_config().unwrap();
6736
    assert_eq!(child.remote_options("origin").token, None);
6737
    parent
6738
        .config
6739
        .set("remote.origin.token", "checkout")
6740
        .unwrap();
6741
    parent.save_config().unwrap();
6742
    assert_eq!(
6743
        child.remote_options("origin").token.as_deref(),
6744
        Some("checkout")
6745
    );
6746
    // Another hub's checkout token is not borrowed.
6747
    child
6748
        .config
6749
        .set("remote.origin.url", "https://other.example/o/child")
6750
        .unwrap();
6751
    assert_eq!(child.remote_options("origin").token, None);
6752
}
6753
6754
#[test]
ce14f0d6 Andy McCall ↶ 6755
fn the_metadata_cache_survives_a_torn_tail() {
6756
    hermetic();
6757
    let dir = tempfile::tempdir().unwrap();
6758
    let root = dir.path();
6759
    let repo = Repo::init(root).unwrap();
6760
    write(root, "a.txt", b"1\n");
6761
    let h = repo.commit("first", &[]).unwrap();
6762
    let meta = repo.store().get_change_meta(&h).unwrap();
6763
    let cache = repo.store().dir().join("metas");
6764
    let len = fs::metadata(&cache).unwrap().len();
6765
    assert!(len > 0, "a change read is cached");
6766
    // A torn record at the end: the cache reads up to it and cuts it off.
6767
    fs::OpenOptions::new()
6768
        .append(true)
6769
        .open(&cache)
6770
        .unwrap()
6771
        .write_all(&[7; 20])
6772
        .unwrap();
6773
    let again = Repo::open(root).unwrap();
6774
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
6775
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
6776
}
f9466021 Andy McCall ↶ 6777
6778
#[test]
6779
fn a_manifest_that_does_not_check_reads_as_none() {
6780
    hermetic();
6781
    let dir = tempfile::tempdir().unwrap();
6782
    let root = dir.path();
6783
    let repo = Repo::init(root).unwrap();
6784
    write(root, "a.txt", b"1\n");
6785
    repo.commit("first", &[]).unwrap();
6786
    let path = repo.manifest_path();
6787
    let mut bytes = fs::read(&path).unwrap();
6788
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
6789
    let last = bytes.len() - 1;
6790
    bytes[last] ^= 1;
6791
    fs::write(&path, &bytes).unwrap();
6792
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
6793
    // The next status reads the files and writes it again.
6794
    let again = Repo::open(root).unwrap();
6795
    assert!(!again.snapshot("status").unwrap().changed);
6796
    assert!(again.read_manifest().unwrap().is_some());
6797
}
6798
6799
#[test]
6800
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
6801
    hermetic();
6802
    let dir = tempfile::tempdir().unwrap();
6803
    let root = dir.path();
6804
    let repo = Repo::init(root).unwrap();
6805
    write(root, "a.txt", b"1\n");
6806
    write(root, "b.txt", b"2\n");
6807
    // b.txt outside the racy window, so snapshots take it as unchanged.
6808
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6809
    fs::File::options()
6810
        .write(true)
6811
        .open(root.join("b.txt"))
6812
        .unwrap()
6813
        .set_modified(old)
6814
        .unwrap();
6815
    repo.commit("first", &[]).unwrap();
6816
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
6817
    repo.snapshot_status("status").unwrap();
6818
    write(root, "a.txt", b"1\n2\n");
6819
    repo.commit("second", &[]).unwrap();
6820
    assert!(
6821
        repo.clean_by_manifest().unwrap(),
6822
        "after a commit of one file"
6823
    );
6824
    // Edited, seen by a status, edited again, then committed: the status
6825
    // left the first edit's stat, which the commit must not keep.
6826
    write(root, "a.txt", b"1\n2\n3\n");
6827
    repo.snapshot_status("status").unwrap();
6828
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
6829
    repo.commit("third", &[]).unwrap();
6830
    assert!(
6831
        repo.clean_by_manifest().unwrap(),
6832
        "after an edit a status saw"
6833
    );
6834
}
e266b7d4 Andy McCall ↶ 6835
6836
#[test]
6837
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
6838
    hermetic();
6839
    let dir = tempfile::tempdir().unwrap();
6840
    let root = dir.path();
6841
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6842
    write(root, "a.txt", b"1\n2\n");
6843
    let a = repo.commit("A", &[]).unwrap();
6844
    repo.bookmark_create("develop", Some(&[a])).unwrap();
6845
    write(root, "a.txt", b"1\nX\n");
6846
    let c = repo.commit("C: 2 to X", &[]).unwrap();
6847
    repo.bookmark_switch("develop", false).unwrap();
6848
    write(root, "a.txt", b"1\nY\n");
6849
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
6850
    repo.bookmark_switch("main", false).unwrap();
6851
6852
    let err = repo.rebase(&c, &[d]).unwrap_err();
6853
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
6854
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
6855
    assert!(r.changed && r.checked_out);
6856
    let snap = repo.snapshot_status("status").unwrap();
6857
    assert!(
6858
        snap.base_snapshot.is_conflicted(),
6859
        "the conflict is in the working copy"
6860
    );
6861
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
6862
    assert!(text.contains('X') && text.contains('Y'), "{text}");
6863
6864
    write(root, "a.txt", b"1\nXY\n");
6865
    repo.commit("Resolve", &[]).unwrap();
6866
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
6867
    assert!(st.contains(&c) && st.contains(&d));
6868
    let files = st.materialize().files;
6869
    assert!(!files["a.txt"].is_conflicted());
6870
    assert!(
6871
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
6872
    );
6873
6874
    // A change the current bookmark does not hold is refused.
6875
    repo.bookmark_switch("develop", false).unwrap();
6876
    write(root, "b.txt", b"b\n");
6877
    let e = repo.commit("E", &[]).unwrap();
6878
    repo.bookmark_switch("main", false).unwrap();
6879
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
6880
    assert!(
6881
        err.to_string().contains("not on the current bookmark"),
6882
        "{err}"
6883
    );
6884
}
d4dbab97 Andy McCall ↶ 6885
6886
#[test]
6887
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
6888
    hermetic();
6889
    let dir = tempfile::tempdir().unwrap();
6890
    let root = dir.path();
6891
    let repo = Repo::init(root).unwrap();
6892
    write(root, "a.txt", b"a\n");
6893
    write(root, "kept.log", b"tracked\n");
6894
    repo.commit("first", &[]).unwrap();
6895
    write(root, "build.log", b"made\n");
6896
    let snap = repo.snapshot_status("status").unwrap();
6897
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
6898
    // A rule written afterwards leaves the added file out again, while the
6899
    // committed one stays tracked.
6900
    write(root, ".gitignore", b"*.log\n");
6901
    let snap = repo.snapshot_status("status").unwrap();
6902
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
6903
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
6904
    write(root, "kept.log", b"tracked, edited\n");
6905
    let snap = repo.snapshot_status("status").unwrap();
6906
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
6907
}
fd280228 Andy McCall ↶ 6908
6909
#[test]
6910
fn shed_graphs_come_back_the_same() {
6911
    hermetic();
6912
    let dir = tempfile::tempdir().unwrap();
6913
    let root = dir.path();
6914
    let repo = Repo::init(root).unwrap();
6915
    write(root, "a.txt", b"1\n2\n3\n");
6916
    write(root, "b.txt", b"x\n");
6917
    repo.commit("first", &[]).unwrap();
6918
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
6919
    repo.commit("second", &[]).unwrap();
6920
    let heads = repo.bookmark_heads().unwrap();
6921
    let mut st = repo.load_state_history(&heads).unwrap();
6922
    let view = st.tree().view();
6923
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
6924
        .iter()
6925
        .map(|p| view.entries[*p].node)
6926
        .collect();
6927
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6928
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6929
    assert_eq!(st.built_count(), 2);
6930
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
6931
    assert_eq!((shed, st.built_count()), (2, 0));
6932
    // A later change applies on top of the shed history.
6933
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
6934
    let h3 = repo.commit("third", &[]).unwrap();
6935
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
6936
    st.add_known(h3, skeleton, texts);
6937
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6938
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6939
    assert_eq!(after[1], before[1]);
6940
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
6941
}
360aa74a Andy McCall ↶ 6942
6943
#[test]
6944
fn many_edited_files_diff_in_parallel() {
6945
    // Enough edited files that the builder diffs them in parallel; the
6946
    // commit must hold exactly what is on disk, and a second snapshot
6947
    // must find nothing left to commit.
6948
    hermetic();
6949
    let dir = tempfile::tempdir().unwrap();
6950
    let root = dir.path();
6951
    let repo = Repo::init(root).unwrap();
6952
    let text = |i: usize, round: usize| {
6953
        let mut s = String::new();
6954
        for line in 0..50 {
6955
            if round > 0 && line % 7 == i % 7 {
6956
                s.push_str(&format!("edited {round} {i} {line}\n"));
6957
            } else {
6958
                s.push_str(&format!("file {i} line {line}\n"));
6959
            }
6960
        }
6961
        if round > 0 && i.is_multiple_of(3) {
6962
            s.push_str("appended\n");
6963
        }
6964
        s
6965
    };
6966
    for i in 0..40 {
6967
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
6968
    }
6969
    repo.commit("first", &[]).unwrap();
6970
    for i in 0..40 {
6971
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
6972
    }
6973
    let h = repo.commit("edit every file", &[]).unwrap();
6974
    let snap = repo.load_state(&[h]).unwrap().materialize();
6975
    for i in 0..40 {
6976
        let want = text(i, 1);
6977
        assert!(
6978
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
6979
            "d/f{i}.txt as committed"
6980
        );
6981
    }
6982
    assert!(
6983
        repo.commit("nothing", &[]).is_err(),
6984
        "nothing left to commit"
6985
    );
6986
}
b35df36b Andy McCall ↶ 6987
6988
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
6989
/// is known (fetch printed "up to date" while main was behind), a change
6990
/// only fetched resolves and says where it is, and a checkout whose only
6991
/// remote is not `origin` uses that one.
6992
#[test]
6993
fn a_fetched_change_shows_as_behind_and_resolves() {
6994
    hermetic();
6995
    let dir = tempfile::tempdir().unwrap();
6996
    let root = dir.path();
6997
    let origin = Repo::init(&root.join("origin")).unwrap();
6998
    drop(origin);
6999
    let url = root.join("origin").to_string_lossy().to_string();
7000
    let a = Repo::clone(&url, &root.join("a"))
7001
        .unwrap()
7002
        .with_home(root.join("home-a"));
7003
    write(&root.join("a"), "f.txt", b"one\n");
7004
    a.commit("one", &[]).unwrap();
7005
    a.push("origin", false).unwrap();
7006
    let b = Repo::clone(&url, &root.join("b"))
7007
        .unwrap()
7008
        .with_home(root.join("home-b"));
7009
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7010
7011
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7012
    let h2 = a.commit("two", &[]).unwrap();
7013
    a.push("origin", false).unwrap();
7014
    b.fetch("origin").unwrap();
7015
    // Fetched, not pulled: one behind, the change found and placed.
7016
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7017
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7018
    assert_eq!(
7019
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7020
            .unwrap(),
7021
        h2
7022
    );
7023
    assert_eq!(
7024
        b.remote_only_location(&h2).unwrap().as_deref(),
7025
        Some("origin/main")
7026
    );
7027
    // Fetching again changes nothing: still behind, which is what the
7028
    // CLI now says rather than "up to date".
7029
    b.fetch("origin").unwrap();
7030
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7031
    b.pull("origin").unwrap();
7032
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7033
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7034
7035
    // One remote, not called origin: it is the default.
7036
    let mut c = Repo::init(&root.join("c")).unwrap();
7037
    assert_eq!(c.default_remote(), "origin");
7038
    c.config.set("remote.earth.url", &url).unwrap();
7039
    assert_eq!(c.default_remote(), "earth");
7040
    c.config.set("remote.origin.url", &url).unwrap();
7041
    assert_eq!(c.default_remote(), "origin");
7042
}
827281ee Andy McCall ↶ 7043
7044
/// oxygen#57: a clone from a relative local path records the remote as an
7045
/// absolute path, so fetch still finds it from inside the clone.
7046
#[test]
7047
fn a_clone_from_a_relative_path_records_it_absolute() {
7048
    hermetic();
7049
    let dir = tempfile::tempdir().unwrap();
7050
    let root = dir.path();
7051
    Repo::init(&root.join("origin")).unwrap();
7052
    let rel = crate::protocol::stored_url("relative/repo");
7053
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7054
    assert_eq!(
7055
        crate::protocol::stored_url("https://hub.example/o/n"),
7056
        "https://hub.example/o/n"
7057
    );
7058
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8d803563 Andy McCall ↶ 7059
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7060
    // A bucket is kept as written: it is not a path.
7061
    assert_eq!(
7062
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7063
        "s3://bucket/prefix?profile=p"
7064
    );
827281ee Andy McCall ↶ 7065
    let url = root.join("origin").to_string_lossy().to_string();
7066
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7067
    assert_eq!(b.config.remotes["origin"], url);
7068
    b.fetch("origin").unwrap();
7069
}
a46f3e4f Andy McCall ↶ 7070
7071
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7072
/// and gets its subrepos at their pins from this workspace's copies, with
7073
/// their remotes pointing where the subrepos come from.
7074
#[test]
7075
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7076
    hermetic();
7077
    let dir = tempfile::tempdir().unwrap();
7078
    let root = dir.path();
7079
    Repo::init(&root.join("lib-origin")).unwrap();
7080
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7081
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7082
        .unwrap()
7083
        .with_home(root.join("home"));
7084
    write(&root.join("lib"), "lib.txt", b"v1\n");
7085
    let l1 = lib.commit("lib v1", &[]).unwrap();
7086
    assert!(lib.push("origin", false).unwrap()[0].ok);
7087
7088
    let app_dir = root.join("app");
7089
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7090
    write(&app_dir, "main.txt", b"app\n");
7091
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7092
    app.commit("app with lib", &[]).unwrap();
7093
    // A second bookmark, and the main workspace on another.
7094
    app.bookmark_create("develop", None).unwrap();
7095
    app.bookmark_create("feature", None).unwrap();
7096
    let mut app = app;
7097
    app.bookmark_switch("feature", false).unwrap();
7098
    assert_eq!(app.config.bookmark, "feature");
7099
7100
    // The library's origin goes away: the subrepo must come from here.
7101
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7102
    let heads = app.resolve_heads("develop").unwrap();
7103
    let ws = app
7104
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7105
        .unwrap();
7106
    assert_eq!(
7107
        ws.config.bookmark, "develop",
7108
        "the new workspace is on develop"
7109
    );
7110
    assert_eq!(
7111
        app.config.bookmark, "feature",
7112
        "and this one stays on its own"
7113
    );
7114
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7115
    assert_eq!(
7116
        sub.config.remotes["origin"], lib_url,
7117
        "its origin is the subrepo's URL"
7118
    );
7119
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7120
    assert_eq!(
7121
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7122
        b"v1\n"
7123
    );
7124
}
47ce8b8e Andy McCall ↶ 7125
7126
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7127
/// operators and the predicates, over a small graph with two heads and
7128
/// a rename.
7129
#[test]
7130
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7131
    hermetic();
7132
    let dir = tempfile::tempdir().unwrap();
7133
    let root = dir.path();
7134
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7135
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7136
        .unwrap();
7137
    write(root, "src/a.rs", b"one\n");
7138
    let a = repo.commit("first: add a", &[]).unwrap();
7139
    write(root, "src/a.rs", b"one\ntwo\n");
7140
    let b = repo.commit("second: grow a", &[]).unwrap();
7141
    // A second head, independent of b: a new file on top of a.
7142
    repo.checkout(&[a], false, "checkout a").unwrap();
7143
    write(root, "docs/notes.md", b"notes\n");
7144
    let c = repo.commit("third: notes", &[]).unwrap();
7145
    // Back to both heads, then rename a.rs: the node keeps its identity.
7146
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7147
        .unwrap();
7148
    fs::remove_file(root.join("src/a.rs")).unwrap();
7149
    write(root, "src/z.rs", b"one\ntwo\n");
7150
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7151
    let wc = repo.working_copy().unwrap().0;
7152
    // A saved revset is checked when set.
7153
    repo.set_user_config("revset.mine", "author(me) & ::main")
7154
        .unwrap();
7155
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7156
    let set = |src: &str| -> Vec<ChangeHash> {
7157
        let mut v = repo.revset(src).unwrap().hashes;
7158
        v.sort();
7159
        v
7160
    };
7161
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7162
        let mut v = hs.to_vec();
7163
        v.sort();
7164
        v
7165
    };
7166
7167
    // Changes commute: a new file depends on nothing and the rename on the
7168
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7169
    // copy on the three heads b, c, d.
7170
    let heads = sorted(&repo.bookmark_heads().unwrap());
7171
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7172
    assert!(heads.contains(&d) && heads.contains(&c));
7173
    // Symbols and closures.
7174
    assert_eq!(set("main"), heads);
7175
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7176
    assert_eq!(set("@"), vec![wc]);
7177
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7178
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7179
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7180
    assert_eq!(
7181
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7182
        sorted(&[a, b])
7183
    );
7184
    // Ranges: what main has beyond b, and `..` forms.
7185
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7186
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7187
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7188
    // Operators and precedence: ~ binds tighter than &, & than |.
7189
    assert_eq!(
7190
        set(&format!("::main ~ #{}", d.short(12))),
7191
        sorted(&[a, b, c])
7192
    );
7193
    assert_eq!(
7194
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7195
        sorted(&[b, c])
7196
    );
7197
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7198
    // Relations.
7199
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7200
    head_deps.sort();
7201
    head_deps.dedup();
7202
    assert_eq!(set("deps(main)"), head_deps);
7203
    let on_a: Vec<ChangeHash> = [b, c, d]
7204
        .into_iter()
7205
        .filter(|h| meta(h).deps.contains(&a))
7206
        .collect();
7207
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7208
    assert_eq!(set("heads(::main)"), heads);
7209
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7210
    assert_eq!(
7211
        set(&format!(
7212
            "heads(#{} | #{} | #{})",
7213
            a.short(12),
7214
            b.short(12),
7215
            c.short(12)
7216
        )),
7217
        sorted(&[b, c])
7218
    );
7219
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7220
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7221
    assert_eq!(set("none()"), vec![]);
7222
    // Predicates: author by name, email, key prefix and `me`.
7223
    let key = repo.config.author_key.unwrap();
7224
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7225
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7226
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7227
    assert_eq!(set("author(me) & ::main").len(), 4);
7228
    assert_eq!(set("author(nobody)"), vec![]);
7229
    assert_eq!(set("description(notes)"), vec![c]);
7230
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7231
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7232
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7233
    // touches follows the node through the rename, in the current state.
7234
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7235
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7236
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7237
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7238
    // Newest first in the result order.
7239
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7240
    // The saved revset, and errors that say what is wrong.
7241
    assert_eq!(set("mine()").len(), 4);
7242
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7243
    assert!(e.contains("unknown function nosuch()"), "{e}");
7244
    let e = repo.revset("main &").unwrap_err().to_string();
7245
    assert!(e.contains("at character"), "{e}");
7246
    let e = repo.revset("zzzz").unwrap_err().to_string();
7247
    assert!(e.contains("no change matches"), "{e}");
7248
    let e = repo
7249
        .revset_with_budget("::main", std::time::Duration::ZERO)
7250
        .unwrap_err()
7251
        .to_string();
7252
    assert!(e.contains("budget"), "{e}");
7253
    // The log entries carry the bookmark's heads and the working copy.
7254
    let entries = repo.log_revset("::@").unwrap();
7255
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
2c9ddac3 Andy McCall ↶ 7256
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7257
    // push); then a signed change, a tag, and a revocation.
7258
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7259
    assert_eq!(set("signed_by(me)"), vec![]);
7260
    repo.sign_change(&d).unwrap();
7261
    assert_eq!(set("signed_by(me)"), vec![d]);
7262
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7263
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7264
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7265
    assert_eq!(set("delegated()"), vec![]);
7266
    assert_eq!(set("revoked()"), vec![]);
7267
    assert_eq!(set("attested(tag)"), vec![]);
7268
    repo.tag_create("v1", &[b], "first").unwrap();
7269
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7270
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7271
    assert_eq!(set("attested(receipt)"), vec![]);
7272
    assert_eq!(set("built(test)"), vec![]);
7273
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7274
    assert!(e.contains("tag, receipt or ref"), "{e}");
7275
    repo.revoke_identity(&key, "test").unwrap();
7276
    assert_eq!(set("revoked()"), vec![d]);
7277
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
543bbf64 Andy McCall ↶ 7278
    // independent(X, IN): what could ship without X. c and d neither
7279
    // depend on b nor are depended on by it; a is below, the working copy
7280
    // above.
7281
    assert_eq!(
7282
        set(&format!("independent(#{}, ::@)", b.short(12))),
7283
        sorted(&[c, d])
7284
    );
7285
    assert_eq!(
7286
        set(&format!("independent(#{}, ::main)", a.short(12))),
7287
        vec![c]
7288
    );
7289
    // conflicts(S): nothing conflicts yet; then two edits of one line.
7290
    assert_eq!(set("conflicts()"), vec![]);
7291
    assert_eq!(set("conflicts(main)"), vec![]);
7292
    // (The saved revset above edited the user config under the root:
7293
    // discard it.)
7294
    repo.checkout(&[a], true, "checkout a").unwrap();
7295
    write(root, "src/a.rs", b"one\nTWO\n");
7296
    let e = repo
7297
        .commit("fifth: the other edit of line two", &[])
7298
        .unwrap();
7299
    repo.checkout(&repo.bookmark_heads().unwrap(), true, "checkout main")
7300
        .unwrap();
7301
    let conflicted = repo.revset("conflicts()").unwrap().hashes;
7302
    assert!(
7303
        conflicted.contains(&e) && conflicted.contains(&b),
7304
        "{conflicted:?} should hold b and e"
7305
    );
7306
    assert!(!conflicted.contains(&c));
7307
    assert_eq!(set("conflicts() & author(nobody)"), vec![]);
47ce8b8e Andy McCall ↶ 7308
}
614f55e1 Andy McCall ↶ 7309
7310
#[test]
7311
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7312
    let dir = tempfile::tempdir().unwrap();
7313
    let root = dir.path();
7314
    let home = root.join("home");
7315
    // Ada's identity lives in the user file; repository `a` pins the same
7316
    // key in its own file, repository `b` names none.
7317
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7318
    let (key, _) = a
7319
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7320
        .unwrap();
7321
    a.config.set("author.key", &key.to_hex()).unwrap();
7322
    a.save_config().unwrap();
7323
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7324
    let r = a
7325
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7326
        .unwrap();
7327
    assert_eq!(
7328
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7329
        r.new.to_hex(),
7330
        "the user file follows"
7331
    );
7332
    assert_eq!(
7333
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7334
        r.new.to_hex(),
7335
        "the pinning repository follows"
7336
    );
7337
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7338
    assert_eq!(
7339
        b.config.author_key,
7340
        Some(r.new),
7341
        "a checkout without a pin follows the user file"
7342
    );
7343
    // A repository-scoped identity leaves the user file alone.
7344
    let other_home = root.join("home2");
7345
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7346
    let (ck, _) = c
7347
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7348
        .unwrap();
7349
    assert!(!other_home.join("config.toml").exists());
7350
    let r2 = c.rotate_identity().unwrap();
7351
    assert_ne!(r2.new, ck);
7352
    assert_eq!(
7353
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7354
        r2.new.to_hex()
7355
    );
7356
    assert!(
7357
        !other_home.join("config.toml").exists(),
7358
        "a repository-scoped identity stays repository-scoped"
7359
    );
7360
    // Several delegates in one rotation; a repeat is refused.
7361
    let (d1, d2) = (
7362
        SecretKey::generate().identity("D1", "d1@x", 1),
7363
        SecretKey::generate().identity("D2", "d2@x", 1),
7364
    );
7365
    let r3 = c
7366
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7367
        .unwrap();
7368
    assert_eq!(r3.identity.delegates.len(), 2);
7369
    assert!(c
7370
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7371
        .is_err());
7372
}
33be2409 Andy McCall ↶ 7373
7374
/// Two unrelated histories that both add the same file, joined by two
7375
/// independent merges on two branches, then those branches merged: Git
7376
/// merges identical additions cleanly, and the import must too (#71,
7377
/// found in VS Code's history).
7378
#[test]
7379
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7380
    // Batches of one: every merge renders apart from the state, where a
7381
    // file whose graph the state had built came out empty (#71).
7382
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7383
    hermetic();
7384
    if std::process::Command::new("git")
7385
        .arg("--version")
7386
        .output()
7387
        .is_err()
7388
    {
7389
        eprintln!("git not installed; skipping");
7390
        return;
7391
    }
7392
    let dir = tempfile::tempdir().unwrap();
7393
    let root = dir.path();
7394
    let g = root.join("src.git");
7395
    fs::create_dir_all(&g).unwrap();
7396
    let git = |args: &[&str]| -> String {
7397
        let out = std::process::Command::new("git")
7398
            .arg("-C")
7399
            .arg(&g)
7400
            .args([
7401
                "-c",
7402
                "user.name=Grace",
7403
                "-c",
7404
                "[email protected]",
7405
                "-c",
7406
                "commit.gpgsign=false",
7407
            ])
7408
            .args(args)
7409
            .output()
7410
            .unwrap();
7411
        assert!(
7412
            out.status.success(),
7413
            "git {args:?}: {}",
7414
            String::from_utf8_lossy(&out.stderr)
7415
        );
7416
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7417
    };
7418
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7419
    // History A: main.
7420
    git(&["init", "-q", "-b", "main"]);
7421
    write(&g, "gulpfile.js", text);
7422
    write(&g, "a.txt", b"a\n");
7423
    git(&["add", "."]);
7424
    git(&["commit", "-q", "-m", "A root"]);
7425
    // History B: an unrelated root adding the same file, identical.
7426
    git(&["checkout", "-q", "--orphan", "fork"]);
7427
    git(&["rm", "-q", "-r", "--cached", "."]);
7428
    for f in ["gulpfile.js", "a.txt"] {
7429
        let _ = fs::remove_file(g.join(f));
7430
    }
7431
    write(&g, "gulpfile.js", text);
7432
    write(&g, "b.txt", b"b\n");
7433
    git(&["add", "."]);
7434
    git(&["commit", "-q", "-m", "B root"]);
7435
    // Two branches from main, each joining B on its own.
7436
    git(&["checkout", "-q", "-b", "one", "main"]);
7437
    git(&[
7438
        "merge",
7439
        "-q",
7440
        "--no-ff",
7441
        "--allow-unrelated-histories",
7442
        "-m",
7443
        "join on one",
7444
        "fork",
7445
    ]);
7446
    git(&["checkout", "-q", "-b", "two", "main"]);
7447
    write(&g, "a.txt", b"a\ntwo\n");
7448
    git(&["commit", "-q", "-am", "work on two"]);
7449
    git(&[
7450
        "merge",
7451
        "-q",
7452
        "--no-ff",
7453
        "--allow-unrelated-histories",
7454
        "-m",
7455
        "join on two",
7456
        "fork",
7457
    ]);
7458
    // Then the two joins meet, and the file is reformatted after.
7459
    git(&["checkout", "-q", "main"]);
7460
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7461
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7462
    write(
7463
        &g,
7464
        "gulpfile.js",
7465
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7466
    );
7467
    git(&["commit", "-q", "-am", "after"]);
7468
7469
    let dest = root.join("dest");
7470
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7471
    repo.import_git(&g, "main").unwrap();
7472
    let v = repo.verify_git_import(&g, "main").unwrap();
7473
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7474
    assert_eq!(
7475
        fs::read(dest.join("gulpfile.js")).unwrap(),
7476
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7477
    );
7478
}
7479
7480
/// As above, but the two joins keep different copies (each branch had a
7481
/// different version when it joined), and later work edits each copy:
7482
/// the shape of VS Code's c67ef57cda90 (#71).
7483
#[test]
7484
fn git_import_joins_where_each_join_kept_a_different_copy() {
7485
    // Batches of one: every merge renders apart from the state, where a
7486
    // file whose graph the state had built came out empty (#71).
7487
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7488
    hermetic();
7489
    if std::process::Command::new("git")
7490
        .arg("--version")
7491
        .output()
7492
        .is_err()
7493
    {
7494
        eprintln!("git not installed; skipping");
7495
        return;
7496
    }
7497
    let dir = tempfile::tempdir().unwrap();
7498
    let root = dir.path();
7499
    let g = root.join("src.git");
7500
    fs::create_dir_all(&g).unwrap();
7501
    let run = |args: &[&str]| {
7502
        std::process::Command::new("git")
7503
            .arg("-C")
7504
            .arg(&g)
7505
            .args([
7506
                "-c",
7507
                "user.name=Grace",
7508
                "-c",
7509
                "[email protected]",
7510
                "-c",
7511
                "commit.gpgsign=false",
7512
            ])
7513
            .args(args)
7514
            .output()
7515
            .unwrap()
7516
    };
7517
    let git = |args: &[&str]| -> String {
7518
        let out = run(args);
7519
        assert!(
7520
            out.status.success(),
7521
            "git {args:?}: {}",
7522
            String::from_utf8_lossy(&out.stderr)
7523
        );
7524
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7525
    };
7526
    git(&["init", "-q", "-b", "main"]);
7527
    write(
7528
        &g,
7529
        "gulpfile.js",
7530
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7531
    );
7532
    git(&["add", "."]);
7533
    git(&["commit", "-q", "-m", "A root"]);
7534
    write(
7535
        &g,
7536
        "gulpfile.js",
7537
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7538
    );
7539
    git(&["commit", "-q", "-am", "whitespace"]);
7540
    git(&["checkout", "-q", "--orphan", "fork"]);
7541
    git(&["rm", "-q", "-r", "--cached", "."]);
7542
    let _ = fs::remove_file(g.join("gulpfile.js"));
7543
    write(
7544
        &g,
7545
        "gulpfile.js",
7546
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7547
    );
7548
    git(&["add", "."]);
7549
    git(&["commit", "-q", "-m", "B root"]);
7550
    // Branch one joins B keeping main's copy; branch two keeps B's.
7551
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7552
        git(&["checkout", "-q", "-b", branch, "main"]);
7553
        let _ = run(&[
7554
            "merge",
7555
            "-q",
7556
            "--no-ff",
7557
            "--allow-unrelated-histories",
7558
            "-m",
7559
            "join",
7560
            "fork",
7561
        ]);
7562
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7563
        git(&["add", "gulpfile.js"]);
7564
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7565
    }
7566
    // Each branch then edits its copy.
7567
    git(&["checkout", "-q", "one"]);
7568
    write(
7569
        &g,
7570
        "gulpfile.js",
7571
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7572
    );
7573
    git(&["commit", "-q", "-am", "tslint on one"]);
7574
    git(&["checkout", "-q", "two"]);
7575
    write(
7576
        &g,
7577
        "gulpfile.js",
7578
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7579
    );
7580
    write(&g, "extra.txt", b"x\n");
7581
    write(&g, "more.txt", b"m\n");
7582
    git(&["add", "."]);
7583
    git(&["commit", "-q", "-am", "fmt on two"]);
7584
    // They meet: resolved by hand.
7585
    git(&["checkout", "-q", "one"]);
7586
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7587
    write(
7588
        &g,
7589
        "gulpfile.js",
7590
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7591
    );
7592
    git(&["add", "gulpfile.js"]);
7593
    git(&["commit", "-q", "-m", "merge two into one"]);
7594
7595
    let dest = root.join("dest");
7596
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7597
    repo.import_git(&g, "one").unwrap();
7598
    let v = repo.verify_git_import(&g, "one").unwrap();
7599
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7600
}
dd21fd82 Andy McCall ↶ 7601
7602
/// oxygen#68: on a store that is not this disk's directory, the operation
7603
/// head is the store's reference record, moved by compare-and-swap. Two
7604
/// handles recording from the same head both get through, merged; a swap
7605
/// from a stale version is refused; a second repository cannot start on a
7606
/// store that already holds one.
7607
#[test]
7608
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
7609
    use crate::strata::{MemoryStore, Store as _};
7610
    let backend = std::sync::Arc::new(MemoryStore::new());
7611
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
7612
    let dir = tempfile::tempdir().unwrap();
7613
    let a = Repo::init(dir.path()).unwrap();
7614
    assert!(
7615
        !dir.path().join(".oxy/ops/head").exists(),
7616
        "the head is not a file"
7617
    );
7618
    let (h0, op0) = a.head_op().unwrap();
7619
    let record = backend
7620
        .read_ref(HEAD_RECORD)
7621
        .unwrap()
7622
        .expect("the head is the store's record");
7623
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
7624
7625
    let b = Repo::open(dir.path()).unwrap();
7626
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
7627
    let mut va = op0.view.clone();
7628
    va.bookmarks.insert("from-a".into(), state);
7629
    let mut vb = op0.view.clone();
7630
    vb.bookmarks.insert("from-b".into(), state);
7631
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
7632
    assert_eq!(b.head_ref().unwrap(), rb);
7633
    // a recorded from h0 too: the head moved, so the two are merged.
7634
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
7635
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
7636
    assert_eq!(head, ra);
7637
    assert!(
7638
        op.command.ends_with("(merged with a concurrent operation)"),
7639
        "{}",
7640
        op.command
7641
    );
7642
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
7643
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
7644
7645
    // A swap from a version that is no longer current moves nothing.
7646
    let (h, v) = a.read_head().unwrap();
7647
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
7648
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
7649
    assert_eq!(a.head_ref().unwrap(), rb);
7650
7651
    let other = tempfile::tempdir().unwrap();
7652
    let err = Repo::init(other.path())
7653
        .err()
7654
        .expect("the store already holds a log")
7655
        .to_string();
7656
    assert!(
7657
        err.contains("already holds a repository's operation log"),
7658
        "{err}"
7659
    );
7660
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
7661
}
d069701a Andy McCall ↶ 7662
7663
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
7664
/// objects and operation head there, with `.oxy/cache` in front: it works
7665
/// as one on disk does, reopens, and survives losing its cache.
7666
#[test]
7667
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
7668
    hermetic();
7669
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
7670
        return;
7671
    }
7672
    let dir = tempfile::tempdir().unwrap();
7673
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
7674
    let url = format!("dir://{}", bucket.display());
7675
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
7676
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
7677
    write(&root, "a.txt", b"one\n");
7678
    let h1 = repo.commit("First", &[]).unwrap();
7679
    write(&root, "a.txt", b"one\ntwo\n");
7680
    let h2 = repo.commit("Second", &[]).unwrap();
7681
    assert!(
7682
        !root.join(".oxy/ops/head").exists(),
7683
        "the head is in the store"
7684
    );
7685
    assert!(bucket.join("ops/head").is_file());
7686
    assert!(root.join(".oxy/cache").is_dir());
7687
    drop(repo);
7688
7689
    // Reopened, and again with no cache at all: everything comes from the store.
7690
    for drop_cache in [false, true] {
7691
        if drop_cache {
7692
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
7693
        }
7694
        let repo = Repo::open(&root).unwrap();
7695
        let log: Vec<String> = repo
7696
            .op_log()
7697
            .unwrap()
7698
            .into_iter()
7699
            .map(|(_, op)| op.command)
7700
            .collect();
7701
        assert!(log.len() >= 3, "{log:?}");
7702
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
7703
        let heads = repo
7704
            .store()
7705
            .get_state(&repo.view().unwrap().bookmarks["main"])
7706
            .unwrap()
7707
            .heads;
7708
        assert_eq!(heads, vec![h2]);
7709
        assert_eq!(
7710
            repo.load_state(&heads).unwrap().materialize().files.len(),
7711
            1
7712
        );
7713
    }
7714
7715
    // A second repository cannot start on the same store.
7716
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
7717
        .err()
7718
        .unwrap()
7719
        .to_string();
7720
    assert!(
7721
        err.contains("already holds a repository's operation log"),
7722
        "{err}"
7723
    );
7724
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
7725
        .err()
7726
        .unwrap()
7727
        .to_string();
7728
    assert!(err.contains("cannot open that kind of store"), "{err}");
7729
}
80677b7a Andy McCall ↶ 7730
7731
/// oxygen#75: the prompt's quick check agrees with status in a repository
7732
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
7733
/// another state, clean again once that pin is committed. (It compared the
7734
/// subrepo's directory as if it were a file, so it was always dirty.)
7735
#[test]
7736
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
7737
    hermetic();
7738
    let dir = tempfile::tempdir().unwrap();
7739
    let root = dir.path();
7740
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7741
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7742
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7743
        .unwrap()
7744
        .with_home(root.join("home"));
7745
    write(&root.join("lib"), "lib.txt", b"v1\n");
7746
    lib.commit("lib v1", &[]).unwrap();
7747
    assert!(lib.push("origin", false).unwrap()[0].ok);
7748
    let app_dir = root.join("app");
7749
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7750
    write(&app_dir, "main.txt", b"app\n");
7751
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7752
    app.commit("app with lib", &[]).unwrap();
7753
    // Out of the racy window, so the stat-only path decides.
7754
    std::thread::sleep(std::time::Duration::from_millis(2100));
7755
    let reopen = || Repo::open(&app_dir).unwrap();
7756
    assert_eq!(
7757
        reopen().quick_dirty().unwrap(),
7758
        Some(false),
7759
        "clean, as status says"
7760
    );
7761
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
7762
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
7763
    nested.commit("lib v2", &[]).unwrap();
7764
    assert_eq!(
7765
        reopen().quick_dirty().unwrap(),
7766
        Some(true),
7767
        "the subrepo moved"
7768
    );
7769
    reopen().commit("pin lib v2", &[]).unwrap();
7770
    std::thread::sleep(std::time::Duration::from_millis(2100));
7771
    assert_eq!(
7772
        reopen().quick_dirty().unwrap(),
7773
        Some(false),
7774
        "the new pin is committed"
7775
    );
7776
}
7993d465 Andy McCall ↶ 7777
7778
#[test]
7779
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
7780
    // oxygen#72: a .oxymodules section with no subrepo behind it.
7781
    hermetic();
7782
    let dir = tempfile::tempdir().unwrap();
7783
    let root = dir.path();
7784
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7785
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7786
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7787
        .unwrap()
7788
        .with_home(root.join("home"));
7789
    write(&root.join("lib"), "lib.txt", b"v1\n");
7790
    lib.commit("lib v1", &[]).unwrap();
7791
    assert!(lib.push("origin", false).unwrap()[0].ok);
7792
    let app_dir = root.join("app");
7793
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7794
    write(
7795
        &app_dir,
7796
        ".oxymodules",
7797
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
7798
    );
7799
    let unpinned = app.unpinned_modules().unwrap();
7800
    assert_eq!(unpinned.len(), 1);
7801
    assert_eq!(unpinned[0].0, "libs/lib");
7802
    assert_eq!(unpinned[0].1.url, lib_url);
7803
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
7804
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7805
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
7806
}
bf3a6781 Andy McCall ↶ 7807
7808
#[test]
7809
fn the_bookmark_revset_function_names_only_bookmarks() {
7810
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
7811
    hermetic();
7812
    let dir = tempfile::tempdir().unwrap();
7813
    let repo = Repo::init(dir.path()).unwrap();
7814
    write(dir.path(), "a.txt", b"a\n");
7815
    let a = repo.commit("A", &[]).unwrap();
7816
    write(dir.path(), "b.txt", b"b\n");
7817
    let b = repo.commit("B", &[]).unwrap();
7818
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
7819
    heads.sort();
7820
    let mut want = repo.bookmark_heads().unwrap();
7821
    want.sort();
7822
    assert_eq!(heads, want);
7823
    assert!(heads.contains(&b));
7824
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
7825
    // A change prefix is a symbol, not a bookmark.
7826
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
7827
    assert!(repo.revset(&prefix).is_ok());
7828
    let e = repo
7829
        .revset(&format!("bookmark({prefix})"))
7830
        .unwrap_err()
7831
        .to_string();
7832
    assert!(e.contains("no such bookmark"), "{e}");
7833
}
72484195 Andy McCall ↶ 7834
7835
#[test]
7836
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
7837
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
7838
    // pinning the subrepo, and the nested repository on disk at that pin.
7839
    hermetic();
7840
    let dir = tempfile::tempdir().unwrap();
7841
    let root = dir.path();
7842
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
7843
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7844
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7845
        .unwrap()
7846
        .with_home(root.join("home"));
7847
    write(&root.join("lib"), "lib.txt", b"v1\n");
7848
    lib.commit("lib v1", &[]).unwrap();
7849
    assert!(lib.push("origin", false).unwrap()[0].ok);
7850
    let app_dir = root.join("app");
7851
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7852
    write(&app_dir, "main.txt", b"app\n");
7853
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7854
    // The stale state: registered in .oxymodules, never pinned.
7855
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
7856
    app.commit("initial", &[]).unwrap();
7857
    let stale = app.bookmark_heads().unwrap();
7858
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
7859
    app.commit("pin lib", &[]).unwrap();
7860
    let newer = app.bookmark_heads().unwrap();
7861
    app.checkout(&stale, false, "test").unwrap();
7862
    write(&app_dir, "notes.txt", b"mine\n");
7863
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
7864
    assert_eq!(carried, vec!["notes.txt".to_string()]);
7865
    assert!(app_dir.join("notes.txt").exists());
7866
}
7867
7868
#[test]
7869
fn a_bookmark_only_behind_its_remote_catches_up() {
7870
    // oxygen#74: switch takes the remote's state rather than a stale one.
7871
    hermetic();
7872
    let dir = tempfile::tempdir().unwrap();
7873
    let root = dir.path();
7874
    let _origin = Repo::init(&root.join("origin")).unwrap();
7875
    let url = root.join("origin").to_string_lossy().to_string();
7876
    let one = Repo::clone(&url, &root.join("one"))
7877
        .unwrap()
7878
        .with_home(root.join("home"));
7879
    write(&root.join("one"), "a.txt", b"a\n");
7880
    one.commit("A", &[]).unwrap();
7881
    assert!(one.push("origin", false).unwrap()[0].ok);
7882
    let two = Repo::clone(&url, &root.join("two"))
7883
        .unwrap()
7884
        .with_home(root.join("home"));
7885
    write(&root.join("two"), "b.txt", b"b\n");
7886
    two.commit("B", &[]).unwrap();
7887
    assert!(two.push("origin", false).unwrap()[0].ok);
7888
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
7889
    one.fetch("origin").unwrap();
7890
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
7891
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
7892
    // Local work the remote lacks: left alone.
7893
    write(&root.join("one"), "c.txt", b"c\n");
7894
    one.commit("C", &[]).unwrap();
7895
    write(&root.join("two"), "d.txt", b"d\n");
7896
    two.commit("D", &[]).unwrap();
7897
    assert!(two.push("origin", false).unwrap()[0].ok);
7898
    one.fetch("origin").unwrap();
7899
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
7900
}
42ccf504 Andy McCall ↶ 7901
7902
#[test]
7903
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
7904
    // oxygen#83: remotes earth and gcs, origin removed.
7905
    hermetic();
7906
    let dir = tempfile::tempdir().unwrap();
7907
    let root = dir.path();
7908
    let _up = Repo::init(&root.join("up")).unwrap();
7909
    let url = root.join("up").to_string_lossy().to_string();
7910
    let other = Repo::clone(&url, &root.join("other"))
7911
        .unwrap()
7912
        .with_home(root.join("home"));
7913
    write(&root.join("other"), "a.txt", b"a\n");
7914
    other.commit("a", &[]).unwrap();
7915
    assert!(other.push("origin", false).unwrap()[0].ok);
7916
    let mut one = Repo::clone(&url, &root.join("one"))
7917
        .unwrap()
7918
        .with_home(root.join("home"));
7919
    one.config.set("remote.earth.url", &url).unwrap();
7920
    one.config.set("remote.gcs.url", &url).unwrap();
7921
    one.config.set("remote.origin.url", "").unwrap();
7922
    one.save_config().unwrap();
7923
    write(&root.join("other"), "b.txt", b"b\n");
7924
    other.commit("b", &[]).unwrap();
7925
    assert!(other.push("origin", false).unwrap()[0].ok);
7926
    one.fetch("earth").unwrap();
7927
    let b = one
7928
        .bookmarks()
7929
        .unwrap()
7930
        .into_iter()
7931
        .find(|b| b.name == "main")
7932
        .unwrap();
7933
    assert_eq!(
7934
        (b.remote.as_deref(), b.behind),
7935
        (Some("earth"), Some(1)),
7936
        "a stale origin copy is not used"
7937
    );
7938
    assert_eq!(
7939
        one.default_remote(),
7940
        "origin",
7941
        "no default chosen among several"
7942
    );
7943
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
7944
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
7945
    one.config.set("core.remote", "earth").unwrap();
7946
    assert_eq!(one.default_remote(), "earth");
7947
}
cbe8499a Andy McCall ↶ 7948
7949
#[test]
7950
fn a_missing_author_identity_says_how_to_fix_it() {
7951
    // oxygen#82: an agent home's author.key naming an identity the
7952
    // repository does not hold.
7953
    hermetic();
7954
    let dir = tempfile::tempdir().unwrap();
7955
    let mut repo = Repo::init(dir.path()).unwrap();
7956
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
7957
    repo.config.set("author.key", &missing.to_hex()).unwrap();
7958
    let e = repo.identity(&missing).unwrap_err().to_string();
7959
    assert!(
7960
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
7961
        "{e}"
7962
    );
7963
    assert!(e.contains("this repository's config"), "{e}");
7964
}
f6dccc45 Andy McCall ↶ 7965
7966
#[test]
7967
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
7968
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
7969
    // the working copy, a pull with nothing new left it there, and status
7970
    // said "clean".
7971
    hermetic();
7972
    let dir = tempfile::tempdir().unwrap();
7973
    let root = dir.path();
7974
    let _up = Repo::init(&root.join("up")).unwrap();
7975
    let url = root.join("up").to_string_lossy().to_string();
7976
    let other = Repo::clone(&url, &root.join("other"))
7977
        .unwrap()
7978
        .with_home(root.join("home"));
7979
    write(&root.join("other"), "a.txt", b"a\n");
7980
    other.commit("a", &[]).unwrap();
7981
    assert!(other.push("origin", false).unwrap()[0].ok);
7982
    let one = Repo::clone(&url, &root.join("one"))
7983
        .unwrap()
7984
        .with_home(root.join("home"));
7985
    write(&root.join("other"), "b.txt", b"b\n");
7986
    other.commit("b", &[]).unwrap();
7987
    assert!(other.push("origin", false).unwrap()[0].ok);
7988
    one.fetch("origin").unwrap();
7989
    // The bookmark moves; the working copy does not.
7990
    let theirs = one.resolve_heads("origin/main").unwrap();
7991
    one.bookmark_set("main", &theirs).unwrap();
7992
    assert!(!root.join("one/b.txt").exists());
7993
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
7994
    let r = one.pull("origin").unwrap();
7995
    assert!(
7996
        !r.changed && r.checked_out,
7997
        "nothing new, but the working copy caught up"
7998
    );
7999
    assert!(root.join("one/b.txt").exists());
8000
    assert_eq!(one.working_copy_behind().unwrap(), None);
8001
}
170bb436 Andy McCall ↶ 8002
8003
#[test]
8004
fn touched_nodes_cache_answers_as_the_changes_do() {
8005
    hermetic();
8006
    let dir = tempfile::tempdir().unwrap();
8007
    let repo = Repo::init(dir.path()).unwrap();
8008
    write(dir.path(), "a.txt", b"one\n");
8009
    write(dir.path(), "b.txt", b"x\n");
8010
    repo.snapshot("t").unwrap();
8011
    let c1 = repo.commit("first", &[]).unwrap();
8012
    write(dir.path(), "b.txt", b"y\n");
8013
    repo.snapshot("t").unwrap();
8014
    repo.commit("b only", &[]).unwrap();
8015
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8016
    write(dir.path(), "c.txt", b"one\ntwo\n");
8017
    repo.snapshot("t").unwrap();
8018
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8019
    // Uncommitted work, so the working copy touches a file too.
8020
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8021
    repo.snapshot("t").unwrap();
8022
8023
    let path = dir.path().join(".oxy/index/touched");
8024
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8025
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8026
    assert!(path.exists(), "the first query writes the cache");
8027
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8028
    assert_eq!(cold, warm, "the cache answers as the changes do");
8029
    let (wc, _) = repo.working_copy().unwrap();
8030
    assert_eq!(
8031
        cold,
8032
        vec![wc, c3, c1],
8033
        "renames followed, the working copy included"
8034
    );
8035
8036
    // Working-copy changes are not kept: they are replaced by every snapshot.
8037
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8038
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8039
    assert!(cached.contains(&c1) && cached.contains(&c3));
8040
8041
    // A damaged cache is ignored, not trusted.
8042
    let mut bytes = fs::read(&path).unwrap();
8043
    let last = bytes.len() - 40;
8044
    bytes[last] ^= 1;
8045
    fs::write(&path, &bytes).unwrap();
8046
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8047
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8048
    assert_eq!(hashes(touches), vec![c3, c1]);
8049
}
e8e6e0ca Andy McCall ↶ 8050
8051
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8052
/// file back where it was leave two placements at one place, which the
8053
/// tree shows as one file. Removing it, and then its directory, retires
8054
/// both, so no copy is left under a directory that is gone.
8055
#[test]
8056
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8057
    hermetic();
8058
    if std::process::Command::new("git")
8059
        .arg("--version")
8060
        .output()
8061
        .is_err()
8062
    {
8063
        eprintln!("git not installed; skipping");
8064
        return;
8065
    }
8066
    let dir = tempfile::tempdir().unwrap();
8067
    let root = dir.path();
8068
    let g = root.join("src.git");
8069
    fs::create_dir_all(&g).unwrap();
8070
    let git = |args: &[&str]| {
8071
        let out = std::process::Command::new("git")
8072
            .arg("-C")
8073
            .arg(&g)
8074
            .args([
8075
                "-c",
8076
                "user.name=Grace",
8077
                "-c",
8078
                "[email protected]",
8079
                "-c",
8080
                "commit.gpgsign=false",
8081
            ])
8082
            .args(args)
8083
            .output()
8084
            .unwrap();
8085
        assert!(
8086
            out.status.success(),
8087
            "git {args:?}: {}",
8088
            String::from_utf8_lossy(&out.stderr)
8089
        );
8090
    };
8091
    git(&["init", "-q", "-b", "main"]);
8092
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8093
    write(&g, "keep.txt", b"k\n");
8094
    git(&["add", "."]);
8095
    git(&["commit", "-qm", "base"]);
8096
    fs::create_dir_all(g.join("d/sub")).unwrap();
8097
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8098
    git(&["commit", "-qm", "into sub"]);
8099
    git(&["checkout", "-qb", "side"]);
8100
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8101
    git(&["commit", "-qm", "back, on side"]);
8102
    git(&["checkout", "-q", "main"]);
8103
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8104
    git(&["commit", "-qm", "back, on main"]);
8105
    git(&["merge", "-q", "--no-edit", "side"]);
8106
    git(&["rm", "-rq", "d"]);
8107
    git(&["commit", "-qm", "d goes"]);
8108
8109
    let repo = Repo::init(&root.join("o")).unwrap();
8110
    repo.import_git(&g, "main").unwrap();
8111
    let v = repo.verify_git_import(&g, "main").unwrap();
8112
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8113
    let st = repo
8114
        .load_state_history(&repo.bookmark_heads().unwrap())
8115
        .unwrap();
8116
    let view = st.tree().view();
8117
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8118
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8119
}
5552e69c Andy McCall ↶ 8120
8121
/// oxygen#94: a state index's file histories are read, and checked by
8122
/// their own hashes, only when a file is built. One found damaged is an
8123
/// error that says so, the index is removed, and the next read rebuilds it.
8124
#[test]
8125
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8126
    hermetic();
8127
    let dir = tempfile::tempdir().unwrap();
8128
    let repo = Repo::init(dir.path()).unwrap();
8129
    for i in 0..6 {
8130
        write(
8131
            dir.path(),
8132
            &format!("f{i}.txt"),
8133
            format!("one {i}\n").as_bytes(),
8134
        );
8135
    }
8136
    repo.snapshot("t").unwrap();
8137
    repo.commit("first", &[]).unwrap();
8138
    for i in 0..6 {
8139
        write(
8140
            dir.path(),
8141
            &format!("f{i}.txt"),
8142
            format!("one {i}\ntwo\n").as_bytes(),
8143
        );
8144
    }
8145
    repo.snapshot("t").unwrap();
8146
    repo.commit("second", &[]).unwrap();
8147
    let want: Vec<Vec<u8>> = (0..6)
8148
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8149
        .collect();
8150
    // The index of the working copy's base, holding every file's history
8151
    // (a few changes behind, an index is replayed onto, not rewritten).
8152
    let (_, wc) = repo.working_copy().unwrap();
8153
    let base = repo.load_state_history(&wc.deps).unwrap();
8154
    repo.write_state_index(&wc.deps, &base);
8155
    for (i, w) in want.iter().enumerate() {
8156
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8157
    }
8158
    let index = repo.state_indexes();
8159
    assert!(!index.is_empty(), "a state index was written");
8160
    // The histories are last in the file: damage the last of them.
8161
    let mut bytes = fs::read(&index[0]).unwrap();
8162
    let last = bytes.len() - 1;
8163
    bytes[last] ^= 0x40;
8164
    fs::write(&index[0], &bytes).unwrap();
8165
8166
    let reads: Vec<_> = (0..6)
8167
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8168
        .collect();
8169
    let damaged: Vec<String> = reads
8170
        .iter()
8171
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8172
        .collect();
8173
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8174
    assert!(
8175
        damaged[0].contains("state index was damaged")
8176
            && damaged[0].contains("run the command again"),
8177
        "{}",
8178
        damaged[0]
8179
    );
8180
    // Every file reads right again, from an index rebuilt from history.
8181
    for (i, w) in want.iter().enumerate() {
8182
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8183
    }
8184
}
cb8b8082 Andy McCall ↶ 8185
8186
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8187
/// objects alone and in dependency order, and the last moves the bookmark.
8188
/// The remote ends with every change and the same state, and says how each
8189
/// part went.
8190
#[test]
8191
fn a_long_push_goes_in_parts() {
8192
    hermetic();
8193
    let dir = tempfile::tempdir().unwrap();
8194
    let root = dir.path();
8195
    let origin = root.join("origin");
8196
    Repo::init_bare_unbound(&origin).unwrap();
8197
    let main = root.join("main");
8198
    let mut repo = Repo::init(&main).unwrap();
8199
    repo.config
8200
        .set("remote.origin.url", &origin.to_string_lossy())
8201
        .unwrap();
8202
    // One byte: every change is a part of its own.
8203
    repo.config.set("push.batch-bytes", "1").unwrap();
8204
    repo.save_config().unwrap();
8205
    for i in 0..6 {
8206
        write(
8207
            &main,
8208
            &format!("f{i}.txt"),
8209
            format!("file {i}\n").as_bytes(),
8210
        );
8211
        repo.commit(&format!("c{i}"), &[]).unwrap();
8212
    }
8213
    let mut parts = Vec::new();
8214
    let results = repo
8215
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8216
        .unwrap();
8217
    assert!(
8218
        results.iter().any(|r| r.ok && r.name == "main"),
8219
        "{results:?}"
8220
    );
8221
    assert_eq!(parts.len(), 6, "{parts:?}");
8222
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8223
8224
    let remote = Repo::open(&origin).unwrap();
8225
    let heads = repo.bookmark_heads().unwrap();
8226
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8227
    assert_eq!(
8228
        remote.log_state(&heads).unwrap().len(),
8229
        repo.log_state(&heads).unwrap().len()
8230
    );
8231
    // A push of objects alone reports how it went, as `objects`.
8232
    let got = remote
8233
        .receive_push(Bundle::default(), vec![], None, vec![])
8234
        .unwrap();
8235
    assert_eq!(got.len(), 1);
8236
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8237
}
d6e0d5b8 Andy McCall ↶ 8238
8239
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8240
/// own commits (Git author email = its email, any case) with its key, and
8241
/// leaves anyone else's with the zero key; the history verifies as before.
8242
#[test]
8243
fn git_import_claims_your_own_commits() {
8244
    hermetic();
8245
    if std::process::Command::new("git")
8246
        .arg("--version")
8247
        .output()
8248
        .is_err()
8249
    {
8250
        eprintln!("git not installed; skipping");
8251
        return;
8252
    }
8253
    let dir = tempfile::tempdir().unwrap();
8254
    let root = dir.path();
8255
    let g = root.join("src.git");
8256
    fs::create_dir_all(&g).unwrap();
8257
    let git = |who: &str, args: &[&str]| {
8258
        let (name, email) = who.split_once(' ').unwrap();
8259
        let out = std::process::Command::new("git")
8260
            .arg("-C")
8261
            .arg(&g)
8262
            .args([
8263
                "-c",
8264
                &format!("user.name={name}"),
8265
                "-c",
8266
                &format!("user.email={email}"),
8267
                "-c",
8268
                "commit.gpgsign=false",
8269
            ])
8270
            .args(args)
8271
            .output()
8272
            .unwrap();
8273
        assert!(
8274
            out.status.success(),
8275
            "git {args:?}: {}",
8276
            String::from_utf8_lossy(&out.stderr)
8277
        );
8278
    };
8279
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8280
    write(&g, "a.txt", b"a\n");
8281
    git("Grace [email protected]", &["add", "."]);
8282
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8283
    write(&g, "b.txt", b"b\n");
8284
    git("Ada [email protected]", &["add", "."]);
8285
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8286
8287
    let mut repo = Repo::init(&root.join("o")).unwrap();
8288
    let (key, _) = repo
8289
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8290
        .unwrap();
8291
    repo.config.set("git.claim", "true").unwrap();
8292
    repo.save_config().unwrap();
8293
    let repo = Repo::open(&root.join("o")).unwrap();
8294
    repo.import_git(&g, "main").unwrap();
8295
    let v = repo.verify_git_import(&g, "main").unwrap();
8296
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8297
    let heads = repo.bookmark_heads().unwrap();
8298
    let by_message: std::collections::HashMap<String, KeyId> = repo
8299
        .log_state(&heads)
8300
        .unwrap()
8301
        .into_iter()
8302
        .map(|e| {
8303
            (
8304
                e.change.message.lines().next().unwrap_or("").to_string(),
8305
                e.change.author,
8306
            )
8307
        })
8308
        .collect();
8309
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8310
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8311
}
34fad4a9 Andy McCall ↶ 8312
8313
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8314
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8315
#[test]
8316
fn removing_a_remote_leaves_nothing_of_it() {
8317
    hermetic();
8318
    let dir = tempfile::tempdir().unwrap();
8319
    let origin = dir.path().join("origin");
8320
    Repo::init_bare_unbound(&origin).unwrap();
8321
    let main = dir.path().join("main");
8322
    let mut repo = Repo::init(&main).unwrap();
8323
    repo.config
8324
        .set("remote.origin.url", &origin.to_string_lossy())
8325
        .unwrap();
8326
    repo.config
8327
        .set("remote.origin.token", "secret-ish")
8328
        .unwrap();
8329
    repo.config
8330
        .set("remote.keep.url", &origin.to_string_lossy())
8331
        .unwrap();
8332
    repo.save_config().unwrap();
8333
    write(&main, "a.txt", b"a\n");
8334
    repo.commit("a", &[]).unwrap();
8335
    assert!(repo.push("origin", false).unwrap()[0].ok);
8336
    assert!(
8337
        repo.view().unwrap().remotes.contains_key("origin"),
8338
        "a tracking bookmark"
8339
    );
8340
8341
    repo.remove_remote("origin").unwrap();
8342
    let again = Repo::open(&main).unwrap();
8343
    assert!(
8344
        !again
8345
            .config
8346
            .repo_layer()
8347
            .keys()
8348
            .any(|k| k.starts_with("remote.origin.")),
8349
        "{:?}",
8350
        again.config.repo_layer()
8351
    );
8352
    assert!(!again.config.remotes.contains_key("origin"));
8353
    assert!(
8354
        !again.view().unwrap().remotes.contains_key("origin"),
8355
        "its tracking bookmarks go"
8356
    );
8357
    assert!(
8358
        again.config.remotes.contains_key("keep"),
8359
        "another remote stays"
8360
    );
8361
    let mut again = again;
8362
    assert!(
8363
        again.remove_remote("origin").is_err(),
8364
        "a second removal is refused"
8365
    );
8366
}
9d580f21 Andy McCall ↶ 8367
8368
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
8369
/// unreachable from history, so gc prunes it, unless the host names it:
8370
/// then it and its chunks stay, and it reads back whole.
8371
#[test]
8372
fn gc_keeps_the_blobs_a_host_names() {
8373
    hermetic();
8374
    let dir = tempfile::tempdir().unwrap();
8375
    let repo = Repo::init(dir.path()).unwrap();
8376
    write(dir.path(), "a.txt", b"a\n");
8377
    repo.commit("a", &[]).unwrap();
8378
    // Large enough to be several chunks.
8379
    let body: Vec<u8> = (0..400_000u32)
8380
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
8381
        .collect();
8382
    let kept = repo.store_blob(&body).unwrap();
8383
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
8384
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
8385
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
8386
    assert!(!repo.store().has(&lost), "not named: pruned");
8387
    repo.gc(true).unwrap();
8388
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
8389
}
530a0fc6 Andy McCall ↶ 8390
8391
/// oxygen#99: undo in one workspace undoes that workspace's last command,
8392
/// never another workspace's, says what it undid, and goes further back
8393
/// when run again.
8394
#[test]
8395
fn undo_is_scoped_to_its_workspace() {
8396
    hermetic();
8397
    let dir = tempfile::tempdir().unwrap();
8398
    let root = dir.path().join("main");
8399
    let a = Repo::init(&root).unwrap();
8400
    write(&root, "base.txt", b"base\n");
8401
    let base = a.commit("base", &[]).unwrap();
8402
    a.bookmark_create("feature", None).unwrap();
8403
    let ws_dir = dir.path().join("ws");
8404
    let heads = a.resolve_heads("feature").unwrap();
8405
    let b = a
8406
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
8407
        .unwrap();
8408
8409
    // A commits on main, then B commits on feature: B's is the newest.
8410
    write(&root, "a.txt", b"a\n");
8411
    let ca = a.commit("from a", &[]).unwrap();
8412
    write(&ws_dir, "b.txt", b"b\n");
8413
    let cb = b.commit("from b", &[]).unwrap();
8414
8415
    // A's undo undoes A's commit and leaves B's.
8416
    let u = a.undo().unwrap();
8417
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8418
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
8419
    assert!(!u.changes.is_empty());
8420
    let view = a.view().unwrap();
8421
    // (Independent changes commute, so a bookmark's heads may hold base too.)
8422
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
8423
    assert!(
8424
        a.heads_of(&view, "feature").unwrap().contains(&cb),
8425
        "B's commit stands"
8426
    );
8427
    assert!(
8428
        a.store().get_change(&ca).is_ok(),
8429
        "the change itself is still in the store"
8430
    );
8431
    // A's working copy was clean, so its files followed; B's are untouched.
8432
    assert!(!root.join("a.txt").exists());
8433
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
8434
    assert!(ws_dir.join("b.txt").exists());
8435
8436
    // B's undo still finds B's own commit, under A's undo.
8437
    let u = b.undo().unwrap();
8438
    assert_eq!(u.command, "oxy commit -m \"from b\"");
8439
    assert!(!b
8440
        .heads_of(&b.view().unwrap(), "feature")
8441
        .unwrap()
8442
        .contains(&cb));
8443
    assert_eq!(
8444
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
8445
        vec![base],
8446
        "A's undo stands"
8447
    );
8448
8449
    // A's next undo goes past the commit it already undid, to adding B's
8450
    // workspace: refused, since B has worked there since.
8451
    let e = a.undo().unwrap_err().to_string();
8452
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
8453
}
8454
8455
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
8456
/// own commit's head, and the other workspace's head stays.
8457
#[test]
8458
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
8459
    hermetic();
8460
    let dir = tempfile::tempdir().unwrap();
8461
    let root = dir.path().join("main");
8462
    let a = Repo::init(&root).unwrap();
8463
    write(&root, "base.txt", b"base\n");
8464
    a.commit("base", &[]).unwrap();
8465
    let ws_dir = dir.path().join("ws");
8466
    let b = a.workspace_add(&ws_dir, None).unwrap();
8467
    write(&root, "a.txt", b"a\n");
8468
    let ca = a.commit("from a", &[]).unwrap();
8469
    write(&ws_dir, "b.txt", b"b\n");
8470
    let cb = b.commit("from b", &[]).unwrap();
8471
    let u = a.undo().unwrap();
8472
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8473
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
8474
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
8475
}
8476
8477
/// oxygen#99: an undo that would also take back what another workspace
8478
/// did since to the same bookmark is refused, naming it.
8479
#[test]
8480
fn undo_refuses_to_take_back_another_workspaces_work() {
8481
    hermetic();
8482
    let dir = tempfile::tempdir().unwrap();
8483
    let root = dir.path().join("main");
8484
    let a = Repo::init(&root).unwrap();
8485
    write(&root, "base.txt", b"base\n");
8486
    a.commit("base", &[]).unwrap();
8487
    let ws_dir = dir.path().join("ws");
8488
    let b = a.workspace_add(&ws_dir, None).unwrap();
8489
    // Both on main: A commits, then B builds on it, editing A's file.
8490
    write(&root, "a.txt", b"a\n");
8491
    a.commit("from a", &[]).unwrap();
8492
    let heads = b.resolve_heads("main").unwrap();
8493
    b.checkout(&heads, false, "oxy checkout").unwrap();
8494
    write(&ws_dir, "a.txt", b"a, then b\n");
8495
    b.commit("from b", &[]).unwrap();
8496
    let e = a.undo().unwrap_err().to_string();
8497
    assert!(
8498
        e.contains("bookmark main") && e.contains("builds on"),
8499
        "{e}"
8500
    );
8501
    assert!(e.contains("oxy op restore"), "{e}");
8502
}
8503
8504
/// oxygen#99: undoing a commit that was already pushed says so: the remote
8505
/// still has it.
8506
#[test]
8507
fn undo_says_when_the_commit_was_pushed() {
8508
    hermetic();
8509
    let dir = tempfile::tempdir().unwrap();
8510
    let root = dir.path();
8511
    Repo::init(&root.join("origin")).unwrap();
8512
    let url = root.join("origin").to_string_lossy().to_string();
8513
    let repo = Repo::clone(&url, &root.join("work"))
8514
        .unwrap()
8515
        .with_home(root.join("home"));
8516
    write(&root.join("work"), "a.txt", b"a\n");
8517
    repo.commit("a", &[]).unwrap();
8518
    assert!(repo.push("origin", false).unwrap()[0].ok);
8519
    // The push itself is passed over: the remote keeps what it was sent.
8520
    let u = repo.undo().unwrap();
8521
    assert_eq!(u.command, "oxy commit -m \"a\"");
8522
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
8523
}
b689779e Andy McCall ↶ 8524
8525
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
8526
/// out of the snapshot and named; tracked files and files already in the
8527
/// working copy are not.
8528
#[test]
8529
fn large_new_files_are_left_out_of_snapshots() {
8530
    hermetic();
8531
    let dir = tempfile::tempdir().unwrap();
8532
    let root = dir.path();
8533
    let mut repo = Repo::init(root).unwrap();
8534
    repo.config.max_new_file = 1024;
8535
    write(root, "small.txt", b"small\n");
8536
    write(root, "big.bin", &vec![0u8; 4096]);
8537
    let s = repo.snapshot("oxy status").unwrap();
8538
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8539
    assert_eq!(paths, ["small.txt"]);
8540
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
8541
    repo.commit("small", &[]).unwrap();
8542
8543
    // A tracked file may grow past the limit.
8544
    write(root, "small.txt", &vec![b'x'; 4096]);
8545
    let s = repo.snapshot("oxy status").unwrap();
8546
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
8547
    // With no limit the big file is taken in, and stays once it is.
8548
    repo.config.max_new_file = 0;
8549
    let s = repo.snapshot("oxy status").unwrap();
8550
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
8551
    repo.config.max_new_file = 1024;
8552
    let s = repo.snapshot("oxy status").unwrap();
8553
    assert!(
8554
        s.statuses.iter().any(|p| p.path == "big.bin"),
8555
        "already in the working copy"
8556
    );
8557
    assert!(repo.skipped_large().is_empty());
8558
}
8559
8560
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
8561
/// snapshots expire, and kept while they have not.
8562
#[test]
8563
fn gc_prunes_what_only_expired_snapshots_held() {
8564
    hermetic();
8565
    let dir = tempfile::tempdir().unwrap();
8566
    let root = dir.path();
8567
    let mut repo = Repo::init(root).unwrap();
8568
    repo.config.gc_grace_days = 0;
8569
    write(root, "a.txt", b"a\n");
8570
    repo.commit("a", &[]).unwrap();
8571
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
8572
    write(root, "image.tar", &image);
8573
    repo.snapshot("oxy status").unwrap();
8574
    std::fs::remove_file(root.join("image.tar")).unwrap();
8575
    repo.snapshot("oxy status").unwrap();
8576
    let blob = Repo::blob_ref(&image);
8577
    assert!(repo.store().has(&blob));
8578
    repo.gc(true).unwrap();
8579
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
8580
    repo.config.snapshot_retention_days = 0;
8581
    repo.gc(true).unwrap();
8582
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
8583
    assert_eq!(
8584
        repo.file_at("a.txt", None).unwrap(),
8585
        b"a\n",
8586
        "committed files stay"
8587
    );
fe9586d9 Andy McCall ↶ 8588
}
8589
8590
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
8591
/// already has is no conflict: the switch goes through, nothing is lost,
8592
/// and other carried work still comes along.
8593
#[test]
8594
fn carrying_work_the_target_already_has_is_no_conflict() {
8595
    hermetic();
8596
    let dir = tempfile::tempdir().unwrap();
8597
    let root = dir.path();
8598
    let mut repo = Repo::init(root).unwrap();
8599
    write(root, "a.txt", b"one\n");
8600
    write(root, "b.txt", b"b\n");
8601
    repo.commit("one", &[]).unwrap();
8602
    repo.bookmark_create("landed", None).unwrap();
8603
    // On landed, a.txt becomes "two" (as a proposal landing would).
8604
    repo.bookmark_switch("landed", false).unwrap();
8605
    write(root, "a.txt", b"two\n");
8606
    repo.commit("two", &[]).unwrap();
8607
    repo.bookmark_switch("main", false).unwrap();
8608
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
8609
    // The same edit, uncommitted, on main; and another edit besides.
8610
    write(root, "a.txt", b"two\n");
8611
    write(root, "b.txt", b"b, edited\n");
8612
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
8613
    assert_eq!(
8614
        carried,
8615
        vec!["b.txt".to_string()],
8616
        "only the work landed lacks is carried"
8617
    );
8618
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
8619
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
8620
    let s = repo.snapshot("oxy status").unwrap();
8621
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8622
    assert_eq!(paths, ["b.txt"]);
8623
8624
    // A real difference is still refused.
8625
    repo.bookmark_switch("main", true).unwrap();
8626
    write(root, "a.txt", b"three\n");
8627
    let e = repo
8628
        .bookmark_switch_carry("landed")
8629
        .unwrap_err()
8630
        .to_string();
8631
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
b689779e Andy McCall ↶ 8632
}
aa4939e0 Andy McCall ↶ 8633
8634
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
8635
/// resolves, so JSON output feeds back into commands.
8636
#[test]
8637
fn a_full_hash_resolves_without_its_hash_sign() {
8638
    hermetic();
8639
    let dir = tempfile::tempdir().unwrap();
8640
    let root = dir.path();
8641
    let repo = Repo::init(root).unwrap();
8642
    write(root, "a.txt", b"a\n");
8643
    let h = repo.commit("a", &[]).unwrap();
8644
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
8645
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
8646
    assert!(repo
8647
        .resolve_change(&"0".repeat(64))
8648
        .unwrap_err()
8649
        .to_string()
8650
        .contains("no change matches"));
8651
}