OXYGENHUB
◆ v0.4.6 oxygen / crates / oxy-core / src / repo / tests.rs
337.6 KiB · Rust · last changed Release 0.4.6: agents push as themselves 18 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
f0a517d2 Andy McCall ↶ 995
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
996
/// key whose certificate an issuer gave pushes when the policy grants its
997
/// subject, and a fetch accepts what it attested; an expired certificate,
998
/// or a subject the policy does not grant, may not move the bookmark.
83e0677b Andy McCall ↶ 999
#[test]
f0a517d2 Andy McCall ↶ 1000
fn a_certified_key_pushes_under_a_subject_grant() {
1001
    use crate::cert::{Certificate, SignedCertificate};
1002
    use crate::identity::Scope;
1003
    hermetic();
1004
    let dir = tempfile::tempdir().unwrap();
1005
    let root = dir.path();
1006
    let _origin = Repo::init(&root.join("origin")).unwrap();
1007
    let url = root.join("origin").to_string_lossy().to_string();
1008
    let mut a = Repo::clone(&url, &root.join("a"))
1009
        .unwrap()
1010
        .with_home(root.join("home-a"));
1011
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1012
        .unwrap();
1013
    write(&root.join("a"), "a.txt", b"a\n");
1014
    a.commit("a", &[]).unwrap();
1015
    a.policy_init().unwrap();
1016
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1017
    let hub_sk = SecretKey::generate();
1018
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1019
    a.policy_grant_subject(
1020
        "agent:claude@ada",
1021
        hub.clone(),
1022
        Scope::CHANGES | Scope::REFS,
1023
        None,
1024
    )
1025
    .unwrap();
1026
    assert!(a
1027
        .push("origin", false)
1028
        .unwrap()
1029
        .iter()
1030
        .any(|r| r.name == "policy" && r.ok));
1031
1032
    let now = Hlc::now().wall_ms;
1033
    // An agent repository whose key the hub certified for `subject`, from
1034
    // `from` to `to`.
1035
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1036
        let mut r = Repo::clone(&url, &root.join(name))
1037
            .unwrap()
1038
            .with_home(root.join(format!("home-{name}")));
1039
        let (_, id) = r
1040
            .create_identity(name, "[email protected]", IdentityScope::User)
1041
            .unwrap();
1042
        let cert = SignedCertificate::sign(
1043
            Certificate {
1044
                key: id,
1045
                issuer: hub.hash(),
1046
                subject: subject.into(),
1047
                claims: vec![],
1048
                scope: Scope::CHANGES | Scope::REFS,
1049
                not_before: from,
1050
                expires: to,
a2387d54 Andy McCall ↶ 1051
                grant: None,
f0a517d2 Andy McCall ↶ 1052
            },
1053
            &hub,
1054
            &hub_sk,
1055
        );
1056
        r.store().put_identity(&hub).unwrap();
1057
        r.store().put_certificate(&cert).unwrap();
1058
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1059
        r.commit("work", &[]).unwrap();
1060
        r
1061
    };
1062
1063
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1064
    let r = claude.push("origin", false).unwrap();
1065
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1066
    // Ada's fetch accepts the bookmark the certified key attested.
1067
    a.pull("origin").unwrap();
1068
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1069
        .store()
1070
        .get_change(h)
1071
        .map(|c| c.message == "work")
1072
        .unwrap_or(false)));
1073
f53cbe7a Andy McCall ↶ 1074
    // Step 4c: a host with an acceptor key records when it accepted the
1075
    // certified update and serves it; a fetch checks the certificate at
1076
    // that time only when the certificate's issuer signed it for exactly
1077
    // this attestation, else at the attestation's own time.
1078
    let host = Repo::open(&root.join("origin"))
1079
        .unwrap()
1080
        .with_acceptor(hub.clone(), hub_sk.clone());
1081
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1082
    host.record_acceptance(&attest_ref).unwrap();
1083
    let served = host.remote_refs().unwrap();
1084
    let acc = served
1085
        .refs
1086
        .iter()
1087
        .find(|r| r.name == "main")
1088
        .unwrap()
1089
        .accepted
1090
        .clone()
1091
        .expect("served with the refs");
1092
    let signer = sa.sigs[0].key;
1093
    assert_eq!(
1094
        a.certified_time(&signer, &sa, Some(&acc)),
1095
        acc.attest.hlc.wall_ms
1096
    );
1097
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1098
    let stranger_sk = SecretKey::generate();
1099
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1100
    let mut forged = acc.clone();
1101
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1102
    assert_eq!(
1103
        a.certified_time(&signer, &sa, Some(&forged)),
1104
        sa.attest.hlc.wall_ms,
1105
        "not the issuer's"
1106
    );
1107
    let mut elsewhere = acc.clone();
1108
    elsewhere.attest.body = AttestBody::Accepted {
1109
        attest: ObjectRef([7; 32]),
1110
    };
1111
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1112
    assert_eq!(
1113
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1114
        sa.attest.hlc.wall_ms,
1115
        "another attestation's"
1116
    );
1117
    a.pull("origin").unwrap();
1118
    // gc keeps the acceptance with the attestation.
1119
    host.gc(true).unwrap();
1120
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1121
f0a517d2 Andy McCall ↶ 1122
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1123
    let r = late.push("origin", false).unwrap();
1124
    assert!(
1125
        !r[0].ok && r[0].reason.contains("may not update"),
1126
        "an expired certificate: {r:?}"
1127
    );
1128
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1129
    let r = other.push("origin", false).unwrap();
1130
    assert!(
1131
        !r[0].ok && r[0].reason.contains("may not update"),
1132
        "a subject not granted: {r:?}"
1133
    );
1134
}
1135
a2387d54 Andy McCall ↶ 1136
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
1137
/// subject the author granted, seals changes in the author's name; with
1138
/// no grant, a stranger's, or one that had ended, it is neither the
1139
/// author nor a delegate.
f0a517d2 Andy McCall ↶ 1140
#[test]
a2387d54 Andy McCall ↶ 1141
fn a_certified_key_acts_for_its_author_under_a_grant() {
1142
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
1143
    use crate::identity::{Identity, Scope};
1144
    hermetic();
1145
    let dir = tempfile::tempdir().unwrap();
1146
    let root = dir.path();
1147
    let _origin = Repo::init(&root.join("origin")).unwrap();
1148
    let url = root.join("origin").to_string_lossy().to_string();
1149
    let mut a = Repo::clone(&url, &root.join("a"))
1150
        .unwrap()
1151
        .with_home(root.join("home-a"));
1152
    let (ada, _) = a
1153
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1154
        .unwrap();
1155
    write(&root.join("a"), "a.txt", b"a\n");
1156
    a.commit("a", &[]).unwrap();
1157
    a.policy_init().unwrap();
1158
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1159
    let hub_sk = SecretKey::generate();
1160
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1161
    a.policy_grant_subject(
1162
        "agent:claude@ada",
1163
        hub.clone(),
1164
        Scope::CHANGES | Scope::REFS,
1165
        None,
1166
    )
1167
    .unwrap();
1168
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1169
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
1170
    let ada_id = a.identity(&ada).unwrap();
1171
1172
    let now = Hlc::now().wall_ms;
1173
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
1174
        SignedGrant::sign(
1175
            Grant {
1176
                grantor: by.hash(),
1177
                subject: "agent:claude@ada".into(),
1178
                issuer: hub.hash(),
1179
                scope: Scope::CHANGES | Scope::SEAL,
1180
                not_before: from,
1181
                expires: to,
1182
            },
1183
            by,
1184
            sk,
1185
        )
1186
    };
1187
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
1188
    // certified (with `g` inside) the signer.
1189
    let agent = |name: &str, g: Option<SignedGrant>| {
1190
        let mut r = Repo::clone(&url, &root.join(name))
1191
            .unwrap()
1192
            .with_home(root.join(format!("home-{name}")));
1193
        let (key, id) = r
1194
            .create_identity(name, "[email protected]", IdentityScope::User)
1195
            .unwrap();
1196
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
1197
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
1198
        let cert = SignedCertificate::sign(
1199
            Certificate {
1200
                key: id,
1201
                issuer: hub.hash(),
1202
                subject: "agent:claude@ada".into(),
1203
                claims: vec![],
1204
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1205
                not_before: now - 60_000,
1206
                expires: now + 600_000,
1207
                grant: g,
1208
            },
1209
            &hub,
1210
            &hub_sk,
1211
        );
1212
        r.store().put_identity(&hub).unwrap();
1213
        r.store().put_certificate(&cert).unwrap();
1214
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1215
        let h = r.commit("work", &[]).unwrap();
1216
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
1217
        (r, key, h)
1218
    };
1219
1220
    let (claude, key, h) = agent(
1221
        "claude",
1222
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
1223
    );
1224
    let r = claude.push("origin", false).unwrap();
1225
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1226
    let host = Repo::open(&root.join("origin")).unwrap();
68dcf21f Andy McCall ↶ 1227
    assert!(
1228
        matches!(
1229
            host.authenticate_change(&h).unwrap(),
1230
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
1231
        ),
1232
        "named by its certificate's subject"
1233
    );
a2387d54 Andy McCall ↶ 1234
    a.pull("origin").unwrap();
1235
    assert!(matches!(
1236
        a.authenticate_change(&h).unwrap(),
1237
        SignatureStatus::Valid { key: k, .. } if k == key
1238
    ));
1239
1240
    let (none, _, _) = agent("none", None);
1241
    let r = none.push("origin", false).unwrap();
1242
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
1243
    let mallory_sk = SecretKey::generate();
1244
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
1245
    let (stranger, _, _) = agent(
1246
        "stranger",
1247
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
1248
    );
1249
    let r = stranger.push("origin", false).unwrap();
1250
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
1251
    let (ended, _, eh) = agent(
1252
        "ended",
1253
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
1254
    );
1255
    let r = ended.push("origin", false).unwrap();
1256
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
1257
    assert!(matches!(
1258
        ended.authenticate_change(&eh).unwrap(),
1259
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
1260
    ));
1261
}
1262
1263
#[test]
83e0677b Andy McCall ↶ 1264
fn trust_policy_governs_pushes_and_fetches() {
1265
    hermetic();
1266
    let dir = tempfile::tempdir().unwrap();
1267
    let root = dir.path();
1268
    let origin = Repo::init(&root.join("origin")).unwrap();
1269
    let url = root.join("origin").to_string_lossy().to_string();
1270
1271
    // A is the root. Before the policy, an unsigned push from B is fine.
75167672 Andy McCall 1272
    let mut a = Repo::clone(&url, &root.join("a"))
1273
        .unwrap()
1274
        .with_home(root.join("home-a"));
1275
    let (key_a, _) = a
1276
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1277
        .unwrap();
1278
    let mut b = Repo::clone(&url, &root.join("b"))
1279
        .unwrap()
1280
        .with_home(root.join("home-b"));
83e0677b Andy McCall ↶ 1281
    write(&root.join("b"), "b.txt", b"b\n");
1282
    b.commit("unsigned before policy", &[]).unwrap();
1283
    assert!(b.push("origin", false).unwrap()[0].ok);
1284
1285
    // A creates the policy and pushes it; origin now enforces it.
1286
    write(&root.join("a"), "a.txt", b"a\n");
1287
    a.commit("a", &[]).unwrap();
1288
    let sp = a.policy_init().unwrap();
1289
    assert_eq!(sp.policy.serial, 1);
1290
    a.pull("origin").unwrap();
1291
    let results = a.push("origin", false).unwrap();
1292
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1293
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1294
1295
    // B pulls the policy. Without an identity B cannot push at all.
1296
    b.pull("origin").unwrap();
75167672 Andy McCall 1297
    assert!(
1298
        b.current_policy().unwrap().is_some(),
1299
        "the policy arrived with the fetch"
1300
    );
83e0677b Andy McCall ↶ 1301
    assert!(b.push("origin", false).is_err());
1302
    // With an identity the policy does not list, the push is rejected by origin.
75167672 Andy McCall 1303
    let (key_b, id_b) = b
1304
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1305
        .unwrap();
83e0677b Andy McCall ↶ 1306
    write(&root.join("b"), "b.txt", b"b2\n");
1307
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1308
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1309
    let r = b.push("origin", false).unwrap();
75167672 Andy McCall 1310
    assert!(
1311
        !r[0].ok && r[0].reason.contains("may not update"),
1312
        "{:?}",
1313
        r
1314
    );
83e0677b Andy McCall ↶ 1315
1316
    // A grants B (identity handed over as a file) and publishes the policy.
1317
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1318
    assert_eq!(sp.policy.serial, 2);
1319
    let r = a.push("origin", false).unwrap();
1320
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1321
    // B must fetch the new policy before pushing.
75167672 Andy McCall 1322
    assert!(b
1323
        .push("origin", false)
1324
        .unwrap_or_else(|e| vec![RefResult {
1325
            name: "main".into(),
1326
            ok: false,
1327
            reason: e.to_string()
1328
        }])
1329
        .iter()
1330
        .all(|x| !x.ok));
83e0677b Andy McCall ↶ 1331
    b.pull("origin").unwrap();
1332
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1333
    let r = b.push("origin", false).unwrap();
1334
    assert!(r[0].ok, "{:?}", r);
1335
    // Origin verified B's change under the policy.
1336
    let heads = origin.bookmark_heads().unwrap();
1337
    for h in &heads {
1338
        let c = origin.store().get_change(h).unwrap();
1339
        if c.author == key_b {
75167672 Andy McCall 1340
            origin
1341
                .change_allowed(
1342
                    h,
1343
                    &origin.current_policy().unwrap().unwrap().1.policy,
1344
                    "main",
1345
                )
1346
                .unwrap();
83e0677b Andy McCall ↶ 1347
        }
1348
    }
1349
1350
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1351
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1352
    forged.serial = 3;
1353
    forged.roots = vec![key_b];
1354
    let fh = forged.hash();
1355
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 1356
    let forged = SignedPolicy {
1357
        policy: forged,
1358
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1359
    };
1360
    let r = origin
1361
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1362
        .unwrap();
83e0677b Andy McCall ↶ 1363
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1364
    let stale = a.current_policy().unwrap().unwrap().1;
1365
    let mut old = stale.clone();
1366
    old.policy.serial = 1;
75167672 Andy McCall 1367
    let r = origin
1368
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1369
        .unwrap();
83e0677b Andy McCall ↶ 1370
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1371
1372
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1373
    a.pull("origin").unwrap();
1374
    a.policy_revoke(&key_b).unwrap();
1375
    let r = a.push("origin", false).unwrap();
1376
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1377
    b.pull("origin").unwrap();
1378
    write(&root.join("b"), "b.txt", b"b3\n");
1379
    b.commit("b3", &[]).unwrap();
1380
    let r = b.push("origin", false).unwrap();
1381
    assert!(!r[0].ok, "{:?}", r);
1382
1383
    // A clone by a third party receives and verifies everything.
75167672 Andy McCall 1384
    let c = Repo::clone(&url, &root.join("c"))
1385
        .unwrap()
1386
        .with_home(root.join("home-c"));
83e0677b Andy McCall ↶ 1387
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
75167672 Andy McCall 1388
    assert!(c
1389
        .current_policy()
1390
        .unwrap()
1391
        .unwrap()
1392
        .1
1393
        .policy
1394
        .roots
1395
        .contains(&key_a));
83e0677b Andy McCall ↶ 1396
    assert!(!c.snapshot("status").unwrap().changed);
1397
}
d02e545d Andy McCall ↶ 1398
9ae4d15a Andy McCall ↶ 1399
/// oxygen#66: a gc says what it is doing, phase by phase.
d02e545d Andy McCall ↶ 1400
#[test]
9ae4d15a Andy McCall ↶ 1401
fn gc_reports_its_phases() {
1402
    hermetic();
1403
    let dir = tempfile::tempdir().unwrap();
1404
    let repo = Repo::init(dir.path()).unwrap();
1405
    for i in 0..3 {
1406
        write(
1407
            dir.path(),
1408
            &format!("f{i}.txt"),
1409
            format!("{i}\n").as_bytes(),
1410
        );
1411
        repo.commit(&format!("c{i}"), &[]).unwrap();
1412
    }
1413
    let mut phases = Vec::new();
1414
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1415
        .unwrap();
1416
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1417
    assert!(
1418
        phases.iter().any(|p| p.starts_with("pruning")),
1419
        "{phases:?}"
1420
    );
1421
    assert!(
1422
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1423
        "{phases:?}"
1424
    );
1425
    assert!(
1426
        phases
1427
            .iter()
1428
            .any(|p| p.starts_with("writing the index of ")),
1429
        "{phases:?}"
1430
    );
1431
}
1432
1433
#[test]
d02e545d Andy McCall ↶ 1434
fn gc_packs_objects_and_history_still_works() {
1435
    hermetic();
1436
    let dir = tempfile::tempdir().unwrap();
1437
    let root = dir.path();
1438
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1439
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1440
        .unwrap();
d02e545d Andy McCall ↶ 1441
    repo.set_user_config("core.sign", "change").unwrap();
1442
    write(root, "a.txt", b"one\n");
1443
    let h1 = repo.commit("one", &[]).unwrap();
1444
    write(root, "a.txt", b"two\n");
1445
    write(root, "big.bin", &vec![0u8; 100_000]);
1446
    let h2 = repo.commit("two", &[]).unwrap();
ba160f60 Andy McCall ↶ 1447
    // Several snapshots leave superseded working-copy versions behind.
1448
    for i in 0..5 {
1449
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1450
        repo.snapshot("status").unwrap();
1451
    }
1452
    write(root, "a.txt", b"two\n");
1453
    repo.snapshot("status").unwrap();
d02e545d Andy McCall ↶ 1454
    let before = repo.store().list().unwrap();
1455
    assert!(repo.store().loose_count().unwrap() > 0);
ba160f60 Andy McCall ↶ 1456
1457
    // With the default retention every operation's view is a root: nothing prunes.
1458
    let r = repo.gc(true).unwrap();
1459
    assert_eq!(r.packed.objects, before.len());
1460
    assert_eq!(r.pruned.objects, 0);
d02e545d Andy McCall ↶ 1461
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1462
    assert_eq!(repo.store().list().unwrap(), before);
ba160f60 Andy McCall ↶ 1463
1464
    // With zero retention only the current view is a root: superseded
1465
    // working copies go, everything reachable stays.
1466
    repo.config.set("core.op-retention", "0").unwrap();
1467
    repo.save_config().unwrap();
21b2aec2 Andy McCall ↶ 1468
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
ba160f60 Andy McCall ↶ 1469
    let r = repo.gc(true).unwrap();
1470
    assert!(r.pruned.objects >= 5, "{r:?}");
1471
    let after = repo.store().list().unwrap();
1472
    assert!(after.len() < before.len());
1473
    assert!(after.contains(&h1) && after.contains(&h2));
1474
    for (_, op) in repo.op_log().unwrap() {
1475
        assert!(!op.command.is_empty(), "operation objects are all kept");
1476
    }
1477
    // Everything still works from the pruned, packed store.
d02e545d Andy McCall ↶ 1478
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
75167672 Andy McCall 1479
    assert!(matches!(
1480
        repo.verify_change(&h2).unwrap(),
1481
        SignatureStatus::Valid { .. }
1482
    ));
d02e545d Andy McCall ↶ 1483
    assert_eq!(repo.log().unwrap().len(), 3);
1484
    repo.checkout(&[h1], false, "checkout").unwrap();
1485
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1486
    repo.checkout(&[h2], false, "checkout").unwrap();
1487
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1488
    assert!(!repo.snapshot("status").unwrap().changed);
ba160f60 Andy McCall ↶ 1489
    // Grace period defers pruning of young garbage.
d02e545d Andy McCall ↶ 1490
    write(root, "a.txt", b"three\n");
1491
    repo.commit("three", &[]).unwrap();
ba160f60 Andy McCall ↶ 1492
    let r = repo.gc(false).unwrap();
1493
    assert_eq!(r.pruned.objects, 0);
1494
    assert!(r.pruned.deferred > 0);
1495
    let r = repo.gc(true).unwrap();
1496
    assert!(r.pruned.objects > 0);
1497
    assert_eq!(repo.log().unwrap().len(), 4);
21b2aec2 Andy McCall ↶ 1498
    // Restoring the default retention makes the old views roots again; the
1499
    // working copies they name were pruned, which gc tolerates.
1500
    repo.config.set("core.op-retention", "90").unwrap();
1501
    repo.save_config().unwrap();
1502
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1503
    let r = repo.gc(false).unwrap();
1504
    assert_eq!(r.pruned.objects, 0);
1505
    assert_eq!(repo.log().unwrap().len(), 4);
d02e545d Andy McCall ↶ 1506
}
614541c3 Andy McCall ↶ 1507
1508
#[test]
1509
fn describe_amend_abandon_heads() {
1510
    hermetic();
1511
    let dir = tempfile::tempdir().unwrap();
1512
    let root = dir.path();
1513
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1514
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1515
        .unwrap();
614541c3 Andy McCall ↶ 1516
    repo.set_user_config("core.sign", "change").unwrap();
1517
    write(root, "a.txt", b"one\n");
1518
    let h1 = repo.commit("first", &[]).unwrap();
1519
    write(root, "a.txt", b"one\ntwo\n");
1520
    let h2 = repo.commit("secnod", &[]).unwrap();
1521
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1522
1523
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1524
    let h2b = repo.describe(&h2, "second").unwrap();
1525
    assert_ne!(h2b, h2);
1526
    let c = repo.store().get_change(&h2b).unwrap();
75167672 Andy McCall 1527
    assert_eq!(
1528
        (c.change_id, c.message.as_str(), c.deps.clone()),
1529
        (id2, "second", vec![h1])
1530
    );
614541c3 Andy McCall ↶ 1531
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
75167672 Andy McCall 1532
    assert!(matches!(
1533
        repo.verify_change(&h2b).unwrap(),
1534
        SignatureStatus::Valid { .. }
1535
    ));
614541c3 Andy McCall ↶ 1536
    let s = repo.snapshot("status").unwrap();
1537
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
75167672 Andy McCall 1538
    assert_eq!(
1539
        repo.resolve_change(&id2.short(8)).unwrap(),
1540
        h2b,
1541
        "the old object is no longer reachable from the log"
1542
    );
c07e0e7d Andy McCall ↶ 1543
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1544
    let h1b = repo.describe(&h1, "first, described").unwrap();
1545
    assert_ne!(h1b, h1);
1546
    let heads = repo.bookmark_heads().unwrap();
1547
    assert_eq!(heads.len(), 1);
1548
    let top = repo.store().get_change(&heads[0]).unwrap();
1549
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
75167672 Andy McCall 1550
    assert!(
1551
        matches!(
1552
            repo.verify_change(&heads[0]).unwrap(),
1553
            SignatureStatus::Valid { .. }
1554
        ),
1555
        "rewritten own change is re-signed"
1556
    );
c07e0e7d Andy McCall ↶ 1557
    let (_, wc) = repo.working_copy().unwrap();
75167672 Andy McCall 1558
    assert_eq!(
1559
        wc.deps,
1560
        vec![heads[0]],
1561
        "the working copy follows the rewrite"
1562
    );
c07e0e7d Andy McCall ↶ 1563
    assert!(!repo.snapshot("status").unwrap().changed);
1564
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 1565
    assert!(
1566
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1567
    );
614541c3 Andy McCall ↶ 1568
1569
    // amend: fold an edit into the head; the result is one change from h1.
1570
    write(root, "a.txt", b"one\ntwo\nthree\n");
1571
    write(root, "b.txt", b"b\n");
1572
    let h2c = repo.amend(None).unwrap();
1573
    let c = repo.store().get_change(&h2c).unwrap();
1574
    assert_eq!(c.change_id, id2);
1575
    assert_eq!(c.message, "second");
1576
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
75167672 Andy McCall 1577
    assert_eq!(
1578
        repo.log().unwrap().len(),
1579
        3,
1580
        "working copy, amended head, first"
1581
    );
614541c3 Andy McCall ↶ 1582
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
75167672 Andy McCall 1583
    assert!(
1584
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1585
    );
614541c3 Andy McCall ↶ 1586
    assert!(snap.files.contains_key("b.txt"));
1587
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 1588
    assert!(
1589
        repo.amend(None).is_err(),
1590
        "clean working copy and no message"
1591
    );
614541c3 Andy McCall ↶ 1592
    let h2d = repo.amend(Some("second, amended")).unwrap();
75167672 Andy McCall 1593
    assert_eq!(
1594
        repo.store().get_change(&h2d).unwrap().message,
1595
        "second, amended"
1596
    );
614541c3 Andy McCall ↶ 1597
1598
    // abandon: the head goes, its content stays as uncommitted work.
1599
    repo.abandon(&h2d).unwrap();
75167672 Andy McCall 1600
    assert_eq!(
1601
        repo.bookmark_heads().unwrap(),
1602
        vec![h1b],
1603
        "the described first change is the head again"
1604
    );
614541c3 Andy McCall ↶ 1605
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 1606
    let paths: Vec<_> = s
1607
        .statuses
1608
        .iter()
1609
        .map(|p| (p.path.as_str(), p.status))
1610
        .collect();
1611
    assert_eq!(
1612
        paths,
1613
        vec![
1614
            ("a.txt", ChangeStatus::Modified),
1615
            ("b.txt", ChangeStatus::Added)
1616
        ]
1617
    );
614541c3 Andy McCall ↶ 1618
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1619
    let h3 = repo.commit("recommitted", &[]).unwrap();
1620
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1621
    // undo brings the abandoned head back.
1622
    repo.undo().unwrap();
1623
    repo.undo().unwrap();
1624
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
c07e0e7d Andy McCall ↶ 1625
6706bdcf Andy McCall ↶ 1626
    // Abandoning a non-head whose dependent references its atoms reifies
1627
    // the references (here: a.txt vanishes with it, so the dependent's edit
1628
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
c07e0e7d Andy McCall ↶ 1629
    let base = repo.bookmark_heads().unwrap()[0];
1630
    let base_change = repo.store().get_change(&base).unwrap();
1631
    let h1_now = base_change.deps[0];
6706bdcf Andy McCall ↶ 1632
    let notes = repo.abandon(&h1_now).unwrap();
75167672 Andy McCall 1633
    assert!(
1634
        !notes.is_empty(),
1635
        "the dependent's edit of a.txt was reified"
1636
    );
6706bdcf Andy McCall ↶ 1637
    let heads = repo.bookmark_heads().unwrap();
1638
    let after = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 1639
    assert!(
1640
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1641
        "{:?}",
1642
        after.files.keys()
1643
    );
6706bdcf Andy McCall ↶ 1644
    repo.undo().unwrap();
1645
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
c07e0e7d Andy McCall ↶ 1646
    write(root, "c.txt", b"c\n");
1647
    let hc = repo.commit("c", &[]).unwrap();
1648
    write(root, "d.txt", b"d\n");
1649
    let hd = repo.commit("d", &[hc]).unwrap();
1650
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1651
    repo.abandon(&hc).unwrap();
1652
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1653
    assert!(!heads.contains(&hc));
75167672 Andy McCall 1654
    let d_now = heads
1655
        .iter()
1656
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1657
        .copied()
1658
        .unwrap();
1659
    assert!(
1660
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1661
        "d inherited c's (empty) dependencies"
1662
    );
c07e0e7d Andy McCall ↶ 1663
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 1664
    assert_eq!(
1665
        s.statuses
1666
            .iter()
1667
            .map(|p| p.path.as_str())
1668
            .collect::<Vec<_>>(),
1669
        vec!["c.txt"],
1670
        "c's content is now uncommitted work"
1671
    );
614541c3 Andy McCall ↶ 1672
}
79ab8528 Andy McCall ↶ 1673
1674
#[test]
1675
fn git_export_mirrors_history() {
1676
    hermetic();
75167672 Andy McCall 1677
    if std::process::Command::new("git")
1678
        .arg("--version")
1679
        .output()
1680
        .is_err()
1681
    {
79ab8528 Andy McCall ↶ 1682
        eprintln!("git not installed; skipping");
1683
        return;
1684
    }
1685
    let dir = tempfile::tempdir().unwrap();
1686
    let root = dir.path();
75167672 Andy McCall 1687
    let mut repo = Repo::init(&root.join("r"))
1688
        .unwrap()
1689
        .with_home(root.join("home"));
1690
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1691
        .unwrap();
79ab8528 Andy McCall ↶ 1692
    let r = root.join("r");
1693
    write(&r, "README.md", b"hello\n");
1694
    write(&r, "src/main.rs", b"fn main() {}\n");
1695
    let h1 = repo.commit("first", &[]).unwrap();
1696
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1697
    write(&r, "logo.png", b"\x89PNG\0\0");
1698
    let h2 = repo.commit("second", &[]).unwrap();
1699
1700
    let git_dir = root.join("mirror.git");
1701
    let rep = repo.git_export(&git_dir).unwrap();
1702
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1703
    let git = |args: &[&str]| -> String {
75167672 Andy McCall 1704
        let out = std::process::Command::new("git")
1705
            .arg("-C")
1706
            .arg(&git_dir)
1707
            .args(args)
1708
            .output()
1709
            .unwrap();
1710
        assert!(
1711
            out.status.success(),
1712
            "{}",
1713
            String::from_utf8_lossy(&out.stderr)
1714
        );
79ab8528 Andy McCall ↶ 1715
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1716
    };
1717
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1718
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1719
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1720
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 1721
    assert!(
1722
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1723
        "{body}"
1724
    );
79ab8528 Andy McCall ↶ 1725
    assert!(body.contains("Change-Id: "), "{body}");
75167672 Andy McCall 1726
    assert_eq!(
1727
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1728
        "Ada Lovelace <[email protected]>"
1729
    );
1730
    assert_eq!(
1731
        git(&["ls-tree", "--name-only", "main"]),
1732
        "README.md\nlogo.png\nsrc"
1733
    );
79ab8528 Andy McCall ↶ 1734
1735
    // Re-export is incremental.
1736
    let rep = repo.git_export(&git_dir).unwrap();
1737
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1738
1739
    // An independent change makes two heads; the next state is one more
1740
    // commit on the linear branch whose tree is the union.
1741
    repo.checkout(&[h1], false, "checkout").unwrap();
1742
    write(&r, "other.txt", b"o\n");
1743
    let h3 = repo.commit("third", &[]).unwrap();
1744
    let rep = repo.git_export(&git_dir).unwrap();
1745
    assert_eq!((rep.exported, rep.heads), (1, 2));
1746
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1747
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1748
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1749
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1750
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
75167672 Andy McCall 1751
    assert_eq!(
1752
        git(&["ls-tree", "--name-only", "main"]),
1753
        "README.md\nlogo.png\nother.txt\nsrc"
1754
    );
79ab8528 Andy McCall ↶ 1755
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 1756
    assert!(
1757
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1758
        "{body}"
1759
    );
79ab8528 Andy McCall ↶ 1760
    // A rewrite is a new state whose one new change is the rewritten one.
1761
    repo.describe(&h3, "third, described").unwrap();
1762
    let rep = repo.git_export(&git_dir).unwrap();
1763
    assert_eq!(rep.exported, 1);
75167672 Andy McCall 1764
    assert_eq!(
1765
        git(&["log", "-1", "--format=%s", "main"]),
1766
        "third, described"
1767
    );
79ab8528 Andy McCall ↶ 1768
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1769
    let _ = h2;
1770
}
c3069537 Andy McCall ↶ 1771
1772
#[test]
1773
fn git_import_reproduces_trees() {
c3d2ef61 Andy McCall ↶ 1774
    git_import_reproduces_trees_with(None);
1775
}
1776
1777
/// The same import with every merge rendered in batches of one file
1778
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1779
#[test]
1780
fn git_import_reproduces_trees_in_batches() {
1781
    git_import_reproduces_trees_with(Some(1));
1782
}
1783
1784
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1785
    crate::repo::git::set_merge_batch_for_tests(batch);
c3069537 Andy McCall ↶ 1786
    hermetic();
75167672 Andy McCall 1787
    if std::process::Command::new("git")
1788
        .arg("--version")
1789
        .output()
1790
        .is_err()
1791
    {
c3069537 Andy McCall ↶ 1792
        eprintln!("git not installed; skipping");
1793
        return;
1794
    }
1795
    let dir = tempfile::tempdir().unwrap();
1796
    let root = dir.path();
1797
    let g = root.join("src.git");
1798
    fs::create_dir_all(&g).unwrap();
1799
    let git = |args: &[&str]| -> String {
1800
        let out = std::process::Command::new("git")
1801
            .arg("-C")
1802
            .arg(&g)
75167672 Andy McCall 1803
            .args([
1804
                "-c",
1805
                "user.name=Grace",
1806
                "-c",
1807
                "[email protected]",
1808
                "-c",
1809
                "commit.gpgsign=false",
1810
            ])
c3069537 Andy McCall ↶ 1811
            .args(args)
1812
            .output()
1813
            .unwrap();
75167672 Andy McCall 1814
        assert!(
1815
            out.status.success(),
1816
            "git {args:?}: {}",
1817
            String::from_utf8_lossy(&out.stderr)
1818
        );
c3069537 Andy McCall ↶ 1819
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1820
    };
1821
    git(&["init", "-q", "-b", "main"]);
1822
    write(&g, "README.md", b"# Hi\n");
1823
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1824
    git(&["add", "."]);
1825
    git(&["commit", "-q", "-m", "initial"]);
1826
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1827
    write(&g, "run.sh", b"#!/bin/sh\n");
1828
    #[cfg(unix)]
1829
    {
1830
        use std::os::unix::fs::PermissionsExt;
1831
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1832
    }
1833
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1834
    git(&["add", "."]);
75167672 Andy McCall 1835
    git(&[
1836
        "commit",
1837
        "-q",
1838
        "-m",
1839
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1840
    ]);
c3069537 Andy McCall ↶ 1841
    // A branch that edits README, merged back with a conflict-free merge.
1842
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1843
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1844
    git(&["commit", "-q", "-am", "readme"]);
1845
    git(&["checkout", "-q", "main"]);
1846
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1847
    // A branch from the initial commit inserting at the same place as
1848
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1849
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1850
    git(&["checkout", "-q", "-b", "clash", &initial]);
1851
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1852
    git(&["commit", "-q", "-am", "clash"]);
1853
    git(&["checkout", "-q", "main"]);
7df9007b Andy McCall ↶ 1854
    // Expected to stop at the conflict, so its status is ignored; the
1855
    // identity is passed as for every other git call here, or a machine
1856
    // without one refuses to start the merge at all.
75167672 Andy McCall 1857
    let _ = std::process::Command::new("git")
1858
        .arg("-C")
1859
        .arg(&g)
7df9007b Andy McCall ↶ 1860
        .args([
1861
            "-c",
1862
            "user.name=Grace",
1863
            "-c",
1864
            "[email protected]",
1865
            "merge",
1866
            "-q",
1867
            "clash",
1868
        ])
75167672 Andy McCall 1869
        .output();
7df9007b Andy McCall ↶ 1870
    assert!(
1871
        g.join(".git/MERGE_HEAD").exists(),
1872
        "the clash merge stopped at its conflict"
1873
    );
75167672 Andy McCall 1874
    write(
1875
        &g,
1876
        "src/lib.rs",
1877
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1878
    );
c3069537 Andy McCall ↶ 1879
    git(&["add", "."]);
1880
    git(&["commit", "-q", "-m", "resolve clash"]);
1881
    git(&["rm", "-q", "logo.png"]);
1882
    git(&["commit", "-q", "-m", "drop logo"]);
6e723b81 Andy McCall ↶ 1883
    // A rename with a small edit is imported as a move of the same node.
1884
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
75167672 Andy McCall 1885
    write(
1886
        &g,
1887
        "src/lib2.rs",
1888
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1889
    );
6e723b81 Andy McCall ↶ 1890
    git(&["add", "."]);
1891
    git(&["commit", "-q", "-m", "rename lib"]);
958fb27d Andy McCall ↶ 1892
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1893
    // run.sh is the same as in the first parent's tree, but the merged
1894
    // change touched it, so the importer must compare it, not skip it.
1895
    git(&["checkout", "-q", "-b", "discarded"]);
1896
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1897
    git(&["commit", "-q", "-am", "discarded edit"]);
1898
    git(&["checkout", "-q", "main"]);
314db9b4 Andy McCall ↶ 1899
    git(&[
1900
        "merge",
1901
        "-q",
1902
        "-s",
1903
        "ours",
1904
        "-m",
1905
        "merge discarded, keeping ours",
1906
        "discarded",
1907
    ]);
c3069537 Andy McCall ↶ 1908
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1909
1910
    let dest = root.join("oxy");
1911
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1912
    let rep = repo.import_git(&g, "main").unwrap();
1913
    assert_eq!(rep.commits, expected_count);
958fb27d Andy McCall ↶ 1914
    assert_eq!(rep.merges, 3);
314db9b4 Andy McCall ↶ 1915
    assert_eq!(
1916
        fs::read(dest.join("run.sh")).unwrap(),
1917
        b"#!/bin/sh\n",
1918
        "the ours merge kept main's run.sh"
1919
    );
958fb27d Andy McCall ↶ 1920
    let v = repo.verify_git_import(&g, "main").unwrap();
1921
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1922
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
c3069537 Andy McCall ↶ 1923
    // The working copy equals the Git tree at main.
75167672 Andy McCall 1924
    assert_eq!(
1925
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1926
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1927
    );
6e723b81 Andy McCall ↶ 1928
    assert!(!dest.join("src/lib.rs").exists());
75167672 Andy McCall 1929
    assert_eq!(
1930
        fs::read(dest.join("README.md")).unwrap(),
1931
        b"# Hi\n\nMore.\n"
1932
    );
c3069537 Andy McCall ↶ 1933
    assert!(!dest.join("logo.png").exists());
1934
    #[cfg(unix)]
1935
    {
1936
        use std::os::unix::fs::PermissionsExt;
75167672 Andy McCall 1937
        assert!(
1938
            fs::metadata(dest.join("run.sh"))
1939
                .unwrap()
1940
                .permissions()
1941
                .mode()
1942
                & 0o111
1943
                != 0
1944
        );
c3069537 Andy McCall ↶ 1945
    }
75167672 Andy McCall 1946
    assert!(
1947
        !repo.snapshot("status").unwrap().changed,
1948
        "clean after import"
1949
    );
c3069537 Andy McCall ↶ 1950
    let heads = repo.bookmark_heads().unwrap();
1951
    let st = repo.load_state(&heads).unwrap();
1952
    assert!(!st.materialize().is_conflicted());
1953
    assert_eq!(st.len(), expected_count);
75167672 Andy McCall 1954
    let tip = repo
1955
        .log()
1956
        .unwrap()
1957
        .into_iter()
1958
        .find(|e| e.change.message.starts_with("rename lib"))
1959
        .unwrap();
6e723b81 Andy McCall ↶ 1960
    let c = repo.store().get_change(&tip.hash).unwrap();
75167672 Andy McCall 1961
    assert!(
1962
        c.tree_ops
1963
            .iter()
1964
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1965
        "{:?}",
1966
        c.tree_ops
1967
    );
1968
    assert!(!c
1969
        .tree_ops
1970
        .iter()
1971
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
c3069537 Andy McCall ↶ 1972
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1973
    let log = repo.log().unwrap();
75167672 Andy McCall 1974
    let second = log
1975
        .iter()
1976
        .find(|e| e.change.message.starts_with("second"))
1977
        .unwrap();
1978
    assert_eq!(
1979
        second.change.change_id,
1980
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1981
    );
1982
    assert!(second
1983
        .change
1984
        .message
1985
        .contains("Git-Author: Grace <[email protected]>"));
1986
    let resolve = log
1987
        .iter()
1988
        .find(|e| e.change.message.starts_with("resolve clash"))
1989
        .unwrap();
1990
    assert_eq!(
1991
        resolve.change.kind,
1992
        ChangeKind::Resolution,
1993
        "a conflicting Git merge becomes a resolution"
1994
    );
c3069537 Andy McCall ↶ 1995
    // Re-importing into another fresh repository gives the same ChangeIds.
75167672 Andy McCall 1996
    let repo2 = Repo::init(&root.join("oxy2"))
1997
        .unwrap()
1998
        .with_home(root.join("home"));
c3069537 Andy McCall ↶ 1999
    repo2.import_git(&g, "main").unwrap();
dfb23a3a Andy McCall ↶ 2000
    // New nodes' identifiers derive from the commit (spec §23), so the
2001
    // re-import is not just the same ChangeIds but the same changes.
2002
    assert_eq!(
2003
        repo2.bookmark_heads().unwrap(),
2004
        repo.bookmark_heads().unwrap()
2005
    );
75167672 Andy McCall 2006
    let ids: BTreeSet<ChangeId> = repo
2007
        .log()
2008
        .unwrap()
2009
        .iter()
2010
        .filter(|e| !e.is_working_copy)
2011
        .map(|e| e.change.change_id)
2012
        .collect();
2013
    let ids2: BTreeSet<ChangeId> = repo2
2014
        .log()
2015
        .unwrap()
2016
        .iter()
2017
        .filter(|e| !e.is_working_copy)
2018
        .map(|e| e.change.change_id)
2019
        .collect();
c3069537 Andy McCall ↶ 2020
    assert_eq!(ids, ids2);
2021
    // Round trip back out to Git reproduces the tip tree.
2022
    let mirror = root.join("mirror.git");
2023
    repo.git_export(&mirror).unwrap();
75167672 Andy McCall 2024
    let out = std::process::Command::new("git")
2025
        .arg("-C")
2026
        .arg(&mirror)
2027
        .args(["show", "main:src/lib2.rs"])
2028
        .output()
2029
        .unwrap();
2030
    assert_eq!(
2031
        String::from_utf8_lossy(&out.stdout),
2032
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2033
    );
2034
    let out = std::process::Command::new("git")
2035
        .arg("-C")
2036
        .arg(&mirror)
2037
        .args(["show", "main:src/lib.rs"])
2038
        .output()
2039
        .unwrap();
2040
    assert!(
2041
        !out.status.success(),
2042
        "the old path is gone from the export"
2043
    );
c3069537 Andy McCall ↶ 2044
}
252e8cb2 Andy McCall ↶ 2045
2046
#[test]
2047
fn checkpoints_accelerate_loading_and_stay_correct() {
2048
    hermetic();
2049
    let dir = tempfile::tempdir().unwrap();
2050
    let root = dir.path();
2051
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2052
    repo.config.set("core.checkpoint-interval", "5").unwrap();
2053
    repo.save_config().unwrap();
2054
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2055
    let mut hashes = Vec::new();
2056
    for i in 0..12 {
75167672 Andy McCall 2057
        write(
2058
            root,
2059
            "a.txt",
2060
            format!(
2061
                "{}\n",
2062
                (0..=i)
2063
                    .map(|k| k.to_string())
2064
                    .collect::<Vec<_>>()
2065
                    .join("\n")
2066
            )
2067
            .as_bytes(),
2068
        );
252e8cb2 Andy McCall ↶ 2069
        write(root, &format!("f{i}.txt"), b"x\n");
2070
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
2071
    }
75167672 Andy McCall 2072
    let (_, cp) = repo
2073
        .latest_checkpoint("main")
2074
        .unwrap()
2075
        .expect("automatic checkpoint");
252e8cb2 Andy McCall ↶ 2076
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
2077
    // Loading through the checkpoint equals loading everything.
2078
    let heads = repo.bookmark_heads().unwrap();
2079
    let fast = repo.load_state(&heads).unwrap();
2080
    let full = repo.load_state_full(&heads).unwrap();
2081
    assert_eq!(fast.len(), full.len());
2082
    assert_eq!(fast.heads(), full.heads());
2083
    let (a, b) = (fast.materialize(), full.materialize());
75167672 Andy McCall 2084
    assert_eq!(
2085
        a.files.keys().collect::<Vec<_>>(),
2086
        b.files.keys().collect::<Vec<_>>()
2087
    );
252e8cb2 Andy McCall ↶ 2088
    for (p, f) in &a.files {
2089
        assert_eq!(f.content, b.files[p].content, "{p}");
2090
    }
2091
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
2092
    // A head set that does not contain the checkpoint's heads falls back.
75167672 Andy McCall 2093
    assert!(repo
2094
        .load_state_checkpointed(&[hashes[0]])
2095
        .unwrap()
2096
        .is_none());
252e8cb2 Andy McCall ↶ 2097
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
2098
    // Everything else keeps working on top of the checkpoint.
2099
    assert!(!repo.snapshot("status").unwrap().changed);
2100
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
2101
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
2102
    let (r, n, bytes) = repo.checkpoint().unwrap();
2103
    assert!(n >= 12 && bytes > 0);
2104
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
2105
    write(root, "a.txt", b"after\n");
2106
    let h_after = repo.commit("after", &[]).unwrap();
2107
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
2108
    assert!(st.contains(&h_after));
75167672 Andy McCall 2109
    assert!(
2110
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
2111
    );
252e8cb2 Andy McCall ↶ 2112
    assert_eq!(repo.log().unwrap().len(), 14);
2113
    // Checkpoints survive gc.
2114
    repo.gc(true).unwrap();
2115
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
75167672 Andy McCall 2116
    assert!(repo
2117
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
2118
        .unwrap()
2119
        .is_some());
252e8cb2 Andy McCall ↶ 2120
}
135212de Andy McCall ↶ 2121
2122
#[test]
2123
fn quick_status_for_prompts() {
2124
    hermetic();
2125
    let dir = tempfile::tempdir().unwrap();
2126
    let root = dir.path();
2127
    let origin = Repo::init(&root.join("origin")).unwrap();
2128
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2129
    let a = Repo::clone(&url, &root.join("a"))
2130
        .unwrap()
2131
        .with_home(root.join("home"));
135212de Andy McCall ↶ 2132
    let ops_before = a.op_log().unwrap().len();
2133
    let info = a.quick_status().unwrap();
75167672 Andy McCall 2134
    assert_eq!(
2135
        (
2136
            info.bookmark.as_str(),
2137
            info.heads,
2138
            info.dirty,
2139
            info.conflicted,
2140
            info.ahead,
2141
            info.behind
2142
        ),
2143
        ("main", 0, false, false, Some(0), Some(0))
2144
    );
135212de Andy McCall ↶ 2145
    write(&root.join("a"), "f.txt", b"f\n");
2146
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
75167672 Andy McCall 2147
    assert_eq!(
2148
        a.op_log().unwrap().len(),
2149
        ops_before,
2150
        "quick_status records nothing"
2151
    );
135212de Andy McCall ↶ 2152
    // A snapshotted but uncommitted change is still dirty.
2153
    a.snapshot("status").unwrap();
2154
    assert!(a.quick_status().unwrap().dirty);
2155
    a.commit("f", &[]).unwrap();
2156
    let info = a.quick_status().unwrap();
2157
    assert!(!info.dirty, "clean right after a commit");
2158
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
75167672 Andy McCall 2159
    assert_eq!(
2160
        info.format("%b %c%d%x%A%D"),
2161
        format!("main {}+1", info.change_id)
2162
    );
135212de Andy McCall ↶ 2163
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
2164
    // Touching a file without changing it is not dirty; changing content of
2165
    // the same size is.
2166
    let p = root.join("a/f.txt");
2167
    let content = fs::read(&p).unwrap();
2168
    fs::write(&p, &content).unwrap();
2169
    assert!(!a.quick_status().unwrap().dirty);
2170
    fs::write(&p, b"g\n").unwrap();
2171
    assert!(a.quick_status().unwrap().dirty);
2172
    fs::write(&p, b"f\n").unwrap();
2173
    // Push, then a second clone commits and pushes: we are behind.
2174
    assert!(a.push("origin", false).unwrap()[0].ok);
2175
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
75167672 Andy McCall 2176
    let b = Repo::clone(&url, &root.join("b"))
2177
        .unwrap()
2178
        .with_home(root.join("home-b"));
135212de Andy McCall ↶ 2179
    write(&root.join("b"), "g.txt", b"g\n");
2180
    b.commit("g", &[]).unwrap();
2181
    b.push("origin", false).unwrap();
2182
    a.fetch("origin").unwrap();
2183
    let info = a.quick_status().unwrap();
2184
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
2185
    assert_eq!(info.format("%A%D"), "-1");
2186
    let _ = origin;
2187
}
b3c5a59a Andy McCall ↶ 2188
2189
#[test]
2190
fn lazy_blobs_are_fetched_on_first_read() {
2191
    hermetic();
2192
    let dir = tempfile::tempdir().unwrap();
2193
    let root = dir.path();
2194
    let origin_dir = root.join("origin");
75167672 Andy McCall 2195
    let origin = Repo::init(&origin_dir)
2196
        .unwrap()
2197
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 2198
    let url = origin_dir.to_string_lossy().to_string();
2199
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
2200
    write(&origin_dir, "big.bin", &big);
2201
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
2202
    write(&origin_dir, "t.txt", b"t\n");
2203
    let h = origin.commit("blobs", &[]).unwrap();
2204
    let big_ref = Repo::blob_ref(&big);
2205
2206
    // Fetch only (no checkout) with a filter: the big blob stays absent.
75167672 Andy McCall 2207
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
2208
        .unwrap()
2209
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 2210
    let a = {
2211
        let mut a = a;
2212
        a.config.set("remote.origin.url", &url).unwrap();
2213
        a.config.set("filter.max-blob", "100K").unwrap();
2214
        a.save_config().unwrap();
2215
        a
2216
    };
2217
    assert_eq!(a.config.max_blob, Some(100 * 1024));
2218
    a.fetch("origin").unwrap();
2219
    assert!(a.store().has(&h));
2220
    assert!(!a.store().has(&big_ref), "withheld");
75167672 Andy McCall 2221
    assert!(
2222
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
2223
        "small blob came along"
2224
    );
b3c5a59a Andy McCall ↶ 2225
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
2226
2227
    // status and commit do not need it: adopt the state, edit a text file, commit.
2228
    let (op_ref, op) = a.head_op().unwrap();
2229
    let mut view = op.view.clone();
75167672 Andy McCall 2230
    view.bookmarks.insert(
2231
        "main".into(),
2232
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
2233
    );
b3c5a59a Andy McCall ↶ 2234
    a.record_op(&[op_ref], "adopt", view).unwrap();
2235
    // Checkout reads the blob lazily, which fetches it.
2236
    a.checkout(&[h], true, "checkout").unwrap();
2237
    assert!(a.store().has(&big_ref), "fetched on first read");
2238
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
2239
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
2240
    write(&root.join("a"), "t.txt", b"t2\n");
2241
    a.commit("text edit", &[]).unwrap();
2242
2243
    // clone --max-blob records the filter; the checkout fetches lazily.
7421309f Andy McCall ↶ 2244
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
b3c5a59a Andy McCall ↶ 2245
    assert_eq!(b.config.max_blob, Some(1024));
2246
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
2247
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
2248
    assert!(parse_size("lots").is_err());
2249
}
7421309f Andy McCall ↶ 2250
2251
#[test]
2252
fn sparse_checkout_materializes_only_chosen_paths() {
2253
    hermetic();
2254
    let dir = tempfile::tempdir().unwrap();
2255
    let root = dir.path();
2256
    let origin_dir = root.join("origin");
75167672 Andy McCall 2257
    let origin = Repo::init(&origin_dir)
2258
        .unwrap()
2259
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 2260
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
2261
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
2262
    write(&origin_dir, "docs/guide.md", b"# guide\n");
2263
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
2264
    write(&origin_dir, "docs/logo.png", &logo);
2265
    write(&origin_dir, "README.md", b"# top\n");
2266
    let h1 = origin.commit("tree", &[]).unwrap();
2267
    let url = origin_dir.to_string_lossy().to_string();
2268
75167672 Andy McCall 2269
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
2270
        .unwrap()
2271
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 2272
    assert_eq!(a.config.sparse_paths, vec!["src"]);
2273
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
2274
    assert!(root.join("a/src/main.rs").exists());
2275
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
75167672 Andy McCall 2276
    assert!(
2277
        !a.store().has(&Repo::blob_ref(&logo)),
2278
        "out-of-scope blob never fetched"
2279
    );
2280
    assert!(
2281
        !a.snapshot("status").unwrap().changed,
2282
        "out-of-scope files are not removals"
2283
    );
05e71ed6 Andy McCall ↶ 2284
    assert!(!a.quick_status().unwrap().dirty);
7421309f Andy McCall ↶ 2285
2286
    // Edits in scope commit normally and keep the rest of the tree intact.
75167672 Andy McCall 2287
    write(
2288
        &root.join("a"),
2289
        "src/lib.rs",
2290
        b"pub fn a() {}\npub fn b() {}\n",
2291
    );
7421309f Andy McCall ↶ 2292
    let h2 = a.commit("edit lib", &[]).unwrap();
2293
    let st = a.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 2294
    assert!(
2295
        st.files.contains_key("docs/guide.md"),
2296
        "the state still has everything"
2297
    );
7421309f Andy McCall ↶ 2298
    assert!(a.push("origin", false).unwrap()[0].ok);
2299
    // Files created outside the scope are ignored by status.
2300
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2301
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2302
2303
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2304
    let mut a = a;
2305
    a.config.set("filter.paths", "src,docs").unwrap();
2306
    a.save_config().unwrap();
75167672 Andy McCall 2307
    let r = a
2308
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2309
        .unwrap();
7421309f Andy McCall ↶ 2310
    assert!(r.written >= 2);
75167672 Andy McCall 2311
    assert_eq!(
2312
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2313
        logo,
2314
        "now fetched lazily"
2315
    );
7421309f Andy McCall ↶ 2316
    assert!(!root.join("a/README.md").exists());
2317
    // Origin sees the change made under a sparse checkout with the full tree intact.
2318
    origin.pull("origin").err();
75167672 Andy McCall 2319
    let full = origin
2320
        .load_state(&origin.bookmark_heads().unwrap())
2321
        .unwrap()
2322
        .materialize();
2323
    assert!(
2324
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2325
    );
7421309f Andy McCall ↶ 2326
    assert!(full.files.contains_key("README.md"));
2327
    let _ = h1;
2328
}
2863456a Andy McCall ↶ 2329
2330
#[test]
2331
fn shallow_clone_and_deepen() {
2332
    hermetic();
2333
    let dir = tempfile::tempdir().unwrap();
2334
    let root = dir.path();
2335
    let origin_dir = root.join("origin");
75167672 Andy McCall 2336
    let origin = Repo::init(&origin_dir)
2337
        .unwrap()
2338
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2339
    let mut hashes = Vec::new();
2340
    for i in 0..8 {
75167672 Andy McCall 2341
        write(
2342
            &origin_dir,
2343
            "a.txt",
2344
            format!(
2345
                "{}\n",
2346
                (0..=i)
2347
                    .map(|k| k.to_string())
2348
                    .collect::<Vec<_>>()
2349
                    .join("\n")
2350
            )
2351
            .as_bytes(),
2352
        );
2863456a Andy McCall ↶ 2353
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2354
    }
2355
    let url = origin_dir.to_string_lossy().to_string();
75167672 Andy McCall 2356
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2357
        .unwrap()
2358
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2359
    assert!(a.is_shallow());
75167672 Andy McCall 2360
    assert_eq!(
2361
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2362
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2363
    );
2364
    assert!(
2365
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2366
        "three levels present"
2367
    );
2863456a Andy McCall ↶ 2368
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2369
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
75167672 Andy McCall 2370
    assert_eq!(
2371
        a.log().unwrap().len(),
2372
        9,
2373
        "the log shows every change from the checkpoint's metadata"
2374
    );
2863456a Andy McCall ↶ 2375
    assert!(!a.snapshot("status").unwrap().changed);
2376
    assert_eq!(a.quick_status().unwrap().heads, 1);
2377
2378
    // Work continues on top of the shallow history and pushes back.
2379
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2380
    let h_new = a.commit("c8", &[]).unwrap();
2381
    assert!(a.push("origin", false).unwrap()[0].ok);
2382
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2383
    // Fetching new work from origin into the shallow clone works too.
2384
    write(&origin_dir, "b.txt", b"b\n");
2385
    origin.pull("origin").err();
2386
    let (_, wc) = origin.working_copy().unwrap();
2387
    let _ = wc;
75167672 Andy McCall 2388
    origin
2389
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2390
        .unwrap();
2863456a Andy McCall ↶ 2391
    write(&origin_dir, "b.txt", b"b\n");
2392
    let h_b = origin.commit("b", &[]).unwrap();
2393
    let pr = a.pull("origin").unwrap();
2394
    assert!(pr.changed);
2395
    assert!(a.store().has(&h_b));
2396
    assert!(root.join("a/b.txt").exists());
2397
2398
    // Deepening fetches older history until the boundary is gone.
2399
    // Every commit also depends on the change that created the file, so two
2400
    // levels below the boundary hold h4, h3, and the root.
2401
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2402
    assert!(a.store().has(&hashes[3]));
2403
    assert!(a.is_shallow());
2404
    a.deepen("origin", 100).unwrap();
2405
    assert!(!a.is_shallow(), "boundary reached the root");
2406
    assert!(a.store().has(&hashes[0]));
75167672 Andy McCall 2407
    assert_eq!(
2408
        a.load_state_full(&a.bookmark_heads().unwrap())
2409
            .unwrap()
2410
            .len(),
2411
        10
2412
    );
2863456a Andy McCall ↶ 2413
}
132b884b Andy McCall ↶ 2414
2415
#[test]
2416
fn tags_are_immutable_named_states_and_travel() {
2417
    hermetic();
2418
    let dir = tempfile::tempdir().unwrap();
2419
    let root = dir.path();
2420
    let origin = Repo::init(&root.join("origin")).unwrap();
2421
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2422
    let mut a = Repo::clone(&url, &root.join("a"))
2423
        .unwrap()
2424
        .with_home(root.join("home-a"));
2425
    let (key_a, _) = a
2426
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2427
        .unwrap();
132b884b Andy McCall ↶ 2428
    write(&root.join("a"), "f.txt", b"1\n");
2429
    let h1 = a.commit("one", &[]).unwrap();
2430
    write(&root.join("a"), "f.txt", b"1\n2\n");
2431
    let h2 = a.commit("two", &[]).unwrap();
2432
2433
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
75167672 Andy McCall 2434
    assert_eq!(
2435
        (t.heads.clone(), t.signer.as_deref()),
2436
        (vec![h1], Some("Ada"))
2437
    );
132b884b Andy McCall ↶ 2438
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2439
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2440
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2441
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2442
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2443
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2444
    assert_eq!(sa.sigs[0].key, key_a);
2445
    // Checkout by tag.
75167672 Andy McCall 2446
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2447
        .unwrap();
132b884b Andy McCall ↶ 2448
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
75167672 Andy McCall 2449
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2450
        .unwrap();
132b884b Andy McCall ↶ 2451
2452
    // Push carries the tag; a second attestation for the name is refused.
2453
    let r = a.push("origin", false).unwrap();
2454
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2455
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
75167672 Andy McCall 2456
    let mut forged = a
2457
        .tag_refs()
2458
        .unwrap()
2459
        .into_iter()
2460
        .find(|t| t.name == "v1")
2461
        .unwrap();
2462
    forged.state = origin
2463
        .store()
2464
        .put_state(&StateObject::new(vec![h2]))
2465
        .unwrap();
132b884b Andy McCall ↶ 2466
    forged.heads = vec![h2];
2467
    forged.attestation = None;
75167672 Andy McCall 2468
    let r = origin
2469
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2470
        .unwrap();
132b884b Andy McCall ↶ 2471
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2472
2473
    // A clone gets the tag; a later tag arrives on fetch.
75167672 Andy McCall 2474
    let b = Repo::clone(&url, &root.join("b"))
2475
        .unwrap()
2476
        .with_home(root.join("home-b"));
132b884b Andy McCall ↶ 2477
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2478
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2479
    a.tag_create("v2", &[h2], "second").unwrap();
2480
    a.push("origin", false).unwrap();
2481
    let rep = b.fetch("origin").unwrap();
2482
    assert_eq!(rep.new_tags, 1);
2483
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2484
2485
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2486
    a.policy_init().unwrap();
2487
    a.push("origin", false).unwrap();
75167672 Andy McCall 2488
    let unattested = crate::protocol::TagRef {
2489
        name: "v3".into(),
2490
        state: origin
2491
            .store()
2492
            .put_state(&StateObject::new(vec![h2]))
2493
            .unwrap(),
2494
        heads: vec![h2],
2495
        attestation: None,
2496
    };
2497
    let r = origin
2498
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2499
        .unwrap();
132b884b Andy McCall ↶ 2500
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2501
    a.tag_create("v3", &[h2], "").unwrap();
2502
    let r = a.push("origin", false).unwrap();
2503
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2504
    assert!(a.gc(true).is_ok());
2505
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
e5d9b051 Andy McCall ↶ 2506
2507
    // After a rotation the policy names only the new key, yet a fresh clone
2508
    // still takes the tags the old key made before it; the old key makes
2509
    // nothing new.
2510
    let rot = a.rotate_identity().unwrap();
2511
    let r = a.push("origin", false).unwrap();
2512
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2513
    let c = Repo::clone(&url, &root.join("c"))
2514
        .unwrap()
2515
        .with_home(root.join("home-c"));
2516
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
2517
    let (_, sp) = c.current_policy().unwrap().unwrap();
2518
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
2519
    let made = c.identity(&rot.new).unwrap().created;
2520
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
2521
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
2522
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
132b884b Andy McCall ↶ 2523
}
4e88e774 Andy McCall ↶ 2524
2525
#[test]
2526
fn multiple_workspaces_share_a_repository() {
2527
    hermetic();
2528
    let dir = tempfile::tempdir().unwrap();
2529
    let root = dir.path();
2530
    let main_dir = root.join("main");
2531
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2532
    write(&main_dir, "a.txt", b"a\n");
2533
    let h1 = repo.commit("a", &[]).unwrap();
2534
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2535
2536
    // A second workspace elsewhere, checked out on the bookmark.
2537
    let ws_dir = root.join("ws2");
2538
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2539
    assert!(ws_dir.join(".oxy").is_file());
2540
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2541
    assert_ne!(ws.workspace(), repo.workspace());
2542
    let list = repo.workspaces().unwrap();
2543
    assert_eq!(list.len(), 2);
75167672 Andy McCall 2544
    assert!(list
2545
        .iter()
2546
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
4e88e774 Andy McCall ↶ 2547
    assert!(!ws.snapshot("status").unwrap().changed);
2548
2549
    // Work in the second workspace: its own working copy, shared bookmark.
2550
    write(&ws_dir, "b.txt", b"b\n");
2551
    let s = ws.snapshot("status").unwrap();
2552
    assert_eq!(s.statuses.len(), 1);
75167672 Andy McCall 2553
    assert!(
2554
        !repo.snapshot("status").unwrap().changed,
2555
        "the first workspace is untouched"
2556
    );
4e88e774 Andy McCall ↶ 2557
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2558
    let mut heads = repo.bookmark_heads().unwrap();
2559
    heads.sort();
2560
    let mut want = vec![h1, h2];
2561
    want.sort();
2562
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2563
    assert!(!main_dir.join("b.txt").exists());
75167672 Andy McCall 2564
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2565
        .unwrap();
4e88e774 Andy McCall ↶ 2566
    assert!(main_dir.join("b.txt").exists());
2567
2568
    // Reopening from inside the second workspace finds the shared repository.
2569
    let reopened = Repo::open(&ws_dir).unwrap();
2570
    assert_eq!(reopened.workspace(), ws.workspace());
2571
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2572
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2573
2574
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2575
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2576
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2577
    repo.workspace_forget(&ws.workspace()).unwrap();
2578
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2579
    assert!(ws_dir.join("b.txt").exists());
75167672 Andy McCall 2580
    assert!(
2581
        ws.snapshot("status").is_err(),
2582
        "a forgotten workspace is no longer in the view"
2583
    );
4e88e774 Andy McCall ↶ 2584
6caacfff Andy McCall ↶ 2585
    // The working-copy lock: re-entrant in a thread; a lock whose process
2586
    // is gone is taken over, and a live process's is not, however old.
4e88e774 Andy McCall ↶ 2587
    let lock = repo.lock_snapshot().unwrap();
6caacfff Andy McCall ↶ 2588
    let again = repo.lock_working_copy().unwrap();
2589
    drop(again);
4e88e774 Andy McCall ↶ 2590
    drop(lock);
75167672 Andy McCall 2591
    let lock_path = main_dir
2592
        .join(".oxy/workspaces")
2593
        .join(repo.workspace().to_hex())
2594
        .join("lock");
4e88e774 Andy McCall ↶ 2595
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
6caacfff Andy McCall ↶ 2596
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2597
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2598
    age(&lock_path);
2599
    assert!(
2600
        !super::workspace::lock_is_stale(&lock_path),
2601
        "a live process keeps its lock"
2602
    );
2603
    fs::write(&lock_path, "4294967295").unwrap();
2604
    age(&lock_path);
4e88e774 Andy McCall ↶ 2605
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2606
}
cdb5beba Andy McCall ↶ 2607
2608
#[test]
2609
fn attributes_binary_eol_nocompress_lockable() {
2610
    hermetic();
2611
    let dir = tempfile::tempdir().unwrap();
2612
    let root = dir.path();
2613
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2614
    write(
2615
        root,
2616
        ".oxyattributes",
2617
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2618
    );
cdb5beba Andy McCall ↶ 2619
    write(root, "plain.dat", b"no nul bytes here\n");
2620
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2621
    write(root, "assets/model.bin", b"\0model");
2622
    let h = repo.commit("attrs", &[]).unwrap();
2623
    let snap = repo.load_state(&[h]).unwrap().materialize();
75167672 Andy McCall 2624
    assert!(
2625
        snap.files["plain.dat"].mode.opaque,
2626
        "binary attribute forces opaque without NUL bytes"
2627
    );
2628
    assert!(
2629
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2630
        "stored with LF"
2631
    );
2632
    assert!(
2633
        !repo.snapshot("status").unwrap().changed,
2634
        "CRLF on disk equals LF in the state"
2635
    );
cdb5beba Andy McCall ↶ 2636
    // nocompress chunks pack raw.
2637
    let r = repo.gc(true).unwrap();
2638
    assert!(r.packed.objects > 0);
2639
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2640
    fs::remove_file(root.join("notes.txt")).unwrap();
2641
    repo.checkout(&[h], true, "co").unwrap();
2642
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
75167672 Andy McCall 2643
    assert!(fs::metadata(root.join("assets/model.bin"))
2644
        .unwrap()
2645
        .permissions()
2646
        .readonly());
cdb5beba Andy McCall ↶ 2647
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2648
    repo.lock_path("assets/model.bin").unwrap();
75167672 Andy McCall 2649
    assert!(!fs::metadata(root.join("assets/model.bin"))
2650
        .unwrap()
2651
        .permissions()
2652
        .readonly());
cdb5beba Andy McCall ↶ 2653
    assert!(repo.is_locked("assets/model.bin"));
2654
    write(root, "assets/model.bin", b"\0model2");
2655
    repo.commit("edit model", &[]).unwrap();
2656
    repo.unlock_path("assets/model.bin").unwrap();
75167672 Andy McCall 2657
    assert!(fs::metadata(root.join("assets/model.bin"))
2658
        .unwrap()
2659
        .permissions()
2660
        .readonly());
cdb5beba Andy McCall ↶ 2661
    // A later checkout can still overwrite a read-only lockable file.
2662
    repo.checkout(&[h], true, "co").unwrap();
2663
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2664
}
6d3eefbc Andy McCall ↶ 2665
2666
#[cfg(unix)]
2667
#[test]
2668
fn hooks_can_veto_observe_and_add_dependencies() {
2669
    use std::os::unix::fs::PermissionsExt;
2670
    hermetic();
2671
    let dir = tempfile::tempdir().unwrap();
2672
    let root = dir.path();
2673
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2674
    let hooks = root.join(".oxy/hooks");
2675
    fs::create_dir_all(&hooks).unwrap();
2676
    let hook = |name: &str, body: &str| {
2677
        let p = hooks.join(name);
2678
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2679
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2680
    };
2681
    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");
2682
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2683
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2684
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2685
    write(root, ".oxyignore", b".last-*\n");
2686
    write(root, "a.txt", b"a\n");
2687
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2688
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2689
    let h1 = repo.commit("first", &[]).unwrap();
2690
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
75167672 Andy McCall 2691
    assert!(
2692
        pre.contains("\"event\":\"pre-commit\"")
2693
            && pre.contains("\"path\":\"a.txt\"")
2694
            && pre.contains("\"message\":\"first\""),
2695
        "{pre}"
2696
    );
6d3eefbc Andy McCall ↶ 2697
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2698
    assert!(post.contains(&h1.to_hex()), "{post}");
2699
    repo.checkout(&[h1], false, "co").unwrap();
75167672 Andy McCall 2700
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2701
        .unwrap()
2702
        .contains("post-checkout"));
6d3eefbc Andy McCall ↶ 2703
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2704
    repo.save_config().unwrap();
2705
    let err = repo.push("origin", false).unwrap_err().to_string();
2706
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2707
2708
    // semantic-deps: only when enabled; adds an explicit dependency.
2709
    write(root, "b.txt", b"b\n");
75167672 Andy McCall 2710
    hook(
2711
        "semantic-deps",
2712
        &format!(
2713
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2714
            h1.to_hex()
2715
        ),
2716
    );
6d3eefbc Andy McCall ↶ 2717
    let h2 = repo.commit("b without hook", &[]).unwrap();
75167672 Andy McCall 2718
    assert!(
2719
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2720
        "hook disabled by default"
2721
    );
6d3eefbc Andy McCall ↶ 2722
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2723
    repo.save_config().unwrap();
2724
    write(root, "c.txt", b"c\n");
2725
    let h3 = repo.commit("c with hook", &[]).unwrap();
2726
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2727
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
75167672 Andy McCall 2728
    assert!(
2729
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2730
        "{sem}"
2731
    );
6d3eefbc Andy McCall ↶ 2732
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2733
}
23b217d7 Andy McCall ↶ 2734
2735
#[test]
2736
fn amend_into_older_change_and_split() {
2737
    hermetic();
2738
    let dir = tempfile::tempdir().unwrap();
2739
    let root = dir.path();
2740
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2741
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2742
        .unwrap();
23b217d7 Andy McCall ↶ 2743
    repo.set_user_config("core.sign", "change").unwrap();
2744
    write(root, "a.txt", b"one\ntwo\n");
2745
    let h0 = repo.commit("base", &[]).unwrap();
2746
    write(root, "a.txt", b"one\nTWO\n");
2747
    let h1 = repo.commit("edit two", &[]).unwrap();
2748
    write(root, "a.txt", b"one\nTWO\nthree\n");
2749
    let h2 = repo.commit("add three", &[]).unwrap();
2750
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2751
2752
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2753
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2754
    let h1b = repo.amend_into(&h1, None).unwrap();
2755
    assert_ne!(h1b, h1);
2756
    let c1b = repo.store().get_change(&h1b).unwrap();
2757
    assert_eq!(c1b.change_id, id1);
2758
    assert_eq!(c1b.deps, vec![h0]);
75167672 Andy McCall 2759
    assert!(matches!(
2760
        repo.verify_change(&h1b).unwrap(),
2761
        SignatureStatus::Valid { .. }
2762
    ));
23b217d7 Andy McCall ↶ 2763
    let heads = repo.bookmark_heads().unwrap();
2764
    assert_eq!(heads.len(), 1);
2765
    let top = repo.store().get_change(&heads[0]).unwrap();
2766
    assert_eq!(top.message, "add three");
75167672 Andy McCall 2767
    assert_eq!(
2768
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2769
        [h0, h1b].into_iter().collect(),
2770
        "depends on the file's creator and the rewritten line"
2771
    );
23b217d7 Andy McCall ↶ 2772
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 2773
    assert!(
2774
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2775
    );
2776
    assert!(
2777
        !repo.snapshot("status").unwrap().changed,
2778
        "the working copy is clean after folding"
2779
    );
23b217d7 Andy McCall ↶ 2780
    // Only h1b's own state shows the fix without "three".
2781
    let only = repo.load_state(&[h1b]).unwrap().materialize();
75167672 Andy McCall 2782
    assert!(
2783
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2784
    );
23b217d7 Andy McCall ↶ 2785
    assert_eq!(repo.log().unwrap().len(), 4);
2786
2787
    // An edit to a line introduced by h2 cannot fold into h1.
2788
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2789
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2790
    assert!(err.contains("introduced after"), "{err}");
75167672 Andy McCall 2791
    assert!(
2792
        repo.snapshot("status").unwrap().statuses.len() == 1,
2793
        "nothing was changed by the refusal"
2794
    );
23b217d7 Andy McCall ↶ 2795
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2796
2797
    // Split the head that touches two files.
2798
    write(root, "b.txt", b"b\n");
2799
    write(root, "c.txt", b"c\n");
2800
    let h3 = repo.commit("b and c", &[]).unwrap();
2801
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2802
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2803
    let c_1 = repo.store().get_change(&p1).unwrap();
2804
    let c_2 = repo.store().get_change(&p2).unwrap();
2805
    assert!(c_1.message.contains("part 1: b.txt"));
2806
    assert_eq!(c_2.change_id, id3);
2807
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
75167672 Andy McCall 2808
    assert!(
2809
        heads.contains(&p1) && heads.contains(&p2),
2810
        "independent parts are both heads"
2811
    );
2812
    let snap = repo
2813
        .load_state(&repo.bookmark_heads().unwrap())
2814
        .unwrap()
2815
        .materialize();
23b217d7 Andy McCall ↶ 2816
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2817
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2818
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2819
    assert!(!repo.snapshot("status").unwrap().changed);
2820
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2821
    let _ = h2;
2822
}
28fc23d7 Andy McCall ↶ 2823
2824
#[test]
2825
fn identity_lifecycle() {
2826
    hermetic();
2827
    let dir = tempfile::tempdir().unwrap();
2828
    let root = dir.path();
2829
    let origin = Repo::init(&root.join("origin")).unwrap();
2830
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2831
    let mut a = Repo::clone(&url, &root.join("a"))
2832
        .unwrap()
2833
        .with_home(root.join("home-a"));
28fc23d7 Andy McCall ↶ 2834
    a.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 2835
    let (key_a, _) = a
2836
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2837
        .unwrap();
28fc23d7 Andy McCall ↶ 2838
    write(&root.join("a"), "a.txt", b"a\n");
2839
    let h1 = a.commit("one", &[]).unwrap();
2840
    assert!(a.policy_init().unwrap().applied);
2841
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2842
2843
    // Expiry: an identity that had expired when the change was made does not authenticate it.
75167672 Andy McCall 2844
    let mut e = Repo::init(&root.join("e"))
2845
        .unwrap()
2846
        .with_home(root.join("home-e"));
28fc23d7 Andy McCall ↶ 2847
    e.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 2848
    e.create_identity_with(
2849
        "Eve",
2850
        "[email protected]",
2851
        IdentityScope::User,
2852
        Some(Hlc::now().wall_ms - 1),
2853
    )
2854
    .unwrap();
28fc23d7 Andy McCall ↶ 2855
    write(&root.join("e"), "e.txt", b"e\n");
2856
    let he = e.commit("late", &[]).unwrap();
75167672 Andy McCall 2857
    assert!(
2858
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2859
    );
28fc23d7 Andy McCall ↶ 2860
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
75167672 Andy McCall 2861
    let r = e
2862
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2863
        .unwrap();
28fc23d7 Andy McCall ↶ 2864
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2865
    write(&root.join("e"), "e.txt", b"e2\n");
2866
    let he2 = e.commit("in time", &[]).unwrap();
75167672 Andy McCall 2867
    assert!(
2868
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2869
    );
28fc23d7 Andy McCall ↶ 2870
2871
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2872
    let r = a.rotate_identity().unwrap();
2873
    assert_eq!(r.old, key_a);
2874
    assert_eq!(a.config.author_key, Some(r.new));
2875
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2876
    assert!(r.policy.as_ref().unwrap().applied);
2877
    let (_, sp) = a.current_policy().unwrap().unwrap();
75167672 Andy McCall 2878
    assert_eq!(
2879
        (sp.policy.serial, sp.policy.roots.clone()),
2880
        (2, vec![r.new])
2881
    );
2882
    assert!(
2883
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2884
        "superseded, not revoked"
2885
    );
28fc23d7 Andy McCall ↶ 2886
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
75167672 Andy McCall 2887
    assert!(
2888
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2889
    );
28fc23d7 Andy McCall ↶ 2890
    write(&root.join("a"), "a.txt", b"a2\n");
2891
    let h2 = a.commit("two", &[]).unwrap();
75167672 Andy McCall 2892
    assert!(
2893
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2894
    );
28fc23d7 Andy McCall ↶ 2895
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2896
    let res = a.push("origin", false).unwrap();
2897
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2898
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2899
    let key_a = r.new;
2900
2901
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2902
    // identity object, so Ada's KeyId changes while her keys stay the same.
75167672 Andy McCall 2903
    let mut b = Repo::clone(&url, &root.join("b"))
2904
        .unwrap()
2905
        .with_home(root.join("home-b"));
2906
    let (key_b, id_b) = b
2907
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2908
        .unwrap();
7ba155f2 Andy McCall ↶ 2909
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
28fc23d7 Andy McCall ↶ 2910
    assert_eq!(r.old, key_a);
2911
    let key_a2 = r.new;
75167672 Andy McCall 2912
    assert_eq!(
7ba155f2 Andy McCall ↶ 2913
        a.identity(&key_a2).unwrap().delegates,
2914
        vec![Delegate::full(key_b)]
2915
    );
2916
    assert_eq!(
75167672 Andy McCall 2917
        a.identity(&key_a2).unwrap().ed25519_pk,
2918
        a.identity(&key_a).unwrap().ed25519_pk
7ba155f2 Andy McCall ↶ 2919
    );
2920
    assert!(
2921
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2922
        "already a delegate"
75167672 Andy McCall 2923
    );
28fc23d7 Andy McCall ↶ 2924
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2925
    write(&root.join("a"), "a.txt", b"a3\n");
2926
    let h3 = a.commit("three", &[]).unwrap();
75167672 Andy McCall 2927
    assert!(
2928
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2929
        "the same secret signs under the new KeyId"
2930
    );
28fc23d7 Andy McCall ↶ 2931
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2932
    a.set_user_config("core.sign", "seal").unwrap();
2933
    write(&root.join("a"), "a.txt", b"a4\n");
2934
    let h4 = a.commit("four", &[]).unwrap();
2935
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2936
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 2937
    a.store()
2938
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2939
        .unwrap();
2940
    assert!(
2941
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2942
    );
28fc23d7 Andy McCall ↶ 2943
    a.set_user_config("core.sign", "change").unwrap();
2944
    // Withdrawing the delegation re-issues the identity again.
2945
    let r = a.delegate_remove(&key_b).unwrap();
2946
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2947
    assert!(a.delegate_remove(&key_b).is_err());
2948
    let key_a3 = r.new;
2949
    let res = a.push("origin", false).unwrap();
2950
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2951
2952
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2953
    // both applied under the old threshold of 1. A grant then needs Bob too.
2954
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2955
    assert!(a.policy_root_add(id_b.clone()).is_err());
2956
    assert!(a.policy_set_threshold(3).is_err());
2957
    assert!(a.policy_set_threshold(2).unwrap().applied);
2958
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2959
    b.pull("origin").unwrap();
75167672 Andy McCall 2960
    assert_eq!(
2961
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2962
        2
2963
    );
2964
    let mut c = Repo::init(&root.join("c"))
2965
        .unwrap()
2966
        .with_home(root.join("home-c"));
2967
    let (key_c, id_c) = c
2968
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2969
        .unwrap();
28fc23d7 Andy McCall ↶ 2970
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2971
    let proposal = a.policy_grant(id_c, None).unwrap();
2972
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2973
    assert_eq!(proposal.policy.serial, serial_before + 1);
75167672 Andy McCall 2974
    assert_eq!(
2975
        a.current_policy().unwrap().unwrap().1.policy.serial,
2976
        serial_before,
2977
        "a proposal changes nothing yet"
2978
    );
28fc23d7 Andy McCall ↶ 2979
    // Bob signs the proposal, handed over as a file, and it applies for him.
2980
    let bytes = proposal.signed().encode();
75167672 Andy McCall 2981
    let signed = b
2982
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2983
        .unwrap();
28fc23d7 Andy McCall ↶ 2984
    assert!(signed.applied && signed.sigs.len() == 2);
75167672 Andy McCall 2985
    assert!(b
2986
        .current_policy()
2987
        .unwrap()
2988
        .unwrap()
2989
        .1
2990
        .policy
2991
        .authorizes(&key_c, "main"));
2992
    assert!(
2993
        b.policy_sign(signed.signed()).is_err(),
2994
        "a stale proposal is refused"
2995
    );
28fc23d7 Andy McCall ↶ 2996
    // Bob publishes it and Ada picks it up.
75167672 Andy McCall 2997
    assert!(b
2998
        .push("origin", false)
2999
        .unwrap()
3000
        .iter()
3001
        .any(|x| x.name == "policy" && x.ok));
28fc23d7 Andy McCall ↶ 3002
    a.pull("origin").unwrap();
75167672 Andy McCall 3003
    assert_eq!(
3004
        a.current_policy().unwrap().unwrap().1.policy.serial,
3005
        serial_before + 1
3006
    );
28fc23d7 Andy McCall ↶ 3007
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
3008
    assert!(a.policy_revoke(&key_a3).is_err());
75167672 Andy McCall 3009
    let u = a
3010
        .revoke_identity(&key_c, "left the project")
3011
        .unwrap()
3012
        .unwrap();
28fc23d7 Andy McCall ↶ 3013
    assert!(!u.applied);
3014
    assert!(a.is_revoked(&key_c).unwrap());
3015
    assert!(!b.is_revoked(&key_c).unwrap());
3016
    let u = b.policy_sign(u.signed()).unwrap();
3017
    assert!(u.applied && u.policy.is_revoked(&key_c));
3018
    assert!(b.is_revoked(&key_c).unwrap());
3019
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
75167672 Andy McCall 3020
    assert!(
3021
        b.policy_revoke(&key_a3).is_err(),
3022
        "would leave one root for a threshold of 2"
3023
    );
28fc23d7 Andy McCall ↶ 3024
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
3025
    let key_c_own = c.config.author_key.unwrap();
75167672 Andy McCall 3026
    assert!(c
3027
        .revoke_identity(&key_c_own, "lost laptop")
3028
        .unwrap()
3029
        .is_none());
28fc23d7 Andy McCall ↶ 3030
    assert!(c.is_revoked(&key_c_own).unwrap());
3031
    assert_eq!(key_c_own, key_c);
3032
}
3033
6e723b81 Andy McCall ↶ 3034
#[test]
3035
fn renames_are_detected_and_tracked_as_moves() {
3036
    hermetic();
3037
    let dir = tempfile::tempdir().unwrap();
3038
    let root = dir.path();
3039
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3040
    write(
3041
        root,
3042
        "src/old.rs",
3043
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
3044
    );
6e723b81 Andy McCall ↶ 3045
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
3046
    write(root, "tiny.txt", b"x\n");
3047
    let h1 = repo.commit("base", &[]).unwrap();
3048
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
3049
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
3050
3051
    // Rename with a small edit, a binary moved unchanged, and a rewrite
3052
    // that shares nothing with the removed file.
3053
    fs::remove_file(root.join("src/old.rs")).unwrap();
75167672 Andy McCall 3054
    write(
3055
        root,
3056
        "lib/new.rs",
3057
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
3058
    );
6e723b81 Andy McCall ↶ 3059
    fs::remove_file(root.join("img.bin")).unwrap();
3060
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
3061
    fs::remove_file(root.join("tiny.txt")).unwrap();
3062
    write(root, "other.txt", b"completely different\n");
3063
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3064
    let statuses: Vec<(&str, ChangeStatus)> = snap
3065
        .statuses
3066
        .iter()
3067
        .map(|s| (s.path.as_str(), s.status))
3068
        .collect();
6e723b81 Andy McCall ↶ 3069
    assert_eq!(
3070
        statuses,
75167672 Andy McCall 3071
        vec![
3072
            ("assets/img.bin", ChangeStatus::Renamed),
3073
            ("lib/new.rs", ChangeStatus::Renamed),
3074
            ("other.txt", ChangeStatus::Added),
3075
            ("src", ChangeStatus::Removed),
3076
            ("tiny.txt", ChangeStatus::Removed)
3077
        ]
6e723b81 Andy McCall ↶ 3078
    );
3079
    let h2 = repo.commit("move things", &[]).unwrap();
3080
    let c = repo.store().get_change(&h2).unwrap();
75167672 Andy McCall 3081
    let moves: Vec<_> = c
3082
        .tree_ops
3083
        .iter()
3084
        .filter(|op| matches!(op, TreeOp::Move { .. }))
3085
        .collect();
6e723b81 Andy McCall ↶ 3086
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
75167672 Andy McCall 3087
    assert!(c.tree_ops.iter().any(
3088
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
3089
    ));
3090
    assert!(c.tree_ops.iter().any(
3091
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
3092
    ));
6e723b81 Andy McCall ↶ 3093
    let snap = repo.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 3094
    assert_eq!(
3095
        snap.files["lib/new.rs"].node, node_old,
3096
        "the node survives the rename"
3097
    );
3098
    assert!(
3099
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
3100
    );
6e723b81 Andy McCall ↶ 3101
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
75167672 Andy McCall 3102
    assert!(render_change(
3103
        &c,
3104
        &repo.load_state(&[h1]).unwrap(),
3105
        &repo.load_state(&[h1]).unwrap().materialize()
3106
    )
0912a033 Andy McCall ↶ 3107
    .contains("R src/old.rs -> lib/new.rs"));
6e723b81 Andy McCall ↶ 3108
    // A fresh checkout reproduces the tree.
3109
    let other = tempfile::tempdir().unwrap();
3110
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
75167672 Andy McCall 3111
    assert_eq!(
3112
        fs::read(other.path().join("lib/new.rs")).unwrap(),
3113
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
3114
    );
6e723b81 Andy McCall ↶ 3115
    assert!(!other.path().join("src").exists());
3116
    assert!(!clone.snapshot("status").unwrap().changed);
3117
    // Similarity is line based, byte weighted.
3118
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
3119
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
3120
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
3121
    assert_eq!(similarity(b"", b"x\n"), 0);
3122
}
3123
30ea9c1e Andy McCall ↶ 3124
#[test]
3125
fn git_fetch_and_push_round_trip() {
3126
    hermetic();
75167672 Andy McCall 3127
    if std::process::Command::new("git")
3128
        .arg("--version")
3129
        .output()
3130
        .is_err()
3131
    {
30ea9c1e Andy McCall ↶ 3132
        eprintln!("git not installed; skipping");
3133
        return;
3134
    }
3135
    let dir = tempfile::tempdir().unwrap();
3136
    let root = dir.path();
3137
    let git_in = |d: &Path, args: &[&str]| -> String {
3138
        let out = std::process::Command::new("git")
3139
            .arg("-C")
3140
            .arg(d)
75167672 Andy McCall 3141
            .args([
3142
                "-c",
3143
                "user.name=Grace",
3144
                "-c",
3145
                "[email protected]",
3146
                "-c",
3147
                "commit.gpgsign=false",
3148
            ])
30ea9c1e Andy McCall ↶ 3149
            .args(args)
3150
            .output()
3151
            .unwrap();
75167672 Andy McCall 3152
        assert!(
3153
            out.status.success(),
3154
            "git {args:?}: {}",
3155
            String::from_utf8_lossy(&out.stderr)
3156
        );
30ea9c1e Andy McCall ↶ 3157
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3158
    };
3159
    // A bare "remote" and a work tree that pushes to it.
3160
    let remote = root.join("remote.git");
3161
    fs::create_dir_all(&remote).unwrap();
3162
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
3163
    let work = root.join("work");
75167672 Andy McCall 3164
    git_in(
3165
        root,
3166
        &[
3167
            "clone",
3168
            "-q",
3169
            remote.to_str().unwrap(),
3170
            work.to_str().unwrap(),
3171
        ],
3172
    );
30ea9c1e Andy McCall ↶ 3173
    git_in(&work, &["checkout", "-q", "-b", "main"]);
3174
    write(&work, "README.md", b"# Project\n");
3175
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
3176
    git_in(&work, &["add", "."]);
3177
    git_in(&work, &["commit", "-q", "-m", "initial"]);
3178
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3179
    git_in(&work, &["commit", "-q", "-am", "second"]);
3180
    git_in(&work, &["push", "-q", "origin", "main"]);
3181
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
3182
3183
    // Fetch into a fresh oxy repository.
3184
    let o = root.join("oxy");
3185
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3186
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3187
        .unwrap();
30ea9c1e Andy McCall ↶ 3188
    let url = remote.to_string_lossy().to_string();
3189
    let r = repo.git_fetch(&url, "main").unwrap();
3190
    assert_eq!((r.commits, r.heads), (2, 1));
75167672 Andy McCall 3191
    assert_eq!(
3192
        fs::read(o.join("src/lib.rs")).unwrap(),
3193
        b"pub fn a() {}\npub fn b() {}\n"
3194
    );
30ea9c1e Andy McCall ↶ 3195
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 3196
    assert_eq!(
3197
        repo.git_fetch(&url, "main").unwrap().commits,
3198
        0,
3199
        "nothing new"
3200
    );
30ea9c1e Andy McCall ↶ 3201
3202
    // An oxy change, pushed back: one commit on top of the Git tip.
75167672 Andy McCall 3203
    write(
3204
        &o,
3205
        "src/lib.rs",
3206
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3207
    );
30ea9c1e Andy McCall ↶ 3208
    write(&o, "NOTES.md", b"from oxy\n");
3209
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
3210
    let r = repo.git_push(&url, "main").unwrap();
3211
    assert_eq!(r.exported, 1, "{r:?}");
3212
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
75167672 Andy McCall 3213
    assert_eq!(
3214
        git_in(&work, &["log", "--format=%s", "main"]),
3215
        "add c and notes\nsecond\ninitial"
3216
    );
30ea9c1e Andy McCall ↶ 3217
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
3218
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
3219
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
75167672 Andy McCall 3220
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
3221
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
3222
    assert_eq!(
3223
        repo.git_push(&url, "main").unwrap().exported,
3224
        0,
3225
        "already pushed"
3226
    );
30ea9c1e Andy McCall ↶ 3227
3228
    // Git moves on; pushing without fetching is refused, fetching brings
3229
    // the commit in and the working copy follows.
3230
    write(&work, "README.md", b"# Project\n\nMore.\n");
3231
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
3232
    git_in(&work, &["push", "-q", "origin", "main"]);
3233
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
75167672 Andy McCall 3234
    assert!(repo
3235
        .git_push(&url, "main")
3236
        .unwrap_err()
3237
        .to_string()
3238
        .contains("fetch"));
30ea9c1e Andy McCall ↶ 3239
    let r = repo.git_fetch(&url, "main").unwrap();
75167672 Andy McCall 3240
    assert_eq!(
3241
        (r.commits, r.heads),
3242
        (1, 2),
3243
        "the Git change and the oxy change commute"
3244
    );
3245
    assert_eq!(
3246
        fs::read(o.join("README.md")).unwrap(),
3247
        b"# Project\n\nMore.\n"
3248
    );
30ea9c1e Andy McCall ↶ 3249
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
3250
    assert!(!repo.snapshot("status").unwrap().changed);
3251
    // Another oxy change pushes on top of Git's newest commit.
3252
    write(&o, "NOTES.md", b"from oxy\nagain\n");
3253
    repo.commit("notes again", &[]).unwrap();
3254
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
3255
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
3256
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
75167672 Andy McCall 3257
    assert_eq!(
3258
        fs::read(work.join("NOTES.md")).unwrap(),
3259
        b"from oxy\nagain\n"
3260
    );
3261
    assert_eq!(
3262
        git_in(&work, &["log", "--format=%s", "main"])
3263
            .lines()
3264
            .count(),
3265
        5
3266
    );
30ea9c1e Andy McCall ↶ 3267
}
3268
2b872d07 Andy McCall ↶ 3269
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
3270
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
3271
#[test]
3272
#[ignore]
3273
fn bench_one_gibibyte_file() {
3274
    hermetic();
3275
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
3276
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
3277
        Some(d) => tempfile::tempdir_in(d).unwrap(),
3278
        None => tempfile::tempdir().unwrap(),
3279
    };
3280
    let root = dir.path();
75167672 Andy McCall 3281
    let repo = Repo::init(&root.join("r"))
3282
        .unwrap()
3283
        .with_home(root.join("home"));
2b872d07 Andy McCall ↶ 3284
    let size = 1usize << 30;
3285
    let mut data = vec![0u8; size];
3286
    let mut x = 0x9e3779b97f4a7c15u64;
3287
    for chunk in data.chunks_mut(8) {
3288
        x ^= x << 13;
3289
        x ^= x >> 7;
3290
        x ^= x << 17;
3291
        let b = x.to_le_bytes();
3292
        chunk.copy_from_slice(&b[..chunk.len()]);
3293
    }
3294
    let t = std::time::Instant::now();
3295
    write(&root.join("r"), "big.bin", &data);
3296
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
3297
    let t = std::time::Instant::now();
3298
    let h = repo.commit("big", &[]).unwrap();
3299
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
3300
    let t = std::time::Instant::now();
3301
    assert!(!repo.snapshot("status").unwrap().changed);
3302
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
3303
    let t = std::time::Instant::now();
3304
    let objects = repo.store().list().unwrap().len();
3305
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
3306
    let t = std::time::Instant::now();
3307
    let g = repo.gc(true).unwrap();
3308
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
3309
    let t = std::time::Instant::now();
3310
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3311
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3312
    let t = std::time::Instant::now();
3313
    let back = fs::read(root.join("c/big.bin")).unwrap();
3314
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3315
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3316
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3317
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
75167672 Andy McCall 3318
    eprintln!(
3319
        "store size: {:.1} MiB for 1 GiB of data",
3320
        store_bytes as f64 / (1024.0 * 1024.0)
3321
    );
2b872d07 Andy McCall ↶ 3322
}
3323
3324
fn walkdir_size(p: &Path) -> u64 {
3325
    let mut total = 0;
3326
    if let Ok(rd) = fs::read_dir(p) {
3327
        for e in rd.flatten() {
3328
            let path = e.path();
3329
            if path.is_dir() {
3330
                total += walkdir_size(&path);
3331
            } else if let Ok(m) = fs::metadata(&path) {
3332
                total += m.len();
3333
            }
3334
        }
3335
    }
3336
    total
3337
}
3338
b7f102fc Andy McCall ↶ 3339
/// An opaque file whose size and mtime match the manifest is not read on
3340
/// the next snapshot: its blob comes from the manifest's stat cache.
3341
#[cfg(unix)]
3342
#[test]
3343
fn stat_cache_skips_reading_unchanged_opaque_files() {
3344
    use std::os::unix::fs::PermissionsExt;
3345
    hermetic();
3346
    let dir = tempfile::tempdir().unwrap();
3347
    let root = dir.path();
3348
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3349
    let mut big = vec![0u8; 300 * 1024];
3350
    for (i, b) in big.iter_mut().enumerate() {
3351
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3352
    }
3353
    big[0] = 0;
3354
    write(root, "big.bin", &big);
3355
    write(root, "a.txt", b"text\n");
3356
    let h1 = repo.commit("base", &[]).unwrap();
3357
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
75167672 Andy McCall 3358
    assert!(
3359
        m.entries["big.bin"].blob.is_some(),
3360
        "opaque files record their blob"
3361
    );
b7f102fc Andy McCall ↶ 3362
    assert!(m.entries["a.txt"].blob.is_none());
3363
    let blob = m.entries["big.bin"].blob.unwrap();
3364
    assert!(repo.store().has(&blob));
3365
3366
    // Files modified within two seconds of the manifest are racy and still
3367
    // read; age the file so the cache applies, then snapshot to record it.
3368
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
75167672 Andy McCall 3369
    fs::File::options()
3370
        .write(true)
3371
        .open(root.join("big.bin"))
3372
        .unwrap()
3373
        .set_modified(old)
3374
        .unwrap();
b7f102fc Andy McCall ↶ 3375
    assert!(!repo.snapshot("status").unwrap().changed);
3376
    // Now the file cannot be read at all; the snapshot succeeds without it.
3377
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3378
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3379
    assert!(
3380
        !snap.changed && snap.statuses.is_empty(),
3381
        "{:?}",
3382
        snap.statuses
3383
    );
b7f102fc Andy McCall ↶ 3384
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3385
    // A real change (new mtime, new content) is seen and committed correctly.
3386
    let mut big2 = big.clone();
3387
    big2[10] ^= 0xff;
3388
    write(root, "big.bin", &big2);
3389
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3390
    assert_eq!(
3391
        snap.statuses
3392
            .iter()
3393
            .map(|s| (s.path.as_str(), s.status))
3394
            .collect::<Vec<_>>(),
3395
        vec![("big.bin", ChangeStatus::Modified)]
3396
    );
b7f102fc Andy McCall ↶ 3397
    let h2 = repo.commit("edit", &[]).unwrap();
3398
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 3399
    assert_eq!(
3400
        files["big.bin"].content,
3401
        FileContent::Opaque {
3402
            blobs: vec![Repo::blob_ref(&big2)]
3403
        }
3404
    );
b7f102fc Andy McCall ↶ 3405
    // Checkout writes a manifest with blobs too, so the next status is cached.
3406
    repo.checkout(&[h1], false, "checkout").unwrap();
3407
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3408
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3409
    assert!(!repo.snapshot("status").unwrap().changed);
3410
}
3411
50a046e4 Andy McCall ↶ 3412
#[test]
3413
fn status_json_lists_conflicts_with_contributors() {
3414
    hermetic();
3415
    let dir = tempfile::tempdir().unwrap();
3416
    let root = dir.path();
3417
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3418
    write(root, "a.txt", b"one\n");
3419
    let h1 = repo.commit("base", &[]).unwrap();
3420
    write(root, "a.txt", b"one\nleft\n");
3421
    let ha = repo.commit("left", &[]).unwrap();
3422
    repo.checkout(&[h1], true, "checkout").unwrap();
3423
    write(root, "a.txt", b"one\nright\n");
3424
    let hb = repo.commit("right", &[]).unwrap();
3425
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3426
    let snap = repo.snapshot("status").unwrap();
3427
    assert!(snap.base_snapshot.is_conflicted());
3428
    let json = repo.status_json(&snap).unwrap();
3429
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3430
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3431
    assert!(json.contains("\"conflicted\":true"), "{json}");
75167672 Andy McCall 3432
    assert!(
3433
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3434
        "{json}"
3435
    );
50a046e4 Andy McCall ↶ 3436
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3437
    assert!(json.contains("\"resolved\":false"), "{json}");
3438
    assert!(json.starts_with('{') && json.ends_with('}'));
3439
    // Resolve and the report says so; a clean copy has no conflicts.
3440
    write(root, "a.txt", b"one\nleft\nright\n");
3441
    let snap = repo.snapshot("status").unwrap();
3442
    let json = repo.status_json(&snap).unwrap();
3443
    assert!(json.contains("\"resolved\":true"), "{json}");
3444
    repo.commit("resolve", &[]).unwrap();
3445
    let snap = repo.snapshot("status").unwrap();
3446
    let json = repo.status_json(&snap).unwrap();
75167672 Andy McCall 3447
    assert!(
3448
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3449
        "{json}"
3450
    );
50a046e4 Andy McCall ↶ 3451
}
3452
9ac1fbe2 Andy McCall ↶ 3453
#[test]
3454
fn ignore_rules_do_not_untrack_files() {
3455
    hermetic();
3456
    let dir = tempfile::tempdir().unwrap();
3457
    let root = dir.path();
3458
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3459
    write(root, "src.c", b"int x;\n");
3460
    write(root, "build/out.o", b"\0obj");
3461
    write(root, "sub/keep.log", b"keep\n");
3462
    write(root, "sub/junk.log", b"junk\n");
3463
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3464
    let snap = repo.snapshot("status").unwrap();
3465
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 3466
    assert_eq!(
3467
        added,
3468
        vec![".oxyignore", "src.c", "sub/keep.log"],
3469
        "anchored, glob, and negated rules"
3470
    );
9ac1fbe2 Andy McCall ↶ 3471
    let h1 = repo.commit("base", &[]).unwrap();
3472
    // Ignoring a tracked file changes nothing about it.
3473
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3474
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3475
    assert_eq!(
3476
        snap.statuses
3477
            .iter()
3478
            .map(|s| s.path.as_str())
3479
            .collect::<Vec<_>>(),
3480
        vec![".oxyignore"]
3481
    );
9ac1fbe2 Andy McCall ↶ 3482
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
75167672 Andy McCall 3483
    assert!(repo
3484
        .load_state(&[h2])
3485
        .unwrap()
3486
        .materialize()
3487
        .files
3488
        .contains_key("src.c"));
9ac1fbe2 Andy McCall ↶ 3489
    // Its edits are still seen, by status and by the prompt.
3490
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3491
    write(root, "src.c", b"int x, y;\n");
3492
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3493
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3494
    assert_eq!(
3495
        snap.statuses
3496
            .iter()
3497
            .map(|s| (s.path.as_str(), s.status))
3498
            .collect::<Vec<_>>(),
3499
        vec![("src.c", ChangeStatus::Modified)]
3500
    );
9ac1fbe2 Andy McCall ↶ 3501
    let h3 = repo.commit("edit src.c", &[]).unwrap();
75167672 Andy McCall 3502
    assert!(
3503
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3504
    );
9ac1fbe2 Andy McCall ↶ 3505
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3506
    fs::remove_file(root.join("src.c")).unwrap();
3507
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3508
    assert_eq!(
3509
        snap.statuses
3510
            .iter()
3511
            .map(|s| (s.path.as_str(), s.status))
3512
            .collect::<Vec<_>>(),
3513
        vec![("src.c", ChangeStatus::Removed)]
3514
    );
9ac1fbe2 Andy McCall ↶ 3515
    repo.checkout(&[h3], true, "checkout").unwrap();
3516
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3517
    assert!(!repo.snapshot("status").unwrap().changed);
3518
    let _ = h1;
3519
}
3520
b837d2b5 Andy McCall ↶ 3521
#[test]
3522
fn split_works_on_non_heads_by_node() {
3523
    hermetic();
3524
    let dir = tempfile::tempdir().unwrap();
3525
    let root = dir.path();
3526
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3527
    write(root, "a.txt", b"one\n");
3528
    write(root, "junk/x.lock", b"lock\n");
3529
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3530
    write(root, "a.txt", b"one\ntwo\n");
3531
    let h2 = repo.commit("more work", &[]).unwrap();
3532
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3533
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3534
    // h1 is not a head: split it by node.
3535
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3536
    assert_ne!(h1b, h1);
75167672 Andy McCall 3537
    assert_eq!(
3538
        repo.store().get_change(&h1b).unwrap().change_id,
3539
        id1,
3540
        "the rest keeps the ChangeId"
3541
    );
b837d2b5 Andy McCall ↶ 3542
    let junk = repo.store().get_change(&hj).unwrap();
75167672 Andy McCall 3543
    assert!(junk.tree_ops.iter().all(
3544
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3545
    ));
b837d2b5 Andy McCall ↶ 3546
    let heads = repo.bookmark_heads().unwrap();
75167672 Andy McCall 3547
    assert!(
3548
        heads.contains(&hj),
3549
        "the split-off part is a head of its own"
3550
    );
b837d2b5 Andy McCall ↶ 3551
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 3552
    assert!(
3553
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3554
        "the dependent was rewritten onto the new hash"
3555
    );
b837d2b5 Andy McCall ↶ 3556
    assert!(snap.files.contains_key("junk/x.lock"));
75167672 Andy McCall 3557
    let h2b = heads
3558
        .iter()
3559
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3560
        .copied()
3561
        .unwrap();
b837d2b5 Andy McCall ↶ 3562
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3563
    assert!(!repo.snapshot("status").unwrap().changed);
3564
    // Abandoning the split-off head removes the junk from history.
3565
    repo.abandon(&hj).unwrap();
3566
    let heads = repo.bookmark_heads().unwrap();
3567
    let snap = repo.load_state(&heads).unwrap().materialize();
3568
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3569
    assert!(snap.files.contains_key("a.txt"));
3570
    // A dependent that touches the split-off paths blocks the split.
3571
    write(root, "junk/y.lock", b"y\n");
3572
    let hb = repo.commit("junk base", &[]).unwrap();
3573
    write(root, "junk/y.lock", b"yy\n");
3574
    write(root, "b.txt", b"b\n");
3575
    repo.commit("touches junk", &[]).unwrap();
3576
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3577
    assert!(err.contains("depends on the split-off paths"), "{err}");
3578
}
3579
7b9809e6 Andy McCall ↶ 3580
#[test]
3581
fn bookmarks_switch_merge_and_push() {
3582
    hermetic();
3583
    let dir = tempfile::tempdir().unwrap();
3584
    let root = dir.path();
3585
    let origin = Repo::init(&root.join("origin")).unwrap();
3586
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3587
    let mut repo = Repo::clone(&url, &root.join("r"))
3588
        .unwrap()
3589
        .with_home(root.join("home"));
7b9809e6 Andy McCall ↶ 3590
    let r = root.join("r");
3591
    write(&r, "a.txt", b"a\n");
3592
    let h_a = repo.commit("a", &[]).unwrap();
3593
    assert!(repo.push("origin", false).unwrap()[0].ok);
3594
3595
    // A bookmark at the working copy's base, then work on it.
3596
    assert!(repo.bookmark_create("bad name..", None).is_err());
3597
    assert!(repo.bookmark_create("-x", None).is_err());
3598
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3599
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3600
    repo.bookmark_switch("feature", false).unwrap();
3601
    assert_eq!(repo.config.bookmark, "feature");
3602
    write(&r, "a.txt", b"a\nb\n");
3603
    write(&r, "b.txt", b"b\n");
3604
    let h_b = repo.commit("b on feature", &[]).unwrap();
75167672 Andy McCall 3605
    assert_eq!(
3606
        repo.bookmark_heads().unwrap(),
3607
        vec![h_b],
3608
        "b edits a.txt, so it depends on a"
3609
    );
3610
    assert_eq!(
3611
        repo.resolve_heads("main").unwrap(),
3612
        vec![h_a],
3613
        "main is untouched"
3614
    );
3615
    assert_eq!(
3616
        repo.resolve_change("feature").unwrap(),
3617
        h_b,
3618
        "a one-head bookmark names its change"
3619
    );
7b9809e6 Andy McCall ↶ 3620
    // Reopening keeps the workspace's bookmark.
3621
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3622
    assert_eq!(reopened.config.bookmark, "feature");
3623
    // Back to main: b.txt goes away; work there.
3624
    repo.bookmark_switch("main", false).unwrap();
3625
    assert!(!r.join("b.txt").exists());
3626
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3627
    write(&r, "c.txt", b"c\n");
3628
    let h_c = repo.commit("c on main", &[]).unwrap();
3629
    let list = repo.bookmarks().unwrap();
75167672 Andy McCall 3630
    assert_eq!(
3631
        list.iter()
3632
            .map(|b| (b.name.as_str(), b.current))
3633
            .collect::<Vec<_>>(),
3634
        vec![("feature", false), ("main", true)]
3635
    );
3636
    assert_eq!(
3637
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3638
        Some(1),
3639
        "c is not on origin yet"
3640
    );
7b9809e6 Andy McCall ↶ 3641
    // Merge feature into main: the union, both heads, no merge change.
3642
    let m = repo.merge("feature").unwrap();
3643
    assert!(m.changed && m.checked_out);
3644
    let mut want = vec![h_b, h_c];
3645
    want.sort();
3646
    assert_eq!(m.heads, want);
3647
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3648
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3649
    assert!(repo.merge("main").is_err());
3650
    // The other bookmark can be pushed by name and appears at origin.
3651
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3652
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3653
    assert!(repo.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 3654
    assert_eq!(
3655
        repo.bookmarks()
3656
            .unwrap()
3657
            .iter()
3658
            .find(|b| b.name == "main")
3659
            .unwrap()
3660
            .ahead,
3661
        Some(0)
3662
    );
7b9809e6 Andy McCall ↶ 3663
    // A second workspace inherits the current bookmark and can switch independently.
3664
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3665
    assert_eq!(ws.config.bookmark, "main");
3666
    let mut ws = ws;
3667
    ws.bookmark_switch("feature", false).unwrap();
75167672 Andy McCall 3668
    assert_eq!(
3669
        Repo::open(&r).unwrap().config.bookmark,
3670
        "main",
3671
        "the first workspace is unaffected"
3672
    );
3673
    assert!(
3674
        repo.bookmark_delete("feature").is_err(),
3675
        "current bookmark of another workspace"
3676
    );
7b9809e6 Andy McCall ↶ 3677
    ws.bookmark_switch("main", false).unwrap();
3678
    // Set and delete.
3679
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3680
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3681
    repo.bookmark_delete("feature").unwrap();
3682
    assert!(repo.resolve_heads("feature").is_err());
3683
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
75167672 Andy McCall 3684
    assert!(
3685
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3686
        "changes of a deleted bookmark remain"
3687
    );
7b9809e6 Andy McCall ↶ 3688
}
3689
4dee277c Andy McCall ↶ 3690
#[test]
3691
fn oxygen_subrepos_pin_follow_and_update() {
3692
    hermetic();
3693
    let dir = tempfile::tempdir().unwrap();
3694
    let root = dir.path();
3695
    // A library repository with two commits, and a bare-ish origin for it.
3696
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3697
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
75167672 Andy McCall 3698
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3699
        .unwrap()
3700
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3701
    write(&root.join("lib"), "lib.txt", b"v1\n");
3702
    let l1 = lib.commit("lib v1", &[]).unwrap();
3703
    assert!(lib.push("origin", false).unwrap()[0].ok);
3704
    let _ = lib_origin;
3705
3706
    // The application (a clone of its own origin) adds it as a subrepo.
3707
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3708
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3709
    let _ = app_origin;
3710
    let app_dir = root.join("app");
75167672 Andy McCall 3711
    let app = Repo::clone(&app_url, &app_dir)
3712
        .unwrap()
3713
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3714
    write(&app_dir, "main.txt", b"app\n");
3715
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3716
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3717
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3718
    let snap = app.snapshot("status").unwrap();
3719
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 3720
    assert_eq!(
3721
        paths,
3722
        vec![".oxymodules", "libs/lib", "main.txt"],
3723
        "the nested files are not walked"
3724
    );
4dee277c Andy McCall ↶ 3725
    let a1 = app.commit("app with lib", &[]).unwrap();
3726
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3727
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3728
    assert!(!files.contains_key("libs/lib/lib.txt"));
3729
    assert!(!app.snapshot("status").unwrap().changed);
3730
    let subs = app.subrepos().unwrap();
3731
    assert_eq!(subs.len(), 1);
3732
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3733
3734
    // Advance the nested repository: the parent sees a modified pin.
75167672 Andy McCall 3735
    let nested = Repo::open(&app_dir.join("libs/lib"))
3736
        .unwrap()
3737
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3738
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3739
    let l2 = nested.commit("lib v2", &[]).unwrap();
3740
    assert!(nested.push("origin", false).unwrap()[0].ok);
3741
    let snap = app.snapshot("status").unwrap();
75167672 Andy McCall 3742
    assert_eq!(
3743
        snap.statuses
3744
            .iter()
3745
            .map(|s| (s.path.as_str(), s.status))
3746
            .collect::<Vec<_>>(),
3747
        vec![("libs/lib", ChangeStatus::Modified)]
3748
    );
4dee277c Andy McCall ↶ 3749
    let a2 = app.commit("bump lib", &[]).unwrap();
1a3b6203 Andy McCall ↶ 3750
    // Checking out the older app state brings the nested working copy back
3751
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4dee277c Andy McCall ↶ 3752
    let r = app.checkout(&[a1], false, "checkout").unwrap();
1a3b6203 Andy McCall ↶ 3753
    assert!(
3754
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3755
        "{:?}",
3756
        r.notes
3757
    );
4dee277c Andy McCall ↶ 3758
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
1a3b6203 Andy McCall ↶ 3759
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3760
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3761
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4dee277c Andy McCall ↶ 3762
    assert!(!app.snapshot("status").unwrap().changed);
3763
    // A dirty nested repository is left alone and reported.
3764
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3765
    let r = app.checkout(&[a2], false, "checkout").unwrap();
75167672 Andy McCall 3766
    assert!(
3767
        r.notes.iter().any(|n| n.contains("uncommitted")),
3768
        "{:?}",
3769
        r.notes
3770
    );
4dee277c Andy McCall ↶ 3771
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3772
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3773
    let r = app.submodule_update(false, &[]).unwrap();
3774
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3775
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3776
    let _ = l2;
3777
3778
    // A fresh clone of the app has the pin but no nested repository until update --init.
3779
    assert!(app.push("origin", false).unwrap()[0].ok);
3780
    let clone_dir = root.join("app-clone");
75167672 Andy McCall 3781
    let clone = Repo::clone(&app_url, &clone_dir)
3782
        .unwrap()
3783
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3784
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
75167672 Andy McCall 3785
    assert_eq!(
3786
        clone.submodule_update(false, &[]).unwrap(),
3787
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3788
    );
3789
    assert_eq!(
3790
        clone.submodule_update(true, &[]).unwrap(),
3791
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3792
    );
3793
    assert_eq!(
3794
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3795
        b"v2\n"
3796
    );
4dee277c Andy McCall ↶ 3797
    assert!(!clone.snapshot("status").unwrap().changed);
3798
    // Removing the subrepo leaves the directory and drops the node.
3799
    clone.submodule_remove("libs/lib").unwrap();
3800
    let snap = clone.snapshot("status").unwrap();
75167672 Andy McCall 3801
    assert!(
3802
        snap.statuses
3803
            .iter()
3804
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3805
        "{:?}",
3806
        snap.statuses
3807
    );
4dee277c Andy McCall ↶ 3808
    let c = clone.commit("drop lib", &[]).unwrap();
75167672 Andy McCall 3809
    assert!(!clone
3810
        .load_state(&[c])
3811
        .unwrap()
3812
        .materialize()
3813
        .files
3814
        .contains_key("libs/lib"));
4dee277c Andy McCall ↶ 3815
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
75167672 Andy McCall 3816
    assert!(
3817
        !clone.snapshot("status").unwrap().changed,
3818
        "an unregistered nested repository is ignored"
3819
    );
4dee277c Andy McCall ↶ 3820
}
3821
3822
#[test]
3823
fn git_submodules_import_and_export_as_gitlinks() {
3824
    hermetic();
75167672 Andy McCall 3825
    if std::process::Command::new("git")
3826
        .arg("--version")
3827
        .output()
3828
        .is_err()
3829
    {
4dee277c Andy McCall ↶ 3830
        eprintln!("git not installed; skipping");
3831
        return;
3832
    }
3833
    let dir = tempfile::tempdir().unwrap();
3834
    let root = dir.path();
3835
    let git_in = |d: &Path, args: &[&str]| -> String {
3836
        let out = std::process::Command::new("git")
3837
            .arg("-C")
3838
            .arg(d)
75167672 Andy McCall 3839
            .args([
3840
                "-c",
3841
                "user.name=Grace",
3842
                "-c",
3843
                "[email protected]",
3844
                "-c",
3845
                "commit.gpgsign=false",
3846
                "-c",
3847
                "protocol.file.allow=always",
3848
            ])
4dee277c Andy McCall ↶ 3849
            .args(args)
3850
            .output()
3851
            .unwrap();
75167672 Andy McCall 3852
        assert!(
3853
            out.status.success(),
3854
            "git {args:?}: {}",
3855
            String::from_utf8_lossy(&out.stderr)
3856
        );
4dee277c Andy McCall ↶ 3857
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3858
    };
3859
    let sub = root.join("sub");
3860
    fs::create_dir_all(&sub).unwrap();
3861
    git_in(&sub, &["init", "-q", "-b", "main"]);
3862
    write(&sub, "s.txt", b"sub\n");
3863
    git_in(&sub, &["add", "."]);
3864
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3865
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3866
    let g = root.join("main.git");
3867
    fs::create_dir_all(&g).unwrap();
3868
    git_in(&g, &["init", "-q", "-b", "main"]);
3869
    write(&g, "README.md", b"# app\n");
3870
    git_in(&g, &["add", "."]);
3871
    git_in(&g, &["commit", "-q", "-m", "initial"]);
75167672 Andy McCall 3872
    git_in(
3873
        &g,
3874
        &[
3875
            "submodule",
3876
            "add",
3877
            "-q",
3878
            sub.to_str().unwrap(),
3879
            "vendor/sub",
3880
        ],
3881
    );
4dee277c Andy McCall ↶ 3882
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3883
3884
    let dest = root.join("oxy");
3885
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3886
    let rep = repo.import_git(&g, "main").unwrap();
3887
    assert_eq!((rep.commits, rep.submodules), (2, 1));
75167672 Andy McCall 3888
    let files = repo
3889
        .load_state(&repo.bookmark_heads().unwrap())
3890
        .unwrap()
3891
        .materialize()
3892
        .files;
4dee277c Andy McCall ↶ 3893
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
75167672 Andy McCall 3894
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3895
        panic!()
3896
    };
3897
    assert_eq!(
3898
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3899
        crate::subrepo::Pin::Git {
3900
            sha: sub_sha.clone(),
3901
            branch: "HEAD".into()
3902
        }
3903
    );
3904
    let modules =
3905
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4dee277c Andy McCall ↶ 3906
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3907
    assert!(modules.entries["vendor/sub"].git);
75167672 Andy McCall 3908
    assert!(
3909
        files.contains_key(".gitmodules"),
3910
        "the Git file is kept for round trips"
3911
    );
3912
    assert!(
3913
        !dest.join("vendor/sub/.git").exists(),
3914
        "not cloned until update --init"
3915
    );
4dee277c Andy McCall ↶ 3916
    assert!(!repo.snapshot("status").unwrap().changed);
3917
    // update --init clones it at the pinned commit; status is unchanged.
75167672 Andy McCall 3918
    assert_eq!(
3919
        repo.submodule_update(true, &[]).unwrap(),
3920
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3921
    );
3922
    assert_eq!(
3923
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3924
        sub_sha
3925
    );
4dee277c Andy McCall ↶ 3926
    assert!(!repo.snapshot("status").unwrap().changed);
3927
    // Export writes the gitlink and .gitmodules back.
3928
    let mirror = root.join("mirror.git");
3929
    let rep = repo.git_export(&mirror).unwrap();
3930
    assert_eq!(rep.skipped_subrepos, 0);
3931
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
75167672 Andy McCall 3932
    assert!(
3933
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3934
        "{ls}"
3935
    );
3936
    assert_eq!(
3937
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3938
        ".gitmodules\nREADME.md\nvendor"
3939
    );
4dee277c Andy McCall ↶ 3940
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
75167672 Andy McCall 3941
    assert_eq!(
3942
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3943
        orig_tree,
3944
        "tree round trip"
3945
    );
4dee277c Andy McCall ↶ 3946
}
3947
957fee30 Andy McCall ↶ 3948
#[test]
3949
fn partial_commits_by_path_and_by_hunk() {
3950
    hermetic();
3951
    let dir = tempfile::tempdir().unwrap();
3952
    let root = dir.path();
3953
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3954
    write(root, "a.txt", b"1\n2\n3\n");
3955
    write(root, "b.txt", b"b\n");
3956
    let h0 = repo.commit("base", &[]).unwrap();
3957
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3958
    write(root, "b.txt", b"b\nbb\n");
3959
    write(root, "c.txt", b"c\n");
3960
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
75167672 Andy McCall 3961
    let h1 = repo
3962
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3963
        .unwrap();
957fee30 Andy McCall ↶ 3964
    let c1 = repo.store().get_change(&h1).unwrap();
75167672 Andy McCall 3965
    assert!(
3966
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3967
        "{:?}",
3968
        c1.tree_ops
3969
    );
957fee30 Andy McCall ↶ 3970
    assert_eq!(c1.deps, vec![h0]);
3971
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
75167672 Andy McCall 3972
    assert!(
3973
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3974
    );
957fee30 Andy McCall ↶ 3975
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3976
    assert!(!files.contains_key("c.txt"));
3977
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3978
    assert_eq!(
3979
        snap.statuses
3980
            .iter()
3981
            .map(|s| (s.path.as_str(), s.status))
3982
            .collect::<Vec<_>>(),
3983
        vec![
3984
            ("b.txt", ChangeStatus::Modified),
3985
            ("c.txt", ChangeStatus::Added)
3986
        ]
3987
    );
3988
    assert_eq!(
3989
        fs::read(root.join("b.txt")).unwrap(),
3990
        b"b\nbb\n",
3991
        "disk untouched"
3992
    );
957fee30 Andy McCall ↶ 3993
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3994
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 3995
    let b_hunk = hunks
3996
        .iter()
3997
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3998
        .unwrap()
3999
        .index;
4000
    let h2 = repo
4001
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
4002
        .unwrap();
957fee30 Andy McCall ↶ 4003
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 4004
    assert!(
4005
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
4006
    );
957fee30 Andy McCall ↶ 4007
    assert!(!files.contains_key("c.txt"));
4008
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4009
    assert_eq!(
4010
        snap.statuses
4011
            .iter()
4012
            .map(|s| s.path.as_str())
4013
            .collect::<Vec<_>>(),
4014
        vec!["c.txt"]
4015
    );
957fee30 Andy McCall ↶ 4016
    // Choosing only the content hunk of a file in a new directory pulls in
4017
    // the directory and file additions it needs.
4018
    write(root, "d/e.txt", b"e\n");
4019
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 4020
    let e_insert = hunks
4021
        .iter()
4022
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
4023
        .unwrap()
4024
        .index;
4025
    let h3 = repo
4026
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
4027
        .unwrap();
957fee30 Andy McCall ↶ 4028
    let c3 = repo.store().get_change(&h3).unwrap();
4029
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
4030
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
4031
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
d8c086ca Andy McCall ↶ 4032
    // Choosing a new file's addition hunk brings its content along.
4033
    write(root, "f/g.txt", b"g\n");
4034
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 4035
    let g_add = hunks
4036
        .iter()
4037
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
4038
        .unwrap()
4039
        .index;
4040
    let h4 = repo
4041
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
4042
        .unwrap();
d8c086ca Andy McCall ↶ 4043
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
75167672 Andy McCall 4044
    assert!(
4045
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
4046
    );
4047
    assert!(!repo
4048
        .snapshot("status")
4049
        .unwrap()
4050
        .statuses
4051
        .iter()
4052
        .any(|s| s.path == "f/g.txt"));
957fee30 Andy McCall ↶ 4053
    // Everything left commits normally; the working copy is then clean.
4054
    repo.commit("the rest", &[]).unwrap();
4055
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 4056
    let files = repo
4057
        .load_state(&repo.bookmark_heads().unwrap())
4058
        .unwrap()
4059
        .materialize()
4060
        .files;
957fee30 Andy McCall ↶ 4061
    assert!(files.contains_key("c.txt"));
4062
}
4063
4064
#[test]
4065
fn blame_attributes_lines_to_introducing_changes_across_renames() {
4066
    hermetic();
4067
    let dir = tempfile::tempdir().unwrap();
4068
    let root = dir.path();
4069
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 4070
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4071
        .unwrap();
957fee30 Andy McCall ↶ 4072
    write(root, "a.txt", b"one\n");
4073
    let h1 = repo.commit("first", &[]).unwrap();
4074
    write(root, "a.txt", b"one\ntwo\n");
4075
    let h2 = repo.commit("second", &[]).unwrap();
4076
    let b = repo.blame("a.txt").unwrap();
75167672 Andy McCall 4077
    assert_eq!(
4078
        b.iter()
4079
            .map(|l| (l.line, l.hash, l.text.as_slice()))
4080
            .collect::<Vec<_>>(),
4081
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
4082
    );
957fee30 Andy McCall ↶ 4083
    assert!(b.iter().all(|l| l.author == "Ada"));
75167672 Andy McCall 4084
    assert_eq!(
4085
        b[0].change_id,
4086
        repo.store().get_change(&h1).unwrap().change_id
4087
    );
957fee30 Andy McCall ↶ 4088
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
4089
    repo.commit("rename", &[]).unwrap();
4090
    let b = repo.blame("b.txt").unwrap();
75167672 Andy McCall 4091
    assert_eq!(
4092
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
4093
        vec![h1, h2],
4094
        "the node survives the rename"
4095
    );
957fee30 Andy McCall ↶ 4096
    assert!(repo.blame("a.txt").is_err());
4097
}
4098
4099
#[test]
4100
fn bisect_finds_the_first_bad_change() {
4101
    hermetic();
4102
    let dir = tempfile::tempdir().unwrap();
4103
    let root = dir.path();
4104
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4105
    let mut content = String::new();
4106
    let mut hashes = Vec::new();
4107
    for i in 1..=8 {
4108
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
4109
        write(root, "f.txt", content.as_bytes());
4110
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
4111
    }
4112
    // Each step appends after the previous line, so the chain is linear.
4113
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
4114
    repo.bisect_start().unwrap();
75167672 Andy McCall 4115
    assert!(matches!(
4116
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
4117
        BisectStep::NeedMarks { good: 1, bad: 0 }
4118
    ));
957fee30 Andy McCall ↶ 4119
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
75167672 Andy McCall 4120
    assert!(
4121
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
4122
        "{step:?}"
4123
    );
957fee30 Andy McCall ↶ 4124
    // Automated: bad when the bug line is present.
75167672 Andy McCall 4125
    let step = repo
4126
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
4127
        .unwrap();
957fee30 Andy McCall ↶ 4128
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
75167672 Andy McCall 4129
    assert_eq!(
4130
        repo.bisect_status().unwrap(),
4131
        Some(BisectStep::Found { culprit: hashes[4] })
4132
    );
957fee30 Andy McCall ↶ 4133
    repo.bisect_reset().unwrap();
4134
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
4135
    assert!(repo.bisect_status().unwrap().is_none());
4136
    assert!(!repo.snapshot("status").unwrap().changed);
4137
    // Manual marks and a skip.
4138
    repo.bisect_start().unwrap();
4139
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4140
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4141
    let mut skipped_once = false;
4142
    let mut guard = 0;
4143
    while let BisectStep::Testing { .. } = step {
4144
        guard += 1;
4145
        assert!(guard < 20);
4146
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
4147
        if !skipped_once && text.contains("line 6") {
4148
            // An untestable state away from the boundary: the search routes around it.
4149
            skipped_once = true;
4150
            step = repo.bisect_mark(None, &[]).unwrap();
4151
            continue;
4152
        }
4153
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
4154
    }
4155
    assert!(skipped_once);
4156
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
4157
    repo.bisect_reset().unwrap();
4158
    // Skipping the culprit itself leaves it among the candidates reported.
4159
    repo.bisect_start().unwrap();
4160
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
4161
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
4162
    let mut guard = 0;
4163
    while let BisectStep::Testing { heads, .. } = &step {
4164
        guard += 1;
4165
        assert!(guard < 20);
4166
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 4167
        let is_culprit_state =
4168
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
4169
        step = if is_culprit_state {
4170
            repo.bisect_mark(None, &[]).unwrap()
4171
        } else {
4172
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
4173
        };
957fee30 Andy McCall ↶ 4174
    }
4175
    match step {
75167672 Andy McCall 4176
        BisectStep::Inconclusive { candidates } => assert!(
4177
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
4178
            "{candidates:?}"
4179
        ),
957fee30 Andy McCall ↶ 4180
        other => panic!("{other:?}"),
4181
    }
4182
    repo.bisect_reset().unwrap();
4183
}
4184
728da0f9 Andy McCall ↶ 4185
#[test]
4186
fn squash_folds_a_change_into_its_dependency() {
4187
    hermetic();
4188
    let dir = tempfile::tempdir().unwrap();
4189
    let root = dir.path();
4190
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4191
    write(root, "a.txt", b"1\n");
4192
    let a = repo.commit("A", &[]).unwrap();
4193
    write(root, "a.txt", b"1\n2\n");
4194
    let c = repo.commit("C", &[]).unwrap();
4195
    write(root, "a.txt", b"1\n2\n3\n");
4196
    let e = repo.commit("E", &[]).unwrap();
4197
    write(root, "b.txt", b"b\n");
4198
    let b = repo.commit("B", &[]).unwrap();
4199
    let id_a = repo.store().get_change(&a).unwrap().change_id;
4200
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4201
    // E depends on C which A lacks: refused, naming it.
4202
    let err = repo.squash(&e, &a).unwrap_err().to_string();
4203
    assert!(err.contains(&c.short(12)), "{err}");
4204
    // C into A: A' has both, C is gone, E follows and still reads the same.
4205
    let a2 = repo.squash(&c, &a).unwrap();
4206
    let a2c = repo.store().get_change(&a2).unwrap();
4207
    assert_eq!(a2c.change_id, id_a);
4208
    assert!(a2c.deps.is_empty());
4209
    let heads = repo.bookmark_heads().unwrap();
4210
    let st = repo.load_state(&heads).unwrap();
4211
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
75167672 Andy McCall 4212
    let e2 = st
4213
        .changes()
4214
        .find(|(_, m)| m.change_id == id_e)
4215
        .map(|(h, _)| *h)
4216
        .unwrap();
4217
    assert_eq!(
4218
        repo.store().get_change(&e2).unwrap().deps,
4219
        vec![a2],
4220
        "E now depends on A' alone"
4221
    );
728da0f9 Andy McCall ↶ 4222
    let files = st.materialize().files;
75167672 Andy McCall 4223
    assert!(
4224
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
4225
    );
728da0f9 Andy McCall ↶ 4226
    assert!(files.contains_key("b.txt"));
4227
    assert!(st.contains(&b));
4228
    assert!(!repo.snapshot("status").unwrap().changed);
4229
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
4230
    // Undo restores the three original changes.
4231
    repo.undo().unwrap();
4232
    repo.undo().unwrap();
4233
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
4234
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
4235
}
4236
4237
#[test]
4238
fn rebase_re_expresses_a_change_against_another_base() {
4239
    hermetic();
4240
    let dir = tempfile::tempdir().unwrap();
4241
    let root = dir.path();
4242
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4243
    write(root, "a.txt", b"1\n2\n");
4244
    let a = repo.commit("A", &[]).unwrap();
4245
    write(root, "a.txt", b"1\n2\n3\n");
4246
    let c = repo.commit("C: append 3", &[]).unwrap();
4247
    write(root, "a.txt", b"1\n2\n3\n4\n");
4248
    let e = repo.commit("E: append 4", &[]).unwrap();
4249
    // A different base: A plus a change that prepends a line.
4250
    repo.checkout(&[a], true, "checkout").unwrap();
4251
    write(root, "a.txt", b"0\n1\n2\n");
4252
    let d = repo.commit("D: prepend 0", &[]).unwrap();
4253
    let id_c = repo.store().get_change(&c).unwrap().change_id;
4254
    let id_e = repo.store().get_change(&e).unwrap().change_id;
4255
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
4256
    let c2 = repo.rebase(&c, &[d]).unwrap();
4257
    let c2c = repo.store().get_change(&c2).unwrap();
4258
    assert_eq!(c2c.change_id, id_c);
4259
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
4260
    let heads = repo.bookmark_heads().unwrap();
4261
    let st = repo.load_state(&heads).unwrap();
4262
    assert!(!st.contains(&c) && st.contains(&d));
75167672 Andy McCall 4263
    let e2 = st
4264
        .changes()
4265
        .find(|(_, m)| m.change_id == id_e)
4266
        .map(|(h, _)| *h)
4267
        .unwrap();
728da0f9 Andy McCall ↶ 4268
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
75167672 Andy McCall 4269
    assert!(
4270
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
4271
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
4272
    );
728da0f9 Andy McCall ↶ 4273
    let files = st.materialize().files;
75167672 Andy McCall 4274
    assert!(
4275
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
4276
        "{:?}",
4277
        files["a.txt"].content
4278
    );
728da0f9 Andy McCall ↶ 4279
    assert!(!files["a.txt"].is_conflicted());
4280
    // Rebasing onto a state that already contains the change is refused.
4281
    assert!(repo.rebase(&c2, &[c2]).is_err());
4282
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
75167672 Andy McCall 4283
    assert!(
4284
        err.contains("lacks dependencies"),
4285
        "E needs C, which D's state does not have: {err}"
4286
    );
728da0f9 Andy McCall ↶ 4287
}
4288
c792033a Andy McCall ↶ 4289
#[test]
4290
fn unsigned_tags_keep_their_message() {
4291
    hermetic();
4292
    let dir = tempfile::tempdir().unwrap();
4293
    let root = dir.path();
4294
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4295
    write(root, "a.txt", b"a\n");
4296
    repo.commit("a", &[]).unwrap();
4297
    assert!(repo.secret_key().unwrap().is_none());
75167672 Andy McCall 4298
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
4299
        .unwrap();
c792033a Andy McCall ↶ 4300
    let tags = repo.tags().unwrap();
75167672 Andy McCall 4301
    assert_eq!(
4302
        (
4303
            tags[0].name.as_str(),
4304
            tags[0].message.as_str(),
4305
            tags[0].signer.as_deref()
4306
        ),
4307
        ("v1", "first release", None)
4308
    );
4309
    assert!(
4310
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4311
        "an unsigned attestation is not advertised"
4312
    );
c792033a Andy McCall ↶ 4313
}
387335ff Andy McCall ↶ 4314
4315
#[test]
4316
fn fsck_passes_a_sound_repository_and_names_each_fault() {
64818938 Andy McCall ↶ 4317
    // Files on disk are what this tests: tampering with them, and the
4318
    // directory store's crash points.
4319
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4320
        return;
4321
    }
387335ff Andy McCall ↶ 4322
    hermetic();
4323
    let dir = tempfile::tempdir().unwrap();
4324
    let root = dir.path();
4325
    let origin_path = root.join("origin");
4326
    let origin = Repo::init(&origin_path).unwrap();
4327
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4328
        .unwrap()
4329
        .with_home(root.join("home-a"));
4330
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4331
        .unwrap();
4332
    write(&root.join("a"), "f.txt", b"one\n");
4333
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4334
    let h1 = a.commit("first", &[]).unwrap();
4335
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4336
    let h2 = a.commit("second", &[]).unwrap();
4337
    a.tag_create("v1", &[h2], "first release").unwrap();
4338
    a.checkpoint().unwrap();
4339
    assert!(a.push("origin", false).unwrap()[0].ok);
4340
4341
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4342
    for repo in [&a, &origin] {
4343
        let rep = repo.fsck().unwrap();
4344
        assert_eq!(rep.problems, vec![], "{rep:?}");
4345
        // The two commits, plus the working copy's change in `a`.
4346
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4347
        assert!(rep.ops > 1 && rep.objects > 5);
4348
    }
4349
    assert!(origin.fsck().unwrap().attestations >= 1);
4350
4351
    // A flipped byte in a stored object is corruption, named by hash.
4352
    let c1 = a.store().path_for(&h1);
4353
    let pristine = fs::read(&c1).unwrap();
4354
    let mut bytes = pristine.clone();
4355
    *bytes.last_mut().unwrap() ^= 1;
4356
    fs::write(&c1, &bytes).unwrap();
4357
    let rep = a.fsck().unwrap();
4358
    assert!(rep.errors() >= 1);
4359
    assert!(
4360
        rep.problems
4361
            .iter()
4362
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4363
        "{rep:?}"
4364
    );
4365
    fs::write(&c1, &pristine).unwrap();
4366
    assert_eq!(a.fsck().unwrap().errors(), 0);
4367
4368
    // A missing change is named with what needed it.
4369
    fs::remove_file(&c1).unwrap();
4370
    let rep = a.fsck().unwrap();
4371
    assert!(
4372
        rep.problems.iter().any(|p| p.severity == Severity::Error
4373
            && p.object == Some(h1)
4374
            && p.what.contains("change missing, needed by change")),
4375
        "{rep:?}"
4376
    );
4377
    fs::write(&c1, &pristine).unwrap();
4378
4379
    // A missing blob is an error in a full clone.
4380
    let c2 = a.store().get_change(&h1).unwrap();
4381
    let blob = c2
4382
        .edits
4383
        .iter()
4384
        .find_map(|e| match e {
4385
            Edit::Replace { new: Some(b), .. } => Some(*b),
4386
            _ => None,
4387
        })
4388
        .expect("the binary file is a blob");
4389
    let bp = a.store().path_for(&blob);
4390
    let blob_bytes = fs::read(&bp).unwrap();
4391
    fs::remove_file(&bp).unwrap();
4392
    let rep = a.fsck().unwrap();
4393
    assert!(
4394
        rep.problems
4395
            .iter()
4396
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4397
        "{rep:?}"
4398
    );
4399
    fs::write(&bp, &blob_bytes).unwrap();
4400
4401
    // A broken op log head is reported, not a crash.
4402
    let head = root.join("a/.oxy/ops/head");
4403
    let saved = fs::read(&head).unwrap();
4404
    fs::write(&head, b"not a hash").unwrap();
4405
    let rep = a.fsck().unwrap();
4406
    assert!(
4407
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4408
        "{rep:?}"
4409
    );
4410
    fs::write(&head, saved).unwrap();
4411
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4412
}
4dcb8c09 Andy McCall ↶ 4413
4414
/// Copy a directory tree (for restoring a pristine repository).
4415
fn copy_tree(from: &Path, to: &Path) {
4416
    fs::create_dir_all(to).unwrap();
4417
    for e in fs::read_dir(from).unwrap() {
4418
        let e = e.unwrap();
4419
        let target = to.join(e.file_name());
4420
        if e.file_type().unwrap().is_dir() {
4421
            copy_tree(&e.path(), &target);
4422
        } else {
4423
            fs::copy(e.path(), &target).unwrap();
4424
        }
4425
    }
4426
}
4427
4428
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4429
/// would, and check that both repositories still open, pass `fsck`, and
4430
/// accept the same operation again.
4431
#[test]
4432
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
64818938 Andy McCall ↶ 4433
    // Files on disk are what this tests: tampering with them, and the
4434
    // directory store's crash points.
4435
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4436
        return;
4437
    }
4dcb8c09 Andy McCall ↶ 4438
    use crate::durable::failpoint;
4439
    hermetic();
4440
    let dir = tempfile::tempdir().unwrap();
4441
    let pristine = dir.path().join("pristine");
4442
    let origin_path = pristine.join("origin");
4443
    Repo::init(&origin_path).unwrap();
4444
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4445
        .unwrap()
4446
        .with_home(dir.path().join("home"));
4447
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4448
        .unwrap();
4449
    write(&pristine.join("a"), "f.txt", b"one\n");
4450
    a.commit("first", &[]).unwrap();
4451
    assert!(a.push("origin", false).unwrap()[0].ok);
4452
    drop(a);
4453
4454
    type Op = fn(&Repo) -> Result<()>;
4455
    let edit_and_commit: Op = |r| {
4456
        write(r.root(), "f.txt", b"one\ntwo\n");
4457
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4458
        r.commit("second", &[]).map(|_| ())
4459
    };
4460
    let push: Op = |r| {
4461
        let res = r.push("origin", false)?;
4462
        if res.iter().all(|x| x.ok) {
4463
            Ok(())
4464
        } else {
4465
            Err(RepoError::Msg(format!("{res:?}")))
4466
        }
4467
    };
4468
4469
    for (name, prepare, op) in [
4470
        ("commit", None, edit_and_commit),
4471
        ("push", Some(edit_and_commit), push),
4472
    ] {
4473
        let mut steps = 0;
4474
        for n in 1.. {
4475
            let run = dir.path().join(format!("{name}-{n}"));
4476
            copy_tree(&pristine, &run);
4477
            // Clones record their remote by path; point it at this copy.
4478
            let open = |p: &Path| {
4479
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4480
                r.config
4481
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4482
                    .unwrap();
4483
                r.save_config().unwrap();
4484
                r
4485
            };
4486
            let a = open(&run.join("a"));
4487
            if let Some(prep) = prepare {
4488
                prep(&a).unwrap();
4489
            }
4490
            failpoint::crash_after(n);
4491
            let outcome = op(&a);
4492
            let crashed = failpoint::disarm();
4493
            drop(a);
4494
            if !crashed {
4495
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4496
                steps = n - 1;
4497
                break;
4498
            }
4499
            assert!(
4500
                outcome.is_err(),
4501
                "{name}: a crash at step {n} was swallowed"
4502
            );
4503
            for repo in ["a", "origin"] {
4504
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4505
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4506
                });
4507
                let rep = r.fsck().unwrap();
4508
                assert_eq!(
4509
                    rep.errors(),
4510
                    0,
4511
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4512
                    rep.problems
4513
                );
4514
            }
4515
            // The interrupted operation can simply be run again.
4516
            let a = open(&run.join("a"));
4517
            // A crash after the commit point leaves the commit done.
4518
            let landed = a
4519
                .bookmark_heads()
4520
                .unwrap()
4521
                .iter()
4522
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4523
            let again = match (name, landed) {
4524
                ("commit", true) => Ok(()),
4525
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4526
                _ => op(&a),
4527
            };
4528
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4529
            assert_eq!(a.fsck().unwrap().errors(), 0);
4530
            fs::remove_dir_all(&run).unwrap();
4531
        }
4532
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4533
    }
4534
}
19555025 Andy McCall ↶ 4535
4536
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4537
/// running at the same time lose nothing: every commit ends up on the
4538
/// bookmark, locally and on the remote, and the repository passes fsck.
4539
#[test]
4540
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4541
    hermetic();
4542
    let dir = tempfile::tempdir().unwrap();
4543
    let root = dir.path();
4544
    let origin = root.join("origin");
4545
    Repo::init_bare_unbound(&origin).unwrap();
4546
    let main = root.join("main");
4547
    let mut repo = Repo::init(&main).unwrap();
4548
    repo.config
4549
        .set("remote.origin.url", &origin.to_string_lossy())
4550
        .unwrap();
4551
    repo.save_config().unwrap();
4552
    write(&main, "seed.txt", b"seed\n");
4553
    repo.commit("seed", &[]).unwrap();
4554
    let second = root.join("second");
4555
    repo.workspace_add(&second, None).unwrap();
4556
    drop(repo);
4557
4558
    const EACH: usize = 15;
4559
    std::thread::scope(|s| {
4560
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4561
            s.spawn(move || {
4562
                let r = Repo::open(&dir).unwrap();
4563
                for i in 0..EACH {
4564
                    write(
4565
                        &dir,
4566
                        &format!("{tag}-{i}.txt"),
4567
                        format!("{tag} {i}\n").as_bytes(),
4568
                    );
4569
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4570
                    if push && i % 5 == 4 {
4571
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4572
                        let _ = r.push("origin", false);
4573
                    }
4574
                }
4575
            });
4576
        }
4577
    });
4578
4579
    let repo = Repo::open(&main).unwrap();
4580
    let heads = repo.bookmark_heads().unwrap();
4581
    let state = repo.load_state(&heads).unwrap();
4582
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4583
    for tag in ["a", "b"] {
4584
        for i in 0..EACH {
4585
            assert!(
4586
                messages.contains(&format!("{tag} {i}")),
4587
                "lost commit {tag} {i}; have {messages:?}"
4588
            );
4589
        }
4590
    }
4591
    let rep = repo.fsck().unwrap();
4592
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4593
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4594
    let hosted = Repo::open(&origin).unwrap();
4595
    let hosted_heads = hosted.bookmark_heads().unwrap();
4596
    assert_eq!(
4597
        hosted.load_state(&hosted_heads).unwrap().len(),
4598
        state.len(),
4599
        "the remote has every commit"
4600
    );
4601
}
4602
4603
/// Two operations recorded from the same parent (what two processes do
4604
/// when they race) are merged: both bookmarks' heads survive, and a
4605
/// change made on one side only is kept.
4606
#[test]
4607
fn operations_from_the_same_parent_are_merged() {
4608
    hermetic();
4609
    let dir = tempfile::tempdir().unwrap();
4610
    let root = dir.path();
4611
    let repo = Repo::init(root).unwrap();
4612
    write(root, "a.txt", b"a\n");
4613
    let a = repo.commit("a", &[]).unwrap();
4614
    write(root, "b.txt", b"b\n");
4615
    let b = repo.commit("b", &[]).unwrap();
4616
    let (x, op) = repo.head_op().unwrap();
4617
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4618
4619
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4620
    let mut one = op.view.clone();
4621
    one.bookmarks.insert("main".into(), state(vec![a]));
4622
    one.bookmarks.insert("topic".into(), state(vec![a]));
4623
    let mut two = op.view.clone();
4624
    two.bookmarks.insert("main".into(), state(vec![b]));
4625
    repo.record_op(&[x], "one", one).unwrap();
4626
    let merged = repo.record_op(&[x], "two", two).unwrap();
4627
4628
    let (head, op) = repo.head_op().unwrap();
4629
    assert_eq!(head, merged);
4630
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4631
    assert!(op.command.contains("merged with a concurrent operation"));
4632
    let mut main = repo
4633
        .store()
4634
        .get_state(&op.view.bookmarks["main"])
4635
        .unwrap()
4636
        .heads;
4637
    main.sort();
4638
    let mut want = vec![a, b];
4639
    want.sort();
4640
    assert_eq!(main, want, "both sides' heads are kept");
4641
    assert!(
4642
        op.view.bookmarks.contains_key("topic"),
4643
        "a one-sided change survives"
4644
    );
4645
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4646
}
3e5772cc Andy McCall ↶ 4647
4648
#[test]
4649
fn failed_requests_come_with_a_next_step() {
4650
    use crate::protocol::hint_for;
4651
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4652
        .unwrap()
4653
        .contains("token"));
4654
    assert!(hint_for("…: HTTP 403: forbidden")
4655
        .unwrap()
4656
        .contains("repo:write"));
4657
    assert!(hint_for("…: HTTP 404: no such repository")
4658
        .unwrap()
4659
        .contains("owner and repository name"));
4660
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4661
        .unwrap()
4662
        .contains("oxyhub-ca.pem"));
4663
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4664
        .unwrap()
4665
        .contains("running"));
4666
    assert!(hint_for("Dns Failed: failed to lookup address information")
4667
        .unwrap()
4668
        .contains("resolve"));
4669
    assert_eq!(hint_for("something else entirely"), None);
4670
}
4671
4672
#[test]
4673
fn doctor_names_problems_and_what_to_do() {
4674
    hermetic();
4675
    let dir = tempfile::tempdir().unwrap();
4676
    let root = dir.path();
4677
    let origin = root.join("origin");
4678
    Repo::init_bare_unbound(&origin).unwrap();
4679
    let mut repo = Repo::init(&root.join("r"))
4680
        .unwrap()
4681
        .with_home(root.join("home"));
4682
    let find = |r: &DoctorReport, area: &str, h: Health| {
4683
        r.checks
4684
            .iter()
4685
            .find(|c| c.area == area && c.health == h)
4686
            .cloned()
4687
    };
4688
4689
    let r = repo.doctor(true);
4690
    assert!(find(&r, "identity", Health::Warn)
4691
        .unwrap()
4692
        .hint
4693
        .unwrap()
4694
        .contains("oxy identity create"));
4695
    assert!(find(&r, "repository", Health::Ok).is_some());
4696
4697
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4698
        .unwrap();
4699
    repo.config.set("author.name", "Ada").unwrap();
4700
    repo.config.set("author.email", "[email protected]").unwrap();
4701
    repo.config
4702
        .set("remote.origin.url", &origin.to_string_lossy())
4703
        .unwrap();
4704
    repo.config
4705
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4706
        .unwrap();
4707
    repo.config.set("remote.down.token", "t").unwrap();
4708
    repo.config
4709
        .set("remote.badca.url", "https://example.invalid/a/b")
4710
        .unwrap();
4711
    repo.config
4712
        .set(
4713
            "remote.badca.ca",
4714
            &root.join("missing.pem").to_string_lossy(),
4715
        )
4716
        .unwrap();
4717
    repo.save_config().unwrap();
4718
4719
    let r = repo.doctor(true);
4720
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4721
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4722
    assert!(find(&r, "remote origin", Health::Ok)
4723
        .unwrap()
4724
        .message
4725
        .contains("first push binds it"));
4726
    let down = find(&r, "remote down", Health::Fail).unwrap();
4727
    assert!(
4728
        down.hint.as_deref().unwrap_or("").contains("running"),
4729
        "{down:?}"
4730
    );
4731
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4732
    assert!(
4733
        badca.hint.unwrap().contains("remote.badca.ca"),
4734
        "the remote's own name is in the hint"
4735
    );
4736
    assert_eq!(r.worst(), Health::Fail);
4737
4738
    // Offline, nothing is contacted.
4739
    let r = repo.doctor(false);
4740
    assert!(find(&r, "remote down", Health::Fail).is_none());
4741
    assert!(find(&r, "remote down", Health::Ok)
4742
        .unwrap()
4743
        .message
4744
        .contains("not contacted"));
4745
}
62794ecc Andy McCall ↶ 4746
4747
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4748
/// after it. Inserting after `b` and then deleting `b`, one commit after
4749
/// the other, must not leave a delete/insert conflict.
4750
#[test]
4751
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4752
    hermetic();
4753
    let dir = tempfile::tempdir().unwrap();
4754
    let root = dir.path();
4755
    let repo = Repo::init(root).unwrap();
4756
    write(root, "f", b"a\nb\nc\n");
4757
    repo.commit("base", &[]).unwrap();
4758
    write(root, "f", b"a\nb\nx\nc\n");
4759
    let insert = repo.commit("insert x after b", &[]).unwrap();
4760
    write(root, "f", b"a\nx\nc\n");
4761
    let delete = repo.commit("delete b", &[]).unwrap();
4762
    assert!(
4763
        repo.store()
4764
            .get_change(&delete)
4765
            .unwrap()
4766
            .deps
4767
            .contains(&insert),
4768
        "the deletion depends on the insertion below the deleted line"
4769
    );
4770
    let heads = repo.bookmark_heads().unwrap();
4771
    assert_eq!(heads, vec![delete]);
4772
    let snap = repo.load_state(&heads).unwrap().materialize();
4773
    assert!(!snap.is_conflicted());
4774
    assert!(
4775
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4776
    );
4777
}
4778
4779
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4780
/// replacement depends on the change that set the blob it replaces.
4781
#[test]
4782
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4783
    hermetic();
4784
    let dir = tempfile::tempdir().unwrap();
4785
    let root = dir.path();
4786
    let repo = Repo::init(root).unwrap();
4787
    write(root, "bin", b"\0A");
4788
    let v1 = repo.commit("v1", &[]).unwrap();
4789
    write(root, "bin", b"\0B");
4790
    let v2 = repo.commit("v2", &[]).unwrap();
4791
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4792
    write(root, "bin", b"\0A");
4793
    let v3 = repo.commit("back to A", &[]).unwrap();
4794
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4795
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4796
    let state = repo.load_state(&[v3]).unwrap();
4797
    let snap = state.materialize();
4798
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4799
        panic!("opaque")
4800
    };
4801
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4802
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4803
}
4804
4805
/// Spec §23: a binary file changed on two branches and merged in Git to
4806
/// one side's version comes back as that version at the merge, and the
4807
/// import verifies commit by commit.
4808
#[test]
4809
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4810
    hermetic();
4811
    if std::process::Command::new("git")
4812
        .arg("--version")
4813
        .output()
4814
        .is_err()
4815
    {
4816
        eprintln!("git not installed; skipping");
4817
        return;
4818
    }
4819
    let dir = tempfile::tempdir().unwrap();
4820
    let root = dir.path();
4821
    let g = root.join("src.git");
4822
    fs::create_dir_all(&g).unwrap();
4823
    let git = |args: &[&str]| -> String {
4824
        let out = std::process::Command::new("git")
4825
            .arg("-C")
4826
            .arg(&g)
4827
            .args([
4828
                "-c",
4829
                "user.name=Grace",
4830
                "-c",
4831
                "[email protected]",
4832
                "-c",
4833
                "commit.gpgsign=false",
4834
            ])
4835
            .args(args)
4836
            .output()
4837
            .unwrap();
4838
        assert!(
4839
            out.status.success(),
4840
            "git {args:?}: {}",
4841
            String::from_utf8_lossy(&out.stderr)
4842
        );
4843
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4844
    };
4845
    git(&["init", "-q", "-b", "main"]);
4846
    write(&g, "logo.bin", b"\0base");
4847
    write(&g, "notes.txt", b"a\nb\nc\n");
4848
    git(&["add", "."]);
4849
    git(&["commit", "-qm", "base"]);
4850
    git(&["checkout", "-qb", "side"]);
4851
    write(&g, "logo.bin", b"\0side");
4852
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4853
    git(&["commit", "-qam", "side"]);
4854
    git(&["checkout", "-q", "main"]);
4855
    write(&g, "logo.bin", b"\0main");
4856
    git(&["commit", "-qam", "main"]);
4857
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4858
    let _ = std::process::Command::new("git")
4859
        .arg("-C")
4860
        .arg(&g)
4861
        .args([
4862
            "-c",
4863
            "user.name=G",
4864
            "-c",
4865
            "user.email=g@e",
4866
            "merge",
4867
            "-q",
4868
            "side",
4869
        ])
4870
        .output();
4871
    write(&g, "logo.bin", b"\0main");
4872
    git(&["add", "."]);
4873
    git(&["commit", "-qm", "merge side"]);
4874
    // Then a revert of the binary to its first version.
4875
    write(&g, "logo.bin", b"\0base");
4876
    git(&["commit", "-qam", "back to base"]);
4877
4878
    let repo = Repo::init(&root.join("o")).unwrap();
4879
    let rep = repo.import_git(&g, "main").unwrap();
4880
    assert_eq!(rep.merges, 1);
4881
    let v = repo.verify_git_import(&g, "main").unwrap();
4882
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4883
    assert_eq!(v.commits, 5);
4884
    let snap = repo
4885
        .load_state(&repo.bookmark_heads().unwrap())
4886
        .unwrap()
4887
        .materialize();
4888
    assert!(!snap.is_conflicted());
4889
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4890
        panic!("opaque")
4891
    };
4892
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4893
}
c863c7a7 Andy McCall ↶ 4894
4895
/// Spec §7.7 on a file system without executable bits or symlinks: the
4896
/// recorded bit is kept, and a symlink checked out as a plain file holding
4897
/// its target is still that symlink.
4898
#[cfg(unix)]
4899
#[test]
4900
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4901
    use crate::portable::Platform;
4902
    use std::os::unix::fs::PermissionsExt;
4903
    hermetic();
4904
    let dir = tempfile::tempdir().unwrap();
4905
    let root = dir.path();
4906
    let repo = Repo::init(root).unwrap();
4907
    write(root, "run.sh", b"#!/bin/sh\n");
4908
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4909
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4910
    repo.commit("script and link", &[]).unwrap();
4911
    drop(repo);
4912
4913
    // What checking out on Windows leaves: no exec bit, the link as a file.
4914
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4915
    fs::remove_file(root.join("link")).unwrap();
4916
    write(root, "link", b"run.sh");
4917
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4918
    let s = win.snapshot("oxy status").unwrap();
4919
    assert!(
4920
        s.statuses.is_empty(),
4921
        "nothing changed on Windows: {:?}",
4922
        statuses(&s)
4923
    );
4924
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4925
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4926
    write(root, "link", b"other");
4927
    let h = win.commit("edit on Windows", &[]).unwrap();
4928
    let snap = win.load_state(&[h]).unwrap().materialize();
4929
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4930
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4931
    // The same working copy read as Linux sees the lost bit and the plain file.
4932
    let linux = Repo::open(root).unwrap();
4933
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4934
}
4935
4936
/// Paths that collide on case-insensitive or Windows file systems are
4937
/// named at checkout there, and by doctor everywhere.
4938
#[test]
4939
fn paths_other_platforms_cannot_hold_are_reported() {
4940
    use crate::portable::Platform;
4941
    hermetic();
4942
    let dir = tempfile::tempdir().unwrap();
4943
    let root = dir.path();
4944
    let repo = Repo::init(root).unwrap();
4945
    write(root, "README.md", b"a\n");
4946
    write(root, "readme.md", b"b\n");
4947
    write(root, "src/aux.c", b"int x;\n");
4948
    let h = repo.commit("unportable", &[]).unwrap();
4949
    let r = repo.doctor(false);
4950
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4951
    assert_eq!(port.health, Health::Warn);
4952
    assert!(
4953
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4954
        "{}",
4955
        port.message
4956
    );
4957
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4958
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4959
    assert!(
4960
        rep.notes
4961
            .iter()
4962
            .any(|n| n.contains("README.md and readme.md")),
4963
        "{:?}",
4964
        rep.notes
4965
    );
4966
    assert!(
4967
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4968
        "macOS allows aux.c"
4969
    );
4970
}
bc489b6c Andy McCall ↶ 4971
4972
#[test]
4973
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4974
    hermetic();
4975
    let dir = tempfile::tempdir().unwrap();
4976
    let repo = Repo::init(dir.path()).unwrap();
4977
    write(dir.path(), "a.txt", b"one\n");
4978
    write(dir.path(), "other.txt", b"x\n");
4979
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4980
    repo.snapshot("t").unwrap();
4981
    let c1 = repo.commit("first", &[]).unwrap();
4982
    write(dir.path(), "other.txt", b"y\n");
4983
    repo.snapshot("t").unwrap();
4984
    repo.commit("other only", &[]).unwrap();
4985
    write(dir.path(), "a.txt", b"one\ntwo\n");
4986
    repo.snapshot("t").unwrap();
4987
    let c3 = repo.commit("second line", &[]).unwrap();
4988
    write(dir.path(), "other.txt", b"z\n");
4989
    repo.snapshot("t").unwrap();
4990
    repo.commit("other again", &[]).unwrap();
4991
4992
    let heads = repo.bookmark_heads().unwrap();
4993
    let state = repo.load_state(&heads).unwrap();
4994
    let full: Vec<ChangeHash> = repo
4995
        .log_for_path_in("a.txt", &heads)
4996
        .unwrap()
4997
        .iter()
4998
        .map(|e| e.hash)
4999
        .collect();
5000
    assert_eq!(
5001
        full,
5002
        vec![c3, c1],
5003
        "newest first, only changes touching the path"
5004
    );
5005
    let newest: Vec<ChangeHash> = repo
5006
        .log_for_path_of(&state, "a.txt", Some(1))
5007
        .unwrap()
5008
        .iter()
5009
        .map(|e| e.hash)
5010
        .collect();
5011
    assert_eq!(newest, vec![c3], "stops at the first");
5012
    assert_eq!(
5013
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
5014
        2
5015
    );
5016
    assert!(repo
5017
        .log_for_path_of(&state, "missing.txt", Some(1))
5018
        .is_err());
5019
    assert_eq!(
5020
        repo.log_state(&heads).unwrap().len(),
5021
        repo.log_of(&state).len()
5022
    );
5023
5024
    let tree = state.tree().view();
5025
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
5026
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
5027
    assert_eq!(
5028
        via_state
5029
            .iter()
5030
            .map(|l| (l.hash, l.text.clone()))
5031
            .collect::<Vec<_>>(),
5032
        via_heads
5033
            .iter()
5034
            .map(|l| (l.hash, l.text.clone()))
5035
            .collect::<Vec<_>>()
5036
    );
5037
    assert_eq!(
5038
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
5039
        vec![c1, c3]
5040
    );
5041
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
5042
}
696bbf29 Andy McCall ↶ 5043
5044
/// A text file whose stat matches the manifest and whose recorded hash is
5045
/// the base's content is taken from the base without reading it; anything
5046
/// else is read, so no edit is missed (spec §12.3).
5047
#[cfg(unix)]
5048
#[test]
5049
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
5050
    use std::os::unix::fs::PermissionsExt;
5051
    hermetic();
5052
    let dir = tempfile::tempdir().unwrap();
5053
    let root = dir.path();
5054
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5055
    write(root, "a.txt", b"one\ntwo\n");
5056
    write(root, "b.txt", b"bee\n");
5057
    repo.commit("base", &[]).unwrap();
5058
    let age = |p: &str| {
5059
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5060
        fs::File::options()
5061
            .write(true)
5062
            .open(root.join(p))
5063
            .unwrap()
5064
            .set_modified(old)
5065
            .unwrap();
5066
    };
5067
    age("a.txt");
5068
    age("b.txt");
5069
    assert!(
5070
        !repo.snapshot("status").unwrap().changed,
5071
        "records the aged stat"
5072
    );
5073
5074
    // Clean and equal to the base: not read at all.
5075
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5076
    let snap = repo.snapshot("status").unwrap();
5077
    assert!(
5078
        !snap.changed && snap.statuses.is_empty(),
5079
        "{:?}",
5080
        snap.statuses
5081
    );
5082
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5083
5084
    // An uncommitted edit that is older than the manifest: stat-clean, but
5085
    // its hash is not the base's, so it is read and stays visible.
5086
    write(root, "b.txt", b"bee edited\n");
5087
    age("b.txt");
5088
    let first = repo.snapshot("status").unwrap();
5089
    assert_eq!(
5090
        statuses(&first),
5091
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
5092
    );
5093
    let again = repo.snapshot("status").unwrap();
5094
    assert_eq!(
5095
        statuses(&again),
5096
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
5097
        "still seen once stat-clean"
5098
    );
5099
    assert!(!again.changed, "and the working copy hashes the same");
5100
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5101
    assert!(
5102
        repo.snapshot("status").is_err(),
5103
        "an edited file must be read, never taken from the base"
5104
    );
5105
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5106
5107
    // A same-size edit made just now is racy and read.
5108
    write(root, "a.txt", b"one\nTWO\n");
5109
    assert_eq!(
5110
        statuses(&repo.snapshot("status").unwrap()),
5111
        vec![
5112
            ("a.txt".to_string(), ChangeStatus::Modified),
5113
            ("b.txt".to_string(), ChangeStatus::Modified)
5114
        ]
5115
    );
5116
    // Committing makes the edits the base: both are clean and served from it again.
5117
    repo.commit("edits", &[]).unwrap();
5118
    age("a.txt");
5119
    age("b.txt");
5120
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5121
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5122
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5123
    let snap = repo.snapshot("status").unwrap();
5124
    assert!(!snap.changed && snap.statuses.is_empty());
5125
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5126
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5127
}
afaba5f1 Andy McCall ↶ 5128
5129
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
5130
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
5131
/// file is unchanged, and loading through the checkpoint equals a full load.
5132
#[test]
5133
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
5134
    hermetic();
5135
    let dir = tempfile::tempdir().unwrap();
5136
    let root = dir.path();
5137
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5138
    let long: String = (0..300)
5139
        .map(|i| format!("line {i} of a long file\n"))
5140
        .collect();
5141
    write(root, "long.txt", long.as_bytes());
5142
    write(root, "short.txt", b"short\n");
5143
    repo.commit("base", &[]).unwrap();
5144
    let (r1, _, _) = repo.checkpoint().unwrap();
5145
    let cp1 = crate::objects::Checkpoint::decode(
5146
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
5147
    )
5148
    .unwrap();
5149
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
5150
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
5151
5152
    // gc keeps the graph blob; fsck finds the checkpoint sound.
5153
    repo.gc(true).unwrap();
5154
    assert!(repo.store().has(&graphs1[0]));
5155
    let report = repo.fsck().unwrap();
5156
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
5157
5158
    // Loading through the checkpoint equals a full load.
5159
    write(root, "short.txt", b"short, edited\n");
5160
    repo.commit("edit the short file", &[]).unwrap();
5161
    let heads = repo.bookmark_heads().unwrap();
5162
    let fast = repo.load_state(&heads).unwrap();
5163
    let full = repo.load_state_full(&heads).unwrap();
5164
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
5165
5166
    // The next checkpoint shares the unchanged long file's graph.
5167
    let (r2, _, _) = repo.checkpoint().unwrap();
5168
    let cp2 = crate::objects::Checkpoint::decode(
5169
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
5170
    )
5171
    .unwrap();
5172
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
5173
5174
    // A shallow clone's bundle carries the graph blob with the checkpoint.
5175
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
5176
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
5177
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
5178
5179
    // A version 1 checkpoint written by an older oxy still loads.
5180
    let state = repo.load_state_full(&heads).unwrap();
5181
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
5182
    let cp_old = crate::objects::Checkpoint {
5183
        heads: cp2.heads.clone(),
5184
        count: cp2.count,
5185
        payload: old,
5186
    };
5187
    let r_old = repo
5188
        .store()
5189
        .put(ObjectType::Checkpoint, &cp_old.encode())
5190
        .unwrap();
5191
    repo.install_checkpoint("main", &r_old).unwrap();
5192
    assert_eq!(
5193
        repo.load_state(&heads).unwrap().checkpoint_payload(),
5194
        full.checkpoint_payload()
5195
    );
5196
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5197
5198
    // A lost graph blob fails the load loudly rather than dropping the
5199
    // file, and fsck reports it (a fresh repository, objects still loose).
5200
    let dir2 = tempfile::tempdir().unwrap();
5201
    let root2 = dir2.path();
5202
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
5203
    write(root2, "long.txt", long.as_bytes());
5204
    repo2.commit("base", &[]).unwrap();
5205
    let (r, _, _) = repo2.checkpoint().unwrap();
5206
    let cp = crate::objects::Checkpoint::decode(
5207
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
5208
    )
5209
    .unwrap();
5210
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
64818938 Andy McCall ↶ 5211
    repo2.store().remove_loose_for_test(&graph).unwrap();
afaba5f1 Andy McCall ↶ 5212
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
5213
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
5214
}
e3d071ce Andy McCall ↶ 5215
5216
/// A new repository has not stored the user's identity yet (that happens
5217
/// at the first signed change); looking it up falls back to the key
5218
/// directory, and a file there that does not hash to the key is refused.
5219
#[test]
5220
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
5221
    hermetic();
5222
    let dir = tempfile::tempdir().unwrap();
5223
    let home = dir.path().join("home");
5224
    let mut first = Repo::init(&dir.path().join("a"))
5225
        .unwrap()
5226
        .with_home(home.clone());
5227
    let (key, _) = first
5228
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5229
        .unwrap();
5230
    let fresh = Repo::init(&dir.path().join("b"))
5231
        .unwrap()
5232
        .with_home(home.clone());
5233
    assert!(!fresh.store().has(&key), "nothing stored yet");
5234
    let id = fresh.identity(&key).unwrap();
5235
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
5236
    // A key file that is not this identity is an error, not a wrong answer.
5237
    let keys = fresh.keys_dir.clone();
5238
    let (other, _) = first
5239
        .create_identity("Bob", "[email protected]", IdentityScope::User)
5240
        .unwrap();
5241
    fs::copy(
5242
        keys.join(format!("{}.identity", other.to_hex())),
5243
        keys.join(format!("{}.identity", key.to_hex())),
5244
    )
5245
    .unwrap();
5246
    assert!(fresh
5247
        .identity(&key)
5248
        .unwrap_err()
5249
        .to_string()
5250
        .contains("does not hold identity"));
5251
}
cc7a0056 Andy McCall ↶ 5252
5253
/// Status snapshots (spec §12.3): a text file whose stat matches the
5254
/// manifest, and whose base graph key is the one the manifest recorded it
5255
/// equal to, is neither read nor rendered; any edit, and any change to the
5256
/// file's graph in the base, brings it back.
5257
#[cfg(unix)]
5258
#[test]
5259
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
5260
    use std::os::unix::fs::PermissionsExt;
5261
    hermetic();
5262
    let dir = tempfile::tempdir().unwrap();
5263
    let root = dir.path();
5264
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5265
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
5266
        write(root, p, c.as_bytes());
5267
    }
5268
    repo.commit("base", &[]).unwrap();
5269
    let age = |p: &str| {
5270
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5271
        fs::File::options()
5272
            .write(true)
5273
            .open(root.join(p))
5274
            .unwrap()
5275
            .set_modified(old)
5276
            .unwrap();
5277
    };
5278
    let lock = |p: &str, mode: u32| {
5279
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
5280
    };
5281
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5282
        age(p);
5283
    }
5284
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
5285
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
5286
    assert!(
5287
        m.entries.values().all(|e| e.graph.is_some()),
5288
        "keys recorded"
5289
    );
5290
5291
    // Unreadable files prove they are not read; the status snapshot does
5292
    // not render them either, and its base lacks their graphs.
5293
    lock("a.txt", 0o000);
5294
    lock("b.txt", 0o000);
5295
    let snap = repo.snapshot_status("status").unwrap();
5296
    assert!(!snap.changed && snap.statuses.is_empty());
5297
    assert_eq!(
5298
        snap.base_snapshot
5299
            .unrendered
5300
            .iter()
5301
            .cloned()
5302
            .collect::<Vec<_>>(),
5303
        vec!["a.txt", "b.txt", "d/c.txt"]
5304
    );
5305
    assert!(!snap.base.is_full());
5306
    assert!(!snap.base_snapshot.is_conflicted());
5307
    // A full snapshot does not read them either, but renders everything.
5308
    let full = repo.snapshot("status").unwrap();
5309
    assert!(full.statuses.is_empty() && full.base.is_full());
5310
    assert!(full.base_snapshot.unrendered.is_empty());
5311
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5312
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5313
5314
    // An edit is seen; the file is rendered, the others still are not.
5315
    write(root, "d/c.txt", b"sea edited\n");
5316
    let snap = repo.snapshot_status("status").unwrap();
5317
    assert_eq!(
5318
        statuses(&snap),
5319
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5320
    );
5321
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5322
    // So is a mode change of an unread file.
5323
    lock("b.txt", 0o100);
5324
    assert_eq!(
5325
        statuses(&repo.snapshot_status("status").unwrap()),
5326
        vec![
5327
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5328
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5329
        ]
5330
    );
5331
    lock("b.txt", 0o000);
5332
5333
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5334
    // stays unread, c.txt is read once and then skipped too.
5335
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5336
        .unwrap();
5337
    age("d/c.txt");
5338
    let snap = repo.snapshot_status("status").unwrap();
5339
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5340
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5341
    lock("d/c.txt", 0o000);
5342
    let snap = repo.snapshot_status("status").unwrap();
5343
    assert!(snap.statuses.is_empty());
5344
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5345
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5346
        lock(p, 0o644);
5347
    }
5348
}
5349
5350
/// Attributes decide how a file compares with the base, so a changed
5351
/// `.oxyattributes` makes every text file be compared again.
5352
#[cfg(unix)]
5353
#[test]
5354
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5355
    hermetic();
5356
    let dir = tempfile::tempdir().unwrap();
5357
    let root = dir.path();
5358
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5359
    write(root, "a.txt", b"crlf\r\n");
5360
    repo.commit("base", &[]).unwrap();
5361
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5362
    fs::File::options()
5363
        .write(true)
5364
        .open(root.join("a.txt"))
5365
        .unwrap()
5366
        .set_modified(old)
5367
        .unwrap();
5368
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5369
    assert!(repo
5370
        .snapshot_status("status")
5371
        .unwrap()
5372
        .base_snapshot
5373
        .unrendered
5374
        .contains("a.txt"));
5375
    // With eol=lf, a.txt as stored no longer equals the base.
5376
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5377
    let snap = repo.snapshot_status("status").unwrap();
5378
    assert_eq!(
5379
        statuses(&snap),
5380
        vec![
5381
            (".oxyattributes".to_string(), ChangeStatus::Added),
5382
            ("a.txt".to_string(), ChangeStatus::Modified)
5383
        ]
5384
    );
5385
}
54cd08a1 Andy McCall ↶ 5386
5387
/// Bookmarks with `/` in their names: pushing records their
5388
/// attestations, and checkpoints are kept for them, beside `feature`
5389
/// itself.
5390
#[test]
5391
fn bookmarks_with_slashes_push_and_checkpoint() {
5392
    hermetic();
5393
    let dir = tempfile::tempdir().unwrap();
5394
    let root = dir.path();
5395
    let origin = Repo::init(&root.join("origin")).unwrap();
5396
    let url = root.join("origin").to_string_lossy().to_string();
5397
    let mut repo = Repo::clone(&url, &root.join("r"))
5398
        .unwrap()
5399
        .with_home(root.join("home"));
5400
    // With an identity, pushes carry reference attestations: the case
5401
    // that failed, since the attestation is a file named after the bookmark.
5402
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5403
        .unwrap();
5404
    let r = root.join("r");
5405
    write(&r, "a.txt", b"a\n");
5406
    let h_a = repo.commit("a", &[]).unwrap();
5407
    assert!(repo.push("origin", false).unwrap()[0].ok);
5408
    repo.bookmark_create("feature", None).unwrap();
5409
    repo.bookmark_create("feature/x", None).unwrap();
5410
    repo.bookmark_switch("feature/x", false).unwrap();
5411
    write(&r, "b.txt", b"b\n");
5412
    let h_b = repo.commit("b", &[]).unwrap();
5413
    for name in ["feature", "feature/x"] {
5414
        let res = repo.push_bookmark("origin", name, false).unwrap();
5415
        assert!(res[0].ok, "{name}: {res:?}");
5416
    }
5417
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5418
    assert_eq!(
5419
        origin.resolve_heads("feature/x").unwrap(),
5420
        repo.resolve_heads("feature/x").unwrap()
5421
    );
5422
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5423
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5424
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5425
5426
    // A checkpoint of feature/x is found again when loading its state.
5427
    let (cp, _, _) = repo.checkpoint().unwrap();
5428
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5429
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5430
    let heads = repo.resolve_heads("feature/x").unwrap();
5431
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
f8c69576 Andy McCall ↶ 5432
}
5433
5434
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5435
/// never the remote's own bookmark, and a bookmark created again later is
5436
/// accepted although the deletion's attestation stays the latest.
5437
#[test]
5438
fn bookmarks_are_deleted_on_a_remote() {
5439
    hermetic();
5440
    let dir = tempfile::tempdir().unwrap();
5441
    let root = dir.path();
5442
    let origin = Repo::init(&root.join("origin")).unwrap();
5443
    let url = root.join("origin").to_string_lossy().to_string();
5444
    let mut repo = Repo::clone(&url, &root.join("r"))
5445
        .unwrap()
5446
        .with_home(root.join("home"));
5447
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5448
        .unwrap();
5449
    let r = root.join("r");
5450
    write(&r, "a.txt", b"a\n");
5451
    repo.commit("a", &[]).unwrap();
5452
    assert!(repo.push("origin", false).unwrap()[0].ok);
5453
    repo.bookmark_create("feature/x", None).unwrap();
5454
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5455
    assert!(origin.resolve_heads("feature/x").is_ok());
5456
5457
    let res = repo.push_delete("origin", "feature/x").unwrap();
5458
    assert!(res[0].ok, "{res:?}");
5459
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5460
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5461
    assert!(
5462
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5463
        "the deletion is attested"
5464
    );
5465
    assert!(
5466
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5467
        "the local bookmark stays"
5468
    );
5469
    assert!(!repo
5470
        .view()
5471
        .unwrap()
5472
        .remotes
5473
        .get("origin")
5474
        .is_some_and(|m| m.contains_key("feature/x")));
5475
5476
    // Pushing it again creates it again, past the deletion's serial.
5477
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5478
    assert!(res[0].ok, "{res:?}");
5479
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5480
5481
    // Nothing to delete, and never the remote's own bookmark.
5482
    assert!(repo.push_delete("origin", "nope").is_err());
5483
    let res = repo.push_delete("origin", "main").unwrap();
5484
    assert!(
5485
        !res[0].ok && res[0].reason.contains("default bookmark"),
5486
        "{res:?}"
5487
    );
5488
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
54cd08a1 Andy McCall ↶ 5489
}
61e3bce7 Andy McCall ↶ 5490
5491
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5492
/// when the target has the same versions of the files it touches, and is
5493
/// refused, untouched, when it has others.
5494
#[test]
5495
fn switching_bookmarks_carries_uncommitted_work() {
5496
    hermetic();
5497
    let dir = tempfile::tempdir().unwrap();
5498
    let root = dir.path();
5499
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5500
    write(root, "a.txt", b"a\n");
5501
    write(root, "b.txt", b"b\n");
5502
    write(root, "gone.txt", b"gone\n");
5503
    repo.commit("base", &[]).unwrap();
5504
    repo.bookmark_create("feature", None).unwrap();
5505
    // Started on main, belongs on feature: edit, add, remove.
5506
    write(root, "a.txt", b"a\nmore\n");
5507
    write(root, "new.txt", b"new\n");
5508
    fs::remove_file(root.join("gone.txt")).unwrap();
5509
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5510
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5511
    assert_eq!(repo.config.bookmark, "feature");
5512
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5513
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5514
    assert!(!root.join("gone.txt").exists());
5515
    let snap = repo.snapshot("status").unwrap();
5516
    assert_eq!(
5517
        statuses(&snap),
5518
        vec![
5519
            ("a.txt".to_string(), ChangeStatus::Modified),
5520
            ("gone.txt".to_string(), ChangeStatus::Removed),
5521
            ("new.txt".to_string(), ChangeStatus::Added)
5522
        ]
5523
    );
5524
    repo.commit("the work", &[]).unwrap();
5525
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5526
5527
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5528
    repo.bookmark_switch("main", false).unwrap();
5529
    write(root, "b.txt", b"b on main\n");
5530
    repo.commit("b on main", &[]).unwrap();
5531
    repo.bookmark_switch("feature", false).unwrap();
5532
    write(root, "b.txt", b"b edited\n");
5533
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5534
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5535
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5536
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5537
}
1c2bd9ab Andy McCall ↶ 5538
5539
/// Merging and checking out (feedback 3): a working copy without changes
5540
/// follows a merge whichever state it sat on; a refused checkout names
5541
/// what is in the way; `checkout --carry` takes the work along.
5542
#[test]
5543
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5544
    hermetic();
5545
    let dir = tempfile::tempdir().unwrap();
5546
    let root = dir.path();
5547
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5548
    write(root, "a.txt", b"a\n");
5549
    let h1 = repo.commit("a", &[]).unwrap();
5550
    write(root, "b.txt", b"b\n");
5551
    repo.commit("b", &[]).unwrap();
5552
    repo.bookmark_create("feature", None).unwrap();
5553
    repo.bookmark_switch("feature", false).unwrap();
5554
    write(root, "c.txt", b"c\n");
5555
    repo.commit("c on feature", &[]).unwrap();
5556
    repo.bookmark_switch("main", false).unwrap();
5557
    // The working copy sits on an older state than main's heads.
5558
    repo.checkout(&[h1], false, "checkout").unwrap();
5559
    assert!(!root.join("b.txt").exists());
5560
    let m = repo.merge("feature").unwrap();
5561
    assert!(m.checked_out, "a clean working copy follows the merge");
5562
    for f in ["a.txt", "b.txt", "c.txt"] {
5563
        assert!(root.join(f).exists(), "{f}");
5564
    }
5565
5566
    // A refusal says which paths are in the way and what to do.
5567
    fs::remove_file(root.join("b.txt")).unwrap();
5568
    write(root, "a.txt", b"a edited\n");
5569
    let err = repo
5570
        .checkout(&[h1], false, "checkout")
5571
        .unwrap_err()
5572
        .to_string();
5573
    assert!(
5574
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5575
        "{err}"
5576
    );
fe9586d9 Andy McCall ↶ 5577
    // --carry takes them along: h1 has a.txt as the base has it, and the
5578
    // removed b.txt is already as h1 has it (none), so that is no conflict
5579
    // either (oxygen#100).
1c2bd9ab Andy McCall ↶ 5580
    let (_, carried) = repo
5581
        .checkout_carry(&[h1], "the first change", "checkout")
5582
        .unwrap();
5583
    assert_eq!(carried, vec!["a.txt"]);
5584
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5585
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5586
}
e7ac6c2e Andy McCall ↶ 5587
5588
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5589
/// user identity not stored in a new repository yet is fine while its
5590
/// secret key is there; an added subrepo is listed as not committed yet.
5591
#[test]
5592
fn a_new_repository_is_healthy_before_its_first_commit() {
5593
    hermetic();
5594
    let dir = tempfile::tempdir().unwrap();
5595
    let root = dir.path();
5596
    let home = root.join("home");
5597
    let mut first = Repo::init(&root.join("first"))
5598
        .unwrap()
5599
        .with_home(home.clone());
5600
    let (key, _) = first
5601
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5602
        .unwrap();
5603
    let repo = Repo::init(&root.join("second"))
5604
        .unwrap()
5605
        .with_home(home.clone());
5606
    // Only the secret key: no identity object anywhere this repository sees.
5607
    let keys = repo.keys_dir.clone();
5608
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5609
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5610
    let r = repo.doctor(true);
5611
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5612
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5613
    assert!(id.message.contains("first signed change"), "{}", id.message);
5614
5615
    // A subrepo added and not committed yet is listed, pinned where it is.
5616
    let lib = root.join("lib");
5617
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5618
    write(&lib, "x.txt", b"x\n");
5619
    l.commit("x", &[]).unwrap();
5620
    let second = root.join("second");
5621
    write(&second, "a.txt", b"a\n");
5622
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5623
        .unwrap();
5624
    let subs = repo.subrepos().unwrap();
5625
    assert_eq!(subs.len(), 1);
5626
    assert_eq!(
5627
        (subs[0].path.as_str(), subs[0].committed),
5628
        ("deps/lib", false)
5629
    );
5630
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5631
    repo.commit("add lib", &[]).unwrap();
5632
    let subs = repo.subrepos().unwrap();
5633
    assert!(subs[0].committed, "committed now");
5634
}
8ab265dc Andy McCall ↶ 5635
5636
/// Commit, diff, hunks and discard use the partial snapshot: a file
5637
/// unchanged since the manifest is neither read nor rendered, and showing
5638
/// a change renders only what it edits, the same as from a full base.
5639
#[cfg(unix)]
5640
#[test]
5641
fn commits_and_diffs_leave_unchanged_files_alone() {
5642
    use std::os::unix::fs::PermissionsExt;
5643
    hermetic();
5644
    let dir = tempfile::tempdir().unwrap();
5645
    let root = dir.path();
5646
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5647
    write(root, "big.txt", b"lots\nof\nlines\n");
5648
    write(root, "a.txt", b"one\ntwo\n");
5649
    repo.commit("base", &[]).unwrap();
5650
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5651
    for f in ["big.txt", "a.txt"] {
5652
        fs::File::options()
5653
            .write(true)
5654
            .open(root.join(f))
5655
            .unwrap()
5656
            .set_modified(old)
5657
            .unwrap();
5658
    }
5659
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5660
    // big.txt cannot be read at all from here on.
5661
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5662
5663
    write(root, "a.txt", b"one\nTWO\nthree\n");
5664
    let diff = repo.diff_files(None).unwrap();
5665
    assert_eq!(
5666
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5667
        ["a.txt"]
5668
    );
5669
    let (_, hunks) = repo.hunks().unwrap();
5670
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5671
    let h = repo.commit("edit a", &[]).unwrap();
5672
5673
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5674
    let c = repo.store().get_change(&h).unwrap();
5675
    let full = repo.load_state(&c.deps).unwrap();
5676
    let want = render_change(&c, &full, &full.materialize());
5677
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5678
    let (base, snap) = repo.change_base(&c).unwrap();
5679
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5680
5681
    // Discarding works the same way.
5682
    write(root, "a.txt", b"scratch\n");
5683
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5684
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5685
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5686
}
f7510b63 Andy McCall ↶ 5687
5688
/// A replace conflict (spec §9.3) is settled by a change that writes one
5689
/// candidate, or new bytes, at the path when the caller names it; a plain
5690
/// snapshot of a checkout never settles it on its own.
5691
#[test]
5692
fn replace_conflicts_are_settled_when_asked() {
5693
    hermetic();
5694
    let dir = tempfile::tempdir().unwrap();
5695
    let root = dir.path();
5696
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5697
    let blob = |n: u8| {
5698
        let mut v = vec![0u8; 64];
5699
        v[1] = n;
5700
        v
5701
    };
5702
    write(root, "img.bin", &blob(1));
5703
    repo.commit("add img", &[]).unwrap();
5704
    repo.bookmark_create("other", None).unwrap();
5705
    write(root, "img.bin", &blob(2));
5706
    repo.commit("img two", &[]).unwrap();
5707
    repo.bookmark_switch("other", false).unwrap();
5708
    write(root, "img.bin", &blob(3));
5709
    repo.commit("img three", &[]).unwrap();
5710
    repo.bookmark_switch("main", false).unwrap();
5711
    repo.merge("other").unwrap();
5712
    let heads = repo.bookmark_heads().unwrap();
5713
    let merged = repo.load_state(&heads).unwrap().materialize();
5714
    assert!(
5715
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5716
        "a replace conflict"
5717
    );
5718
    // A snapshot of the checkout records nothing.
5719
    assert!(repo
5720
        .snapshot("status")
5721
        .unwrap()
5722
        .statuses
5723
        .iter()
5724
        .all(|s| s.path != "img.bin"));
5725
5726
    // Keeping candidate 3 settles it.
5727
    let author = repo.author();
5728
    let edits = [FileEdit {
5729
        path: "img.bin".into(),
5730
        content: Some(blob(3)),
5731
    }];
5732
    let c = repo
5733
        .build_change(&heads, &edits, "keep three", author)
5734
        .unwrap();
5735
    assert_eq!(c.kind, ChangeKind::Resolution);
5736
    let mut st = repo.load_state(&heads).unwrap();
5737
    for d in &c.deps {
5738
        assert!(st.contains(d));
5739
    }
5740
    assert!(
5741
        heads.iter().all(|h| c.deps.contains(h)),
5742
        "depends on both contributors"
5743
    );
5744
    st.add(c).unwrap();
5745
    let after = st.materialize();
5746
    assert!(!after.is_conflicted());
5747
    assert_eq!(
5748
        after.files["img.bin"].content,
5749
        FileContent::Opaque {
5750
            blobs: vec![Repo::blob_ref(&blob(3))]
5751
        }
5752
    );
5753
5754
    // New bytes settle it too.
5755
    let edits = [FileEdit {
5756
        path: "img.bin".into(),
5757
        content: Some(blob(9)),
5758
    }];
5759
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5760
    let mut st = repo.load_state(&heads).unwrap();
5761
    st.add(c).unwrap();
5762
    assert_eq!(
5763
        st.materialize().files["img.bin"].content,
5764
        FileContent::Opaque {
5765
            blobs: vec![Repo::blob_ref(&blob(9))]
5766
        }
5767
    );
5768
}
83d61e80 Andy McCall ↶ 5769
5770
/// The history of a range of lines (spec §27): the changes that wrote
5771
/// or deleted its atoms, or deleted atoms from between them; edits outside
5772
/// the range and changes the range's lines survived are not in it.
5773
#[test]
5774
fn line_ranges_have_exact_histories() {
5775
    hermetic();
5776
    let dir = tempfile::tempdir().unwrap();
5777
    let root = dir.path();
5778
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5779
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5780
    let base = repo.commit("add f", &[]).unwrap();
5781
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5782
    let outside = repo.commit("change the import", &[]).unwrap();
5783
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5784
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5785
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5786
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5787
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5788
    let after = repo.commit("add b after a", &[]).unwrap();
5789
    let heads = repo.bookmark_heads().unwrap();
5790
5791
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5792
    let hist: Vec<ChangeHash> = repo
5793
        .line_history(&heads, "f.rs", 2, 4)
5794
        .unwrap()
5795
        .iter()
5796
        .map(|e| e.hash)
5797
        .collect();
5798
    for (h, what) in [
5799
        (base, "wrote it"),
5800
        (inside, "edited a line"),
5801
        (deleted, "deleted a line from inside"),
5802
    ] {
5803
        assert!(hist.contains(&h), "{what}");
5804
    }
5805
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5806
        assert!(!hist.contains(&h), "{what}");
5807
    }
5808
    assert_eq!(hist[0], deleted, "newest first");
5809
    // One line: only what touched it.
5810
    let one: Vec<ChangeHash> = repo
5811
        .line_history(&heads, "f.rs", 1, 1)
5812
        .unwrap()
5813
        .iter()
5814
        .map(|e| e.hash)
5815
        .collect();
5816
    assert!(one.contains(&outside) && !one.contains(&inside));
5817
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5818
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5819
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5820
}
fc1a466a Andy McCall ↶ 5821
5822
#[test]
5823
fn receipts_are_kept_with_their_state_and_verified() {
5824
    use crate::receipt::{Receipt, SignedReceipt};
5825
    hermetic();
5826
    let dir = tempfile::tempdir().unwrap();
5827
    let root = dir.path();
5828
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5829
    write(root, "a.txt", b"1\n");
5830
    repo.commit("A", &[]).unwrap();
5831
    let heads = repo.bookmark_heads().unwrap();
5832
    let state = repo
5833
        .store()
5834
        .put_state(&StateObject::new(heads.clone()))
5835
        .unwrap();
5836
    let out = repo.store_blob(b"built\n").unwrap();
5837
    let receipt = Receipt {
5838
        job_name: "build".into(),
5839
        pipeline_hash: ObjectRef([1; 32]),
5840
        scope_tree_hash: ObjectRef([2; 32]),
5841
        inputs: vec![],
5842
        environment: ObjectRef([3; 32]),
5843
        outputs: vec![out],
5844
        exit_code: 0,
5845
        duration_ms: 42,
5846
    };
5847
    let sk = SecretKey::generate();
5848
    let runner = sk.identity("earth-1", "runner@earth", 1);
5849
    let sr = SignedReceipt::sign(
5850
        receipt.clone(),
5851
        repo.id().unwrap(),
5852
        state,
5853
        "demo#1",
5854
        &runner,
5855
        &sk,
5856
    );
5857
5858
    let r = repo.add_receipt(&sr).unwrap();
5859
    let found = repo.receipts(&heads).unwrap();
5860
    assert_eq!(found.len(), 1);
5861
    assert_eq!(found[0].attest, r);
5862
    assert_eq!(found[0].signed, sr);
5863
    assert!(found[0].problem.is_none() && !found[0].revoked);
5864
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5865
5866
    // Another repository's receipt, or a forged one, is refused.
5867
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5868
    assert!(repo
5869
        .add_receipt(&elsewhere)
5870
        .unwrap_err()
5871
        .to_string()
5872
        .contains("another repository"));
5873
    let mut forged = sr.clone();
5874
    forged.receipt.exit_code = 1;
5875
    assert!(repo
5876
        .add_receipt(&forged)
5877
        .unwrap_err()
5878
        .to_string()
5879
        .contains("does not verify"));
5880
c63fed2e Andy McCall ↶ 5881
    // A receipt signed by a short-lived key keeps its certificate and the
5882
    // issuer's identity, and reads back with them (oxygenhub#241).
5883
    let hub_sk = SecretKey::generate();
5884
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
5885
    let job_sk = SecretKey::generate();
5886
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
5887
    let mut test_receipt = receipt.clone();
5888
    test_receipt.job_name = "test".into();
5889
    let plain = SignedReceipt::sign(
5890
        test_receipt,
5891
        repo.id().unwrap(),
5892
        state,
5893
        "demo#2",
5894
        &job,
5895
        &job_sk,
5896
    );
5897
    let now = plain.attest.hlc.wall_ms;
5898
    let cert = crate::cert::SignedCertificate::sign(
5899
        crate::cert::Certificate {
5900
            key: job.clone(),
5901
            issuer: hub.hash(),
5902
            subject: "repo:andy/demo:bookmark:main".into(),
5903
            claims: vec![],
5904
            scope: crate::identity::Scope::SEAL,
5905
            not_before: now - 1_000,
5906
            expires: now + 600_000,
a2387d54 Andy McCall ↶ 5907
            grant: None,
c63fed2e Andy McCall ↶ 5908
        },
5909
        &hub,
5910
        &hub_sk,
5911
    );
5912
    let certified = plain.with_certificate(cert, hub.clone());
5913
    repo.add_receipt(&certified).unwrap();
5914
    let found = repo.receipts(&heads).unwrap();
5915
    let got = found
5916
        .iter()
5917
        .find(|i| i.signed.receipt.job_name == "test")
5918
        .unwrap();
5919
    assert_eq!(got.signed, certified);
5920
    assert!(got.problem.is_none(), "{:?}", got.problem);
5921
5922
    // gc keeps the receipts, their runners, the certificate and its issuer,
5923
    // and the output while the state lives.
fc1a466a Andy McCall ↶ 5924
    repo.gc(true).unwrap();
c63fed2e Andy McCall ↶ 5925
    let found = repo.receipts(&heads).unwrap();
5926
    assert_eq!(found.len(), 2);
5927
    let got = found
5928
        .iter()
5929
        .find(|i| i.signed.receipt.job_name == "test")
5930
        .unwrap();
5931
    assert_eq!(got.signed, certified, "the certificate survives gc");
5932
    assert!(got.problem.is_none());
fc1a466a Andy McCall ↶ 5933
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5934
    assert!(repo.fsck().unwrap().problems.is_empty());
dfb23a3a Andy McCall ↶ 5935
}
5936
5937
#[test]
3a4b3e01 Andy McCall ↶ 5938
fn approvals_are_kept_with_their_state_and_survive_gc() {
5939
    hermetic();
5940
    let dir = tempfile::tempdir().unwrap();
5941
    let root = dir.path();
5942
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5943
    write(root, "a.txt", b"1\n");
5944
    repo.commit("A", &[]).unwrap();
5945
    let heads = repo.bookmark_heads().unwrap();
5946
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
5947
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
5948
    let sk = SecretKey::generate();
5949
    let andy = sk.identity("Andy", "[email protected]", 1);
5950
    let statement = crate::approval::Statement {
5951
        repo: repo.id().unwrap(),
5952
        run: "https://hub.example/andy/infra/flow/8".into(),
5953
        job: "apply".into(),
5954
        job_hash: ObjectRef([1; 32]),
5955
        state,
5956
        inputs: vec![plan],
5957
        environment: "prod".into(),
5958
        approve: true,
5959
    };
5960
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
5961
    let r = repo.add_approval(&sa).unwrap();
5962
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
5963
    // Another repository's approval, or a changed one, is refused.
5964
    let elsewhere = crate::approval::SignedApproval::sign(
5965
        &crate::approval::Statement {
5966
            repo: [0; 16],
5967
            ..statement.clone()
5968
        },
5969
        &andy,
5970
        &sk,
5971
    );
5972
    assert!(repo
5973
        .add_approval(&elsewhere)
5974
        .unwrap_err()
5975
        .to_string()
5976
        .contains("another repository"));
5977
    let mut forged = sa.clone();
5978
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
5979
        *environment = "dev".into();
5980
    }
5981
    assert!(repo
5982
        .add_approval(&forged)
5983
        .unwrap_err()
5984
        .to_string()
5985
        .contains("does not verify"));
5986
    // gc keeps it, its signature and its signer while the state lives.
5987
    repo.gc(true).unwrap();
5988
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
5989
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
5990
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
5991
    assert!(repo.fsck().unwrap().problems.is_empty());
5992
}
5993
5994
#[test]
dfb23a3a Andy McCall ↶ 5995
fn status_leaves_an_unchanged_manifest_alone() {
5996
    hermetic();
5997
    let dir = tempfile::tempdir().unwrap();
5998
    let root = dir.path();
5999
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6000
    write(root, "a.txt", b"1\n");
6001
    write(root, "b.txt", b"2\n");
6002
    repo.commit("A", &[]).unwrap();
6003
    // Files last touched well outside the racy window.
6004
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6005
    for f in ["a.txt", "b.txt"] {
6006
        fs::File::options()
6007
            .write(true)
6008
            .open(root.join(f))
6009
            .unwrap()
6010
            .set_modified(old)
6011
            .unwrap();
6012
    }
6013
    repo.snapshot_status("status").unwrap();
6014
    let path = repo.manifest_path();
6015
    let first = fs::read(&path).unwrap();
6016
    repo.snapshot_status("status").unwrap();
6017
    assert_eq!(
6018
        fs::read(&path).unwrap(),
6019
        first,
6020
        "an unchanged tree does not rewrite the manifest"
6021
    );
6022
    // A change rewrites it.
6023
    write(root, "a.txt", b"1\n2\n");
6024
    repo.snapshot_status("status").unwrap();
6025
    assert_ne!(fs::read(&path).unwrap(), first);
fc1a466a Andy McCall ↶ 6026
}
6f8aeb99 Andy McCall ↶ 6027
6028
#[test]
6029
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
6030
    hermetic();
6031
    let dir = tempfile::tempdir().unwrap();
6032
    let root = dir.path();
6033
    let origin_path = root.join("origin");
6034
    Repo::init(&origin_path).unwrap();
6035
    let origin_url = origin_path.to_string_lossy().to_string();
6036
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
6037
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
6038
    write(&root.join("a"), "big.txt", big.as_bytes());
6039
    write(&root.join("a"), "small.txt", b"small\n");
6040
    let h1 = a.commit("large", &[]).unwrap();
6041
    let (_, body) = a.store().get(&h1).unwrap();
6042
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
6043
    assert!(a.push("origin", false).unwrap()[0].ok);
6044
6045
    // A clone reads the text from the blobs that came with the change.
6046
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
6047
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
6048
    // An edit in the middle of the stored insert is an ordinary change.
6049
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
6050
    write(&root.join("b"), "big.txt", edited.as_bytes());
6051
    let h2 = b.commit("edit", &[]).unwrap();
6052
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
6053
    assert!(b.push("origin", false).unwrap()[0].ok);
6054
    assert!(a.pull("origin").unwrap().checked_out);
6055
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
6056
    assert_eq!(
6057
        a.fsck().unwrap().errors(),
6058
        0,
6059
        "{:?}",
6060
        a.fsck().unwrap().problems
6061
    );
6062
6063
    // With zero retention gc keeps the text blobs of every kept change.
6064
    let mut a = Repo::open(&root.join("a")).unwrap();
6065
    a.config.set("core.op-retention", "0").unwrap();
6066
    a.save_config().unwrap();
6067
    let a = Repo::open(&root.join("a")).unwrap();
6068
    a.gc(true).unwrap();
6069
    let a = Repo::open(&root.join("a")).unwrap();
6070
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
6071
    assert_eq!(
6072
        a.fsck().unwrap().errors(),
6073
        0,
6074
        "{:?}",
6075
        a.fsck().unwrap().problems
6076
    );
6077
    // And a clone of the packed repository reads them from its packs.
6078
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
6079
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
6080
    drop(c);
6caacfff Andy McCall ↶ 6081
}
6082
6083
#[test]
6084
fn operations_that_both_replace_a_working_copy_are_not_merged() {
6085
    hermetic();
6086
    let dir = tempfile::tempdir().unwrap();
6087
    let root = dir.path();
6088
    let repo = Repo::init(root).unwrap();
6089
    write(root, "a.txt", b"a\n");
6090
    let a = repo.commit("a", &[]).unwrap();
6091
    write(root, "b.txt", b"b\n");
6092
    repo.commit("b", &[]).unwrap();
6093
    let (x, op) = repo.head_op().unwrap();
6094
    let ws = *op.view.workspaces.keys().next().unwrap();
6095
    let mut one = op.view.clone();
6096
    one.workspaces.insert(ws, a);
6097
    let mut two = op.view.clone();
6098
    two.workspaces.insert(ws, ObjectRef([7; 32]));
6099
    let first = repo.record_op(&[x], "one", one).unwrap();
6100
    let e = repo.record_op(&[x], "two", two).unwrap_err();
6101
    assert!(
6102
        e.to_string()
6103
            .contains("changed this working copy at the same time"),
6104
        "{e}"
6105
    );
6106
    assert_eq!(
6107
        repo.head_op().unwrap().0,
6108
        first,
6109
        "the second is not recorded"
6110
    );
6111
}
6112
6113
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
6114
/// rewrote the working copy recorded the half-written files as edits, and
6115
/// its view replaced the switch's.
6116
#[test]
6117
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
6118
    hermetic();
6119
    let dir = tempfile::tempdir().unwrap();
6120
    let root = dir.path().to_path_buf();
6121
    let mut repo = Repo::init(&root).unwrap();
6122
    write(&root, "keep.txt", b"keep\n");
6123
    repo.commit("base", &[]).unwrap();
6124
    repo.bookmark_create("small", None).unwrap();
6125
    for i in 0..300 {
6126
        write(
6127
            &root,
6128
            &format!("many/f{i}.txt"),
6129
            format!("file {i}\n").as_bytes(),
6130
        );
6131
    }
6132
    repo.commit("many", &[]).unwrap();
6133
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
6134
    let watcher = {
6135
        let (root, stop) = (root.clone(), stop.clone());
6136
        std::thread::spawn(move || {
6137
            let r = Repo::open(&root).unwrap();
6138
            let mut ran = 0;
6139
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
6140
                if r.snapshot_status("oxy status").is_ok() {
6141
                    ran += 1;
6142
                }
6143
            }
6144
            ran
6145
        })
6146
    };
6147
    for i in 0..20 {
6148
        let to = if i % 2 == 0 { "small" } else { "main" };
6149
        repo.bookmark_switch(to, false).unwrap();
6150
    }
6151
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
6152
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
6153
    // Back on main, clean, with every file where main has it.
6154
    let repo = Repo::open(&root).unwrap();
6155
    let s = repo.snapshot_status("oxy status").unwrap();
6156
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
6157
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
6158
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
6159
    assert!(root.join("many/f299.txt").exists());
1a3b6203 Andy McCall ↶ 6160
}
6161
6162
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
6163
/// put a subrepo that was ahead of its pin back at the pin and moved the
6164
/// subrepo's own bookmark backwards.
6165
#[test]
6166
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
6167
    hermetic();
6168
    let dir = tempfile::tempdir().unwrap();
6169
    let root = dir.path();
6170
    Repo::init(&root.join("lib-origin")).unwrap();
6171
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
6172
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
6173
    write(&root.join("lib"), "lib.txt", b"v1\n");
6174
    lib.commit("lib v1", &[]).unwrap();
6175
    assert!(lib.push("origin", false).unwrap()[0].ok);
6176
6177
    let app_dir = root.join("app");
6178
    let mut app = Repo::init(&app_dir).unwrap();
6179
    write(&app_dir, "main.txt", b"app\n");
6180
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
6181
    app.commit("app with lib", &[]).unwrap();
6182
    app.bookmark_create("feature", None).unwrap();
6183
6184
    // New work in the subrepo, not yet pinned by the parent.
6185
    let nested_dir = app_dir.join("libs/lib");
6186
    let nested = Repo::open(&nested_dir).unwrap();
6187
    write(&nested_dir, "new.txt", b"new\n");
6188
    let l2 = nested.commit("lib: new file", &[]).unwrap();
6189
    drop(nested);
6190
6191
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
6192
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
6193
    let nested = Repo::open(&nested_dir).unwrap();
6194
    assert!(
6195
        nested.bookmark_heads().unwrap().contains(&l2),
6196
        "its bookmark kept its work"
6197
    );
6198
    assert!(nested_dir.join("new.txt").exists(), "and its files");
6199
    let s = app.snapshot("status").unwrap();
6200
    assert_eq!(
6201
        statuses(&s),
6202
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
6203
    );
6f8aeb99 Andy McCall ↶ 6204
}
7d9dab13 Andy McCall ↶ 6205
6206
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
6207
/// moving `main` to a change this clone had pushed on another bookmark,
6208
/// the first `pull` said "Already up to date" while `main` was behind.
6209
#[test]
6210
fn pull_takes_a_remote_move_to_changes_already_here() {
6211
    hermetic();
6212
    let dir = tempfile::tempdir().unwrap();
6213
    let root = dir.path();
6214
    let origin_path = root.join("origin");
6215
    let origin = Repo::init(&origin_path).unwrap();
6216
    let url = origin_path.to_string_lossy().to_string();
6217
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
6218
    write(&root.join("b"), "base.txt", b"base\n");
6219
    b.commit("base", &[]).unwrap();
6220
    assert!(b.push("origin", false).unwrap()[0].ok);
6221
6222
    // A feature bookmark with one change, pushed.
6223
    b.bookmark_create("feat", None).unwrap();
6224
    b.bookmark_switch("feat", false).unwrap();
6225
    write(&root.join("b"), "x.txt", b"x\n");
6226
    let x = b.commit("x", &[]).unwrap();
6227
    assert!(b.push("origin", false).unwrap()[0].ok);
6228
    b.bookmark_switch("main", false).unwrap();
6229
6230
    // The remote lands it: its main moves to the feature's state.
6231
    let feat = origin
6232
        .store()
6233
        .get_state(&origin.view().unwrap().bookmarks["feat"])
6234
        .unwrap()
6235
        .heads;
6236
    origin.bookmark_set("main", &feat).unwrap();
6237
6238
    let r = b.pull("origin").unwrap();
6239
    assert!(r.changed, "{r:?}");
6240
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
6241
    let main = b
6242
        .bookmarks()
6243
        .unwrap()
6244
        .into_iter()
6245
        .find(|m| m.name == "main")
6246
        .unwrap();
6247
    assert_eq!(main.behind, Some(0), "{main:?}");
6248
}
86e1824f Andy McCall ↶ 6249
14edbaaf Andy McCall ↶ 6250
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
6251
/// to one only the remote has makes a local bookmark from it; a pull moves
6252
/// every local bookmark the remote has too; a clone checks out the remote's
6253
/// default bookmark.
6254
#[test]
6255
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
6256
    hermetic();
6257
    let dir = tempfile::tempdir().unwrap();
6258
    let root = dir.path();
6259
    let origin_path = root.join("origin");
6260
    let mut origin = Repo::init(&origin_path).unwrap();
6261
    let url = origin_path.to_string_lossy().to_string();
6262
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
6263
    write(&root.join("a"), "base.txt", b"base\n");
6264
    a.commit("base", &[]).unwrap();
6265
    assert!(a.push("origin", false).unwrap()[0].ok);
6266
    a.bookmark_create("develop", None).unwrap();
6267
    a.bookmark_switch("develop", false).unwrap();
6268
    write(&root.join("a"), "base.txt", b"base\nd1\n");
6269
    let d1 = a.commit("d1", &[]).unwrap();
6270
    assert!(a.push("origin", false).unwrap()[0].ok);
6271
6272
    // A clone has main only; origin/develop is a name all the same.
6273
    let c_root = root.join("c");
6274
    let mut c = Repo::clone(&url, &c_root).unwrap();
6275
    assert_eq!(c.config.bookmark, "main");
6276
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
6277
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
6278
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
6279
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
6280
6281
    // Switching makes the local bookmark from origin's.
6282
    c.bookmark_switch("develop", false).unwrap();
6283
    assert_eq!(c.config.bookmark, "develop");
6284
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
6285
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
6286
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
6287
    assert!(c.bookmark_switch("nowhere", false).is_err());
6288
6289
    // Both bookmarks move on the remote; one pull takes both.
6290
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
6291
    let d2 = a.commit("d2", &[]).unwrap();
6292
    assert!(a.push("origin", false).unwrap()[0].ok);
6293
    a.bookmark_switch("main", false).unwrap();
6294
    write(&root.join("a"), "m.txt", b"m\n");
6295
    let m = a.commit("m", &[]).unwrap();
6296
    assert!(a.push("origin", false).unwrap()[0].ok);
6297
    let r = c.pull("origin").unwrap();
6298
    assert!(r.changed && r.checked_out, "{r:?}");
6299
    assert_eq!(r.heads, vec![d2]);
6300
    assert_eq!(r.others, vec!["main".to_string()]);
6301
    assert!(c.resolve_heads("main").unwrap().contains(&m));
6302
    assert_eq!(
6303
        fs::read(c_root.join("base.txt")).unwrap(),
6304
        b"base\nd1\nd2\n"
6305
    );
6306
    let again = c.pull("origin").unwrap();
6307
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
6308
6309
    // A clone checks out the remote's default bookmark.
6310
    origin.config.set("workspace.bookmark", "develop").unwrap();
6311
    origin.save_config().unwrap();
6312
    let e = Repo::clone(&url, &root.join("e")).unwrap();
6313
    assert_eq!(e.config.bookmark, "develop");
6314
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
6315
    let reopened = Repo::open(&root.join("e")).unwrap();
6316
    assert_eq!(reopened.config.bookmark, "develop");
6317
    // REMOTE/NAME names the remote's bookmark to switch to.
6318
    let mut e = reopened;
6319
    e.bookmark_switch("origin/main", false).unwrap();
6320
    assert_eq!(e.config.bookmark, "main");
6321
    assert!(e.bookmark_heads().unwrap().contains(&m));
6322
}
6323
98a1620a Andy McCall ↶ 6324
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
6325
/// op restore goes back to an operation, files included, and undo takes
6326
/// the restore back whole; op revert undoes one operation alone; each
6327
/// operation's changes are described from the views.
6328
#[test]
6329
fn operations_can_be_read_restored_and_reverted() {
6330
    hermetic();
6331
    let dir = tempfile::tempdir().unwrap();
6332
    let root = dir.path();
6333
    let repo = Repo::init(root).unwrap();
6334
    write(root, "a.txt", b"a\n");
6335
    let first = repo.commit("first", &[]).unwrap();
6336
    write(root, "a.txt", b"a\nb\n");
6337
    let second = repo.commit("second", &[]).unwrap();
6338
    let at_second = repo.head_op().unwrap().0.to_hex();
6339
    repo.bookmark_create("keep", None).unwrap();
6340
    let created = repo.head_op().unwrap().0.to_hex();
6341
    write(root, "n.txt", b"n\n");
6342
    let third = repo.commit("third", &[]).unwrap();
6343
6344
    // What each operation changed.
6345
    let ops = repo.op_log().unwrap();
6346
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
6347
    assert!(
6348
        changes
6349
            .iter()
6350
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
6351
        "{changes:?}"
6352
    );
6353
    assert!(changes
6354
        .iter()
6355
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
6356
6357
    // Reading at an earlier operation.
6358
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
6359
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
6360
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
6361
    write(root, "z.txt", b"z\n");
6362
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
6363
    fs::remove_file(root.join("z.txt")).unwrap();
6364
    assert!(repo.resolve_op("zz").is_err());
6365
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
6366
6367
    // Restore goes back, files and all; undo takes it back whole.
6368
    repo.op_restore(&at_second, false).unwrap();
6369
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
6370
    assert!(!root.join("n.txt").exists());
6371
    repo.undo().unwrap();
6372
    let mut heads = repo.bookmark_heads().unwrap();
6373
    heads.sort();
6374
    let mut want = vec![second, third];
6375
    want.sort();
6376
    assert_eq!(heads, want);
6377
    assert!(
6378
        root.join("n.txt").exists(),
6379
        "the files came back with the undo"
6380
    );
6381
6382
    // Revert the bookmark's creation alone: the commit after it stays.
6383
    let r = repo.op_revert(&created).unwrap();
6384
    assert_eq!(r.reverted, vec!["keep".to_string()]);
6385
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
6386
    assert!(repo
6387
        .load_state(&repo.bookmark_heads().unwrap())
6388
        .unwrap()
6389
        .contains(&third));
6390
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
6391
    let _ = first;
6392
}
6393
36041796 Andy McCall ↶ 6394
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
6395
/// from the status cache while every file is as the snapshot left it, and
6396
/// from a snapshot again as soon as one is not.
6397
#[test]
6398
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
6399
    hermetic();
6400
    let dir = tempfile::tempdir().unwrap();
6401
    let root = dir.path();
6402
    let repo = Repo::init(root).unwrap();
6403
    write(root, "a.txt", b"a\n");
6404
    write(root, "b.txt", b"b\n");
6405
    repo.commit("base", &[]).unwrap();
6406
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
6407
6408
    write(root, "a.txt", b"a\nmore\n");
6409
    assert_eq!(
6410
        repo.status_by_manifest().unwrap(),
6411
        None,
6412
        "no snapshot of the edit yet"
6413
    );
6414
    let snap = repo.snapshot_status("oxy status").unwrap();
6415
    assert_eq!(snap.statuses.len(), 1);
6416
    let cached = repo
6417
        .status_by_manifest()
6418
        .unwrap()
6419
        .expect("answered from the cache");
6420
    assert_eq!(cached.len(), 1);
6421
    assert_eq!(
6422
        (cached[0].path.as_str(), cached[0].status),
6423
        ("a.txt", ChangeStatus::Modified)
6424
    );
6425
6426
    // Any further change sends status back to a snapshot.
6427
    write(root, "a.txt", b"a\nmore\nand more\n");
6428
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6429
    repo.snapshot_status("oxy status").unwrap();
6430
    assert!(repo.status_by_manifest().unwrap().is_some());
6431
    write(root, "new.txt", b"n\n");
6432
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6433
    fs::remove_file(root.join("new.txt")).unwrap();
6434
    assert!(
6435
        repo.status_by_manifest().unwrap().is_some(),
6436
        "back as it was"
6437
    );
6438
    fs::remove_file(root.join("b.txt")).unwrap();
6439
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6440
    write(root, "b.txt", b"b\n");
6441
6442
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6443
    repo.snapshot_status("oxy status").unwrap();
6444
    repo.commit("more", &[]).unwrap();
6445
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6446
}
6447
77445673 Andy McCall ↶ 6448
/// oxygen#41: while the status cache holds, the working copy's diff is
6449
/// rendered from the stored working-copy change, and says exactly what a
6450
/// snapshot's diff says.
6451
#[test]
6452
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6453
    hermetic();
6454
    let dir = tempfile::tempdir().unwrap();
6455
    let root = dir.path();
6456
    let repo = Repo::init(root).unwrap();
6457
    write(root, "a.txt", b"one\ntwo\nthree\n");
6458
    write(root, "gone.txt", b"bye\n");
6459
    repo.commit("base", &[]).unwrap();
6460
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6461
    write(root, "new.txt", b"hello\n");
6462
    fs::remove_file(root.join("gone.txt")).unwrap();
6463
    let snap = repo.snapshot_status("oxy status").unwrap();
6464
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6465
    assert!(
6466
        repo.status_by_manifest().unwrap().is_some(),
6467
        "the cache holds"
6468
    );
6469
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6470
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6471
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
74b4a3c6 Andy McCall ↶ 6472
6473
    // Committed, nothing changes: the diff is empty without loading the
6474
    // base (oxygen#94), and the same as rendering it.
6475
    repo.commit("all", &[]).unwrap();
6476
    repo.snapshot_status("oxy status").unwrap();
6477
    assert!(repo.status_by_manifest().unwrap().is_some());
6478
    assert!(repo
6479
        .working_copy_with_base_unless_unchanged()
6480
        .unwrap()
6481
        .is_none());
6482
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6483
    assert_eq!(render_change(&wc, &base, &snapshot), "");
6484
    assert!(repo.diff_files(None).unwrap().is_empty());
77445673 Andy McCall ↶ 6485
}
6486
1ec3f008 Andy McCall ↶ 6487
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6488
/// while none has moved, the check stats the tracked files without listing
6489
/// the tree, and a file added or removed anywhere moves its directory's
6490
/// time, so the tree is listed again.
6491
#[test]
6492
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6493
    hermetic();
6494
    let dir = tempfile::tempdir().unwrap();
6495
    let root = dir.path();
6496
    let repo = Repo::init(root).unwrap();
6497
    write(root, "a.txt", b"a\n");
6498
    write(root, "sub/deep/b.txt", b"b\n");
6499
    repo.commit("base", &[]).unwrap();
6500
    // Out of the racy window: every file and directory a minute old.
6501
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6502
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6503
        fs::File::open(root.join(p))
6504
            .unwrap()
6505
            .set_modified(old)
6506
            .unwrap();
6507
    }
6508
    repo.snapshot_status("oxy status").unwrap();
6509
    repo.write_manifest(false, false).unwrap();
6510
    let m = repo.read_manifest().unwrap().unwrap().2;
6511
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6512
    assert_eq!(
6513
        repo.disk_differs_by_dirs(&m),
6514
        Some(false),
6515
        "no listing needed"
6516
    );
6517
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6518
6519
    // A same-size edit with a new time: found by its stat.
6520
    write(root, "sub/deep/b.txt", b"c\n");
6521
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6522
    write(root, "sub/deep/b.txt", b"b\n");
6523
    fs::File::open(root.join("sub/deep/b.txt"))
6524
        .unwrap()
6525
        .set_modified(old)
6526
        .unwrap();
6527
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6528
6529
    // A new file moves its directory's time: the tree must be listed.
6530
    write(root, "sub/deep/new.txt", b"n\n");
6531
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6532
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6533
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6534
    // A removed one too.
6535
    fs::remove_file(root.join("a.txt")).unwrap();
6536
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6537
}
6538
e226a6cc Andy McCall ↶ 6539
/// oxygen#41: a commit right after a status takes the snapshot the status
6540
/// left (the status cache holds) rather than walking again, and commits
6541
/// exactly what a snapshot would have.
6542
#[test]
6543
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6544
    hermetic();
6545
    let dir = tempfile::tempdir().unwrap();
6546
    let root = dir.path();
6547
    let repo = Repo::init(root).unwrap();
6548
    write(root, "a.txt", b"a\nb\n");
6549
    write(root, ".oxyattributes", b"*.bin binary\n");
6550
    repo.commit("base", &[]).unwrap();
6551
    write(root, "a.txt", b"a\nB\n");
6552
    write(root, "new.txt", b"new\n");
6553
    let snap = repo.snapshot_status("oxy status").unwrap();
6554
    let cached = repo
6555
        .snapshot_from_cache()
6556
        .unwrap()
6557
        .expect("the cache holds");
6558
    assert_eq!(cached.wc_hash, snap.wc_hash);
6559
    assert_eq!(cached.statuses, snap.statuses);
6560
    assert!(
6561
        !cached.attributes.is_empty(),
6562
        "the .oxyattributes file was read"
6563
    );
6564
    let h = repo.commit("edit", &[]).unwrap();
6565
    let c = repo.store().get_change(&h).unwrap();
6566
    assert_eq!(
6567
        c.tree_ops.len() + c.edits.len(),
6568
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6569
    );
6570
    assert_eq!(
6571
        repo.status_by_manifest().unwrap(),
6572
        Some(vec![]),
6573
        "clean after the commit"
6574
    );
6575
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6576
}
6577
0389c3e8 Andy McCall ↶ 6578
/// oxygen#41: a clean check that verified racy entries restamps the
6579
/// manifest, so later checks can trust them, and a same-size rewrite
6580
/// straight afterwards is still found: entries within two seconds of the
6581
/// new time stay racy.
6582
#[test]
6583
fn a_verified_clean_check_restamps_the_manifest_safely() {
6584
    hermetic();
6585
    let dir = tempfile::tempdir().unwrap();
6586
    let root = dir.path();
6587
    let repo = Repo::init(root).unwrap();
6588
    write(root, "a.txt", b"one\n");
6589
    repo.commit("one", &[]).unwrap();
6590
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6591
    assert!(repo.clean_by_manifest().unwrap());
6592
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6593
    assert!(after > before, "restamped");
6594
    write(root, "a.txt", b"two\n");
6595
    assert!(
6596
        !repo.clean_by_manifest().unwrap(),
6597
        "a same-size rewrite is still seen"
6598
    );
6599
}
6600
86e1824f Andy McCall ↶ 6601
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6602
/// stored insert's text blob only when it builds that file's graph, and
6603
/// builds the same graph a full load does.
6604
#[test]
6605
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6606
    hermetic();
6607
    let dir = tempfile::tempdir().unwrap();
6608
    let root = dir.path();
6609
    let repo = Repo::init(root).unwrap();
6610
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6611
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6612
    write(root, "big.txt", big.as_bytes());
6613
    write(root, "other.txt", other.as_bytes());
6614
    let h = repo.commit("two large files", &[]).unwrap();
6615
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6616
    let h2 = repo.commit("append", &[]).unwrap();
6617
6618
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6619
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6620
        FileContent::Text { bytes, .. } => bytes.clone(),
6621
        other => panic!("{other:?}"),
6622
    };
6623
    // Built on demand, every graph renders as the full load's.
6624
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6625
    let big_node = full.files["big.txt"].node;
6626
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6627
    repo.load_all_graphs(&mut hist).unwrap();
6628
    let rendered = hist.materialize();
6629
    for p in ["big.txt", "other.txt"] {
6630
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6631
    }
6632
6633
    // Without other.txt's text blob, history still loads and big.txt still
6634
    // builds: nothing read the other text.
6635
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6636
    assert_eq!(texts.len(), 2);
6637
    let content = |r: &ObjectRef| -> Vec<u8> {
6638
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6639
        blob.chunks
6640
            .iter()
6641
            .flat_map(|c| repo.store().get(c).unwrap().1)
6642
            .collect()
6643
    };
6644
    let other_text = texts
6645
        .iter()
a4fad5b0 Andy McCall ↶ 6646
        .filter_map(|t| match t {
0f93f49c Andy McCall ↶ 6647
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
a4fad5b0 Andy McCall ↶ 6648
            _ => None,
6649
        })
86e1824f Andy McCall ↶ 6650
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6651
        .unwrap();
64818938 Andy McCall ↶ 6652
    repo.store().remove_loose_for_test(&other_text).unwrap();
86e1824f Andy McCall ↶ 6653
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6654
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6655
    assert!(repo
6656
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6657
        .is_err());
6658
}
6659
6660
/// oxygen#35: the first status after a commit read and rendered every
6661
/// file (79 s and more than 14 GB on the Linux tree), because the
6662
/// manifest had no graph keys for files the commit added.
6663
#[test]
6664
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6665
    use std::os::unix::fs::PermissionsExt;
6666
    hermetic();
6667
    let dir = tempfile::tempdir().unwrap();
6668
    let root = dir.path();
6669
    let repo = Repo::init(root).unwrap();
6670
    let files = ["a.txt", "b.txt", "d/c.txt"];
6671
    for p in files {
6672
        write(root, p, format!("{p}\n").as_bytes());
6673
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6674
        fs::File::options()
6675
            .write(true)
6676
            .open(root.join(p))
6677
            .unwrap()
6678
            .set_modified(old)
6679
            .unwrap();
6680
    }
6681
    repo.commit("added", &[]).unwrap();
6682
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6683
    assert!(
6684
        m.entries.values().all(|e| e.graph.is_some()),
6685
        "keys recorded at commit"
6686
    );
6687
    // Unreadable files prove the next status reads none of them.
6688
    for p in files {
6689
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6690
    }
6691
    let snap = repo.snapshot_status("status").unwrap();
6692
    for p in files {
6693
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6694
    }
6695
    assert!(!snap.changed && snap.statuses.is_empty());
6696
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6697
}
c5ce0367 Andy McCall ↶ 6698
6699
/// oxygen#35: a checkout reads, renders and writes only the files whose
6700
/// graphs differ, and renders the rest a batch at a time.
6701
#[test]
6702
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6703
    use std::os::unix::fs::PermissionsExt;
6704
    hermetic();
6705
    let dir = tempfile::tempdir().unwrap();
6706
    let root = dir.path();
6707
    let origin = root.join("origin");
6708
    let mut repo = Repo::init(&origin).unwrap();
6709
    // More files than one batch holds.
6710
    let n = 2100;
6711
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6712
    for i in 0..n {
6713
        let p = format!("f/{i:04}.txt");
6714
        write(&origin, &p, format!("file {i}\n").as_bytes());
6715
        fs::File::options()
6716
            .write(true)
6717
            .open(origin.join(&p))
6718
            .unwrap()
6719
            .set_modified(old)
6720
            .unwrap();
6721
    }
6722
    repo.commit("many", &[]).unwrap();
6723
    repo.bookmark_create("feature", None).unwrap();
6724
    repo.bookmark_switch("feature", false).unwrap();
6725
    write(&origin, "f/0007.txt", b"changed\n");
6726
    repo.commit("one change", &[]).unwrap();
6727
6728
    // Switching back to main must not read the unchanged files.
6729
    for i in 0..n {
6730
        if i != 7 {
6731
            let p = origin.join(format!("f/{i:04}.txt"));
6732
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6733
        }
6734
    }
6735
    let r = repo.bookmark_switch("main", false).unwrap();
6736
    for i in 0..n {
6737
        let p = origin.join(format!("f/{i:04}.txt"));
6738
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6739
    }
6740
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6741
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6742
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6743
6744
    // A clone renders every file, across batches.
6745
    let c = root.join("clone");
6746
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6747
    for i in [0, 2047, 2048, n - 1] {
6748
        assert_eq!(
6749
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6750
            format!("file {i}\n").as_bytes()
6751
        );
6752
    }
6753
    let cloned = Repo::open(&c).unwrap();
6754
    assert!(cloned
6755
        .snapshot_status("status")
6756
        .unwrap()
6757
        .statuses
6758
        .is_empty());
d3cd7ef9 Andy McCall ↶ 6759
}
6760
6761
/// A file written just before the manifest (inside the racy window) is
6762
/// checked by its hash: trusted when equal, caught when edited in place
6763
/// with the same size and time.
6764
#[test]
6765
fn a_racy_manifest_entry_is_checked_by_hash() {
6766
    hermetic();
6767
    let dir = tempfile::tempdir().unwrap();
6768
    let root = dir.path();
6769
    let repo = Repo::init(root).unwrap();
6770
    write(root, "a.txt", b"one\n");
6771
    repo.commit("fresh", &[]).unwrap();
6772
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6773
    let t = fs::metadata(root.join("a.txt"))
6774
        .unwrap()
6775
        .modified()
6776
        .unwrap();
6777
    write(root, "a.txt", b"two\n");
6778
    fs::File::options()
6779
        .write(true)
6780
        .open(root.join("a.txt"))
6781
        .unwrap()
6782
        .set_modified(t)
6783
        .unwrap();
6784
    assert!(
6785
        !repo.clean_by_manifest().unwrap(),
6786
        "same size and time, other bytes"
6787
    );
6788
    assert_eq!(
6789
        statuses(&repo.snapshot_status("status").unwrap()),
6790
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6791
    );
c5ce0367 Andy McCall ↶ 6792
}
2c75672f Andy McCall ↶ 6793
6794
/// A fetch on one machine moves changes as stored, text blobs among the
6795
/// objects; a change whose text blob did not come is refused, not stored.
6796
#[test]
6797
fn a_raw_bundle_without_a_changes_text_is_refused() {
6798
    hermetic();
6799
    let dir = tempfile::tempdir().unwrap();
6800
    let root = dir.path();
6801
    let a = Repo::init(&root.join("a")).unwrap();
6802
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6803
    write(&root.join("a"), "big.txt", big.as_bytes());
6804
    let h = a.commit("big", &[]).unwrap();
6805
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6806
    assert_eq!(bundle.raw_changes.len(), 1);
6807
    assert!(bundle.changes.is_empty());
6808
    let b = Repo::init(&root.join("b")).unwrap();
6809
    let mut without = bundle.clone();
6810
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6811
    let e = b.import_bundle(&without, false).unwrap_err();
6812
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6813
    assert!(!b.store().has(&h));
6814
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6815
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6816
}
a87c7b9d Andy McCall ↶ 6817
6818
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6819
/// again was a second node for one Git path, so a file moved into it on
6820
/// another line, where the first node still stood, ended up in two places.
6821
/// An import now brings the directory back rather than make a new one.
6822
#[test]
6823
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6824
    hermetic();
6825
    if std::process::Command::new("git")
6826
        .arg("--version")
6827
        .output()
6828
        .is_err()
6829
    {
6830
        eprintln!("git not installed; skipping");
6831
        return;
6832
    }
6833
    let dir = tempfile::tempdir().unwrap();
6834
    let root = dir.path();
6835
    let g = root.join("src.git");
6836
    fs::create_dir_all(&g).unwrap();
6837
    let git = |args: &[&str]| -> String {
6838
        let out = std::process::Command::new("git")
6839
            .arg("-C")
6840
            .arg(&g)
6841
            .args([
6842
                "-c",
6843
                "user.name=Grace",
6844
                "-c",
6845
                "[email protected]",
6846
                "-c",
6847
                "commit.gpgsign=false",
6848
            ])
6849
            .args(args)
6850
            .output()
6851
            .unwrap();
6852
        assert!(
6853
            out.status.success(),
6854
            "git {args:?}: {}",
6855
            String::from_utf8_lossy(&out.stderr)
6856
        );
6857
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6858
    };
6859
    git(&["init", "-q", "-b", "main"]);
6860
    write(&g, "d/a.txt", b"a\n");
6861
    write(&g, "c/x.txt", b"x\n");
6862
    git(&["add", "."]);
6863
    git(&["commit", "-qm", "base"]);
6864
    // One line: move x into d while d still stands.
6865
    git(&["checkout", "-qb", "side"]);
6866
    git(&["mv", "c/x.txt", "d/x.txt"]);
6867
    git(&["commit", "-qm", "x into d"]);
6868
    // The other: d goes, comes back, and x moves into it too.
6869
    git(&["checkout", "-q", "main"]);
6870
    git(&["rm", "-q", "d/a.txt"]);
6871
    git(&["commit", "-qm", "d goes"]);
6872
    write(&g, "d/b.txt", b"b\n");
6873
    git(&["add", "."]);
6874
    git(&["commit", "-qm", "d comes back"]);
6875
    git(&["mv", "c/x.txt", "d/x.txt"]);
6876
    git(&["commit", "-qm", "x into d again"]);
6877
    git(&["merge", "-q", "--no-edit", "side"]);
6878
6879
    let repo = Repo::init(&root.join("o")).unwrap();
6880
    repo.import_git(&g, "main").unwrap();
6881
    let v = repo.verify_git_import(&g, "main").unwrap();
6882
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6883
    let st = repo
6884
        .load_state_history(&repo.bookmark_heads().unwrap())
6885
        .unwrap();
6886
    let view = st.tree().view();
6887
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6888
    // The directory is the one the first commit made.
6889
    // Commits made in one second tie on time: find the first by its message.
6890
    let first = repo
6891
        .log()
6892
        .unwrap()
6893
        .into_iter()
6894
        .find(|e| e.change.message.starts_with("base"))
6895
        .unwrap();
6896
    let base = repo
6897
        .load_state_history(&[first.hash])
6898
        .unwrap()
6899
        .tree()
6900
        .view();
6901
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6902
}
6903
6904
/// oxygen#30, the rest: a placement left under a directory another line
6905
/// removed is out of sight, so no diff reaches it; the merge that settles
6906
/// where the file is retires it.
6907
#[test]
6908
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6909
    hermetic();
6910
    if std::process::Command::new("git")
6911
        .arg("--version")
6912
        .output()
6913
        .is_err()
6914
    {
6915
        eprintln!("git not installed; skipping");
6916
        return;
6917
    }
6918
    let dir = tempfile::tempdir().unwrap();
6919
    let root = dir.path();
6920
    let g = root.join("src.git");
6921
    fs::create_dir_all(&g).unwrap();
6922
    let run = |args: &[&str]| {
6923
        std::process::Command::new("git")
6924
            .arg("-C")
6925
            .arg(&g)
6926
            .args([
6927
                "-c",
6928
                "user.name=Grace",
6929
                "-c",
6930
                "[email protected]",
6931
                "-c",
6932
                "commit.gpgsign=false",
6933
            ])
6934
            .args(args)
6935
            .output()
6936
            .unwrap()
6937
    };
6938
    let git = |args: &[&str]| {
6939
        let out = run(args);
6940
        assert!(
6941
            out.status.success(),
6942
            "git {args:?}: {}",
6943
            String::from_utf8_lossy(&out.stderr)
6944
        );
6945
    };
6946
    git(&["init", "-q", "-b", "main"]);
6947
    write(&g, "c/x.txt", b"x\n");
6948
    write(&g, "keep.txt", b"k\n");
6949
    git(&["add", "."]);
6950
    git(&["commit", "-qm", "base"]);
6951
    // One line renames the file within c; the other moves it out of c,
6952
    // which goes.
6953
    git(&["checkout", "-qb", "side"]);
6954
    git(&["mv", "c/x.txt", "c/y.txt"]);
6955
    git(&["commit", "-qm", "rename within c"]);
6956
    git(&["checkout", "-q", "main"]);
6957
    fs::create_dir_all(g.join("n")).unwrap();
6958
    git(&["mv", "c/x.txt", "n/x.txt"]);
6959
    git(&["commit", "-qm", "move out of c"]);
6960
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6961
    let _ = run(&["merge", "-q", "side"]);
6962
    let _ = run(&[
6963
        "rm",
6964
        "-q",
6965
        "--cached",
6966
        "--ignore-unmatch",
6967
        "c/y.txt",
6968
        "c/x.txt",
6969
    ]);
6970
    let _ = std::fs::remove_dir_all(g.join("c"));
6971
    write(&g, "n/x.txt", b"x\n");
6972
    git(&["add", "-A"]);
6973
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6974
6975
    let repo = Repo::init(&root.join("o")).unwrap();
6976
    repo.import_git(&g, "main").unwrap();
6977
    let v = repo.verify_git_import(&g, "main").unwrap();
6978
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6979
    let st = repo
6980
        .load_state_history(&repo.bookmark_heads().unwrap())
6981
        .unwrap();
6982
    let view = st.tree().view();
6983
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6984
    assert!(view.entries.contains_key("n/x.txt"));
6985
}
6986
6987
/// oxygen#30, orphans: a file added on one line into a directory the other
6988
/// line removed is placed where the tree cannot show it; Git's merge keeps
6989
/// the file, and the import's merge leaves exactly one of it.
6990
#[test]
6991
fn git_import_merge_leaves_no_orphan_behind() {
6992
    hermetic();
6993
    if std::process::Command::new("git")
6994
        .arg("--version")
6995
        .output()
6996
        .is_err()
6997
    {
6998
        eprintln!("git not installed; skipping");
6999
        return;
7000
    }
7001
    let dir = tempfile::tempdir().unwrap();
7002
    let root = dir.path();
7003
    let g = root.join("src.git");
7004
    fs::create_dir_all(&g).unwrap();
7005
    let git = |args: &[&str]| {
7006
        let out = std::process::Command::new("git")
7007
            .arg("-C")
7008
            .arg(&g)
7009
            .args([
7010
                "-c",
7011
                "user.name=Grace",
7012
                "-c",
7013
                "[email protected]",
7014
                "-c",
7015
                "commit.gpgsign=false",
7016
            ])
7017
            .args(args)
7018
            .output()
7019
            .unwrap();
7020
        assert!(
7021
            out.status.success(),
7022
            "git {args:?}: {}",
7023
            String::from_utf8_lossy(&out.stderr)
7024
        );
7025
    };
7026
    git(&["init", "-q", "-b", "main"]);
7027
    write(&g, "d/f.txt", b"f\n");
7028
    write(&g, "keep.txt", b"k\n");
7029
    git(&["add", "."]);
7030
    git(&["commit", "-qm", "base"]);
7031
    git(&["checkout", "-qb", "side"]);
7032
    write(&g, "d/new.txt", b"new\n");
7033
    git(&["add", "."]);
7034
    git(&["commit", "-qm", "add into d"]);
7035
    git(&["checkout", "-q", "main"]);
7036
    git(&["rm", "-q", "d/f.txt"]);
7037
    git(&["commit", "-qm", "d goes"]);
7038
    git(&["merge", "-q", "--no-edit", "side"]);
7039
7040
    let repo = Repo::init(&root.join("o")).unwrap();
7041
    repo.import_git(&g, "main").unwrap();
7042
    let v = repo.verify_git_import(&g, "main").unwrap();
7043
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7044
    let st = repo
7045
        .load_state_history(&repo.bookmark_heads().unwrap())
7046
        .unwrap();
7047
    let view = st.tree().view();
7048
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
7049
    assert!(view.entries.contains_key("d/new.txt"));
7050
}
d77e1702 Andy McCall ↶ 7051
7052
/// fsck checks a change's text as the blobs it is stored in, without
7053
/// decoding it: a missing text blob is an error named for the change.
7054
#[test]
7055
fn fsck_names_a_missing_text_blob() {
7056
    hermetic();
7057
    let dir = tempfile::tempdir().unwrap();
7058
    let root = dir.path();
7059
    let repo = Repo::init(root).unwrap();
7060
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7061
    write(root, "big.txt", big.as_bytes());
7062
    let h = repo.commit("big", &[]).unwrap();
7063
    assert_eq!(repo.fsck().unwrap().errors(), 0);
7064
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7065
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
7066
        panic!("a stored text")
7067
    };
64818938 Andy McCall ↶ 7068
    repo.store().remove_loose_for_test(&b).unwrap();
d77e1702 Andy McCall ↶ 7069
    let rep = repo.fsck().unwrap();
7070
    assert!(rep.errors() > 0);
7071
    assert!(
7072
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
7073
        "{:?}",
7074
        rep.problems
7075
    );
7076
}
a07f60a3 Andy McCall ↶ 7077
7078
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
7079
/// reached with that remote's token and CA (a private subrepo then clones
7080
/// for anyone who can read the parent); another hub gets none of them.
7081
#[test]
7082
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
7083
    hermetic();
7084
    let dir = tempfile::tempdir().unwrap();
7085
    let mut repo = Repo::init(dir.path()).unwrap();
7086
    repo.config
7087
        .set(
7088
            "remote.origin.url",
7089
            "https://Hub.example:7343/doomsdayone/metalgear",
7090
        )
7091
        .unwrap();
7092
    repo.config.set("remote.origin.token", "secret").unwrap();
7093
    repo.config
7094
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
7095
        .unwrap();
7096
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
7097
    assert_eq!(same.token.as_deref(), Some("secret"));
7098
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
7099
    for other in [
7100
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
7101
        "https://hub.example/doomsdayone/rstar-api",
7102
        "http://hub.example:7343/doomsdayone/rstar-api",
7103
    ] {
7104
        let o = repo.credentials_for(other);
7105
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
7106
    }
7107
}
ce14f0d6 Andy McCall ↶ 7108
ff1f62fe Andy McCall ↶ 7109
/// oxygen#47: a remote with no token of its own uses the user's credential
7110
/// store for its hub, and a nested checkout finds its parent's remote
7111
/// token there instead of keeping a copy.
ce14f0d6 Andy McCall ↶ 7112
#[test]
ff1f62fe Andy McCall ↶ 7113
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
7114
    hermetic();
7115
    let home = tempfile::tempdir().unwrap();
7116
    let dir = tempfile::tempdir().unwrap();
7117
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
7118
    parent
7119
        .config
7120
        .set("remote.origin.url", "https://hub.example/o/parent")
7121
        .unwrap();
7122
    parent.save_config().unwrap();
7123
    assert_eq!(parent.remote_options("origin").token, None);
7124
    crate::credentials::Credentials::at(home.path())
7125
        .save("https://hub.example", "stored", Some("andy"), None)
7126
        .unwrap();
7127
    assert_eq!(
7128
        parent.remote_options("origin").token.as_deref(),
7129
        Some("stored")
7130
    );
7131
7132
    let empty_home = tempfile::tempdir().unwrap();
7133
    let nested = dir.path().join("deps").join("child");
7134
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
7135
    child
7136
        .config
7137
        .set("remote.origin.url", "https://hub.example/o/child")
7138
        .unwrap();
7139
    child.save_config().unwrap();
7140
    assert_eq!(child.remote_options("origin").token, None);
7141
    parent
7142
        .config
7143
        .set("remote.origin.token", "checkout")
7144
        .unwrap();
7145
    parent.save_config().unwrap();
7146
    assert_eq!(
7147
        child.remote_options("origin").token.as_deref(),
7148
        Some("checkout")
7149
    );
7150
    // Another hub's checkout token is not borrowed.
7151
    child
7152
        .config
7153
        .set("remote.origin.url", "https://other.example/o/child")
7154
        .unwrap();
7155
    assert_eq!(child.remote_options("origin").token, None);
7156
}
7157
7158
#[test]
ce14f0d6 Andy McCall ↶ 7159
fn the_metadata_cache_survives_a_torn_tail() {
7160
    hermetic();
7161
    let dir = tempfile::tempdir().unwrap();
7162
    let root = dir.path();
7163
    let repo = Repo::init(root).unwrap();
7164
    write(root, "a.txt", b"1\n");
7165
    let h = repo.commit("first", &[]).unwrap();
7166
    let meta = repo.store().get_change_meta(&h).unwrap();
7167
    let cache = repo.store().dir().join("metas");
7168
    let len = fs::metadata(&cache).unwrap().len();
7169
    assert!(len > 0, "a change read is cached");
7170
    // A torn record at the end: the cache reads up to it and cuts it off.
7171
    fs::OpenOptions::new()
7172
        .append(true)
7173
        .open(&cache)
7174
        .unwrap()
7175
        .write_all(&[7; 20])
7176
        .unwrap();
7177
    let again = Repo::open(root).unwrap();
7178
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
7179
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
7180
}
f9466021 Andy McCall ↶ 7181
7182
#[test]
7183
fn a_manifest_that_does_not_check_reads_as_none() {
7184
    hermetic();
7185
    let dir = tempfile::tempdir().unwrap();
7186
    let root = dir.path();
7187
    let repo = Repo::init(root).unwrap();
7188
    write(root, "a.txt", b"1\n");
7189
    repo.commit("first", &[]).unwrap();
7190
    let path = repo.manifest_path();
7191
    let mut bytes = fs::read(&path).unwrap();
7192
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
7193
    let last = bytes.len() - 1;
7194
    bytes[last] ^= 1;
7195
    fs::write(&path, &bytes).unwrap();
7196
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
7197
    // The next status reads the files and writes it again.
7198
    let again = Repo::open(root).unwrap();
7199
    assert!(!again.snapshot("status").unwrap().changed);
7200
    assert!(again.read_manifest().unwrap().is_some());
7201
}
7202
7203
#[test]
7204
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
7205
    hermetic();
7206
    let dir = tempfile::tempdir().unwrap();
7207
    let root = dir.path();
7208
    let repo = Repo::init(root).unwrap();
7209
    write(root, "a.txt", b"1\n");
7210
    write(root, "b.txt", b"2\n");
7211
    // b.txt outside the racy window, so snapshots take it as unchanged.
7212
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7213
    fs::File::options()
7214
        .write(true)
7215
        .open(root.join("b.txt"))
7216
        .unwrap()
7217
        .set_modified(old)
7218
        .unwrap();
7219
    repo.commit("first", &[]).unwrap();
7220
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
7221
    repo.snapshot_status("status").unwrap();
7222
    write(root, "a.txt", b"1\n2\n");
7223
    repo.commit("second", &[]).unwrap();
7224
    assert!(
7225
        repo.clean_by_manifest().unwrap(),
7226
        "after a commit of one file"
7227
    );
7228
    // Edited, seen by a status, edited again, then committed: the status
7229
    // left the first edit's stat, which the commit must not keep.
7230
    write(root, "a.txt", b"1\n2\n3\n");
7231
    repo.snapshot_status("status").unwrap();
7232
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
7233
    repo.commit("third", &[]).unwrap();
7234
    assert!(
7235
        repo.clean_by_manifest().unwrap(),
7236
        "after an edit a status saw"
7237
    );
7238
}
e266b7d4 Andy McCall ↶ 7239
7240
#[test]
7241
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
7242
    hermetic();
7243
    let dir = tempfile::tempdir().unwrap();
7244
    let root = dir.path();
7245
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7246
    write(root, "a.txt", b"1\n2\n");
7247
    let a = repo.commit("A", &[]).unwrap();
7248
    repo.bookmark_create("develop", Some(&[a])).unwrap();
7249
    write(root, "a.txt", b"1\nX\n");
7250
    let c = repo.commit("C: 2 to X", &[]).unwrap();
7251
    repo.bookmark_switch("develop", false).unwrap();
7252
    write(root, "a.txt", b"1\nY\n");
7253
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
7254
    repo.bookmark_switch("main", false).unwrap();
7255
7256
    let err = repo.rebase(&c, &[d]).unwrap_err();
7257
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
7258
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
7259
    assert!(r.changed && r.checked_out);
7260
    let snap = repo.snapshot_status("status").unwrap();
7261
    assert!(
7262
        snap.base_snapshot.is_conflicted(),
7263
        "the conflict is in the working copy"
7264
    );
7265
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
7266
    assert!(text.contains('X') && text.contains('Y'), "{text}");
7267
7268
    write(root, "a.txt", b"1\nXY\n");
7269
    repo.commit("Resolve", &[]).unwrap();
7270
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
7271
    assert!(st.contains(&c) && st.contains(&d));
7272
    let files = st.materialize().files;
7273
    assert!(!files["a.txt"].is_conflicted());
7274
    assert!(
7275
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
7276
    );
7277
7278
    // A change the current bookmark does not hold is refused.
7279
    repo.bookmark_switch("develop", false).unwrap();
7280
    write(root, "b.txt", b"b\n");
7281
    let e = repo.commit("E", &[]).unwrap();
7282
    repo.bookmark_switch("main", false).unwrap();
7283
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
7284
    assert!(
7285
        err.to_string().contains("not on the current bookmark"),
7286
        "{err}"
7287
    );
7288
}
d4dbab97 Andy McCall ↶ 7289
7290
#[test]
7291
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
7292
    hermetic();
7293
    let dir = tempfile::tempdir().unwrap();
7294
    let root = dir.path();
7295
    let repo = Repo::init(root).unwrap();
7296
    write(root, "a.txt", b"a\n");
7297
    write(root, "kept.log", b"tracked\n");
7298
    repo.commit("first", &[]).unwrap();
7299
    write(root, "build.log", b"made\n");
7300
    let snap = repo.snapshot_status("status").unwrap();
7301
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
7302
    // A rule written afterwards leaves the added file out again, while the
7303
    // committed one stays tracked.
7304
    write(root, ".gitignore", b"*.log\n");
7305
    let snap = repo.snapshot_status("status").unwrap();
7306
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
7307
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
7308
    write(root, "kept.log", b"tracked, edited\n");
7309
    let snap = repo.snapshot_status("status").unwrap();
7310
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
7311
}
fd280228 Andy McCall ↶ 7312
7313
#[test]
7314
fn shed_graphs_come_back_the_same() {
7315
    hermetic();
7316
    let dir = tempfile::tempdir().unwrap();
7317
    let root = dir.path();
7318
    let repo = Repo::init(root).unwrap();
7319
    write(root, "a.txt", b"1\n2\n3\n");
7320
    write(root, "b.txt", b"x\n");
7321
    repo.commit("first", &[]).unwrap();
7322
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
7323
    repo.commit("second", &[]).unwrap();
7324
    let heads = repo.bookmark_heads().unwrap();
7325
    let mut st = repo.load_state_history(&heads).unwrap();
7326
    let view = st.tree().view();
7327
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
7328
        .iter()
7329
        .map(|p| view.entries[*p].node)
7330
        .collect();
7331
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7332
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7333
    assert_eq!(st.built_count(), 2);
7334
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
7335
    assert_eq!((shed, st.built_count()), (2, 0));
7336
    // A later change applies on top of the shed history.
7337
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
7338
    let h3 = repo.commit("third", &[]).unwrap();
7339
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
7340
    st.add_known(h3, skeleton, texts);
7341
    repo.load_graphs_of(&mut st, &nodes).unwrap();
7342
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
7343
    assert_eq!(after[1], before[1]);
7344
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
7345
}
360aa74a Andy McCall ↶ 7346
7347
#[test]
7348
fn many_edited_files_diff_in_parallel() {
7349
    // Enough edited files that the builder diffs them in parallel; the
7350
    // commit must hold exactly what is on disk, and a second snapshot
7351
    // must find nothing left to commit.
7352
    hermetic();
7353
    let dir = tempfile::tempdir().unwrap();
7354
    let root = dir.path();
7355
    let repo = Repo::init(root).unwrap();
7356
    let text = |i: usize, round: usize| {
7357
        let mut s = String::new();
7358
        for line in 0..50 {
7359
            if round > 0 && line % 7 == i % 7 {
7360
                s.push_str(&format!("edited {round} {i} {line}\n"));
7361
            } else {
7362
                s.push_str(&format!("file {i} line {line}\n"));
7363
            }
7364
        }
7365
        if round > 0 && i.is_multiple_of(3) {
7366
            s.push_str("appended\n");
7367
        }
7368
        s
7369
    };
7370
    for i in 0..40 {
7371
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
7372
    }
7373
    repo.commit("first", &[]).unwrap();
7374
    for i in 0..40 {
7375
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
7376
    }
7377
    let h = repo.commit("edit every file", &[]).unwrap();
7378
    let snap = repo.load_state(&[h]).unwrap().materialize();
7379
    for i in 0..40 {
7380
        let want = text(i, 1);
7381
        assert!(
7382
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
7383
            "d/f{i}.txt as committed"
7384
        );
7385
    }
7386
    assert!(
7387
        repo.commit("nothing", &[]).is_err(),
7388
        "nothing left to commit"
7389
    );
7390
}
b35df36b Andy McCall ↶ 7391
7392
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
7393
/// is known (fetch printed "up to date" while main was behind), a change
7394
/// only fetched resolves and says where it is, and a checkout whose only
7395
/// remote is not `origin` uses that one.
7396
#[test]
7397
fn a_fetched_change_shows_as_behind_and_resolves() {
7398
    hermetic();
7399
    let dir = tempfile::tempdir().unwrap();
7400
    let root = dir.path();
7401
    let origin = Repo::init(&root.join("origin")).unwrap();
7402
    drop(origin);
7403
    let url = root.join("origin").to_string_lossy().to_string();
7404
    let a = Repo::clone(&url, &root.join("a"))
7405
        .unwrap()
7406
        .with_home(root.join("home-a"));
7407
    write(&root.join("a"), "f.txt", b"one\n");
7408
    a.commit("one", &[]).unwrap();
7409
    a.push("origin", false).unwrap();
7410
    let b = Repo::clone(&url, &root.join("b"))
7411
        .unwrap()
7412
        .with_home(root.join("home-b"));
7413
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7414
7415
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
7416
    let h2 = a.commit("two", &[]).unwrap();
7417
    a.push("origin", false).unwrap();
7418
    b.fetch("origin").unwrap();
7419
    // Fetched, not pulled: one behind, the change found and placed.
7420
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7421
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7422
    assert_eq!(
7423
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7424
            .unwrap(),
7425
        h2
7426
    );
7427
    assert_eq!(
7428
        b.remote_only_location(&h2).unwrap().as_deref(),
7429
        Some("origin/main")
7430
    );
7431
    // Fetching again changes nothing: still behind, which is what the
7432
    // CLI now says rather than "up to date".
7433
    b.fetch("origin").unwrap();
7434
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7435
    b.pull("origin").unwrap();
7436
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7437
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7438
7439
    // One remote, not called origin: it is the default.
7440
    let mut c = Repo::init(&root.join("c")).unwrap();
7441
    assert_eq!(c.default_remote(), "origin");
7442
    c.config.set("remote.earth.url", &url).unwrap();
7443
    assert_eq!(c.default_remote(), "earth");
7444
    c.config.set("remote.origin.url", &url).unwrap();
7445
    assert_eq!(c.default_remote(), "origin");
7446
}
827281ee Andy McCall ↶ 7447
7448
/// oxygen#57: a clone from a relative local path records the remote as an
7449
/// absolute path, so fetch still finds it from inside the clone.
7450
#[test]
7451
fn a_clone_from_a_relative_path_records_it_absolute() {
7452
    hermetic();
7453
    let dir = tempfile::tempdir().unwrap();
7454
    let root = dir.path();
7455
    Repo::init(&root.join("origin")).unwrap();
7456
    let rel = crate::protocol::stored_url("relative/repo");
7457
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7458
    assert_eq!(
7459
        crate::protocol::stored_url("https://hub.example/o/n"),
7460
        "https://hub.example/o/n"
7461
    );
7462
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8d803563 Andy McCall ↶ 7463
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7464
    // A bucket is kept as written: it is not a path.
7465
    assert_eq!(
7466
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7467
        "s3://bucket/prefix?profile=p"
7468
    );
827281ee Andy McCall ↶ 7469
    let url = root.join("origin").to_string_lossy().to_string();
7470
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7471
    assert_eq!(b.config.remotes["origin"], url);
7472
    b.fetch("origin").unwrap();
7473
}
a46f3e4f Andy McCall ↶ 7474
7475
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7476
/// and gets its subrepos at their pins from this workspace's copies, with
7477
/// their remotes pointing where the subrepos come from.
7478
#[test]
7479
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7480
    hermetic();
7481
    let dir = tempfile::tempdir().unwrap();
7482
    let root = dir.path();
7483
    Repo::init(&root.join("lib-origin")).unwrap();
7484
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7485
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7486
        .unwrap()
7487
        .with_home(root.join("home"));
7488
    write(&root.join("lib"), "lib.txt", b"v1\n");
7489
    let l1 = lib.commit("lib v1", &[]).unwrap();
7490
    assert!(lib.push("origin", false).unwrap()[0].ok);
7491
7492
    let app_dir = root.join("app");
7493
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7494
    write(&app_dir, "main.txt", b"app\n");
7495
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7496
    app.commit("app with lib", &[]).unwrap();
7497
    // A second bookmark, and the main workspace on another.
7498
    app.bookmark_create("develop", None).unwrap();
7499
    app.bookmark_create("feature", None).unwrap();
7500
    let mut app = app;
7501
    app.bookmark_switch("feature", false).unwrap();
7502
    assert_eq!(app.config.bookmark, "feature");
7503
7504
    // The library's origin goes away: the subrepo must come from here.
7505
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7506
    let heads = app.resolve_heads("develop").unwrap();
7507
    let ws = app
7508
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7509
        .unwrap();
7510
    assert_eq!(
7511
        ws.config.bookmark, "develop",
7512
        "the new workspace is on develop"
7513
    );
7514
    assert_eq!(
7515
        app.config.bookmark, "feature",
7516
        "and this one stays on its own"
7517
    );
7518
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7519
    assert_eq!(
7520
        sub.config.remotes["origin"], lib_url,
7521
        "its origin is the subrepo's URL"
7522
    );
7523
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7524
    assert_eq!(
7525
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7526
        b"v1\n"
7527
    );
7528
}
47ce8b8e Andy McCall ↶ 7529
7530
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7531
/// operators and the predicates, over a small graph with two heads and
7532
/// a rename.
7533
#[test]
7534
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7535
    hermetic();
7536
    let dir = tempfile::tempdir().unwrap();
7537
    let root = dir.path();
7538
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7539
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7540
        .unwrap();
7541
    write(root, "src/a.rs", b"one\n");
7542
    let a = repo.commit("first: add a", &[]).unwrap();
7543
    write(root, "src/a.rs", b"one\ntwo\n");
7544
    let b = repo.commit("second: grow a", &[]).unwrap();
7545
    // A second head, independent of b: a new file on top of a.
7546
    repo.checkout(&[a], false, "checkout a").unwrap();
7547
    write(root, "docs/notes.md", b"notes\n");
7548
    let c = repo.commit("third: notes", &[]).unwrap();
7549
    // Back to both heads, then rename a.rs: the node keeps its identity.
7550
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7551
        .unwrap();
7552
    fs::remove_file(root.join("src/a.rs")).unwrap();
7553
    write(root, "src/z.rs", b"one\ntwo\n");
7554
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7555
    let wc = repo.working_copy().unwrap().0;
7556
    // A saved revset is checked when set.
7557
    repo.set_user_config("revset.mine", "author(me) & ::main")
7558
        .unwrap();
7559
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7560
    let set = |src: &str| -> Vec<ChangeHash> {
7561
        let mut v = repo.revset(src).unwrap().hashes;
7562
        v.sort();
7563
        v
7564
    };
7565
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7566
        let mut v = hs.to_vec();
7567
        v.sort();
7568
        v
7569
    };
7570
7571
    // Changes commute: a new file depends on nothing and the rename on the
7572
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7573
    // copy on the three heads b, c, d.
7574
    let heads = sorted(&repo.bookmark_heads().unwrap());
7575
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7576
    assert!(heads.contains(&d) && heads.contains(&c));
7577
    // Symbols and closures.
7578
    assert_eq!(set("main"), heads);
7579
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7580
    assert_eq!(set("@"), vec![wc]);
7581
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7582
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7583
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7584
    assert_eq!(
7585
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7586
        sorted(&[a, b])
7587
    );
7588
    // Ranges: what main has beyond b, and `..` forms.
7589
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7590
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7591
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7592
    // Operators and precedence: ~ binds tighter than &, & than |.
7593
    assert_eq!(
7594
        set(&format!("::main ~ #{}", d.short(12))),
7595
        sorted(&[a, b, c])
7596
    );
7597
    assert_eq!(
7598
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7599
        sorted(&[b, c])
7600
    );
7601
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7602
    // Relations.
7603
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7604
    head_deps.sort();
7605
    head_deps.dedup();
7606
    assert_eq!(set("deps(main)"), head_deps);
7607
    let on_a: Vec<ChangeHash> = [b, c, d]
7608
        .into_iter()
7609
        .filter(|h| meta(h).deps.contains(&a))
7610
        .collect();
7611
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7612
    assert_eq!(set("heads(::main)"), heads);
7613
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7614
    assert_eq!(
7615
        set(&format!(
7616
            "heads(#{} | #{} | #{})",
7617
            a.short(12),
7618
            b.short(12),
7619
            c.short(12)
7620
        )),
7621
        sorted(&[b, c])
7622
    );
7623
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7624
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7625
    assert_eq!(set("none()"), vec![]);
7626
    // Predicates: author by name, email, key prefix and `me`.
7627
    let key = repo.config.author_key.unwrap();
7628
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7629
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7630
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7631
    assert_eq!(set("author(me) & ::main").len(), 4);
7632
    assert_eq!(set("author(nobody)"), vec![]);
7633
    assert_eq!(set("description(notes)"), vec![c]);
7634
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7635
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7636
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7637
    // touches follows the node through the rename, in the current state.
7638
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7639
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7640
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7641
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7642
    // Newest first in the result order.
7643
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7644
    // The saved revset, and errors that say what is wrong.
7645
    assert_eq!(set("mine()").len(), 4);
7646
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7647
    assert!(e.contains("unknown function nosuch()"), "{e}");
7648
    let e = repo.revset("main &").unwrap_err().to_string();
7649
    assert!(e.contains("at character"), "{e}");
7650
    let e = repo.revset("zzzz").unwrap_err().to_string();
7651
    assert!(e.contains("no change matches"), "{e}");
7652
    let e = repo
7653
        .revset_with_budget("::main", std::time::Duration::ZERO)
7654
        .unwrap_err()
7655
        .to_string();
7656
    assert!(e.contains("budget"), "{e}");
7657
    // The log entries carry the bookmark's heads and the working copy.
7658
    let entries = repo.log_revset("::@").unwrap();
7659
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
2c9ddac3 Andy McCall ↶ 7660
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7661
    // push); then a signed change, a tag, and a revocation.
7662
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7663
    assert_eq!(set("signed_by(me)"), vec![]);
7664
    repo.sign_change(&d).unwrap();
7665
    assert_eq!(set("signed_by(me)"), vec![d]);
7666
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7667
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7668
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7669
    assert_eq!(set("delegated()"), vec![]);
7670
    assert_eq!(set("revoked()"), vec![]);
7671
    assert_eq!(set("attested(tag)"), vec![]);
7672
    repo.tag_create("v1", &[b], "first").unwrap();
7673
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7674
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7675
    assert_eq!(set("attested(receipt)"), vec![]);
7676
    assert_eq!(set("built(test)"), vec![]);
7677
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7678
    assert!(e.contains("tag, receipt or ref"), "{e}");
7679
    repo.revoke_identity(&key, "test").unwrap();
7680
    assert_eq!(set("revoked()"), vec![d]);
7681
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
543bbf64 Andy McCall ↶ 7682
    // independent(X, IN): what could ship without X. c and d neither
7683
    // depend on b nor are depended on by it; a is below, the working copy
7684
    // above.
7685
    assert_eq!(
7686
        set(&format!("independent(#{}, ::@)", b.short(12))),
7687
        sorted(&[c, d])
7688
    );
7689
    assert_eq!(
7690
        set(&format!("independent(#{}, ::main)", a.short(12))),
7691
        vec![c]
7692
    );
7693
    // conflicts(S): nothing conflicts yet; then two edits of one line.
7694
    assert_eq!(set("conflicts()"), vec![]);
7695
    assert_eq!(set("conflicts(main)"), vec![]);
7696
    // (The saved revset above edited the user config under the root:
7697
    // discard it.)
7698
    repo.checkout(&[a], true, "checkout a").unwrap();
7699
    write(root, "src/a.rs", b"one\nTWO\n");
7700
    let e = repo
7701
        .commit("fifth: the other edit of line two", &[])
7702
        .unwrap();
7703
    repo.checkout(&repo.bookmark_heads().unwrap(), true, "checkout main")
7704
        .unwrap();
7705
    let conflicted = repo.revset("conflicts()").unwrap().hashes;
7706
    assert!(
7707
        conflicted.contains(&e) && conflicted.contains(&b),
7708
        "{conflicted:?} should hold b and e"
7709
    );
7710
    assert!(!conflicted.contains(&c));
7711
    assert_eq!(set("conflicts() & author(nobody)"), vec![]);
47ce8b8e Andy McCall ↶ 7712
}
614f55e1 Andy McCall ↶ 7713
7714
#[test]
7715
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
7716
    let dir = tempfile::tempdir().unwrap();
7717
    let root = dir.path();
7718
    let home = root.join("home");
7719
    // Ada's identity lives in the user file; repository `a` pins the same
7720
    // key in its own file, repository `b` names none.
7721
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
7722
    let (key, _) = a
7723
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7724
        .unwrap();
7725
    a.config.set("author.key", &key.to_hex()).unwrap();
7726
    a.save_config().unwrap();
7727
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
7728
    let r = a
7729
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
7730
        .unwrap();
7731
    assert_eq!(
7732
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
7733
        r.new.to_hex(),
7734
        "the user file follows"
7735
    );
7736
    assert_eq!(
7737
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
7738
        r.new.to_hex(),
7739
        "the pinning repository follows"
7740
    );
7741
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
7742
    assert_eq!(
7743
        b.config.author_key,
7744
        Some(r.new),
7745
        "a checkout without a pin follows the user file"
7746
    );
7747
    // A repository-scoped identity leaves the user file alone.
7748
    let other_home = root.join("home2");
7749
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
7750
    let (ck, _) = c
7751
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
7752
        .unwrap();
7753
    assert!(!other_home.join("config.toml").exists());
7754
    let r2 = c.rotate_identity().unwrap();
7755
    assert_ne!(r2.new, ck);
7756
    assert_eq!(
7757
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
7758
        r2.new.to_hex()
7759
    );
7760
    assert!(
7761
        !other_home.join("config.toml").exists(),
7762
        "a repository-scoped identity stays repository-scoped"
7763
    );
7764
    // Several delegates in one rotation; a repeat is refused.
7765
    let (d1, d2) = (
7766
        SecretKey::generate().identity("D1", "d1@x", 1),
7767
        SecretKey::generate().identity("D2", "d2@x", 1),
7768
    );
7769
    let r3 = c
7770
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
7771
        .unwrap();
7772
    assert_eq!(r3.identity.delegates.len(), 2);
7773
    assert!(c
7774
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
7775
        .is_err());
7776
}
33be2409 Andy McCall ↶ 7777
7778
/// Two unrelated histories that both add the same file, joined by two
7779
/// independent merges on two branches, then those branches merged: Git
7780
/// merges identical additions cleanly, and the import must too (#71,
7781
/// found in VS Code's history).
7782
#[test]
7783
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
7784
    // Batches of one: every merge renders apart from the state, where a
7785
    // file whose graph the state had built came out empty (#71).
7786
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7787
    hermetic();
7788
    if std::process::Command::new("git")
7789
        .arg("--version")
7790
        .output()
7791
        .is_err()
7792
    {
7793
        eprintln!("git not installed; skipping");
7794
        return;
7795
    }
7796
    let dir = tempfile::tempdir().unwrap();
7797
    let root = dir.path();
7798
    let g = root.join("src.git");
7799
    fs::create_dir_all(&g).unwrap();
7800
    let git = |args: &[&str]| -> String {
7801
        let out = std::process::Command::new("git")
7802
            .arg("-C")
7803
            .arg(&g)
7804
            .args([
7805
                "-c",
7806
                "user.name=Grace",
7807
                "-c",
7808
                "[email protected]",
7809
                "-c",
7810
                "commit.gpgsign=false",
7811
            ])
7812
            .args(args)
7813
            .output()
7814
            .unwrap();
7815
        assert!(
7816
            out.status.success(),
7817
            "git {args:?}: {}",
7818
            String::from_utf8_lossy(&out.stderr)
7819
        );
7820
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7821
    };
7822
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
7823
    // History A: main.
7824
    git(&["init", "-q", "-b", "main"]);
7825
    write(&g, "gulpfile.js", text);
7826
    write(&g, "a.txt", b"a\n");
7827
    git(&["add", "."]);
7828
    git(&["commit", "-q", "-m", "A root"]);
7829
    // History B: an unrelated root adding the same file, identical.
7830
    git(&["checkout", "-q", "--orphan", "fork"]);
7831
    git(&["rm", "-q", "-r", "--cached", "."]);
7832
    for f in ["gulpfile.js", "a.txt"] {
7833
        let _ = fs::remove_file(g.join(f));
7834
    }
7835
    write(&g, "gulpfile.js", text);
7836
    write(&g, "b.txt", b"b\n");
7837
    git(&["add", "."]);
7838
    git(&["commit", "-q", "-m", "B root"]);
7839
    // Two branches from main, each joining B on its own.
7840
    git(&["checkout", "-q", "-b", "one", "main"]);
7841
    git(&[
7842
        "merge",
7843
        "-q",
7844
        "--no-ff",
7845
        "--allow-unrelated-histories",
7846
        "-m",
7847
        "join on one",
7848
        "fork",
7849
    ]);
7850
    git(&["checkout", "-q", "-b", "two", "main"]);
7851
    write(&g, "a.txt", b"a\ntwo\n");
7852
    git(&["commit", "-q", "-am", "work on two"]);
7853
    git(&[
7854
        "merge",
7855
        "-q",
7856
        "--no-ff",
7857
        "--allow-unrelated-histories",
7858
        "-m",
7859
        "join on two",
7860
        "fork",
7861
    ]);
7862
    // Then the two joins meet, and the file is reformatted after.
7863
    git(&["checkout", "-q", "main"]);
7864
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
7865
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7866
    write(
7867
        &g,
7868
        "gulpfile.js",
7869
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
7870
    );
7871
    git(&["commit", "-q", "-am", "after"]);
7872
7873
    let dest = root.join("dest");
7874
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
7875
    repo.import_git(&g, "main").unwrap();
7876
    let v = repo.verify_git_import(&g, "main").unwrap();
7877
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7878
    assert_eq!(
7879
        fs::read(dest.join("gulpfile.js")).unwrap(),
7880
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
7881
    );
7882
}
7883
7884
/// As above, but the two joins keep different copies (each branch had a
7885
/// different version when it joined), and later work edits each copy:
7886
/// the shape of VS Code's c67ef57cda90 (#71).
7887
#[test]
7888
fn git_import_joins_where_each_join_kept_a_different_copy() {
7889
    // Batches of one: every merge renders apart from the state, where a
7890
    // file whose graph the state had built came out empty (#71).
7891
    crate::repo::git::set_merge_batch_for_tests(Some(1));
7892
    hermetic();
7893
    if std::process::Command::new("git")
7894
        .arg("--version")
7895
        .output()
7896
        .is_err()
7897
    {
7898
        eprintln!("git not installed; skipping");
7899
        return;
7900
    }
7901
    let dir = tempfile::tempdir().unwrap();
7902
    let root = dir.path();
7903
    let g = root.join("src.git");
7904
    fs::create_dir_all(&g).unwrap();
7905
    let run = |args: &[&str]| {
7906
        std::process::Command::new("git")
7907
            .arg("-C")
7908
            .arg(&g)
7909
            .args([
7910
                "-c",
7911
                "user.name=Grace",
7912
                "-c",
7913
                "[email protected]",
7914
                "-c",
7915
                "commit.gpgsign=false",
7916
            ])
7917
            .args(args)
7918
            .output()
7919
            .unwrap()
7920
    };
7921
    let git = |args: &[&str]| -> String {
7922
        let out = run(args);
7923
        assert!(
7924
            out.status.success(),
7925
            "git {args:?}: {}",
7926
            String::from_utf8_lossy(&out.stderr)
7927
        );
7928
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7929
    };
7930
    git(&["init", "-q", "-b", "main"]);
7931
    write(
7932
        &g,
7933
        "gulpfile.js",
7934
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
7935
    );
7936
    git(&["add", "."]);
7937
    git(&["commit", "-q", "-m", "A root"]);
7938
    write(
7939
        &g,
7940
        "gulpfile.js",
7941
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
7942
    );
7943
    git(&["commit", "-q", "-am", "whitespace"]);
7944
    git(&["checkout", "-q", "--orphan", "fork"]);
7945
    git(&["rm", "-q", "-r", "--cached", "."]);
7946
    let _ = fs::remove_file(g.join("gulpfile.js"));
7947
    write(
7948
        &g,
7949
        "gulpfile.js",
7950
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
7951
    );
7952
    git(&["add", "."]);
7953
    git(&["commit", "-q", "-m", "B root"]);
7954
    // Branch one joins B keeping main's copy; branch two keeps B's.
7955
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
7956
        git(&["checkout", "-q", "-b", branch, "main"]);
7957
        let _ = run(&[
7958
            "merge",
7959
            "-q",
7960
            "--no-ff",
7961
            "--allow-unrelated-histories",
7962
            "-m",
7963
            "join",
7964
            "fork",
7965
        ]);
7966
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
7967
        git(&["add", "gulpfile.js"]);
7968
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
7969
    }
7970
    // Each branch then edits its copy.
7971
    git(&["checkout", "-q", "one"]);
7972
    write(
7973
        &g,
7974
        "gulpfile.js",
7975
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
7976
    );
7977
    git(&["commit", "-q", "-am", "tslint on one"]);
7978
    git(&["checkout", "-q", "two"]);
7979
    write(
7980
        &g,
7981
        "gulpfile.js",
7982
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
7983
    );
7984
    write(&g, "extra.txt", b"x\n");
7985
    write(&g, "more.txt", b"m\n");
7986
    git(&["add", "."]);
7987
    git(&["commit", "-q", "-am", "fmt on two"]);
7988
    // They meet: resolved by hand.
7989
    git(&["checkout", "-q", "one"]);
7990
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
7991
    write(
7992
        &g,
7993
        "gulpfile.js",
7994
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
7995
    );
7996
    git(&["add", "gulpfile.js"]);
7997
    git(&["commit", "-q", "-m", "merge two into one"]);
7998
7999
    let dest = root.join("dest");
8000
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8001
    repo.import_git(&g, "one").unwrap();
8002
    let v = repo.verify_git_import(&g, "one").unwrap();
8003
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8004
}
dd21fd82 Andy McCall ↶ 8005
8006
/// oxygen#68: on a store that is not this disk's directory, the operation
8007
/// head is the store's reference record, moved by compare-and-swap. Two
8008
/// handles recording from the same head both get through, merged; a swap
8009
/// from a stale version is refused; a second repository cannot start on a
8010
/// store that already holds one.
8011
#[test]
8012
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
8013
    use crate::strata::{MemoryStore, Store as _};
8014
    let backend = std::sync::Arc::new(MemoryStore::new());
8015
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
8016
    let dir = tempfile::tempdir().unwrap();
8017
    let a = Repo::init(dir.path()).unwrap();
8018
    assert!(
8019
        !dir.path().join(".oxy/ops/head").exists(),
8020
        "the head is not a file"
8021
    );
8022
    let (h0, op0) = a.head_op().unwrap();
8023
    let record = backend
8024
        .read_ref(HEAD_RECORD)
8025
        .unwrap()
8026
        .expect("the head is the store's record");
8027
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
8028
8029
    let b = Repo::open(dir.path()).unwrap();
8030
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
8031
    let mut va = op0.view.clone();
8032
    va.bookmarks.insert("from-a".into(), state);
8033
    let mut vb = op0.view.clone();
8034
    vb.bookmarks.insert("from-b".into(), state);
8035
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
8036
    assert_eq!(b.head_ref().unwrap(), rb);
8037
    // a recorded from h0 too: the head moved, so the two are merged.
8038
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
8039
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
8040
    assert_eq!(head, ra);
8041
    assert!(
8042
        op.command.ends_with("(merged with a concurrent operation)"),
8043
        "{}",
8044
        op.command
8045
    );
8046
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
8047
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
8048
8049
    // A swap from a version that is no longer current moves nothing.
8050
    let (h, v) = a.read_head().unwrap();
8051
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
8052
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
8053
    assert_eq!(a.head_ref().unwrap(), rb);
8054
8055
    let other = tempfile::tempdir().unwrap();
8056
    let err = Repo::init(other.path())
8057
        .err()
8058
        .expect("the store already holds a log")
8059
        .to_string();
8060
    assert!(
8061
        err.contains("already holds a repository's operation log"),
8062
        "{err}"
8063
    );
8064
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
8065
}
d069701a Andy McCall ↶ 8066
8067
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
8068
/// objects and operation head there, with `.oxy/cache` in front: it works
8069
/// as one on disk does, reopens, and survives losing its cache.
8070
#[test]
8071
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
8072
    hermetic();
8073
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
8074
        return;
8075
    }
8076
    let dir = tempfile::tempdir().unwrap();
8077
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
8078
    let url = format!("dir://{}", bucket.display());
8079
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
8080
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
8081
    write(&root, "a.txt", b"one\n");
8082
    let h1 = repo.commit("First", &[]).unwrap();
8083
    write(&root, "a.txt", b"one\ntwo\n");
8084
    let h2 = repo.commit("Second", &[]).unwrap();
8085
    assert!(
8086
        !root.join(".oxy/ops/head").exists(),
8087
        "the head is in the store"
8088
    );
8089
    assert!(bucket.join("ops/head").is_file());
8090
    assert!(root.join(".oxy/cache").is_dir());
8091
    drop(repo);
8092
8093
    // Reopened, and again with no cache at all: everything comes from the store.
8094
    for drop_cache in [false, true] {
8095
        if drop_cache {
8096
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
8097
        }
8098
        let repo = Repo::open(&root).unwrap();
8099
        let log: Vec<String> = repo
8100
            .op_log()
8101
            .unwrap()
8102
            .into_iter()
8103
            .map(|(_, op)| op.command)
8104
            .collect();
8105
        assert!(log.len() >= 3, "{log:?}");
8106
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
8107
        let heads = repo
8108
            .store()
8109
            .get_state(&repo.view().unwrap().bookmarks["main"])
8110
            .unwrap()
8111
            .heads;
8112
        assert_eq!(heads, vec![h2]);
8113
        assert_eq!(
8114
            repo.load_state(&heads).unwrap().materialize().files.len(),
8115
            1
8116
        );
8117
    }
8118
8119
    // A second repository cannot start on the same store.
8120
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
8121
        .err()
8122
        .unwrap()
8123
        .to_string();
8124
    assert!(
8125
        err.contains("already holds a repository's operation log"),
8126
        "{err}"
8127
    );
8128
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
8129
        .err()
8130
        .unwrap()
8131
        .to_string();
8132
    assert!(err.contains("cannot open that kind of store"), "{err}");
8133
}
80677b7a Andy McCall ↶ 8134
8135
/// oxygen#75: the prompt's quick check agrees with status in a repository
8136
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
8137
/// another state, clean again once that pin is committed. (It compared the
8138
/// subrepo's directory as if it were a file, so it was always dirty.)
8139
#[test]
8140
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
8141
    hermetic();
8142
    let dir = tempfile::tempdir().unwrap();
8143
    let root = dir.path();
8144
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8145
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8146
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8147
        .unwrap()
8148
        .with_home(root.join("home"));
8149
    write(&root.join("lib"), "lib.txt", b"v1\n");
8150
    lib.commit("lib v1", &[]).unwrap();
8151
    assert!(lib.push("origin", false).unwrap()[0].ok);
8152
    let app_dir = root.join("app");
8153
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8154
    write(&app_dir, "main.txt", b"app\n");
8155
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8156
    app.commit("app with lib", &[]).unwrap();
8157
    // Out of the racy window, so the stat-only path decides.
8158
    std::thread::sleep(std::time::Duration::from_millis(2100));
8159
    let reopen = || Repo::open(&app_dir).unwrap();
8160
    assert_eq!(
8161
        reopen().quick_dirty().unwrap(),
8162
        Some(false),
8163
        "clean, as status says"
8164
    );
8165
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
8166
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
8167
    nested.commit("lib v2", &[]).unwrap();
8168
    assert_eq!(
8169
        reopen().quick_dirty().unwrap(),
8170
        Some(true),
8171
        "the subrepo moved"
8172
    );
8173
    reopen().commit("pin lib v2", &[]).unwrap();
8174
    std::thread::sleep(std::time::Duration::from_millis(2100));
8175
    assert_eq!(
8176
        reopen().quick_dirty().unwrap(),
8177
        Some(false),
8178
        "the new pin is committed"
8179
    );
8180
}
7993d465 Andy McCall ↶ 8181
8182
#[test]
8183
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
8184
    // oxygen#72: a .oxymodules section with no subrepo behind it.
8185
    hermetic();
8186
    let dir = tempfile::tempdir().unwrap();
8187
    let root = dir.path();
8188
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8189
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8190
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8191
        .unwrap()
8192
        .with_home(root.join("home"));
8193
    write(&root.join("lib"), "lib.txt", b"v1\n");
8194
    lib.commit("lib v1", &[]).unwrap();
8195
    assert!(lib.push("origin", false).unwrap()[0].ok);
8196
    let app_dir = root.join("app");
8197
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8198
    write(
8199
        &app_dir,
8200
        ".oxymodules",
8201
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
8202
    );
8203
    let unpinned = app.unpinned_modules().unwrap();
8204
    assert_eq!(unpinned.len(), 1);
8205
    assert_eq!(unpinned[0].0, "libs/lib");
8206
    assert_eq!(unpinned[0].1.url, lib_url);
8207
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
8208
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8209
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
8210
}
bf3a6781 Andy McCall ↶ 8211
8212
#[test]
8213
fn the_bookmark_revset_function_names_only_bookmarks() {
8214
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
8215
    hermetic();
8216
    let dir = tempfile::tempdir().unwrap();
8217
    let repo = Repo::init(dir.path()).unwrap();
8218
    write(dir.path(), "a.txt", b"a\n");
8219
    let a = repo.commit("A", &[]).unwrap();
8220
    write(dir.path(), "b.txt", b"b\n");
8221
    let b = repo.commit("B", &[]).unwrap();
8222
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
8223
    heads.sort();
8224
    let mut want = repo.bookmark_heads().unwrap();
8225
    want.sort();
8226
    assert_eq!(heads, want);
8227
    assert!(heads.contains(&b));
8228
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
8229
    // A change prefix is a symbol, not a bookmark.
8230
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
8231
    assert!(repo.revset(&prefix).is_ok());
8232
    let e = repo
8233
        .revset(&format!("bookmark({prefix})"))
8234
        .unwrap_err()
8235
        .to_string();
8236
    assert!(e.contains("no such bookmark"), "{e}");
8237
}
72484195 Andy McCall ↶ 8238
8239
#[test]
8240
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
8241
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
8242
    // pinning the subrepo, and the nested repository on disk at that pin.
8243
    hermetic();
8244
    let dir = tempfile::tempdir().unwrap();
8245
    let root = dir.path();
8246
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
8247
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8248
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8249
        .unwrap()
8250
        .with_home(root.join("home"));
8251
    write(&root.join("lib"), "lib.txt", b"v1\n");
8252
    lib.commit("lib v1", &[]).unwrap();
8253
    assert!(lib.push("origin", false).unwrap()[0].ok);
8254
    let app_dir = root.join("app");
8255
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8256
    write(&app_dir, "main.txt", b"app\n");
8257
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8258
    // The stale state: registered in .oxymodules, never pinned.
8259
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
8260
    app.commit("initial", &[]).unwrap();
8261
    let stale = app.bookmark_heads().unwrap();
8262
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
8263
    app.commit("pin lib", &[]).unwrap();
8264
    let newer = app.bookmark_heads().unwrap();
8265
    app.checkout(&stale, false, "test").unwrap();
8266
    write(&app_dir, "notes.txt", b"mine\n");
8267
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
8268
    assert_eq!(carried, vec!["notes.txt".to_string()]);
8269
    assert!(app_dir.join("notes.txt").exists());
8270
}
8271
8272
#[test]
8273
fn a_bookmark_only_behind_its_remote_catches_up() {
8274
    // oxygen#74: switch takes the remote's state rather than a stale one.
8275
    hermetic();
8276
    let dir = tempfile::tempdir().unwrap();
8277
    let root = dir.path();
8278
    let _origin = Repo::init(&root.join("origin")).unwrap();
8279
    let url = root.join("origin").to_string_lossy().to_string();
8280
    let one = Repo::clone(&url, &root.join("one"))
8281
        .unwrap()
8282
        .with_home(root.join("home"));
8283
    write(&root.join("one"), "a.txt", b"a\n");
8284
    one.commit("A", &[]).unwrap();
8285
    assert!(one.push("origin", false).unwrap()[0].ok);
8286
    let two = Repo::clone(&url, &root.join("two"))
8287
        .unwrap()
8288
        .with_home(root.join("home"));
8289
    write(&root.join("two"), "b.txt", b"b\n");
8290
    two.commit("B", &[]).unwrap();
8291
    assert!(two.push("origin", false).unwrap()[0].ok);
8292
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
8293
    one.fetch("origin").unwrap();
8294
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
8295
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
8296
    // Local work the remote lacks: left alone.
8297
    write(&root.join("one"), "c.txt", b"c\n");
8298
    one.commit("C", &[]).unwrap();
8299
    write(&root.join("two"), "d.txt", b"d\n");
8300
    two.commit("D", &[]).unwrap();
8301
    assert!(two.push("origin", false).unwrap()[0].ok);
8302
    one.fetch("origin").unwrap();
8303
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
8304
}
42ccf504 Andy McCall ↶ 8305
8306
#[test]
8307
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
8308
    // oxygen#83: remotes earth and gcs, origin removed.
8309
    hermetic();
8310
    let dir = tempfile::tempdir().unwrap();
8311
    let root = dir.path();
8312
    let _up = Repo::init(&root.join("up")).unwrap();
8313
    let url = root.join("up").to_string_lossy().to_string();
8314
    let other = Repo::clone(&url, &root.join("other"))
8315
        .unwrap()
8316
        .with_home(root.join("home"));
8317
    write(&root.join("other"), "a.txt", b"a\n");
8318
    other.commit("a", &[]).unwrap();
8319
    assert!(other.push("origin", false).unwrap()[0].ok);
8320
    let mut one = Repo::clone(&url, &root.join("one"))
8321
        .unwrap()
8322
        .with_home(root.join("home"));
8323
    one.config.set("remote.earth.url", &url).unwrap();
8324
    one.config.set("remote.gcs.url", &url).unwrap();
8325
    one.config.set("remote.origin.url", "").unwrap();
8326
    one.save_config().unwrap();
8327
    write(&root.join("other"), "b.txt", b"b\n");
8328
    other.commit("b", &[]).unwrap();
8329
    assert!(other.push("origin", false).unwrap()[0].ok);
8330
    one.fetch("earth").unwrap();
8331
    let b = one
8332
        .bookmarks()
8333
        .unwrap()
8334
        .into_iter()
8335
        .find(|b| b.name == "main")
8336
        .unwrap();
8337
    assert_eq!(
8338
        (b.remote.as_deref(), b.behind),
8339
        (Some("earth"), Some(1)),
8340
        "a stale origin copy is not used"
8341
    );
8342
    assert_eq!(
8343
        one.default_remote(),
8344
        "origin",
8345
        "no default chosen among several"
8346
    );
8347
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
8348
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
8349
    one.config.set("core.remote", "earth").unwrap();
8350
    assert_eq!(one.default_remote(), "earth");
8351
}
cbe8499a Andy McCall ↶ 8352
8353
#[test]
8354
fn a_missing_author_identity_says_how_to_fix_it() {
8355
    // oxygen#82: an agent home's author.key naming an identity the
8356
    // repository does not hold.
8357
    hermetic();
8358
    let dir = tempfile::tempdir().unwrap();
8359
    let mut repo = Repo::init(dir.path()).unwrap();
8360
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
8361
    repo.config.set("author.key", &missing.to_hex()).unwrap();
8362
    let e = repo.identity(&missing).unwrap_err().to_string();
8363
    assert!(
8364
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
8365
        "{e}"
8366
    );
8367
    assert!(e.contains("this repository's config"), "{e}");
8368
}
f6dccc45 Andy McCall ↶ 8369
8370
#[test]
8371
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
8372
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
8373
    // the working copy, a pull with nothing new left it there, and status
8374
    // said "clean".
8375
    hermetic();
8376
    let dir = tempfile::tempdir().unwrap();
8377
    let root = dir.path();
8378
    let _up = Repo::init(&root.join("up")).unwrap();
8379
    let url = root.join("up").to_string_lossy().to_string();
8380
    let other = Repo::clone(&url, &root.join("other"))
8381
        .unwrap()
8382
        .with_home(root.join("home"));
8383
    write(&root.join("other"), "a.txt", b"a\n");
8384
    other.commit("a", &[]).unwrap();
8385
    assert!(other.push("origin", false).unwrap()[0].ok);
8386
    let one = Repo::clone(&url, &root.join("one"))
8387
        .unwrap()
8388
        .with_home(root.join("home"));
8389
    write(&root.join("other"), "b.txt", b"b\n");
8390
    other.commit("b", &[]).unwrap();
8391
    assert!(other.push("origin", false).unwrap()[0].ok);
8392
    one.fetch("origin").unwrap();
8393
    // The bookmark moves; the working copy does not.
8394
    let theirs = one.resolve_heads("origin/main").unwrap();
8395
    one.bookmark_set("main", &theirs).unwrap();
8396
    assert!(!root.join("one/b.txt").exists());
8397
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
8398
    let r = one.pull("origin").unwrap();
8399
    assert!(
8400
        !r.changed && r.checked_out,
8401
        "nothing new, but the working copy caught up"
8402
    );
8403
    assert!(root.join("one/b.txt").exists());
8404
    assert_eq!(one.working_copy_behind().unwrap(), None);
8405
}
170bb436 Andy McCall ↶ 8406
8407
#[test]
8408
fn touched_nodes_cache_answers_as_the_changes_do() {
8409
    hermetic();
8410
    let dir = tempfile::tempdir().unwrap();
8411
    let repo = Repo::init(dir.path()).unwrap();
8412
    write(dir.path(), "a.txt", b"one\n");
8413
    write(dir.path(), "b.txt", b"x\n");
8414
    repo.snapshot("t").unwrap();
8415
    let c1 = repo.commit("first", &[]).unwrap();
8416
    write(dir.path(), "b.txt", b"y\n");
8417
    repo.snapshot("t").unwrap();
8418
    repo.commit("b only", &[]).unwrap();
8419
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
8420
    write(dir.path(), "c.txt", b"one\ntwo\n");
8421
    repo.snapshot("t").unwrap();
8422
    let c3 = repo.commit("rename and edit", &[]).unwrap();
8423
    // Uncommitted work, so the working copy touches a file too.
8424
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
8425
    repo.snapshot("t").unwrap();
8426
8427
    let path = dir.path().join(".oxy/index/touched");
8428
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
8429
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
8430
    assert!(path.exists(), "the first query writes the cache");
8431
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
8432
    assert_eq!(cold, warm, "the cache answers as the changes do");
8433
    let (wc, _) = repo.working_copy().unwrap();
8434
    assert_eq!(
8435
        cold,
8436
        vec![wc, c3, c1],
8437
        "renames followed, the working copy included"
8438
    );
8439
8440
    // Working-copy changes are not kept: they are replaced by every snapshot.
8441
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
8442
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
8443
    assert!(cached.contains(&c1) && cached.contains(&c3));
8444
8445
    // A damaged cache is ignored, not trusted.
8446
    let mut bytes = fs::read(&path).unwrap();
8447
    let last = bytes.len() - 40;
8448
    bytes[last] ^= 1;
8449
    fs::write(&path, &bytes).unwrap();
8450
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
8451
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
8452
    assert_eq!(hashes(touches), vec![c3, c1]);
8453
}
e8e6e0ca Andy McCall ↶ 8454
8455
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
8456
/// file back where it was leave two placements at one place, which the
8457
/// tree shows as one file. Removing it, and then its directory, retires
8458
/// both, so no copy is left under a directory that is gone.
8459
#[test]
8460
fn git_import_removes_every_copy_of_a_file_at_one_place() {
8461
    hermetic();
8462
    if std::process::Command::new("git")
8463
        .arg("--version")
8464
        .output()
8465
        .is_err()
8466
    {
8467
        eprintln!("git not installed; skipping");
8468
        return;
8469
    }
8470
    let dir = tempfile::tempdir().unwrap();
8471
    let root = dir.path();
8472
    let g = root.join("src.git");
8473
    fs::create_dir_all(&g).unwrap();
8474
    let git = |args: &[&str]| {
8475
        let out = std::process::Command::new("git")
8476
            .arg("-C")
8477
            .arg(&g)
8478
            .args([
8479
                "-c",
8480
                "user.name=Grace",
8481
                "-c",
8482
                "[email protected]",
8483
                "-c",
8484
                "commit.gpgsign=false",
8485
            ])
8486
            .args(args)
8487
            .output()
8488
            .unwrap();
8489
        assert!(
8490
            out.status.success(),
8491
            "git {args:?}: {}",
8492
            String::from_utf8_lossy(&out.stderr)
8493
        );
8494
    };
8495
    git(&["init", "-q", "-b", "main"]);
8496
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
8497
    write(&g, "keep.txt", b"k\n");
8498
    git(&["add", "."]);
8499
    git(&["commit", "-qm", "base"]);
8500
    fs::create_dir_all(g.join("d/sub")).unwrap();
8501
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
8502
    git(&["commit", "-qm", "into sub"]);
8503
    git(&["checkout", "-qb", "side"]);
8504
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8505
    git(&["commit", "-qm", "back, on side"]);
8506
    git(&["checkout", "-q", "main"]);
8507
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
8508
    git(&["commit", "-qm", "back, on main"]);
8509
    git(&["merge", "-q", "--no-edit", "side"]);
8510
    git(&["rm", "-rq", "d"]);
8511
    git(&["commit", "-qm", "d goes"]);
8512
8513
    let repo = Repo::init(&root.join("o")).unwrap();
8514
    repo.import_git(&g, "main").unwrap();
8515
    let v = repo.verify_git_import(&g, "main").unwrap();
8516
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8517
    let st = repo
8518
        .load_state_history(&repo.bookmark_heads().unwrap())
8519
        .unwrap();
8520
    let view = st.tree().view();
8521
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8522
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
8523
}
5552e69c Andy McCall ↶ 8524
8525
/// oxygen#94: a state index's file histories are read, and checked by
8526
/// their own hashes, only when a file is built. One found damaged is an
8527
/// error that says so, the index is removed, and the next read rebuilds it.
8528
#[test]
8529
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
8530
    hermetic();
8531
    let dir = tempfile::tempdir().unwrap();
8532
    let repo = Repo::init(dir.path()).unwrap();
8533
    for i in 0..6 {
8534
        write(
8535
            dir.path(),
8536
            &format!("f{i}.txt"),
8537
            format!("one {i}\n").as_bytes(),
8538
        );
8539
    }
8540
    repo.snapshot("t").unwrap();
8541
    repo.commit("first", &[]).unwrap();
8542
    for i in 0..6 {
8543
        write(
8544
            dir.path(),
8545
            &format!("f{i}.txt"),
8546
            format!("one {i}\ntwo\n").as_bytes(),
8547
        );
8548
    }
8549
    repo.snapshot("t").unwrap();
8550
    repo.commit("second", &[]).unwrap();
8551
    let want: Vec<Vec<u8>> = (0..6)
8552
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
8553
        .collect();
8554
    // The index of the working copy's base, holding every file's history
8555
    // (a few changes behind, an index is replayed onto, not rewritten).
8556
    let (_, wc) = repo.working_copy().unwrap();
8557
    let base = repo.load_state_history(&wc.deps).unwrap();
8558
    repo.write_state_index(&wc.deps, &base);
8559
    for (i, w) in want.iter().enumerate() {
8560
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8561
    }
8562
    let index = repo.state_indexes();
8563
    assert!(!index.is_empty(), "a state index was written");
8564
    // The histories are last in the file: damage the last of them.
8565
    let mut bytes = fs::read(&index[0]).unwrap();
8566
    let last = bytes.len() - 1;
8567
    bytes[last] ^= 0x40;
8568
    fs::write(&index[0], &bytes).unwrap();
8569
8570
    let reads: Vec<_> = (0..6)
8571
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
8572
        .collect();
8573
    let damaged: Vec<String> = reads
8574
        .iter()
8575
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
8576
        .collect();
8577
    assert_eq!(damaged.len(), 1, "{damaged:?}");
8578
    assert!(
8579
        damaged[0].contains("state index was damaged")
8580
            && damaged[0].contains("run the command again"),
8581
        "{}",
8582
        damaged[0]
8583
    );
8584
    // Every file reads right again, from an index rebuilt from history.
8585
    for (i, w) in want.iter().enumerate() {
8586
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
8587
    }
8588
}
cb8b8082 Andy McCall ↶ 8589
8590
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
8591
/// objects alone and in dependency order, and the last moves the bookmark.
8592
/// The remote ends with every change and the same state, and says how each
8593
/// part went.
8594
#[test]
8595
fn a_long_push_goes_in_parts() {
8596
    hermetic();
8597
    let dir = tempfile::tempdir().unwrap();
8598
    let root = dir.path();
8599
    let origin = root.join("origin");
8600
    Repo::init_bare_unbound(&origin).unwrap();
8601
    let main = root.join("main");
8602
    let mut repo = Repo::init(&main).unwrap();
8603
    repo.config
8604
        .set("remote.origin.url", &origin.to_string_lossy())
8605
        .unwrap();
8606
    // One byte: every change is a part of its own.
8607
    repo.config.set("push.batch-bytes", "1").unwrap();
8608
    repo.save_config().unwrap();
8609
    for i in 0..6 {
8610
        write(
8611
            &main,
8612
            &format!("f{i}.txt"),
8613
            format!("file {i}\n").as_bytes(),
8614
        );
8615
        repo.commit(&format!("c{i}"), &[]).unwrap();
8616
    }
8617
    let mut parts = Vec::new();
8618
    let results = repo
8619
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
8620
        .unwrap();
8621
    assert!(
8622
        results.iter().any(|r| r.ok && r.name == "main"),
8623
        "{results:?}"
8624
    );
8625
    assert_eq!(parts.len(), 6, "{parts:?}");
8626
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
8627
8628
    let remote = Repo::open(&origin).unwrap();
8629
    let heads = repo.bookmark_heads().unwrap();
8630
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
8631
    assert_eq!(
8632
        remote.log_state(&heads).unwrap().len(),
8633
        repo.log_state(&heads).unwrap().len()
8634
    );
8635
    // A push of objects alone reports how it went, as `objects`.
8636
    let got = remote
8637
        .receive_push(Bundle::default(), vec![], None, vec![])
8638
        .unwrap();
8639
    assert_eq!(got.len(), 1);
8640
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
8641
}
d6e0d5b8 Andy McCall ↶ 8642
8643
/// oxygen#97: with `git.claim`, an import authors the importing identity's
8644
/// own commits (Git author email = its email, any case) with its key, and
8645
/// leaves anyone else's with the zero key; the history verifies as before.
8646
#[test]
8647
fn git_import_claims_your_own_commits() {
8648
    hermetic();
8649
    if std::process::Command::new("git")
8650
        .arg("--version")
8651
        .output()
8652
        .is_err()
8653
    {
8654
        eprintln!("git not installed; skipping");
8655
        return;
8656
    }
8657
    let dir = tempfile::tempdir().unwrap();
8658
    let root = dir.path();
8659
    let g = root.join("src.git");
8660
    fs::create_dir_all(&g).unwrap();
8661
    let git = |who: &str, args: &[&str]| {
8662
        let (name, email) = who.split_once(' ').unwrap();
8663
        let out = std::process::Command::new("git")
8664
            .arg("-C")
8665
            .arg(&g)
8666
            .args([
8667
                "-c",
8668
                &format!("user.name={name}"),
8669
                "-c",
8670
                &format!("user.email={email}"),
8671
                "-c",
8672
                "commit.gpgsign=false",
8673
            ])
8674
            .args(args)
8675
            .output()
8676
            .unwrap();
8677
        assert!(
8678
            out.status.success(),
8679
            "git {args:?}: {}",
8680
            String::from_utf8_lossy(&out.stderr)
8681
        );
8682
    };
8683
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
8684
    write(&g, "a.txt", b"a\n");
8685
    git("Grace [email protected]", &["add", "."]);
8686
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
8687
    write(&g, "b.txt", b"b\n");
8688
    git("Ada [email protected]", &["add", "."]);
8689
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
8690
8691
    let mut repo = Repo::init(&root.join("o")).unwrap();
8692
    let (key, _) = repo
8693
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
8694
        .unwrap();
8695
    repo.config.set("git.claim", "true").unwrap();
8696
    repo.save_config().unwrap();
8697
    let repo = Repo::open(&root.join("o")).unwrap();
8698
    repo.import_git(&g, "main").unwrap();
8699
    let v = repo.verify_git_import(&g, "main").unwrap();
8700
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8701
    let heads = repo.bookmark_heads().unwrap();
8702
    let by_message: std::collections::HashMap<String, KeyId> = repo
8703
        .log_state(&heads)
8704
        .unwrap()
8705
        .into_iter()
8706
        .map(|e| {
8707
            (
8708
                e.change.message.lines().next().unwrap_or("").to_string(),
8709
                e.change.author,
8710
            )
8711
        })
8712
        .collect();
8713
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
8714
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
8715
}
34fad4a9 Andy McCall ↶ 8716
8717
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
8718
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
8719
#[test]
8720
fn removing_a_remote_leaves_nothing_of_it() {
8721
    hermetic();
8722
    let dir = tempfile::tempdir().unwrap();
8723
    let origin = dir.path().join("origin");
8724
    Repo::init_bare_unbound(&origin).unwrap();
8725
    let main = dir.path().join("main");
8726
    let mut repo = Repo::init(&main).unwrap();
8727
    repo.config
8728
        .set("remote.origin.url", &origin.to_string_lossy())
8729
        .unwrap();
8730
    repo.config
8731
        .set("remote.origin.token", "secret-ish")
8732
        .unwrap();
8733
    repo.config
8734
        .set("remote.keep.url", &origin.to_string_lossy())
8735
        .unwrap();
8736
    repo.save_config().unwrap();
8737
    write(&main, "a.txt", b"a\n");
8738
    repo.commit("a", &[]).unwrap();
8739
    assert!(repo.push("origin", false).unwrap()[0].ok);
8740
    assert!(
8741
        repo.view().unwrap().remotes.contains_key("origin"),
8742
        "a tracking bookmark"
8743
    );
8744
8745
    repo.remove_remote("origin").unwrap();
8746
    let again = Repo::open(&main).unwrap();
8747
    assert!(
8748
        !again
8749
            .config
8750
            .repo_layer()
8751
            .keys()
8752
            .any(|k| k.starts_with("remote.origin.")),
8753
        "{:?}",
8754
        again.config.repo_layer()
8755
    );
8756
    assert!(!again.config.remotes.contains_key("origin"));
8757
    assert!(
8758
        !again.view().unwrap().remotes.contains_key("origin"),
8759
        "its tracking bookmarks go"
8760
    );
8761
    assert!(
8762
        again.config.remotes.contains_key("keep"),
8763
        "another remote stays"
8764
    );
8765
    let mut again = again;
8766
    assert!(
8767
        again.remove_remote("origin").is_err(),
8768
        "a second removal is refused"
8769
    );
8770
}
9d580f21 Andy McCall ↶ 8771
8772
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
8773
/// unreachable from history, so gc prunes it, unless the host names it:
8774
/// then it and its chunks stay, and it reads back whole.
8775
#[test]
8776
fn gc_keeps_the_blobs_a_host_names() {
8777
    hermetic();
8778
    let dir = tempfile::tempdir().unwrap();
8779
    let repo = Repo::init(dir.path()).unwrap();
8780
    write(dir.path(), "a.txt", b"a\n");
8781
    repo.commit("a", &[]).unwrap();
8782
    // Large enough to be several chunks.
8783
    let body: Vec<u8> = (0..400_000u32)
8784
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
8785
        .collect();
8786
    let kept = repo.store_blob(&body).unwrap();
8787
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
8788
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
8789
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
8790
    assert!(!repo.store().has(&lost), "not named: pruned");
8791
    repo.gc(true).unwrap();
8792
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
8793
}
530a0fc6 Andy McCall ↶ 8794
8795
/// oxygen#99: undo in one workspace undoes that workspace's last command,
8796
/// never another workspace's, says what it undid, and goes further back
8797
/// when run again.
8798
#[test]
8799
fn undo_is_scoped_to_its_workspace() {
8800
    hermetic();
8801
    let dir = tempfile::tempdir().unwrap();
8802
    let root = dir.path().join("main");
8803
    let a = Repo::init(&root).unwrap();
8804
    write(&root, "base.txt", b"base\n");
8805
    let base = a.commit("base", &[]).unwrap();
8806
    a.bookmark_create("feature", None).unwrap();
8807
    let ws_dir = dir.path().join("ws");
8808
    let heads = a.resolve_heads("feature").unwrap();
8809
    let b = a
8810
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
8811
        .unwrap();
8812
8813
    // A commits on main, then B commits on feature: B's is the newest.
8814
    write(&root, "a.txt", b"a\n");
8815
    let ca = a.commit("from a", &[]).unwrap();
8816
    write(&ws_dir, "b.txt", b"b\n");
8817
    let cb = b.commit("from b", &[]).unwrap();
8818
8819
    // A's undo undoes A's commit and leaves B's.
8820
    let u = a.undo().unwrap();
8821
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8822
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
8823
    assert!(!u.changes.is_empty());
8824
    let view = a.view().unwrap();
8825
    // (Independent changes commute, so a bookmark's heads may hold base too.)
8826
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
8827
    assert!(
8828
        a.heads_of(&view, "feature").unwrap().contains(&cb),
8829
        "B's commit stands"
8830
    );
8831
    assert!(
8832
        a.store().get_change(&ca).is_ok(),
8833
        "the change itself is still in the store"
8834
    );
8835
    // A's working copy was clean, so its files followed; B's are untouched.
8836
    assert!(!root.join("a.txt").exists());
8837
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
8838
    assert!(ws_dir.join("b.txt").exists());
8839
8840
    // B's undo still finds B's own commit, under A's undo.
8841
    let u = b.undo().unwrap();
8842
    assert_eq!(u.command, "oxy commit -m \"from b\"");
8843
    assert!(!b
8844
        .heads_of(&b.view().unwrap(), "feature")
8845
        .unwrap()
8846
        .contains(&cb));
8847
    assert_eq!(
8848
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
8849
        vec![base],
8850
        "A's undo stands"
8851
    );
8852
8853
    // A's next undo goes past the commit it already undid, to adding B's
8854
    // workspace: refused, since B has worked there since.
8855
    let e = a.undo().unwrap_err().to_string();
8856
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
8857
}
8858
8859
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
8860
/// own commit's head, and the other workspace's head stays.
8861
#[test]
8862
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
8863
    hermetic();
8864
    let dir = tempfile::tempdir().unwrap();
8865
    let root = dir.path().join("main");
8866
    let a = Repo::init(&root).unwrap();
8867
    write(&root, "base.txt", b"base\n");
8868
    a.commit("base", &[]).unwrap();
8869
    let ws_dir = dir.path().join("ws");
8870
    let b = a.workspace_add(&ws_dir, None).unwrap();
8871
    write(&root, "a.txt", b"a\n");
8872
    let ca = a.commit("from a", &[]).unwrap();
8873
    write(&ws_dir, "b.txt", b"b\n");
8874
    let cb = b.commit("from b", &[]).unwrap();
8875
    let u = a.undo().unwrap();
8876
    assert_eq!(u.command, "oxy commit -m \"from a\"");
8877
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
8878
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
8879
}
8880
8881
/// oxygen#99: an undo that would also take back what another workspace
8882
/// did since to the same bookmark is refused, naming it.
8883
#[test]
8884
fn undo_refuses_to_take_back_another_workspaces_work() {
8885
    hermetic();
8886
    let dir = tempfile::tempdir().unwrap();
8887
    let root = dir.path().join("main");
8888
    let a = Repo::init(&root).unwrap();
8889
    write(&root, "base.txt", b"base\n");
8890
    a.commit("base", &[]).unwrap();
8891
    let ws_dir = dir.path().join("ws");
8892
    let b = a.workspace_add(&ws_dir, None).unwrap();
8893
    // Both on main: A commits, then B builds on it, editing A's file.
8894
    write(&root, "a.txt", b"a\n");
8895
    a.commit("from a", &[]).unwrap();
8896
    let heads = b.resolve_heads("main").unwrap();
8897
    b.checkout(&heads, false, "oxy checkout").unwrap();
8898
    write(&ws_dir, "a.txt", b"a, then b\n");
8899
    b.commit("from b", &[]).unwrap();
8900
    let e = a.undo().unwrap_err().to_string();
8901
    assert!(
8902
        e.contains("bookmark main") && e.contains("builds on"),
8903
        "{e}"
8904
    );
8905
    assert!(e.contains("oxy op restore"), "{e}");
8906
}
8907
8908
/// oxygen#99: undoing a commit that was already pushed says so: the remote
8909
/// still has it.
8910
#[test]
8911
fn undo_says_when_the_commit_was_pushed() {
8912
    hermetic();
8913
    let dir = tempfile::tempdir().unwrap();
8914
    let root = dir.path();
8915
    Repo::init(&root.join("origin")).unwrap();
8916
    let url = root.join("origin").to_string_lossy().to_string();
8917
    let repo = Repo::clone(&url, &root.join("work"))
8918
        .unwrap()
8919
        .with_home(root.join("home"));
8920
    write(&root.join("work"), "a.txt", b"a\n");
8921
    repo.commit("a", &[]).unwrap();
8922
    assert!(repo.push("origin", false).unwrap()[0].ok);
8923
    // The push itself is passed over: the remote keeps what it was sent.
8924
    let u = repo.undo().unwrap();
8925
    assert_eq!(u.command, "oxy commit -m \"a\"");
8926
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
8927
}
b689779e Andy McCall ↶ 8928
8929
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
8930
/// out of the snapshot and named; tracked files and files already in the
8931
/// working copy are not.
8932
#[test]
8933
fn large_new_files_are_left_out_of_snapshots() {
8934
    hermetic();
8935
    let dir = tempfile::tempdir().unwrap();
8936
    let root = dir.path();
8937
    let mut repo = Repo::init(root).unwrap();
8938
    repo.config.max_new_file = 1024;
8939
    write(root, "small.txt", b"small\n");
8940
    write(root, "big.bin", &vec![0u8; 4096]);
8941
    let s = repo.snapshot("oxy status").unwrap();
8942
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
8943
    assert_eq!(paths, ["small.txt"]);
8944
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
8945
    repo.commit("small", &[]).unwrap();
8946
8947
    // A tracked file may grow past the limit.
8948
    write(root, "small.txt", &vec![b'x'; 4096]);
8949
    let s = repo.snapshot("oxy status").unwrap();
8950
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
8951
    // With no limit the big file is taken in, and stays once it is.
8952
    repo.config.max_new_file = 0;
8953
    let s = repo.snapshot("oxy status").unwrap();
8954
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
8955
    repo.config.max_new_file = 1024;
8956
    let s = repo.snapshot("oxy status").unwrap();
8957
    assert!(
8958
        s.statuses.iter().any(|p| p.path == "big.bin"),
8959
        "already in the working copy"
8960
    );
8961
    assert!(repo.skipped_large().is_empty());
8962
}
8963
8964
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
8965
/// snapshots expire, and kept while they have not.
8966
#[test]
8967
fn gc_prunes_what_only_expired_snapshots_held() {
8968
    hermetic();
8969
    let dir = tempfile::tempdir().unwrap();
8970
    let root = dir.path();
8971
    let mut repo = Repo::init(root).unwrap();
8972
    repo.config.gc_grace_days = 0;
8973
    write(root, "a.txt", b"a\n");
8974
    repo.commit("a", &[]).unwrap();
8975
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
8976
    write(root, "image.tar", &image);
8977
    repo.snapshot("oxy status").unwrap();
8978
    std::fs::remove_file(root.join("image.tar")).unwrap();
8979
    repo.snapshot("oxy status").unwrap();
8980
    let blob = Repo::blob_ref(&image);
8981
    assert!(repo.store().has(&blob));
8982
    repo.gc(true).unwrap();
8983
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
8984
    repo.config.snapshot_retention_days = 0;
8985
    repo.gc(true).unwrap();
8986
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
8987
    assert_eq!(
8988
        repo.file_at("a.txt", None).unwrap(),
8989
        b"a\n",
8990
        "committed files stay"
8991
    );
fe9586d9 Andy McCall ↶ 8992
}
8993
8994
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
8995
/// already has is no conflict: the switch goes through, nothing is lost,
8996
/// and other carried work still comes along.
8997
#[test]
8998
fn carrying_work_the_target_already_has_is_no_conflict() {
8999
    hermetic();
9000
    let dir = tempfile::tempdir().unwrap();
9001
    let root = dir.path();
9002
    let mut repo = Repo::init(root).unwrap();
9003
    write(root, "a.txt", b"one\n");
9004
    write(root, "b.txt", b"b\n");
9005
    repo.commit("one", &[]).unwrap();
9006
    repo.bookmark_create("landed", None).unwrap();
9007
    // On landed, a.txt becomes "two" (as a proposal landing would).
9008
    repo.bookmark_switch("landed", false).unwrap();
9009
    write(root, "a.txt", b"two\n");
9010
    repo.commit("two", &[]).unwrap();
9011
    repo.bookmark_switch("main", false).unwrap();
9012
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
9013
    // The same edit, uncommitted, on main; and another edit besides.
9014
    write(root, "a.txt", b"two\n");
9015
    write(root, "b.txt", b"b, edited\n");
9016
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
9017
    assert_eq!(
9018
        carried,
9019
        vec!["b.txt".to_string()],
9020
        "only the work landed lacks is carried"
9021
    );
9022
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
9023
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
9024
    let s = repo.snapshot("oxy status").unwrap();
9025
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
9026
    assert_eq!(paths, ["b.txt"]);
9027
9028
    // A real difference is still refused.
9029
    repo.bookmark_switch("main", true).unwrap();
9030
    write(root, "a.txt", b"three\n");
9031
    let e = repo
9032
        .bookmark_switch_carry("landed")
9033
        .unwrap_err()
9034
        .to_string();
9035
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
b689779e Andy McCall ↶ 9036
}
aa4939e0 Andy McCall ↶ 9037
9038
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
9039
/// resolves, so JSON output feeds back into commands.
9040
#[test]
9041
fn a_full_hash_resolves_without_its_hash_sign() {
9042
    hermetic();
9043
    let dir = tempfile::tempdir().unwrap();
9044
    let root = dir.path();
9045
    let repo = Repo::init(root).unwrap();
9046
    write(root, "a.txt", b"a\n");
9047
    let h = repo.commit("a", &[]).unwrap();
9048
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
9049
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
9050
    assert!(repo
9051
        .resolve_change(&"0".repeat(64))
9052
        .unwrap_err()
9053
        .to_string()
9054
        .contains("no change matches"));
9055
}
f2f91ceb Andy McCall ↶ 9056
9057
#[test]
9058
fn a_pin_change_moves_only_the_pin() {
9059
    hermetic();
9060
    let dir = tempfile::tempdir().unwrap();
9061
    let root = dir.path();
9062
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9063
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9064
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9065
        .unwrap()
9066
        .with_home(root.join("home"));
9067
    write(&root.join("lib"), "lib.txt", b"v1\n");
9068
    lib.commit("lib v1", &[]).unwrap();
9069
    assert!(lib.push("origin", false).unwrap()[0].ok);
9070
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
9071
    let app_dir = root.join("app");
9072
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
9073
        .unwrap()
9074
        .with_home(root.join("home"));
9075
    write(&app_dir, "main.txt", b"app\n");
9076
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9077
    let a1 = app.commit("app with lib", &[]).unwrap();
9078
    // The library moves on.
9079
    write(&root.join("lib"), "more.txt", b"v2\n");
9080
    let l2 = lib.commit("lib v2", &[]).unwrap();
9081
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
9082
        panic!("an Oxygen pin")
9083
    };
9084
    let pin2 = crate::subrepo::Pin::Oxy {
9085
        repo,
9086
        heads: vec![l2],
9087
        bookmark,
9088
    };
9089
    let author = app.store().get_change(&a1).unwrap().author;
9090
    let change = app
9091
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
9092
        .unwrap();
9093
    let mut state = app.load_state(&[a1]).unwrap();
9094
    state.add(change).unwrap();
9095
    let files = state.materialize().files;
9096
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
9097
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
9098
        panic!("a pin is opaque")
9099
    };
9100
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
9101
    assert_eq!(read, pin2, "the new pin");
9102
    assert!(
9103
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
9104
        "nothing else changes"
9105
    );
9106
    // Only a subrepo's pin can be moved this way.
9107
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
9108
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
9109
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
9110
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
9111
}