OXYGENHUB
◆ v0.4.0 oxygen / crates / oxy-core / src / repo / tests.rs
270.1 KiB · Rust · last changed The object store runs on any Store: a directory today, a bucket next 1 month ago source blame history raw
98286406 Andy McCall ↶ 1
//! Tests for the repository layer.
2
3
use super::*;
75167672 Andy McCall 4
use crate::protocol::SignedPolicy;
957fee30 Andy McCall ↶ 5
use crate::repo::{BisectStep, Selection};
98286406 Andy McCall ↶ 6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
75167672 Andy McCall 26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
98286406 Andy McCall ↶ 30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
75167672 Andy McCall 80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
98286406 Andy McCall ↶ 85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
75167672 Andy McCall 103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
98286406 Andy McCall ↶ 108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
75167672 Andy McCall 114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
98286406 Andy McCall ↶ 121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
0912a033 Andy McCall ↶ 137
    assert!(
138
        d.lines()
139
            .any(|l| l.starts_with("M ") && l.ends_with("main.rs")),
140
        "a modified file is in the summary too: {d}"
141
    );
98286406 Andy McCall ↶ 142
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
143
    assert!(d.contains("-fn main() {}"), "{d}");
144
145
    // Resolution by prefix.
146
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
75167672 Andy McCall 147
    assert_eq!(
148
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
149
        h1
150
    );
98286406 Andy McCall ↶ 151
    assert!(repo.resolve_change("zzzz").is_err());
152
153
    // Undo the commit: bookmark and working copy go back.
154
    repo.undo().unwrap();
155
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
156
    let s = repo.snapshot("oxy status").unwrap();
75167672 Andy McCall 157
    assert!(
158
        !s.changed,
159
        "files on disk still match the pre-commit working copy"
160
    );
98286406 Andy McCall ↶ 161
    assert_eq!(s.statuses.len(), 3);
162
}
163
164
/// Make `main` conflicted: two commits on the same base that edit the same line.
165
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
166
    let dir = tempfile::tempdir().unwrap();
167
    let root = dir.path();
168
    let repo = Repo::init(root).unwrap();
169
    write(root, "f.txt", b"a\nb\nc\n");
170
    let h1 = repo.commit("base", &[]).unwrap();
171
    write(root, "f.txt", b"a\nB\nc\n");
172
    let h2 = repo.commit("upper", &[]).unwrap();
173
    repo.checkout(&[h1], false, "checkout").unwrap();
174
    write(root, "f.txt", b"a\nX\nc\n");
175
    let h3 = repo.commit("ex", &[]).unwrap();
176
    (dir, repo, h1, h2, h3)
177
}
178
179
#[test]
180
fn concurrent_edits_conflict_and_can_be_resolved() {
181
    hermetic();
182
    let (dir, repo, h1, h2, h3) = conflicted_repo();
183
    let root = dir.path();
184
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
185
    assert_eq!(heads, [h2, h3].into_iter().collect());
186
    let st = repo.load_state(&[h2, h3]).unwrap();
187
    assert!(st.materialize().is_conflicted());
188
189
    // Checking out main writes markers.
75167672 Andy McCall 190
    let r = repo
191
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
192
        .unwrap();
98286406 Andy McCall ↶ 193
    assert!(r.conflicted);
194
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 195
    assert!(
196
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
197
        "{marked}"
198
    );
199
    assert!(
200
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
201
        "{marked}"
202
    );
98286406 Andy McCall ↶ 203
    assert!(has_conflict_markers(marked.as_bytes()));
204
    // Untouched markers: clean working copy; commit has nothing to do.
205
    let s = repo.snapshot("status").unwrap();
206
    assert!(s.statuses.is_empty());
207
    assert!(!s.resolves);
208
209
    // Partially edited file that still has markers cannot be committed.
210
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
211
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 212
    assert_eq!(
213
        statuses(&s),
214
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
215
    );
98286406 Andy McCall ↶ 216
    assert!(repo.commit("no", &[]).is_err());
217
218
    // Resolve by keeping one side and adding a line elsewhere.
219
    write(root, "f.txt", b"a\nX\nc\nd\n");
220
    let s = repo.snapshot("status").unwrap();
221
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
222
    assert!(s.resolves);
223
    let h4 = repo.commit("resolve", &[]).unwrap();
224
    let c4 = repo.store().get_change(&h4).unwrap();
225
    assert_eq!(c4.kind, ChangeKind::Resolution);
226
    let mut want = vec![h1, h2, h3];
227
    want.sort();
75167672 Andy McCall 228
    assert_eq!(
229
        c4.deps, want,
230
        "a resolution depends on exactly the contributors and what it references"
231
    );
98286406 Andy McCall ↶ 232
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
233
    let snap = repo.load_state(&[h4]).unwrap().materialize();
234
    assert!(!snap.is_conflicted());
75167672 Andy McCall 235
    assert!(
236
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
237
    );
98286406 Andy McCall ↶ 238
    assert!(!repo.snapshot("status").unwrap().changed);
239
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
240
    // whatever order the changes arrive in.
241
    let mut st = State::new();
242
    for h in [h4, h3, h1, h2] {
243
        st.add_unchecked(repo.store().get_change(&h).unwrap());
244
    }
245
    st.validate().unwrap();
75167672 Andy McCall 246
    assert!(
247
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
248
    );
98286406 Andy McCall ↶ 249
}
250
251
#[test]
252
fn resolution_may_keep_both_sides_or_neither() {
253
    hermetic();
254
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
255
    let root = dir.path();
75167672 Andy McCall 256
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
257
        .unwrap();
98286406 Andy McCall ↶ 258
    // Keep both sides in a chosen order.
259
    write(root, "f.txt", b"a\nX\nB\nc\n");
260
    let h = repo.commit("both", &[]).unwrap();
261
    let snap = repo.load_state(&[h]).unwrap().materialize();
262
    assert!(!snap.is_conflicted());
75167672 Andy McCall 263
    assert!(
264
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
265
    );
98286406 Andy McCall ↶ 266
    // Undo and instead drop the whole region.
267
    repo.undo().unwrap();
268
    write(root, "f.txt", b"a\nc\n");
269
    let h = repo.commit("neither", &[]).unwrap();
270
    let snap = repo.load_state(&[h]).unwrap().materialize();
271
    assert!(!snap.is_conflicted());
75167672 Andy McCall 272
    assert!(
273
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
274
    );
98286406 Andy McCall ↶ 275
}
276
277
#[test]
278
fn name_conflict_resolved_by_removing_a_candidate() {
279
    hermetic();
280
    let dir = tempfile::tempdir().unwrap();
281
    let root = dir.path();
282
    let repo = Repo::init(root).unwrap();
283
    write(root, "keep.txt", b"k\n");
284
    let h1 = repo.commit("base", &[]).unwrap();
285
    write(root, "new.txt", b"one\n");
286
    repo.commit("one", &[]).unwrap();
287
    repo.checkout(&[h1], false, "checkout").unwrap();
288
    write(root, "new.txt", b"two\n");
289
    repo.commit("two", &[]).unwrap();
75167672 Andy McCall 290
    let r = repo
291
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
292
        .unwrap();
98286406 Andy McCall ↶ 293
    assert!(r.conflicted);
75167672 Andy McCall 294
    assert!(
295
        root.join("new.txt.oxy-conflict-1").exists()
296
            && root.join("new.txt.oxy-conflict-2").exists()
297
    );
98286406 Andy McCall ↶ 298
    assert!(!root.join("new.txt").exists());
299
    // Candidate numbering follows change-hash order, so pick by content:
300
    // keep the "two" candidate under the real name and drop the other.
75167672 Andy McCall 301
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
302
        (1, 2)
303
    } else {
304
        (2, 1)
305
    };
98286406 Andy McCall ↶ 306
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
75167672 Andy McCall 307
    fs::rename(
308
        root.join(format!("new.txt.oxy-conflict-{keep}")),
309
        root.join("new.txt"),
310
    )
311
    .unwrap();
98286406 Andy McCall ↶ 312
    let h = repo.commit("pick two", &[]).unwrap();
75167672 Andy McCall 313
    assert_eq!(
314
        repo.store().get_change(&h).unwrap().kind,
315
        ChangeKind::Resolution
316
    );
98286406 Andy McCall ↶ 317
    // The resolution does not touch keep.txt, so it does not depend on h1;
318
    // the bookmark keeps both as heads and their union is the state.
319
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
320
    assert_eq!(heads, [h1, h].into_iter().collect());
75167672 Andy McCall 321
    let snap = repo
322
        .load_state(&repo.bookmark_heads().unwrap())
323
        .unwrap()
324
        .materialize();
98286406 Andy McCall ↶ 325
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
75167672 Andy McCall 326
    assert_eq!(
327
        snap.files.keys().cloned().collect::<Vec<_>>(),
328
        ["keep.txt", "new.txt"]
329
    );
330
    assert!(
331
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
332
    );
98286406 Andy McCall ↶ 333
}
334
335
#[test]
336
fn identities_and_signed_commits() {
337
    hermetic();
338
    let dir = tempfile::tempdir().unwrap();
339
    let root = dir.path();
340
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
341
    write(root, "a.txt", b"a\n");
342
    let h0 = repo.commit("unsigned", &[]).unwrap();
343
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
75167672 Andy McCall 344
    assert_eq!(
345
        repo.store().get_change(&h0).unwrap().author,
346
        ObjectRef::ZERO
347
    );
98286406 Andy McCall ↶ 348
75167672 Andy McCall 349
    let (key, id) = repo
350
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
351
        .unwrap();
98286406 Andy McCall ↶ 352
    assert_eq!(id.hash(), key);
353
    assert_eq!(repo.config.author_key, Some(key));
354
    // Config survives reopen; the secret key is found again.
355
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
356
    assert_eq!(reopened.config.author_key, Some(key));
357
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
358
359
    // Default core.sign = seal: commits carry the author but no signature.
360
    write(root, "a.txt", b"a\nb\n");
361
    let h1 = repo.commit("authored", &[]).unwrap();
362
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
363
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
364
    // Signing later works too.
365
    repo.sign_change(&h1).unwrap();
75167672 Andy McCall 366
    assert!(
367
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
368
    );
98286406 Andy McCall ↶ 369
370
    repo.config.set("core.sign", "change").unwrap();
371
    repo.save_config().unwrap();
372
    write(root, "a.txt", b"a\nb\nc\n");
373
    let h2 = repo.commit("signed", &[]).unwrap();
75167672 Andy McCall 374
    assert_eq!(
375
        repo.verify_change(&h2).unwrap(),
376
        SignatureStatus::Valid {
377
            key,
378
            name: "Ada".into(),
379
            email: "[email protected]".into(),
380
            sealed: false,
381
            revoked: false
382
        }
383
    );
98286406 Andy McCall ↶ 384
05e71ed6 Andy McCall ↶ 385
    // A signature by a key that is not the author or a delegate is rejected
386
    // when the change names an author; an anonymous change (made before any
387
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
98286406 Andy McCall ↶ 388
    let other = SecretKey::generate();
389
    let other_id = other.identity("Mallory", "[email protected]", 0);
390
    let other_key = repo.store().put_identity(&other_id).unwrap();
05e71ed6 Andy McCall ↶ 391
    write(root, "a.txt", b"a\nb\nc\nd\n");
392
    repo.config.set("core.sign", "seal").unwrap();
393
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
394
    let forged = other.sign(Domain::Change, &other_key, &h3);
395
    repo.store().put_signature(&h3, &forged).unwrap();
75167672 Andy McCall 396
    assert!(
05e71ed6 Andy McCall ↶ 397
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
75167672 Andy McCall 398
    );
05e71ed6 Andy McCall ↶ 399
    let adopted = other.sign(Domain::Change, &other_key, &h0);
400
    repo.store().put_signature(&h0, &adopted).unwrap();
401
    assert!(
402
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
403
    );
98286406 Andy McCall ↶ 404
405
    // Tampering with the stored signature invalidates it.
406
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
407
    sig.ed[0] ^= 1;
408
    repo.store().put_signature(&h2, &sig).unwrap();
75167672 Andy McCall 409
    assert!(matches!(
410
        repo.verify_change(&h2).unwrap(),
411
        SignatureStatus::Invalid(_)
412
    ));
98286406 Andy McCall ↶ 413
414
    // Without the secret key, signing at commit fails cleanly.
415
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
416
    write(root, "a.txt", b"z\n");
417
    assert!(no_keys.commit("cannot sign", &[]).is_err());
418
}
419
420
#[test]
421
fn checkout_moves_the_working_copy() {
422
    hermetic();
423
    let dir = tempfile::tempdir().unwrap();
424
    let root = dir.path();
425
    let repo = Repo::init(root).unwrap();
426
    write(root, "a.txt", b"one\n");
427
    write(root, "sub/deep/b.txt", b"b\n");
428
    let h1 = repo.commit("first", &[]).unwrap();
429
    write(root, "a.txt", b"two\n");
430
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
431
    write(root, "bin.dat", &[0, 1, 2, 3]);
432
    let h2 = repo.commit("second", &[]).unwrap();
433
434
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
75167672 Andy McCall 435
    assert_eq!(
436
        r,
437
        CheckoutReport {
438
            written: 2,
439
            removed: 1,
440
            conflicted: false,
d3cd7ef9 Andy McCall ↶ 441
            notes: vec![],
442
            lacks: 1,
75167672 Andy McCall 443
        }
444
    );
98286406 Andy McCall ↶ 445
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
446
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
447
    assert!(!root.join("bin.dat").exists());
448
    let (_, wc) = repo.working_copy().unwrap();
449
    assert_eq!(wc.deps, vec![h1]);
75167672 Andy McCall 450
    assert!(
451
        !repo.snapshot("status").unwrap().changed,
452
        "checkout leaves a clean working copy"
453
    );
98286406 Andy McCall ↶ 454
    // The bookmark still points at h2.
455
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
456
457
    // Dirty working copy refuses without --discard.
458
    write(root, "a.txt", b"dirty\n");
459
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
75167672 Andy McCall 460
    let r = repo
461
        .checkout(&[h2], true, "oxy checkout --discard")
462
        .unwrap();
98286406 Andy McCall ↶ 463
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
464
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
465
    assert!(!root.join("sub").exists(), "empty directories are pruned");
466
    assert_eq!(r.removed, 1);
467
    assert!(!repo.snapshot("status").unwrap().changed);
468
469
    // Refuses to write through a symlinked directory.
470
    #[cfg(unix)]
471
    {
472
        fs::remove_dir_all(root.join("sub")).ok();
473
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
474
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
475
    }
476
}
477
478
#[test]
479
fn large_files_are_chunked_and_read_back() {
480
    hermetic();
481
    let dir = tempfile::tempdir().unwrap();
482
    let repo = Repo::init(dir.path()).unwrap();
483
    let mut big = vec![0u8; 700 * 1024];
484
    for (i, b) in big.iter_mut().enumerate() {
485
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
486
    }
487
    let r = repo.store_blob(&big).unwrap();
488
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
489
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
490
    assert_eq!(repo.read_blob(&r).unwrap(), big);
491
    assert_eq!(Repo::blob_ref(&big), r);
492
}
493
494
#[test]
495
fn clone_push_pull_with_seals_and_attestations() {
496
    hermetic();
497
    let dir = tempfile::tempdir().unwrap();
498
    let root = dir.path();
499
    let origin_path = root.join("origin");
500
    let origin = Repo::init(&origin_path).unwrap();
501
    let origin_url = origin_path.to_string_lossy().to_string();
502
503
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
75167672 Andy McCall 504
    let mut a = Repo::clone(&origin_url, &root.join("a"))
505
        .unwrap()
506
        .with_home(root.join("home-a"));
98286406 Andy McCall ↶ 507
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
75167672 Andy McCall 508
    let (key_a, _) = a
509
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
510
        .unwrap();
98286406 Andy McCall ↶ 511
    write(&root.join("a"), "f.txt", b"a\n");
512
    let h1 = a.commit("first", &[]).unwrap();
513
    let results = a.push("origin", false).unwrap();
514
    assert!(results[0].ok, "{}", results[0].reason);
515
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
516
    // The change was sealed at push and the reference attested.
75167672 Andy McCall 517
    assert!(
518
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
519
    );
520
    assert_eq!(
521
        origin.verify_change(&h1).unwrap(),
522
        SignatureStatus::Unsigned
523
    );
f8c69576 Andy McCall ↶ 524
    let serial_of = |att: &SignedAttest| match att.attest.body {
525
        AttestBody::Ref { serial, .. } => serial,
526
        _ => unreachable!(),
527
    };
98286406 Andy McCall ↶ 528
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 529
    // A bookmark new to the remote starts at the clock (past any deleted
530
    // namesake's serial); later updates count up from there.
531
    let first = serial_of(&att);
532
    assert!(first > 1_000_000_000_000, "{first}");
98286406 Andy McCall ↶ 533
    let again = a.push("origin", false).unwrap();
534
    assert!(again[0].ok && again[0].reason.contains("up to date"));
535
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 536
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
98286406 Andy McCall ↶ 537
538
    // B clones and sees the file and the seal.
539
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
540
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
541
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
75167672 Andy McCall 542
    assert!(matches!(
543
        b.authenticate_change(&h1).unwrap(),
544
        SignatureStatus::Valid { sealed: true, .. }
545
    ));
98286406 Andy McCall ↶ 546
547
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
548
    write(&root.join("b"), "f.txt", b"a\nb\n");
549
    let h2 = b.commit("second", &[]).unwrap();
550
    assert!(b.push("origin", false).unwrap()[0].ok);
551
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
552
553
    // A commits an independent change; push is refused until A pulls.
554
    write(&root.join("a"), "g.txt", b"g\n");
555
    let h3 = a.commit("third", &[]).unwrap();
556
    assert!(a.push("origin", false).is_err());
557
    let pr = a.pull("origin").unwrap();
558
    assert!(pr.changed && pr.checked_out);
559
    let mut want = vec![h2, h3];
560
    want.sort();
561
    assert_eq!(pr.heads, want);
562
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
563
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
564
    let results = a.push("origin", false).unwrap();
565
    assert!(results[0].ok, "{}", results[0].reason);
566
    let mut origin_heads = origin.bookmark_heads().unwrap();
567
    origin_heads.sort();
568
    assert_eq!(origin_heads, want);
569
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 570
    assert_eq!(serial_of(&att), first + 1);
98286406 Andy McCall ↶ 571
572
    // B pulls and ends up identical.
573
    let pr = b.pull("origin").unwrap();
574
    assert_eq!(pr.heads, want);
575
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
576
    assert!(!b.snapshot("status").unwrap().changed);
577
578
    // Concurrent edits of the same line: the union is a reified conflict.
579
    write(&root.join("a"), "f.txt", b"a\nA\n");
580
    a.commit("a-edit", &[]).unwrap();
581
    a.push("origin", false).unwrap();
582
    write(&root.join("b"), "f.txt", b"a\nB\n");
583
    b.commit("b-edit", &[]).unwrap();
584
    let pr = b.pull("origin").unwrap();
585
    assert!(pr.changed && pr.checked_out);
586
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
587
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
588
    write(&root.join("b"), "f.txt", b"a\nAB\n");
589
    let hr = b.commit("resolve", &[]).unwrap();
75167672 Andy McCall 590
    assert_eq!(
591
        b.store().get_change(&hr).unwrap().kind,
592
        ChangeKind::Resolution
593
    );
98286406 Andy McCall ↶ 594
    assert!(b.push("origin", false).unwrap()[0].ok);
595
    a.pull("origin").unwrap();
596
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
597
    // The resolution depends on the conflicting edits, but nothing depends
598
    // on "third" (it only added g.txt), so it stays a head beside it.
599
    let mut want = vec![hr, h3];
600
    want.sort();
601
    assert_eq!(a.bookmark_heads().unwrap(), want);
602
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
603
}
604
605
#[test]
606
fn receive_push_rejects_bad_updates() {
607
    hermetic();
608
    let dir = tempfile::tempdir().unwrap();
609
    let root = dir.path();
610
    let origin = Repo::init(&root.join("origin")).unwrap();
611
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 612
    let mut a = Repo::clone(&url, &root.join("a"))
613
        .unwrap()
614
        .with_home(root.join("home"));
615
    let (key, _) = a
616
        .create_identity("Ada", "a@b", IdentityScope::Repo)
617
        .unwrap();
98286406 Andy McCall ↶ 618
    write(&root.join("a"), "f.txt", b"x\n");
619
    let h1 = a.commit("one", &[]).unwrap();
620
    assert!(a.push("origin", false).unwrap()[0].ok);
621
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
75167672 Andy McCall 622
    let s1 = origin
623
        .store()
624
        .put_state(&StateObject::new(vec![h1]))
625
        .unwrap();
98286406 Andy McCall ↶ 626
627
    // Missing head.
75167672 Andy McCall 628
    let ghost = origin
629
        .store()
630
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
631
        .unwrap();
632
    let r = origin
633
        .receive_push(
634
            Bundle::default(),
635
            vec![RefUpdate {
636
                name: "main".into(),
637
                old_state: s1,
638
                new_state: ghost,
639
                force: false,
640
                attestation: None,
641
            }],
642
            None,
643
            vec![],
644
        )
645
        .unwrap();
646
    assert!(
647
        !r[0].ok && r[0].reason.contains("missing"),
648
        "{}",
649
        r[0].reason
650
    );
98286406 Andy McCall ↶ 651
652
    // Stale old_state.
75167672 Andy McCall 653
    let r = origin
654
        .receive_push(
655
            Bundle::default(),
656
            vec![RefUpdate {
657
                name: "main".into(),
658
                old_state: empty,
659
                new_state: s1,
660
                force: false,
661
                attestation: None,
662
            }],
663
            None,
664
            vec![],
665
        )
666
        .unwrap();
98286406 Andy McCall ↶ 667
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
668
669
    // Non-fast-forward without force is refused; with force it passes.
75167672 Andy McCall 670
    let r = origin
671
        .receive_push(
672
            Bundle::default(),
673
            vec![RefUpdate {
674
                name: "main".into(),
675
                old_state: s1,
676
                new_state: empty,
677
                force: false,
678
                attestation: None,
679
            }],
680
            None,
681
            vec![],
682
        )
683
        .unwrap();
684
    assert!(
685
        !r[0].ok && r[0].reason.contains("fast-forward"),
686
        "{}",
687
        r[0].reason
688
    );
689
    let r = origin
690
        .receive_push(
691
            Bundle::default(),
692
            vec![RefUpdate {
693
                name: "main".into(),
694
                old_state: s1,
695
                new_state: empty,
696
                force: true,
697
                attestation: None,
698
            }],
699
            None,
700
            vec![],
701
        )
702
        .unwrap();
98286406 Andy McCall ↶ 703
    assert!(r[0].ok);
704
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
705
706
    // Attestation with a stale serial is a rollback and is refused.
75167672 Andy McCall 707
    let sa = a
708
        .sign_attest(&Attest {
709
            repo: a.id().unwrap(),
710
            hlc: Hlc::now(),
711
            body: AttestBody::Ref {
712
                name: "main".into(),
713
                old_state: empty,
714
                new_state: s1,
715
                serial: 1,
716
            },
717
        })
718
        .unwrap();
719
    let r = origin
720
        .receive_push(
721
            Bundle::default(),
722
            vec![RefUpdate {
723
                name: "main".into(),
724
                old_state: empty,
725
                new_state: s1,
726
                force: false,
727
                attestation: Some(sa.clone()),
728
            }],
729
            None,
730
            vec![],
731
        )
732
        .unwrap();
733
    assert!(
734
        !r[0].ok && r[0].reason.contains("serial"),
735
        "{}",
736
        r[0].reason
737
    );
98286406 Andy McCall ↶ 738
    // An attestation for a different update is refused too.
75167672 Andy McCall 739
    let sa2 = a
740
        .sign_attest(&Attest {
741
            repo: a.id().unwrap(),
742
            hlc: Hlc::now(),
743
            body: AttestBody::Ref {
744
                name: "main".into(),
745
                old_state: s1,
746
                new_state: empty,
747
                serial: 5,
748
            },
749
        })
750
        .unwrap();
751
    let r = origin
752
        .receive_push(
753
            Bundle::default(),
754
            vec![RefUpdate {
755
                name: "main".into(),
756
                old_state: empty,
757
                new_state: s1,
758
                force: false,
759
                attestation: Some(sa2),
760
            }],
761
            None,
762
            vec![],
763
        )
764
        .unwrap();
765
    assert!(
766
        !r[0].ok && r[0].reason.contains("describe"),
767
        "{}",
768
        r[0].reason
769
    );
98286406 Andy McCall ↶ 770
    let _ = key;
771
}
772
773
#[test]
774
fn user_config_supplies_defaults_and_clones_sign() {
775
    hermetic();
776
    let dir = tempfile::tempdir().unwrap();
777
    let root = dir.path();
778
    let home = root.join("home");
779
    let origin = Repo::init(&root.join("origin")).unwrap();
780
    let url = root.join("origin").to_string_lossy().to_string();
781
782
    // Identity at user scope: the repository file stays free of author keys.
783
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
75167672 Andy McCall 784
    let (key, _) = a
785
        .create_identity("Ada", "[email protected]", IdentityScope::User)
786
        .unwrap();
98286406 Andy McCall ↶ 787
    assert!(!a.config.repo_layer().contains_key("author.key"));
788
    assert_eq!(a.config.author_key, Some(key));
789
    assert!(home.join("config.toml").exists());
790
    a.set_user_config("core.sign", "change").unwrap();
791
    assert!(a.config.sign_changes);
792
793
    // Repository settings override user settings and are the only ones saved.
794
    a.config.set("core.sign", "seal").unwrap();
795
    a.save_config().unwrap();
796
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
797
    assert!(!again.config.sign_changes);
798
    assert_eq!(again.config.author_key, Some(key));
75167672 Andy McCall 799
    assert_eq!(
800
        read_config_file(&root.join("a/.oxy/config"))
801
            .unwrap()
802
            .get("core.sign")
803
            .map(String::as_str),
804
        Some("seal")
805
    );
98286406 Andy McCall ↶ 806
807
    // A fresh clone made by this user signs with the user-level identity,
808
    // even though the clone's store has never seen the identity object.
809
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
810
    assert!(b.config.sign_changes);
811
    write(&root.join("b"), "f.txt", b"f\n");
812
    let h = b.commit("signed from a clone", &[]).unwrap();
75167672 Andy McCall 813
    assert!(
814
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
815
    );
98286406 Andy McCall ↶ 816
    assert!(b.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 817
    assert!(matches!(
818
        origin.verify_change(&h).unwrap(),
819
        SignatureStatus::Valid { .. }
820
    ));
98286406 Andy McCall ↶ 821
}
822
823
#[test]
824
fn format1_repositories_are_migrated_on_open() {
825
    hermetic();
826
    use crate::oplog::{Format1Op, Format1View};
827
    let dir = tempfile::tempdir().unwrap();
828
    let root = dir.path();
829
    let repo = Repo::init(root).unwrap();
830
    write(root, "a.txt", b"a\n");
831
    let h1 = repo.commit("one", &[]).unwrap();
832
    let (wc_hash, _) = repo.working_copy().unwrap();
833
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
834
    let mut v1 = Format1View::default();
835
    v1.bookmarks.insert("main".into(), vec![]);
836
    v1.workspaces.insert(repo.workspace(), wc_hash);
75167672 Andy McCall 837
    let init = Format1Op {
838
        parents: vec![],
839
        hlc: Hlc::default(),
840
        command: "oxy init".into(),
841
        view: v1.clone(),
842
    };
98286406 Andy McCall ↶ 843
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
844
    v1.bookmarks.insert("main".into(), vec![h1]);
75167672 Andy McCall 845
    let commit = Format1Op {
846
        parents: vec![init_ref],
847
        hlc: Hlc::default(),
848
        command: "oxy commit".into(),
849
        view: v1,
850
    };
98286406 Andy McCall ↶ 851
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
852
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
853
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
854
    drop(repo);
855
856
    let repo = Repo::open(root).unwrap();
75167672 Andy McCall 857
    assert_eq!(
858
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
859
        FORMAT_LINE
860
    );
98286406 Andy McCall ↶ 861
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
862
    let ops = repo.op_log().unwrap();
75167672 Andy McCall 863
    assert_eq!(
864
        ops.iter()
865
            .map(|(_, o)| o.command.as_str())
866
            .collect::<Vec<_>>(),
867
        ["oxy commit", "oxy init"]
868
    );
98286406 Andy McCall ↶ 869
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
870
    assert!(!repo.snapshot("status").unwrap().changed);
871
    // Reopening again is a no-op.
872
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
873
}
874
875
#[test]
876
fn undo_skips_snapshot_operations() {
877
    hermetic();
878
    let dir = tempfile::tempdir().unwrap();
879
    let root = dir.path();
880
    let repo = Repo::init(root).unwrap();
881
    write(root, "a.txt", b"a\n");
882
    let h1 = repo.commit("a", &[]).unwrap();
883
    // A later command snapshots new edits on top of the commit.
884
    write(root, "b.txt", b"b\n");
885
    let s = repo.snapshot("oxy status").unwrap();
886
    assert!(s.changed);
887
    assert!(repo.head_op().unwrap().1.is_snapshot());
888
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
889
    // Undo must undo the commit, not the snapshot.
890
    repo.undo().unwrap();
891
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
892
    let s = repo.snapshot("oxy status").unwrap();
893
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
75167672 Andy McCall 894
    assert_eq!(
895
        paths,
896
        ["a.txt", "b.txt"],
897
        "both files are back in the working copy"
898
    );
98286406 Andy McCall ↶ 899
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
900
    // Only snapshots remain above `init`, so there is nothing left to undo.
901
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
902
    assert!(repo.undo().is_err());
903
}
904
905
#[test]
906
fn independent_changes_commute_and_make_multiple_heads() {
907
    hermetic();
908
    let dir = tempfile::tempdir().unwrap();
909
    let root = dir.path();
910
    let repo = Repo::init(root).unwrap();
911
    write(root, "a.txt", b"a\n");
912
    let h1 = repo.commit("a", &[]).unwrap();
913
    write(root, "b.txt", b"b\n");
914
    let h2 = repo.commit("b", &[]).unwrap();
915
    let c2 = repo.store().get_change(&h2).unwrap();
916
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
917
    let mut heads = repo.bookmark_heads().unwrap();
918
    heads.sort();
919
    let mut want = vec![h1, h2];
920
    want.sort();
921
    assert_eq!(heads, want);
922
    // Editing a.txt depends on h1 only.
923
    write(root, "a.txt", b"a\na2\n");
924
    let h3 = repo.commit("a2", &[]).unwrap();
925
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
926
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
927
    assert_eq!(heads, [h2, h3].into_iter().collect());
928
    // Explicit dependency.
929
    write(root, "c.txt", b"c\n");
930
    let h4 = repo.commit("c", &[h2]).unwrap();
931
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
932
}
933
934
#[test]
935
fn mode_change_and_text_binary_switch() {
936
    hermetic();
937
    let dir = tempfile::tempdir().unwrap();
938
    let root = dir.path();
939
    let repo = Repo::init(root).unwrap();
940
    write(root, "run.sh", b"#!/bin/sh\n");
941
    repo.commit("add script", &[]).unwrap();
942
    #[cfg(unix)]
943
    {
944
        use std::os::unix::fs::PermissionsExt;
945
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
946
        let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 947
        assert_eq!(
948
            statuses(&s),
949
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
950
        );
98286406 Andy McCall ↶ 951
        let h = repo.commit("exec", &[]).unwrap();
952
        let snap = repo.load_state(&[h]).unwrap().materialize();
953
        assert!(snap.files["run.sh"].mode.exec);
954
    }
955
    // Text → binary → text.
956
    write(root, "run.sh", b"\0binary");
957
    let h = repo.commit("binary", &[]).unwrap();
958
    let snap = repo.load_state(&[h]).unwrap().materialize();
959
    assert!(snap.files["run.sh"].mode.opaque);
960
    write(root, "run.sh", b"text again\n");
961
    let h = repo.commit("text", &[]).unwrap();
962
    let snap = repo.load_state(&[h]).unwrap().materialize();
963
    assert!(!snap.files["run.sh"].mode.opaque);
75167672 Andy McCall 964
    assert!(
965
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
966
    );
98286406 Andy McCall ↶ 967
    assert!(!snap.is_conflicted());
968
}
83e0677b Andy McCall ↶ 969
970
#[test]
971
fn trust_policy_governs_pushes_and_fetches() {
972
    hermetic();
973
    let dir = tempfile::tempdir().unwrap();
974
    let root = dir.path();
975
    let origin = Repo::init(&root.join("origin")).unwrap();
976
    let url = root.join("origin").to_string_lossy().to_string();
977
978
    // A is the root. Before the policy, an unsigned push from B is fine.
75167672 Andy McCall 979
    let mut a = Repo::clone(&url, &root.join("a"))
980
        .unwrap()
981
        .with_home(root.join("home-a"));
982
    let (key_a, _) = a
983
        .create_identity("Ada", "[email protected]", IdentityScope::User)
984
        .unwrap();
985
    let mut b = Repo::clone(&url, &root.join("b"))
986
        .unwrap()
987
        .with_home(root.join("home-b"));
83e0677b Andy McCall ↶ 988
    write(&root.join("b"), "b.txt", b"b\n");
989
    b.commit("unsigned before policy", &[]).unwrap();
990
    assert!(b.push("origin", false).unwrap()[0].ok);
991
992
    // A creates the policy and pushes it; origin now enforces it.
993
    write(&root.join("a"), "a.txt", b"a\n");
994
    a.commit("a", &[]).unwrap();
995
    let sp = a.policy_init().unwrap();
996
    assert_eq!(sp.policy.serial, 1);
997
    a.pull("origin").unwrap();
998
    let results = a.push("origin", false).unwrap();
999
    assert!(results.iter().all(|r| r.ok), "{results:?}");
1000
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
1001
1002
    // B pulls the policy. Without an identity B cannot push at all.
1003
    b.pull("origin").unwrap();
75167672 Andy McCall 1004
    assert!(
1005
        b.current_policy().unwrap().is_some(),
1006
        "the policy arrived with the fetch"
1007
    );
83e0677b Andy McCall ↶ 1008
    assert!(b.push("origin", false).is_err());
1009
    // With an identity the policy does not list, the push is rejected by origin.
75167672 Andy McCall 1010
    let (key_b, id_b) = b
1011
        .create_identity("Bob", "[email protected]", IdentityScope::User)
1012
        .unwrap();
83e0677b Andy McCall ↶ 1013
    write(&root.join("b"), "b.txt", b"b2\n");
1014
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
1015
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
1016
    let r = b.push("origin", false).unwrap();
75167672 Andy McCall 1017
    assert!(
1018
        !r[0].ok && r[0].reason.contains("may not update"),
1019
        "{:?}",
1020
        r
1021
    );
83e0677b Andy McCall ↶ 1022
1023
    // A grants B (identity handed over as a file) and publishes the policy.
1024
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
1025
    assert_eq!(sp.policy.serial, 2);
1026
    let r = a.push("origin", false).unwrap();
1027
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1028
    // B must fetch the new policy before pushing.
75167672 Andy McCall 1029
    assert!(b
1030
        .push("origin", false)
1031
        .unwrap_or_else(|e| vec![RefResult {
1032
            name: "main".into(),
1033
            ok: false,
1034
            reason: e.to_string()
1035
        }])
1036
        .iter()
1037
        .all(|x| !x.ok));
83e0677b Andy McCall ↶ 1038
    b.pull("origin").unwrap();
1039
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
1040
    let r = b.push("origin", false).unwrap();
1041
    assert!(r[0].ok, "{:?}", r);
1042
    // Origin verified B's change under the policy.
1043
    let heads = origin.bookmark_heads().unwrap();
1044
    for h in &heads {
1045
        let c = origin.store().get_change(h).unwrap();
1046
        if c.author == key_b {
75167672 Andy McCall 1047
            origin
1048
                .change_allowed(
1049
                    h,
1050
                    &origin.current_policy().unwrap().unwrap().1.policy,
1051
                    "main",
1052
                )
1053
                .unwrap();
83e0677b Andy McCall ↶ 1054
        }
1055
    }
1056
1057
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
1058
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
1059
    forged.serial = 3;
1060
    forged.roots = vec![key_b];
1061
    let fh = forged.hash();
1062
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 1063
    let forged = SignedPolicy {
1064
        policy: forged,
1065
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
1066
    };
1067
    let r = origin
1068
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
1069
        .unwrap();
83e0677b Andy McCall ↶ 1070
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
1071
    let stale = a.current_policy().unwrap().unwrap().1;
1072
    let mut old = stale.clone();
1073
    old.policy.serial = 1;
75167672 Andy McCall 1074
    let r = origin
1075
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
1076
        .unwrap();
83e0677b Andy McCall ↶ 1077
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
1078
1079
    // A revokes B; after B pulls the policy, B's pushes are refused again.
1080
    a.pull("origin").unwrap();
1081
    a.policy_revoke(&key_b).unwrap();
1082
    let r = a.push("origin", false).unwrap();
1083
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
1084
    b.pull("origin").unwrap();
1085
    write(&root.join("b"), "b.txt", b"b3\n");
1086
    b.commit("b3", &[]).unwrap();
1087
    let r = b.push("origin", false).unwrap();
1088
    assert!(!r[0].ok, "{:?}", r);
1089
1090
    // A clone by a third party receives and verifies everything.
75167672 Andy McCall 1091
    let c = Repo::clone(&url, &root.join("c"))
1092
        .unwrap()
1093
        .with_home(root.join("home-c"));
83e0677b Andy McCall ↶ 1094
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
75167672 Andy McCall 1095
    assert!(c
1096
        .current_policy()
1097
        .unwrap()
1098
        .unwrap()
1099
        .1
1100
        .policy
1101
        .roots
1102
        .contains(&key_a));
83e0677b Andy McCall ↶ 1103
    assert!(!c.snapshot("status").unwrap().changed);
1104
}
d02e545d Andy McCall ↶ 1105
9ae4d15a Andy McCall ↶ 1106
/// oxygen#66: a gc says what it is doing, phase by phase.
d02e545d Andy McCall ↶ 1107
#[test]
9ae4d15a Andy McCall ↶ 1108
fn gc_reports_its_phases() {
1109
    hermetic();
1110
    let dir = tempfile::tempdir().unwrap();
1111
    let repo = Repo::init(dir.path()).unwrap();
1112
    for i in 0..3 {
1113
        write(
1114
            dir.path(),
1115
            &format!("f{i}.txt"),
1116
            format!("{i}\n").as_bytes(),
1117
        );
1118
        repo.commit(&format!("c{i}"), &[]).unwrap();
1119
    }
1120
    let mut phases = Vec::new();
1121
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
1122
        .unwrap();
1123
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
1124
    assert!(
1125
        phases.iter().any(|p| p.starts_with("pruning")),
1126
        "{phases:?}"
1127
    );
1128
    assert!(
1129
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
1130
        "{phases:?}"
1131
    );
1132
    assert!(
1133
        phases
1134
            .iter()
1135
            .any(|p| p.starts_with("writing the index of ")),
1136
        "{phases:?}"
1137
    );
1138
}
1139
1140
#[test]
d02e545d Andy McCall ↶ 1141
fn gc_packs_objects_and_history_still_works() {
1142
    hermetic();
1143
    let dir = tempfile::tempdir().unwrap();
1144
    let root = dir.path();
1145
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1146
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1147
        .unwrap();
d02e545d Andy McCall ↶ 1148
    repo.set_user_config("core.sign", "change").unwrap();
1149
    write(root, "a.txt", b"one\n");
1150
    let h1 = repo.commit("one", &[]).unwrap();
1151
    write(root, "a.txt", b"two\n");
1152
    write(root, "big.bin", &vec![0u8; 100_000]);
1153
    let h2 = repo.commit("two", &[]).unwrap();
ba160f60 Andy McCall ↶ 1154
    // Several snapshots leave superseded working-copy versions behind.
1155
    for i in 0..5 {
1156
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
1157
        repo.snapshot("status").unwrap();
1158
    }
1159
    write(root, "a.txt", b"two\n");
1160
    repo.snapshot("status").unwrap();
d02e545d Andy McCall ↶ 1161
    let before = repo.store().list().unwrap();
1162
    assert!(repo.store().loose_count().unwrap() > 0);
ba160f60 Andy McCall ↶ 1163
1164
    // With the default retention every operation's view is a root: nothing prunes.
1165
    let r = repo.gc(true).unwrap();
1166
    assert_eq!(r.packed.objects, before.len());
1167
    assert_eq!(r.pruned.objects, 0);
d02e545d Andy McCall ↶ 1168
    assert_eq!(repo.store().loose_count().unwrap(), 0);
1169
    assert_eq!(repo.store().list().unwrap(), before);
ba160f60 Andy McCall ↶ 1170
1171
    // With zero retention only the current view is a root: superseded
1172
    // working copies go, everything reachable stays.
1173
    repo.config.set("core.op-retention", "0").unwrap();
1174
    repo.save_config().unwrap();
21b2aec2 Andy McCall ↶ 1175
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
ba160f60 Andy McCall ↶ 1176
    let r = repo.gc(true).unwrap();
1177
    assert!(r.pruned.objects >= 5, "{r:?}");
1178
    let after = repo.store().list().unwrap();
1179
    assert!(after.len() < before.len());
1180
    assert!(after.contains(&h1) && after.contains(&h2));
1181
    for (_, op) in repo.op_log().unwrap() {
1182
        assert!(!op.command.is_empty(), "operation objects are all kept");
1183
    }
1184
    // Everything still works from the pruned, packed store.
d02e545d Andy McCall ↶ 1185
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
75167672 Andy McCall 1186
    assert!(matches!(
1187
        repo.verify_change(&h2).unwrap(),
1188
        SignatureStatus::Valid { .. }
1189
    ));
d02e545d Andy McCall ↶ 1190
    assert_eq!(repo.log().unwrap().len(), 3);
1191
    repo.checkout(&[h1], false, "checkout").unwrap();
1192
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1193
    repo.checkout(&[h2], false, "checkout").unwrap();
1194
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
1195
    assert!(!repo.snapshot("status").unwrap().changed);
ba160f60 Andy McCall ↶ 1196
    // Grace period defers pruning of young garbage.
d02e545d Andy McCall ↶ 1197
    write(root, "a.txt", b"three\n");
1198
    repo.commit("three", &[]).unwrap();
ba160f60 Andy McCall ↶ 1199
    let r = repo.gc(false).unwrap();
1200
    assert_eq!(r.pruned.objects, 0);
1201
    assert!(r.pruned.deferred > 0);
1202
    let r = repo.gc(true).unwrap();
1203
    assert!(r.pruned.objects > 0);
1204
    assert_eq!(repo.log().unwrap().len(), 4);
21b2aec2 Andy McCall ↶ 1205
    // Restoring the default retention makes the old views roots again; the
1206
    // working copies they name were pruned, which gc tolerates.
1207
    repo.config.set("core.op-retention", "90").unwrap();
1208
    repo.save_config().unwrap();
1209
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1210
    let r = repo.gc(false).unwrap();
1211
    assert_eq!(r.pruned.objects, 0);
1212
    assert_eq!(repo.log().unwrap().len(), 4);
d02e545d Andy McCall ↶ 1213
}
614541c3 Andy McCall ↶ 1214
1215
#[test]
1216
fn describe_amend_abandon_heads() {
1217
    hermetic();
1218
    let dir = tempfile::tempdir().unwrap();
1219
    let root = dir.path();
1220
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 1221
    repo.create_identity("Ada", "a@b", IdentityScope::User)
1222
        .unwrap();
614541c3 Andy McCall ↶ 1223
    repo.set_user_config("core.sign", "change").unwrap();
1224
    write(root, "a.txt", b"one\n");
1225
    let h1 = repo.commit("first", &[]).unwrap();
1226
    write(root, "a.txt", b"one\ntwo\n");
1227
    let h2 = repo.commit("secnod", &[]).unwrap();
1228
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
1229
1230
    // describe: same ChangeId, new hash, bookmark and working copy follow.
1231
    let h2b = repo.describe(&h2, "second").unwrap();
1232
    assert_ne!(h2b, h2);
1233
    let c = repo.store().get_change(&h2b).unwrap();
75167672 Andy McCall 1234
    assert_eq!(
1235
        (c.change_id, c.message.as_str(), c.deps.clone()),
1236
        (id2, "second", vec![h1])
1237
    );
614541c3 Andy McCall ↶ 1238
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
75167672 Andy McCall 1239
    assert!(matches!(
1240
        repo.verify_change(&h2b).unwrap(),
1241
        SignatureStatus::Valid { .. }
1242
    ));
614541c3 Andy McCall ↶ 1243
    let s = repo.snapshot("status").unwrap();
1244
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
75167672 Andy McCall 1245
    assert_eq!(
1246
        repo.resolve_change(&id2.short(8)).unwrap(),
1247
        h2b,
1248
        "the old object is no longer reachable from the log"
1249
    );
c07e0e7d Andy McCall ↶ 1250
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
1251
    let h1b = repo.describe(&h1, "first, described").unwrap();
1252
    assert_ne!(h1b, h1);
1253
    let heads = repo.bookmark_heads().unwrap();
1254
    assert_eq!(heads.len(), 1);
1255
    let top = repo.store().get_change(&heads[0]).unwrap();
1256
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
75167672 Andy McCall 1257
    assert!(
1258
        matches!(
1259
            repo.verify_change(&heads[0]).unwrap(),
1260
            SignatureStatus::Valid { .. }
1261
        ),
1262
        "rewritten own change is re-signed"
1263
    );
c07e0e7d Andy McCall ↶ 1264
    let (_, wc) = repo.working_copy().unwrap();
75167672 Andy McCall 1265
    assert_eq!(
1266
        wc.deps,
1267
        vec![heads[0]],
1268
        "the working copy follows the rewrite"
1269
    );
c07e0e7d Andy McCall ↶ 1270
    assert!(!repo.snapshot("status").unwrap().changed);
1271
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 1272
    assert!(
1273
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
1274
    );
614541c3 Andy McCall ↶ 1275
1276
    // amend: fold an edit into the head; the result is one change from h1.
1277
    write(root, "a.txt", b"one\ntwo\nthree\n");
1278
    write(root, "b.txt", b"b\n");
1279
    let h2c = repo.amend(None).unwrap();
1280
    let c = repo.store().get_change(&h2c).unwrap();
1281
    assert_eq!(c.change_id, id2);
1282
    assert_eq!(c.message, "second");
1283
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
75167672 Andy McCall 1284
    assert_eq!(
1285
        repo.log().unwrap().len(),
1286
        3,
1287
        "working copy, amended head, first"
1288
    );
614541c3 Andy McCall ↶ 1289
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
75167672 Andy McCall 1290
    assert!(
1291
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
1292
    );
614541c3 Andy McCall ↶ 1293
    assert!(snap.files.contains_key("b.txt"));
1294
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 1295
    assert!(
1296
        repo.amend(None).is_err(),
1297
        "clean working copy and no message"
1298
    );
614541c3 Andy McCall ↶ 1299
    let h2d = repo.amend(Some("second, amended")).unwrap();
75167672 Andy McCall 1300
    assert_eq!(
1301
        repo.store().get_change(&h2d).unwrap().message,
1302
        "second, amended"
1303
    );
614541c3 Andy McCall ↶ 1304
1305
    // abandon: the head goes, its content stays as uncommitted work.
1306
    repo.abandon(&h2d).unwrap();
75167672 Andy McCall 1307
    assert_eq!(
1308
        repo.bookmark_heads().unwrap(),
1309
        vec![h1b],
1310
        "the described first change is the head again"
1311
    );
614541c3 Andy McCall ↶ 1312
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 1313
    let paths: Vec<_> = s
1314
        .statuses
1315
        .iter()
1316
        .map(|p| (p.path.as_str(), p.status))
1317
        .collect();
1318
    assert_eq!(
1319
        paths,
1320
        vec![
1321
            ("a.txt", ChangeStatus::Modified),
1322
            ("b.txt", ChangeStatus::Added)
1323
        ]
1324
    );
614541c3 Andy McCall ↶ 1325
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
1326
    let h3 = repo.commit("recommitted", &[]).unwrap();
1327
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
1328
    // undo brings the abandoned head back.
1329
    repo.undo().unwrap();
1330
    repo.undo().unwrap();
1331
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
c07e0e7d Andy McCall ↶ 1332
6706bdcf Andy McCall ↶ 1333
    // Abandoning a non-head whose dependent references its atoms reifies
1334
    // the references (here: a.txt vanishes with it, so the dependent's edit
1335
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
c07e0e7d Andy McCall ↶ 1336
    let base = repo.bookmark_heads().unwrap()[0];
1337
    let base_change = repo.store().get_change(&base).unwrap();
1338
    let h1_now = base_change.deps[0];
6706bdcf Andy McCall ↶ 1339
    let notes = repo.abandon(&h1_now).unwrap();
75167672 Andy McCall 1340
    assert!(
1341
        !notes.is_empty(),
1342
        "the dependent's edit of a.txt was reified"
1343
    );
6706bdcf Andy McCall ↶ 1344
    let heads = repo.bookmark_heads().unwrap();
1345
    let after = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 1346
    assert!(
1347
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
1348
        "{:?}",
1349
        after.files.keys()
1350
    );
6706bdcf Andy McCall ↶ 1351
    repo.undo().unwrap();
1352
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
c07e0e7d Andy McCall ↶ 1353
    write(root, "c.txt", b"c\n");
1354
    let hc = repo.commit("c", &[]).unwrap();
1355
    write(root, "d.txt", b"d\n");
1356
    let hd = repo.commit("d", &[hc]).unwrap();
1357
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
1358
    repo.abandon(&hc).unwrap();
1359
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1360
    assert!(!heads.contains(&hc));
75167672 Andy McCall 1361
    let d_now = heads
1362
        .iter()
1363
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
1364
        .copied()
1365
        .unwrap();
1366
    assert!(
1367
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
1368
        "d inherited c's (empty) dependencies"
1369
    );
c07e0e7d Andy McCall ↶ 1370
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 1371
    assert_eq!(
1372
        s.statuses
1373
            .iter()
1374
            .map(|p| p.path.as_str())
1375
            .collect::<Vec<_>>(),
1376
        vec!["c.txt"],
1377
        "c's content is now uncommitted work"
1378
    );
614541c3 Andy McCall ↶ 1379
}
79ab8528 Andy McCall ↶ 1380
1381
#[test]
1382
fn git_export_mirrors_history() {
1383
    hermetic();
75167672 Andy McCall 1384
    if std::process::Command::new("git")
1385
        .arg("--version")
1386
        .output()
1387
        .is_err()
1388
    {
79ab8528 Andy McCall ↶ 1389
        eprintln!("git not installed; skipping");
1390
        return;
1391
    }
1392
    let dir = tempfile::tempdir().unwrap();
1393
    let root = dir.path();
75167672 Andy McCall 1394
    let mut repo = Repo::init(&root.join("r"))
1395
        .unwrap()
1396
        .with_home(root.join("home"));
1397
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
1398
        .unwrap();
79ab8528 Andy McCall ↶ 1399
    let r = root.join("r");
1400
    write(&r, "README.md", b"hello\n");
1401
    write(&r, "src/main.rs", b"fn main() {}\n");
1402
    let h1 = repo.commit("first", &[]).unwrap();
1403
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
1404
    write(&r, "logo.png", b"\x89PNG\0\0");
1405
    let h2 = repo.commit("second", &[]).unwrap();
1406
1407
    let git_dir = root.join("mirror.git");
1408
    let rep = repo.git_export(&git_dir).unwrap();
1409
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
1410
    let git = |args: &[&str]| -> String {
75167672 Andy McCall 1411
        let out = std::process::Command::new("git")
1412
            .arg("-C")
1413
            .arg(&git_dir)
1414
            .args(args)
1415
            .output()
1416
            .unwrap();
1417
        assert!(
1418
            out.status.success(),
1419
            "{}",
1420
            String::from_utf8_lossy(&out.stderr)
1421
        );
79ab8528 Andy McCall ↶ 1422
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1423
    };
1424
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
1425
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
1426
    assert_eq!(git(&["show", "main:README.md"]), "hello");
1427
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 1428
    assert!(
1429
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
1430
        "{body}"
1431
    );
79ab8528 Andy McCall ↶ 1432
    assert!(body.contains("Change-Id: "), "{body}");
75167672 Andy McCall 1433
    assert_eq!(
1434
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
1435
        "Ada Lovelace <[email protected]>"
1436
    );
1437
    assert_eq!(
1438
        git(&["ls-tree", "--name-only", "main"]),
1439
        "README.md\nlogo.png\nsrc"
1440
    );
79ab8528 Andy McCall ↶ 1441
1442
    // Re-export is incremental.
1443
    let rep = repo.git_export(&git_dir).unwrap();
1444
    assert_eq!((rep.exported, rep.skipped), (0, 2));
1445
1446
    // An independent change makes two heads; the next state is one more
1447
    // commit on the linear branch whose tree is the union.
1448
    repo.checkout(&[h1], false, "checkout").unwrap();
1449
    write(&r, "other.txt", b"o\n");
1450
    let h3 = repo.commit("third", &[]).unwrap();
1451
    let rep = repo.git_export(&git_dir).unwrap();
1452
    assert_eq!((rep.exported, rep.heads), (1, 2));
1453
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
1454
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
1455
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
1456
    assert_eq!(git(&["show", "main:other.txt"]), "o");
1457
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
75167672 Andy McCall 1458
    assert_eq!(
1459
        git(&["ls-tree", "--name-only", "main"]),
1460
        "README.md\nlogo.png\nother.txt\nsrc"
1461
    );
79ab8528 Andy McCall ↶ 1462
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 1463
    assert!(
1464
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
1465
        "{body}"
1466
    );
79ab8528 Andy McCall ↶ 1467
    // A rewrite is a new state whose one new change is the rewritten one.
1468
    repo.describe(&h3, "third, described").unwrap();
1469
    let rep = repo.git_export(&git_dir).unwrap();
1470
    assert_eq!(rep.exported, 1);
75167672 Andy McCall 1471
    assert_eq!(
1472
        git(&["log", "-1", "--format=%s", "main"]),
1473
        "third, described"
1474
    );
79ab8528 Andy McCall ↶ 1475
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
1476
    let _ = h2;
1477
}
c3069537 Andy McCall ↶ 1478
1479
#[test]
1480
fn git_import_reproduces_trees() {
c3d2ef61 Andy McCall ↶ 1481
    git_import_reproduces_trees_with(None);
1482
}
1483
1484
/// The same import with every merge rendered in batches of one file
1485
/// (oxygen#25): what a merge onto a base of thousands of files takes.
1486
#[test]
1487
fn git_import_reproduces_trees_in_batches() {
1488
    git_import_reproduces_trees_with(Some(1));
1489
}
1490
1491
fn git_import_reproduces_trees_with(batch: Option<usize>) {
1492
    crate::repo::git::set_merge_batch_for_tests(batch);
c3069537 Andy McCall ↶ 1493
    hermetic();
75167672 Andy McCall 1494
    if std::process::Command::new("git")
1495
        .arg("--version")
1496
        .output()
1497
        .is_err()
1498
    {
c3069537 Andy McCall ↶ 1499
        eprintln!("git not installed; skipping");
1500
        return;
1501
    }
1502
    let dir = tempfile::tempdir().unwrap();
1503
    let root = dir.path();
1504
    let g = root.join("src.git");
1505
    fs::create_dir_all(&g).unwrap();
1506
    let git = |args: &[&str]| -> String {
1507
        let out = std::process::Command::new("git")
1508
            .arg("-C")
1509
            .arg(&g)
75167672 Andy McCall 1510
            .args([
1511
                "-c",
1512
                "user.name=Grace",
1513
                "-c",
1514
                "[email protected]",
1515
                "-c",
1516
                "commit.gpgsign=false",
1517
            ])
c3069537 Andy McCall ↶ 1518
            .args(args)
1519
            .output()
1520
            .unwrap();
75167672 Andy McCall 1521
        assert!(
1522
            out.status.success(),
1523
            "git {args:?}: {}",
1524
            String::from_utf8_lossy(&out.stderr)
1525
        );
c3069537 Andy McCall ↶ 1526
        String::from_utf8_lossy(&out.stdout).trim().to_string()
1527
    };
1528
    git(&["init", "-q", "-b", "main"]);
1529
    write(&g, "README.md", b"# Hi\n");
1530
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
1531
    git(&["add", "."]);
1532
    git(&["commit", "-q", "-m", "initial"]);
1533
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
1534
    write(&g, "run.sh", b"#!/bin/sh\n");
1535
    #[cfg(unix)]
1536
    {
1537
        use std::os::unix::fs::PermissionsExt;
1538
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1539
    }
1540
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
1541
    git(&["add", "."]);
75167672 Andy McCall 1542
    git(&[
1543
        "commit",
1544
        "-q",
1545
        "-m",
1546
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
1547
    ]);
c3069537 Andy McCall ↶ 1548
    // A branch that edits README, merged back with a conflict-free merge.
1549
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
1550
    write(&g, "README.md", b"# Hi\n\nMore.\n");
1551
    git(&["commit", "-q", "-am", "readme"]);
1552
    git(&["checkout", "-q", "main"]);
1553
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
1554
    // A branch from the initial commit inserting at the same place as
1555
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
1556
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
1557
    git(&["checkout", "-q", "-b", "clash", &initial]);
1558
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
1559
    git(&["commit", "-q", "-am", "clash"]);
1560
    git(&["checkout", "-q", "main"]);
7df9007b Andy McCall ↶ 1561
    // Expected to stop at the conflict, so its status is ignored; the
1562
    // identity is passed as for every other git call here, or a machine
1563
    // without one refuses to start the merge at all.
75167672 Andy McCall 1564
    let _ = std::process::Command::new("git")
1565
        .arg("-C")
1566
        .arg(&g)
7df9007b Andy McCall ↶ 1567
        .args([
1568
            "-c",
1569
            "user.name=Grace",
1570
            "-c",
1571
            "[email protected]",
1572
            "merge",
1573
            "-q",
1574
            "clash",
1575
        ])
75167672 Andy McCall 1576
        .output();
7df9007b Andy McCall ↶ 1577
    assert!(
1578
        g.join(".git/MERGE_HEAD").exists(),
1579
        "the clash merge stopped at its conflict"
1580
    );
75167672 Andy McCall 1581
    write(
1582
        &g,
1583
        "src/lib.rs",
1584
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
1585
    );
c3069537 Andy McCall ↶ 1586
    git(&["add", "."]);
1587
    git(&["commit", "-q", "-m", "resolve clash"]);
1588
    git(&["rm", "-q", "logo.png"]);
1589
    git(&["commit", "-q", "-m", "drop logo"]);
6e723b81 Andy McCall ↶ 1590
    // A rename with a small edit is imported as a move of the same node.
1591
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
75167672 Andy McCall 1592
    write(
1593
        &g,
1594
        "src/lib2.rs",
1595
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
1596
    );
6e723b81 Andy McCall ↶ 1597
    git(&["add", "."]);
1598
    git(&["commit", "-q", "-m", "rename lib"]);
958fb27d Andy McCall ↶ 1599
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
1600
    // run.sh is the same as in the first parent's tree, but the merged
1601
    // change touched it, so the importer must compare it, not skip it.
1602
    git(&["checkout", "-q", "-b", "discarded"]);
1603
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
1604
    git(&["commit", "-q", "-am", "discarded edit"]);
1605
    git(&["checkout", "-q", "main"]);
314db9b4 Andy McCall ↶ 1606
    git(&[
1607
        "merge",
1608
        "-q",
1609
        "-s",
1610
        "ours",
1611
        "-m",
1612
        "merge discarded, keeping ours",
1613
        "discarded",
1614
    ]);
c3069537 Andy McCall ↶ 1615
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
1616
1617
    let dest = root.join("oxy");
1618
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
1619
    let rep = repo.import_git(&g, "main").unwrap();
1620
    assert_eq!(rep.commits, expected_count);
958fb27d Andy McCall ↶ 1621
    assert_eq!(rep.merges, 3);
314db9b4 Andy McCall ↶ 1622
    assert_eq!(
1623
        fs::read(dest.join("run.sh")).unwrap(),
1624
        b"#!/bin/sh\n",
1625
        "the ours merge kept main's run.sh"
1626
    );
958fb27d Andy McCall ↶ 1627
    let v = repo.verify_git_import(&g, "main").unwrap();
1628
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
1629
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
c3069537 Andy McCall ↶ 1630
    // The working copy equals the Git tree at main.
75167672 Andy McCall 1631
    assert_eq!(
1632
        fs::read(dest.join("src/lib2.rs")).unwrap(),
1633
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1634
    );
6e723b81 Andy McCall ↶ 1635
    assert!(!dest.join("src/lib.rs").exists());
75167672 Andy McCall 1636
    assert_eq!(
1637
        fs::read(dest.join("README.md")).unwrap(),
1638
        b"# Hi\n\nMore.\n"
1639
    );
c3069537 Andy McCall ↶ 1640
    assert!(!dest.join("logo.png").exists());
1641
    #[cfg(unix)]
1642
    {
1643
        use std::os::unix::fs::PermissionsExt;
75167672 Andy McCall 1644
        assert!(
1645
            fs::metadata(dest.join("run.sh"))
1646
                .unwrap()
1647
                .permissions()
1648
                .mode()
1649
                & 0o111
1650
                != 0
1651
        );
c3069537 Andy McCall ↶ 1652
    }
75167672 Andy McCall 1653
    assert!(
1654
        !repo.snapshot("status").unwrap().changed,
1655
        "clean after import"
1656
    );
c3069537 Andy McCall ↶ 1657
    let heads = repo.bookmark_heads().unwrap();
1658
    let st = repo.load_state(&heads).unwrap();
1659
    assert!(!st.materialize().is_conflicted());
1660
    assert_eq!(st.len(), expected_count);
75167672 Andy McCall 1661
    let tip = repo
1662
        .log()
1663
        .unwrap()
1664
        .into_iter()
1665
        .find(|e| e.change.message.starts_with("rename lib"))
1666
        .unwrap();
6e723b81 Andy McCall ↶ 1667
    let c = repo.store().get_change(&tip.hash).unwrap();
75167672 Andy McCall 1668
    assert!(
1669
        c.tree_ops
1670
            .iter()
1671
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
1672
        "{:?}",
1673
        c.tree_ops
1674
    );
1675
    assert!(!c
1676
        .tree_ops
1677
        .iter()
1678
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
c3069537 Andy McCall ↶ 1679
    // Messages carry Git trailers; the Change-Id trailer was honoured.
1680
    let log = repo.log().unwrap();
75167672 Andy McCall 1681
    let second = log
1682
        .iter()
1683
        .find(|e| e.change.message.starts_with("second"))
1684
        .unwrap();
1685
    assert_eq!(
1686
        second.change.change_id,
1687
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
1688
    );
1689
    assert!(second
1690
        .change
1691
        .message
1692
        .contains("Git-Author: Grace <[email protected]>"));
1693
    let resolve = log
1694
        .iter()
1695
        .find(|e| e.change.message.starts_with("resolve clash"))
1696
        .unwrap();
1697
    assert_eq!(
1698
        resolve.change.kind,
1699
        ChangeKind::Resolution,
1700
        "a conflicting Git merge becomes a resolution"
1701
    );
c3069537 Andy McCall ↶ 1702
    // Re-importing into another fresh repository gives the same ChangeIds.
75167672 Andy McCall 1703
    let repo2 = Repo::init(&root.join("oxy2"))
1704
        .unwrap()
1705
        .with_home(root.join("home"));
c3069537 Andy McCall ↶ 1706
    repo2.import_git(&g, "main").unwrap();
dfb23a3a Andy McCall ↶ 1707
    // New nodes' identifiers derive from the commit (spec §23), so the
1708
    // re-import is not just the same ChangeIds but the same changes.
1709
    assert_eq!(
1710
        repo2.bookmark_heads().unwrap(),
1711
        repo.bookmark_heads().unwrap()
1712
    );
75167672 Andy McCall 1713
    let ids: BTreeSet<ChangeId> = repo
1714
        .log()
1715
        .unwrap()
1716
        .iter()
1717
        .filter(|e| !e.is_working_copy)
1718
        .map(|e| e.change.change_id)
1719
        .collect();
1720
    let ids2: BTreeSet<ChangeId> = repo2
1721
        .log()
1722
        .unwrap()
1723
        .iter()
1724
        .filter(|e| !e.is_working_copy)
1725
        .map(|e| e.change.change_id)
1726
        .collect();
c3069537 Andy McCall ↶ 1727
    assert_eq!(ids, ids2);
1728
    // Round trip back out to Git reproduces the tip tree.
1729
    let mirror = root.join("mirror.git");
1730
    repo.git_export(&mirror).unwrap();
75167672 Andy McCall 1731
    let out = std::process::Command::new("git")
1732
        .arg("-C")
1733
        .arg(&mirror)
1734
        .args(["show", "main:src/lib2.rs"])
1735
        .output()
1736
        .unwrap();
1737
    assert_eq!(
1738
        String::from_utf8_lossy(&out.stdout),
1739
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
1740
    );
1741
    let out = std::process::Command::new("git")
1742
        .arg("-C")
1743
        .arg(&mirror)
1744
        .args(["show", "main:src/lib.rs"])
1745
        .output()
1746
        .unwrap();
1747
    assert!(
1748
        !out.status.success(),
1749
        "the old path is gone from the export"
1750
    );
c3069537 Andy McCall ↶ 1751
}
252e8cb2 Andy McCall ↶ 1752
1753
#[test]
1754
fn checkpoints_accelerate_loading_and_stay_correct() {
1755
    hermetic();
1756
    let dir = tempfile::tempdir().unwrap();
1757
    let root = dir.path();
1758
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
1759
    repo.config.set("core.checkpoint-interval", "5").unwrap();
1760
    repo.save_config().unwrap();
1761
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
1762
    let mut hashes = Vec::new();
1763
    for i in 0..12 {
75167672 Andy McCall 1764
        write(
1765
            root,
1766
            "a.txt",
1767
            format!(
1768
                "{}\n",
1769
                (0..=i)
1770
                    .map(|k| k.to_string())
1771
                    .collect::<Vec<_>>()
1772
                    .join("\n")
1773
            )
1774
            .as_bytes(),
1775
        );
252e8cb2 Andy McCall ↶ 1776
        write(root, &format!("f{i}.txt"), b"x\n");
1777
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
1778
    }
75167672 Andy McCall 1779
    let (_, cp) = repo
1780
        .latest_checkpoint("main")
1781
        .unwrap()
1782
        .expect("automatic checkpoint");
252e8cb2 Andy McCall ↶ 1783
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
1784
    // Loading through the checkpoint equals loading everything.
1785
    let heads = repo.bookmark_heads().unwrap();
1786
    let fast = repo.load_state(&heads).unwrap();
1787
    let full = repo.load_state_full(&heads).unwrap();
1788
    assert_eq!(fast.len(), full.len());
1789
    assert_eq!(fast.heads(), full.heads());
1790
    let (a, b) = (fast.materialize(), full.materialize());
75167672 Andy McCall 1791
    assert_eq!(
1792
        a.files.keys().collect::<Vec<_>>(),
1793
        b.files.keys().collect::<Vec<_>>()
1794
    );
252e8cb2 Andy McCall ↶ 1795
    for (p, f) in &a.files {
1796
        assert_eq!(f.content, b.files[p].content, "{p}");
1797
    }
1798
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
1799
    // A head set that does not contain the checkpoint's heads falls back.
75167672 Andy McCall 1800
    assert!(repo
1801
        .load_state_checkpointed(&[hashes[0]])
1802
        .unwrap()
1803
        .is_none());
252e8cb2 Andy McCall ↶ 1804
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
1805
    // Everything else keeps working on top of the checkpoint.
1806
    assert!(!repo.snapshot("status").unwrap().changed);
1807
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
1808
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
1809
    let (r, n, bytes) = repo.checkpoint().unwrap();
1810
    assert!(n >= 12 && bytes > 0);
1811
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
1812
    write(root, "a.txt", b"after\n");
1813
    let h_after = repo.commit("after", &[]).unwrap();
1814
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
1815
    assert!(st.contains(&h_after));
75167672 Andy McCall 1816
    assert!(
1817
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
1818
    );
252e8cb2 Andy McCall ↶ 1819
    assert_eq!(repo.log().unwrap().len(), 14);
1820
    // Checkpoints survive gc.
1821
    repo.gc(true).unwrap();
1822
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
75167672 Andy McCall 1823
    assert!(repo
1824
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
1825
        .unwrap()
1826
        .is_some());
252e8cb2 Andy McCall ↶ 1827
}
135212de Andy McCall ↶ 1828
1829
#[test]
1830
fn quick_status_for_prompts() {
1831
    hermetic();
1832
    let dir = tempfile::tempdir().unwrap();
1833
    let root = dir.path();
1834
    let origin = Repo::init(&root.join("origin")).unwrap();
1835
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 1836
    let a = Repo::clone(&url, &root.join("a"))
1837
        .unwrap()
1838
        .with_home(root.join("home"));
135212de Andy McCall ↶ 1839
    let ops_before = a.op_log().unwrap().len();
1840
    let info = a.quick_status().unwrap();
75167672 Andy McCall 1841
    assert_eq!(
1842
        (
1843
            info.bookmark.as_str(),
1844
            info.heads,
1845
            info.dirty,
1846
            info.conflicted,
1847
            info.ahead,
1848
            info.behind
1849
        ),
1850
        ("main", 0, false, false, Some(0), Some(0))
1851
    );
135212de Andy McCall ↶ 1852
    write(&root.join("a"), "f.txt", b"f\n");
1853
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
75167672 Andy McCall 1854
    assert_eq!(
1855
        a.op_log().unwrap().len(),
1856
        ops_before,
1857
        "quick_status records nothing"
1858
    );
135212de Andy McCall ↶ 1859
    // A snapshotted but uncommitted change is still dirty.
1860
    a.snapshot("status").unwrap();
1861
    assert!(a.quick_status().unwrap().dirty);
1862
    a.commit("f", &[]).unwrap();
1863
    let info = a.quick_status().unwrap();
1864
    assert!(!info.dirty, "clean right after a commit");
1865
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
75167672 Andy McCall 1866
    assert_eq!(
1867
        info.format("%b %c%d%x%A%D"),
1868
        format!("main {}+1", info.change_id)
1869
    );
135212de Andy McCall ↶ 1870
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
1871
    // Touching a file without changing it is not dirty; changing content of
1872
    // the same size is.
1873
    let p = root.join("a/f.txt");
1874
    let content = fs::read(&p).unwrap();
1875
    fs::write(&p, &content).unwrap();
1876
    assert!(!a.quick_status().unwrap().dirty);
1877
    fs::write(&p, b"g\n").unwrap();
1878
    assert!(a.quick_status().unwrap().dirty);
1879
    fs::write(&p, b"f\n").unwrap();
1880
    // Push, then a second clone commits and pushes: we are behind.
1881
    assert!(a.push("origin", false).unwrap()[0].ok);
1882
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
75167672 Andy McCall 1883
    let b = Repo::clone(&url, &root.join("b"))
1884
        .unwrap()
1885
        .with_home(root.join("home-b"));
135212de Andy McCall ↶ 1886
    write(&root.join("b"), "g.txt", b"g\n");
1887
    b.commit("g", &[]).unwrap();
1888
    b.push("origin", false).unwrap();
1889
    a.fetch("origin").unwrap();
1890
    let info = a.quick_status().unwrap();
1891
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
1892
    assert_eq!(info.format("%A%D"), "-1");
1893
    let _ = origin;
1894
}
b3c5a59a Andy McCall ↶ 1895
1896
#[test]
1897
fn lazy_blobs_are_fetched_on_first_read() {
1898
    hermetic();
1899
    let dir = tempfile::tempdir().unwrap();
1900
    let root = dir.path();
1901
    let origin_dir = root.join("origin");
75167672 Andy McCall 1902
    let origin = Repo::init(&origin_dir)
1903
        .unwrap()
1904
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 1905
    let url = origin_dir.to_string_lossy().to_string();
1906
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
1907
    write(&origin_dir, "big.bin", &big);
1908
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
1909
    write(&origin_dir, "t.txt", b"t\n");
1910
    let h = origin.commit("blobs", &[]).unwrap();
1911
    let big_ref = Repo::blob_ref(&big);
1912
1913
    // Fetch only (no checkout) with a filter: the big blob stays absent.
75167672 Andy McCall 1914
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
1915
        .unwrap()
1916
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 1917
    let a = {
1918
        let mut a = a;
1919
        a.config.set("remote.origin.url", &url).unwrap();
1920
        a.config.set("filter.max-blob", "100K").unwrap();
1921
        a.save_config().unwrap();
1922
        a
1923
    };
1924
    assert_eq!(a.config.max_blob, Some(100 * 1024));
1925
    a.fetch("origin").unwrap();
1926
    assert!(a.store().has(&h));
1927
    assert!(!a.store().has(&big_ref), "withheld");
75167672 Andy McCall 1928
    assert!(
1929
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
1930
        "small blob came along"
1931
    );
b3c5a59a Andy McCall ↶ 1932
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
1933
1934
    // status and commit do not need it: adopt the state, edit a text file, commit.
1935
    let (op_ref, op) = a.head_op().unwrap();
1936
    let mut view = op.view.clone();
75167672 Andy McCall 1937
    view.bookmarks.insert(
1938
        "main".into(),
1939
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
1940
    );
b3c5a59a Andy McCall ↶ 1941
    a.record_op(&[op_ref], "adopt", view).unwrap();
1942
    // Checkout reads the blob lazily, which fetches it.
1943
    a.checkout(&[h], true, "checkout").unwrap();
1944
    assert!(a.store().has(&big_ref), "fetched on first read");
1945
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
1946
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
1947
    write(&root.join("a"), "t.txt", b"t2\n");
1948
    a.commit("text edit", &[]).unwrap();
1949
1950
    // clone --max-blob records the filter; the checkout fetches lazily.
7421309f Andy McCall ↶ 1951
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
b3c5a59a Andy McCall ↶ 1952
    assert_eq!(b.config.max_blob, Some(1024));
1953
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
1954
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
1955
    assert!(parse_size("lots").is_err());
1956
}
7421309f Andy McCall ↶ 1957
1958
#[test]
1959
fn sparse_checkout_materializes_only_chosen_paths() {
1960
    hermetic();
1961
    let dir = tempfile::tempdir().unwrap();
1962
    let root = dir.path();
1963
    let origin_dir = root.join("origin");
75167672 Andy McCall 1964
    let origin = Repo::init(&origin_dir)
1965
        .unwrap()
1966
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 1967
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
1968
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
1969
    write(&origin_dir, "docs/guide.md", b"# guide\n");
1970
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
1971
    write(&origin_dir, "docs/logo.png", &logo);
1972
    write(&origin_dir, "README.md", b"# top\n");
1973
    let h1 = origin.commit("tree", &[]).unwrap();
1974
    let url = origin_dir.to_string_lossy().to_string();
1975
75167672 Andy McCall 1976
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
1977
        .unwrap()
1978
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 1979
    assert_eq!(a.config.sparse_paths, vec!["src"]);
1980
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
1981
    assert!(root.join("a/src/main.rs").exists());
1982
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
75167672 Andy McCall 1983
    assert!(
1984
        !a.store().has(&Repo::blob_ref(&logo)),
1985
        "out-of-scope blob never fetched"
1986
    );
1987
    assert!(
1988
        !a.snapshot("status").unwrap().changed,
1989
        "out-of-scope files are not removals"
1990
    );
05e71ed6 Andy McCall ↶ 1991
    assert!(!a.quick_status().unwrap().dirty);
7421309f Andy McCall ↶ 1992
1993
    // Edits in scope commit normally and keep the rest of the tree intact.
75167672 Andy McCall 1994
    write(
1995
        &root.join("a"),
1996
        "src/lib.rs",
1997
        b"pub fn a() {}\npub fn b() {}\n",
1998
    );
7421309f Andy McCall ↶ 1999
    let h2 = a.commit("edit lib", &[]).unwrap();
2000
    let st = a.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 2001
    assert!(
2002
        st.files.contains_key("docs/guide.md"),
2003
        "the state still has everything"
2004
    );
7421309f Andy McCall ↶ 2005
    assert!(a.push("origin", false).unwrap()[0].ok);
2006
    // Files created outside the scope are ignored by status.
2007
    write(&root.join("a"), "docs/new.md", b"ignored\n");
2008
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
2009
2010
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
2011
    let mut a = a;
2012
    a.config.set("filter.paths", "src,docs").unwrap();
2013
    a.save_config().unwrap();
75167672 Andy McCall 2014
    let r = a
2015
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
2016
        .unwrap();
7421309f Andy McCall ↶ 2017
    assert!(r.written >= 2);
75167672 Andy McCall 2018
    assert_eq!(
2019
        fs::read(root.join("a/docs/logo.png")).unwrap(),
2020
        logo,
2021
        "now fetched lazily"
2022
    );
7421309f Andy McCall ↶ 2023
    assert!(!root.join("a/README.md").exists());
2024
    // Origin sees the change made under a sparse checkout with the full tree intact.
2025
    origin.pull("origin").err();
75167672 Andy McCall 2026
    let full = origin
2027
        .load_state(&origin.bookmark_heads().unwrap())
2028
        .unwrap()
2029
        .materialize();
2030
    assert!(
2031
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
2032
    );
7421309f Andy McCall ↶ 2033
    assert!(full.files.contains_key("README.md"));
2034
    let _ = h1;
2035
}
2863456a Andy McCall ↶ 2036
2037
#[test]
2038
fn shallow_clone_and_deepen() {
2039
    hermetic();
2040
    let dir = tempfile::tempdir().unwrap();
2041
    let root = dir.path();
2042
    let origin_dir = root.join("origin");
75167672 Andy McCall 2043
    let origin = Repo::init(&origin_dir)
2044
        .unwrap()
2045
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2046
    let mut hashes = Vec::new();
2047
    for i in 0..8 {
75167672 Andy McCall 2048
        write(
2049
            &origin_dir,
2050
            "a.txt",
2051
            format!(
2052
                "{}\n",
2053
                (0..=i)
2054
                    .map(|k| k.to_string())
2055
                    .collect::<Vec<_>>()
2056
                    .join("\n")
2057
            )
2058
            .as_bytes(),
2059
        );
2863456a Andy McCall ↶ 2060
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
2061
    }
2062
    let url = origin_dir.to_string_lossy().to_string();
75167672 Andy McCall 2063
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
2064
        .unwrap()
2065
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 2066
    assert!(a.is_shallow());
75167672 Andy McCall 2067
    assert_eq!(
2068
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
2069
        "0\n1\n2\n3\n4\n5\n6\n7\n"
2070
    );
2071
    assert!(
2072
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
2073
        "three levels present"
2074
    );
2863456a Andy McCall ↶ 2075
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
2076
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
75167672 Andy McCall 2077
    assert_eq!(
2078
        a.log().unwrap().len(),
2079
        9,
2080
        "the log shows every change from the checkpoint's metadata"
2081
    );
2863456a Andy McCall ↶ 2082
    assert!(!a.snapshot("status").unwrap().changed);
2083
    assert_eq!(a.quick_status().unwrap().heads, 1);
2084
2085
    // Work continues on top of the shallow history and pushes back.
2086
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
2087
    let h_new = a.commit("c8", &[]).unwrap();
2088
    assert!(a.push("origin", false).unwrap()[0].ok);
2089
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
2090
    // Fetching new work from origin into the shallow clone works too.
2091
    write(&origin_dir, "b.txt", b"b\n");
2092
    origin.pull("origin").err();
2093
    let (_, wc) = origin.working_copy().unwrap();
2094
    let _ = wc;
75167672 Andy McCall 2095
    origin
2096
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
2097
        .unwrap();
2863456a Andy McCall ↶ 2098
    write(&origin_dir, "b.txt", b"b\n");
2099
    let h_b = origin.commit("b", &[]).unwrap();
2100
    let pr = a.pull("origin").unwrap();
2101
    assert!(pr.changed);
2102
    assert!(a.store().has(&h_b));
2103
    assert!(root.join("a/b.txt").exists());
2104
2105
    // Deepening fetches older history until the boundary is gone.
2106
    // Every commit also depends on the change that created the file, so two
2107
    // levels below the boundary hold h4, h3, and the root.
2108
    assert!(a.deepen("origin", 2).unwrap() >= 2);
2109
    assert!(a.store().has(&hashes[3]));
2110
    assert!(a.is_shallow());
2111
    a.deepen("origin", 100).unwrap();
2112
    assert!(!a.is_shallow(), "boundary reached the root");
2113
    assert!(a.store().has(&hashes[0]));
75167672 Andy McCall 2114
    assert_eq!(
2115
        a.load_state_full(&a.bookmark_heads().unwrap())
2116
            .unwrap()
2117
            .len(),
2118
        10
2119
    );
2863456a Andy McCall ↶ 2120
}
132b884b Andy McCall ↶ 2121
2122
#[test]
2123
fn tags_are_immutable_named_states_and_travel() {
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 mut a = Repo::clone(&url, &root.join("a"))
2130
        .unwrap()
2131
        .with_home(root.join("home-a"));
2132
    let (key_a, _) = a
2133
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2134
        .unwrap();
132b884b Andy McCall ↶ 2135
    write(&root.join("a"), "f.txt", b"1\n");
2136
    let h1 = a.commit("one", &[]).unwrap();
2137
    write(&root.join("a"), "f.txt", b"1\n2\n");
2138
    let h2 = a.commit("two", &[]).unwrap();
2139
2140
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
75167672 Andy McCall 2141
    assert_eq!(
2142
        (t.heads.clone(), t.signer.as_deref()),
2143
        (vec![h1], Some("Ada"))
2144
    );
132b884b Andy McCall ↶ 2145
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
2146
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
2147
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
2148
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
2149
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
2150
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
2151
    assert_eq!(sa.sigs[0].key, key_a);
2152
    // Checkout by tag.
75167672 Andy McCall 2153
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
2154
        .unwrap();
132b884b Andy McCall ↶ 2155
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
75167672 Andy McCall 2156
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
2157
        .unwrap();
132b884b Andy McCall ↶ 2158
2159
    // Push carries the tag; a second attestation for the name is refused.
2160
    let r = a.push("origin", false).unwrap();
2161
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
2162
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
75167672 Andy McCall 2163
    let mut forged = a
2164
        .tag_refs()
2165
        .unwrap()
2166
        .into_iter()
2167
        .find(|t| t.name == "v1")
2168
        .unwrap();
2169
    forged.state = origin
2170
        .store()
2171
        .put_state(&StateObject::new(vec![h2]))
2172
        .unwrap();
132b884b Andy McCall ↶ 2173
    forged.heads = vec![h2];
2174
    forged.attestation = None;
75167672 Andy McCall 2175
    let r = origin
2176
        .receive_push(Bundle::default(), vec![], None, vec![forged])
2177
        .unwrap();
132b884b Andy McCall ↶ 2178
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
2179
2180
    // A clone gets the tag; a later tag arrives on fetch.
75167672 Andy McCall 2181
    let b = Repo::clone(&url, &root.join("b"))
2182
        .unwrap()
2183
        .with_home(root.join("home-b"));
132b884b Andy McCall ↶ 2184
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
2185
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
2186
    a.tag_create("v2", &[h2], "second").unwrap();
2187
    a.push("origin", false).unwrap();
2188
    let rep = b.fetch("origin").unwrap();
2189
    assert_eq!(rep.new_tags, 1);
2190
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
2191
2192
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
2193
    a.policy_init().unwrap();
2194
    a.push("origin", false).unwrap();
75167672 Andy McCall 2195
    let unattested = crate::protocol::TagRef {
2196
        name: "v3".into(),
2197
        state: origin
2198
            .store()
2199
            .put_state(&StateObject::new(vec![h2]))
2200
            .unwrap(),
2201
        heads: vec![h2],
2202
        attestation: None,
2203
    };
2204
    let r = origin
2205
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
2206
        .unwrap();
132b884b Andy McCall ↶ 2207
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
2208
    a.tag_create("v3", &[h2], "").unwrap();
2209
    let r = a.push("origin", false).unwrap();
2210
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
2211
    assert!(a.gc(true).is_ok());
2212
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
2213
}
4e88e774 Andy McCall ↶ 2214
2215
#[test]
2216
fn multiple_workspaces_share_a_repository() {
2217
    hermetic();
2218
    let dir = tempfile::tempdir().unwrap();
2219
    let root = dir.path();
2220
    let main_dir = root.join("main");
2221
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
2222
    write(&main_dir, "a.txt", b"a\n");
2223
    let h1 = repo.commit("a", &[]).unwrap();
2224
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2225
2226
    // A second workspace elsewhere, checked out on the bookmark.
2227
    let ws_dir = root.join("ws2");
2228
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
2229
    assert!(ws_dir.join(".oxy").is_file());
2230
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
2231
    assert_ne!(ws.workspace(), repo.workspace());
2232
    let list = repo.workspaces().unwrap();
2233
    assert_eq!(list.len(), 2);
75167672 Andy McCall 2234
    assert!(list
2235
        .iter()
2236
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
4e88e774 Andy McCall ↶ 2237
    assert!(!ws.snapshot("status").unwrap().changed);
2238
2239
    // Work in the second workspace: its own working copy, shared bookmark.
2240
    write(&ws_dir, "b.txt", b"b\n");
2241
    let s = ws.snapshot("status").unwrap();
2242
    assert_eq!(s.statuses.len(), 1);
75167672 Andy McCall 2243
    assert!(
2244
        !repo.snapshot("status").unwrap().changed,
2245
        "the first workspace is untouched"
2246
    );
4e88e774 Andy McCall ↶ 2247
    let h2 = ws.commit("b from ws2", &[]).unwrap();
2248
    let mut heads = repo.bookmark_heads().unwrap();
2249
    heads.sort();
2250
    let mut want = vec![h1, h2];
2251
    want.sort();
2252
    assert_eq!(heads, want, "both workspaces see the bookmark move");
2253
    assert!(!main_dir.join("b.txt").exists());
75167672 Andy McCall 2254
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
2255
        .unwrap();
4e88e774 Andy McCall ↶ 2256
    assert!(main_dir.join("b.txt").exists());
2257
2258
    // Reopening from inside the second workspace finds the shared repository.
2259
    let reopened = Repo::open(&ws_dir).unwrap();
2260
    assert_eq!(reopened.workspace(), ws.workspace());
2261
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
2262
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
2263
2264
    // Workspaces cannot nest; forget drops one from the view but keeps files.
2265
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
2266
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
2267
    repo.workspace_forget(&ws.workspace()).unwrap();
2268
    assert_eq!(repo.workspaces().unwrap().len(), 1);
2269
    assert!(ws_dir.join("b.txt").exists());
75167672 Andy McCall 2270
    assert!(
2271
        ws.snapshot("status").is_err(),
2272
        "a forgotten workspace is no longer in the view"
2273
    );
4e88e774 Andy McCall ↶ 2274
6caacfff Andy McCall ↶ 2275
    // The working-copy lock: re-entrant in a thread; a lock whose process
2276
    // is gone is taken over, and a live process's is not, however old.
4e88e774 Andy McCall ↶ 2277
    let lock = repo.lock_snapshot().unwrap();
6caacfff Andy McCall ↶ 2278
    let again = repo.lock_working_copy().unwrap();
2279
    drop(again);
4e88e774 Andy McCall ↶ 2280
    drop(lock);
75167672 Andy McCall 2281
    let lock_path = main_dir
2282
        .join(".oxy/workspaces")
2283
        .join(repo.workspace().to_hex())
2284
        .join("lock");
4e88e774 Andy McCall ↶ 2285
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
6caacfff Andy McCall ↶ 2286
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
2287
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
2288
    age(&lock_path);
2289
    assert!(
2290
        !super::workspace::lock_is_stale(&lock_path),
2291
        "a live process keeps its lock"
2292
    );
2293
    fs::write(&lock_path, "4294967295").unwrap();
2294
    age(&lock_path);
4e88e774 Andy McCall ↶ 2295
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
2296
}
cdb5beba Andy McCall ↶ 2297
2298
#[test]
2299
fn attributes_binary_eol_nocompress_lockable() {
2300
    hermetic();
2301
    let dir = tempfile::tempdir().unwrap();
2302
    let root = dir.path();
2303
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2304
    write(
2305
        root,
2306
        ".oxyattributes",
2307
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
2308
    );
cdb5beba Andy McCall ↶ 2309
    write(root, "plain.dat", b"no nul bytes here\n");
2310
    write(root, "notes.txt", b"one\r\ntwo\r\n");
2311
    write(root, "assets/model.bin", b"\0model");
2312
    let h = repo.commit("attrs", &[]).unwrap();
2313
    let snap = repo.load_state(&[h]).unwrap().materialize();
75167672 Andy McCall 2314
    assert!(
2315
        snap.files["plain.dat"].mode.opaque,
2316
        "binary attribute forces opaque without NUL bytes"
2317
    );
2318
    assert!(
2319
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
2320
        "stored with LF"
2321
    );
2322
    assert!(
2323
        !repo.snapshot("status").unwrap().changed,
2324
        "CRLF on disk equals LF in the state"
2325
    );
cdb5beba Andy McCall ↶ 2326
    // nocompress chunks pack raw.
2327
    let r = repo.gc(true).unwrap();
2328
    assert!(r.packed.objects > 0);
2329
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
2330
    fs::remove_file(root.join("notes.txt")).unwrap();
2331
    repo.checkout(&[h], true, "co").unwrap();
2332
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
75167672 Andy McCall 2333
    assert!(fs::metadata(root.join("assets/model.bin"))
2334
        .unwrap()
2335
        .permissions()
2336
        .readonly());
cdb5beba Andy McCall ↶ 2337
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
2338
    repo.lock_path("assets/model.bin").unwrap();
75167672 Andy McCall 2339
    assert!(!fs::metadata(root.join("assets/model.bin"))
2340
        .unwrap()
2341
        .permissions()
2342
        .readonly());
cdb5beba Andy McCall ↶ 2343
    assert!(repo.is_locked("assets/model.bin"));
2344
    write(root, "assets/model.bin", b"\0model2");
2345
    repo.commit("edit model", &[]).unwrap();
2346
    repo.unlock_path("assets/model.bin").unwrap();
75167672 Andy McCall 2347
    assert!(fs::metadata(root.join("assets/model.bin"))
2348
        .unwrap()
2349
        .permissions()
2350
        .readonly());
cdb5beba Andy McCall ↶ 2351
    // A later checkout can still overwrite a read-only lockable file.
2352
    repo.checkout(&[h], true, "co").unwrap();
2353
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
2354
}
6d3eefbc Andy McCall ↶ 2355
2356
#[cfg(unix)]
2357
#[test]
2358
fn hooks_can_veto_observe_and_add_dependencies() {
2359
    use std::os::unix::fs::PermissionsExt;
2360
    hermetic();
2361
    let dir = tempfile::tempdir().unwrap();
2362
    let root = dir.path();
2363
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2364
    let hooks = root.join(".oxy/hooks");
2365
    fs::create_dir_all(&hooks).unwrap();
2366
    let hook = |name: &str, body: &str| {
2367
        let p = hooks.join(name);
2368
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
2369
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
2370
    };
2371
    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");
2372
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
2373
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
2374
    hook("pre-push", "echo pushing blocked >&2; exit 3");
2375
    write(root, ".oxyignore", b".last-*\n");
2376
    write(root, "a.txt", b"a\n");
2377
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
2378
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
2379
    let h1 = repo.commit("first", &[]).unwrap();
2380
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
75167672 Andy McCall 2381
    assert!(
2382
        pre.contains("\"event\":\"pre-commit\"")
2383
            && pre.contains("\"path\":\"a.txt\"")
2384
            && pre.contains("\"message\":\"first\""),
2385
        "{pre}"
2386
    );
6d3eefbc Andy McCall ↶ 2387
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
2388
    assert!(post.contains(&h1.to_hex()), "{post}");
2389
    repo.checkout(&[h1], false, "co").unwrap();
75167672 Andy McCall 2390
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
2391
        .unwrap()
2392
        .contains("post-checkout"));
6d3eefbc Andy McCall ↶ 2393
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
2394
    repo.save_config().unwrap();
2395
    let err = repo.push("origin", false).unwrap_err().to_string();
2396
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
2397
2398
    // semantic-deps: only when enabled; adds an explicit dependency.
2399
    write(root, "b.txt", b"b\n");
75167672 Andy McCall 2400
    hook(
2401
        "semantic-deps",
2402
        &format!(
2403
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
2404
            h1.to_hex()
2405
        ),
2406
    );
6d3eefbc Andy McCall ↶ 2407
    let h2 = repo.commit("b without hook", &[]).unwrap();
75167672 Andy McCall 2408
    assert!(
2409
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
2410
        "hook disabled by default"
2411
    );
6d3eefbc Andy McCall ↶ 2412
    repo.config.set("hooks.semantic-deps", "true").unwrap();
2413
    repo.save_config().unwrap();
2414
    write(root, "c.txt", b"c\n");
2415
    let h3 = repo.commit("c with hook", &[]).unwrap();
2416
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2417
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
75167672 Andy McCall 2418
    assert!(
2419
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
2420
        "{sem}"
2421
    );
6d3eefbc Andy McCall ↶ 2422
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
2423
}
23b217d7 Andy McCall ↶ 2424
2425
#[test]
2426
fn amend_into_older_change_and_split() {
2427
    hermetic();
2428
    let dir = tempfile::tempdir().unwrap();
2429
    let root = dir.path();
2430
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2431
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2432
        .unwrap();
23b217d7 Andy McCall ↶ 2433
    repo.set_user_config("core.sign", "change").unwrap();
2434
    write(root, "a.txt", b"one\ntwo\n");
2435
    let h0 = repo.commit("base", &[]).unwrap();
2436
    write(root, "a.txt", b"one\nTWO\n");
2437
    let h1 = repo.commit("edit two", &[]).unwrap();
2438
    write(root, "a.txt", b"one\nTWO\nthree\n");
2439
    let h2 = repo.commit("add three", &[]).unwrap();
2440
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
2441
2442
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
2443
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2444
    let h1b = repo.amend_into(&h1, None).unwrap();
2445
    assert_ne!(h1b, h1);
2446
    let c1b = repo.store().get_change(&h1b).unwrap();
2447
    assert_eq!(c1b.change_id, id1);
2448
    assert_eq!(c1b.deps, vec![h0]);
75167672 Andy McCall 2449
    assert!(matches!(
2450
        repo.verify_change(&h1b).unwrap(),
2451
        SignatureStatus::Valid { .. }
2452
    ));
23b217d7 Andy McCall ↶ 2453
    let heads = repo.bookmark_heads().unwrap();
2454
    assert_eq!(heads.len(), 1);
2455
    let top = repo.store().get_change(&heads[0]).unwrap();
2456
    assert_eq!(top.message, "add three");
75167672 Andy McCall 2457
    assert_eq!(
2458
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
2459
        [h0, h1b].into_iter().collect(),
2460
        "depends on the file's creator and the rewritten line"
2461
    );
23b217d7 Andy McCall ↶ 2462
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 2463
    assert!(
2464
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
2465
    );
2466
    assert!(
2467
        !repo.snapshot("status").unwrap().changed,
2468
        "the working copy is clean after folding"
2469
    );
23b217d7 Andy McCall ↶ 2470
    // Only h1b's own state shows the fix without "three".
2471
    let only = repo.load_state(&[h1b]).unwrap().materialize();
75167672 Andy McCall 2472
    assert!(
2473
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
2474
    );
23b217d7 Andy McCall ↶ 2475
    assert_eq!(repo.log().unwrap().len(), 4);
2476
2477
    // An edit to a line introduced by h2 cannot fold into h1.
2478
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
2479
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
2480
    assert!(err.contains("introduced after"), "{err}");
75167672 Andy McCall 2481
    assert!(
2482
        repo.snapshot("status").unwrap().statuses.len() == 1,
2483
        "nothing was changed by the refusal"
2484
    );
23b217d7 Andy McCall ↶ 2485
    write(root, "a.txt", b"one\nTWO!\nthree\n");
2486
2487
    // Split the head that touches two files.
2488
    write(root, "b.txt", b"b\n");
2489
    write(root, "c.txt", b"c\n");
2490
    let h3 = repo.commit("b and c", &[]).unwrap();
2491
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
2492
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
2493
    let c_1 = repo.store().get_change(&p1).unwrap();
2494
    let c_2 = repo.store().get_change(&p2).unwrap();
2495
    assert!(c_1.message.contains("part 1: b.txt"));
2496
    assert_eq!(c_2.change_id, id3);
2497
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
75167672 Andy McCall 2498
    assert!(
2499
        heads.contains(&p1) && heads.contains(&p2),
2500
        "independent parts are both heads"
2501
    );
2502
    let snap = repo
2503
        .load_state(&repo.bookmark_heads().unwrap())
2504
        .unwrap()
2505
        .materialize();
23b217d7 Andy McCall ↶ 2506
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
2507
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
2508
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
2509
    assert!(!repo.snapshot("status").unwrap().changed);
2510
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
2511
    let _ = h2;
2512
}
28fc23d7 Andy McCall ↶ 2513
2514
#[test]
2515
fn identity_lifecycle() {
2516
    hermetic();
2517
    let dir = tempfile::tempdir().unwrap();
2518
    let root = dir.path();
2519
    let origin = Repo::init(&root.join("origin")).unwrap();
2520
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 2521
    let mut a = Repo::clone(&url, &root.join("a"))
2522
        .unwrap()
2523
        .with_home(root.join("home-a"));
28fc23d7 Andy McCall ↶ 2524
    a.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 2525
    let (key_a, _) = a
2526
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2527
        .unwrap();
28fc23d7 Andy McCall ↶ 2528
    write(&root.join("a"), "a.txt", b"a\n");
2529
    let h1 = a.commit("one", &[]).unwrap();
2530
    assert!(a.policy_init().unwrap().applied);
2531
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2532
2533
    // Expiry: an identity that had expired when the change was made does not authenticate it.
75167672 Andy McCall 2534
    let mut e = Repo::init(&root.join("e"))
2535
        .unwrap()
2536
        .with_home(root.join("home-e"));
28fc23d7 Andy McCall ↶ 2537
    e.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 2538
    e.create_identity_with(
2539
        "Eve",
2540
        "[email protected]",
2541
        IdentityScope::User,
2542
        Some(Hlc::now().wall_ms - 1),
2543
    )
2544
    .unwrap();
28fc23d7 Andy McCall ↶ 2545
    write(&root.join("e"), "e.txt", b"e\n");
2546
    let he = e.commit("late", &[]).unwrap();
75167672 Andy McCall 2547
    assert!(
2548
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
2549
    );
28fc23d7 Andy McCall ↶ 2550
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
75167672 Andy McCall 2551
    let r = e
2552
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
2553
        .unwrap();
28fc23d7 Andy McCall ↶ 2554
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
2555
    write(&root.join("e"), "e.txt", b"e2\n");
2556
    let he2 = e.commit("in time", &[]).unwrap();
75167672 Andy McCall 2557
    assert!(
2558
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
2559
    );
28fc23d7 Andy McCall ↶ 2560
2561
    // Rotation: a fresh key; the old change still verifies; the policy follows.
2562
    let r = a.rotate_identity().unwrap();
2563
    assert_eq!(r.old, key_a);
2564
    assert_eq!(a.config.author_key, Some(r.new));
2565
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
2566
    assert!(r.policy.as_ref().unwrap().applied);
2567
    let (_, sp) = a.current_policy().unwrap().unwrap();
75167672 Andy McCall 2568
    assert_eq!(
2569
        (sp.policy.serial, sp.policy.roots.clone()),
2570
        (2, vec![r.new])
2571
    );
2572
    assert!(
2573
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
2574
        "superseded, not revoked"
2575
    );
28fc23d7 Andy McCall ↶ 2576
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
75167672 Andy McCall 2577
    assert!(
2578
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
2579
    );
28fc23d7 Andy McCall ↶ 2580
    write(&root.join("a"), "a.txt", b"a2\n");
2581
    let h2 = a.commit("two", &[]).unwrap();
75167672 Andy McCall 2582
    assert!(
2583
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
2584
    );
28fc23d7 Andy McCall ↶ 2585
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
2586
    let res = a.push("origin", false).unwrap();
2587
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2588
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
2589
    let key_a = r.new;
2590
2591
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
2592
    // identity object, so Ada's KeyId changes while her keys stay the same.
75167672 Andy McCall 2593
    let mut b = Repo::clone(&url, &root.join("b"))
2594
        .unwrap()
2595
        .with_home(root.join("home-b"));
2596
    let (key_b, id_b) = b
2597
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2598
        .unwrap();
7ba155f2 Andy McCall ↶ 2599
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
28fc23d7 Andy McCall ↶ 2600
    assert_eq!(r.old, key_a);
2601
    let key_a2 = r.new;
75167672 Andy McCall 2602
    assert_eq!(
7ba155f2 Andy McCall ↶ 2603
        a.identity(&key_a2).unwrap().delegates,
2604
        vec![Delegate::full(key_b)]
2605
    );
2606
    assert_eq!(
75167672 Andy McCall 2607
        a.identity(&key_a2).unwrap().ed25519_pk,
2608
        a.identity(&key_a).unwrap().ed25519_pk
7ba155f2 Andy McCall ↶ 2609
    );
2610
    assert!(
2611
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
2612
        "already a delegate"
75167672 Andy McCall 2613
    );
28fc23d7 Andy McCall ↶ 2614
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2615
    write(&root.join("a"), "a.txt", b"a3\n");
2616
    let h3 = a.commit("three", &[]).unwrap();
75167672 Andy McCall 2617
    assert!(
2618
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
2619
        "the same secret signs under the new KeyId"
2620
    );
28fc23d7 Andy McCall ↶ 2621
    // A change authored by Ada but signed only by Bob verifies through the delegation.
2622
    a.set_user_config("core.sign", "seal").unwrap();
2623
    write(&root.join("a"), "a.txt", b"a4\n");
2624
    let h4 = a.commit("four", &[]).unwrap();
2625
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
2626
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 2627
    a.store()
2628
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
2629
        .unwrap();
2630
    assert!(
2631
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
2632
    );
28fc23d7 Andy McCall ↶ 2633
    a.set_user_config("core.sign", "change").unwrap();
2634
    // Withdrawing the delegation re-issues the identity again.
2635
    let r = a.delegate_remove(&key_b).unwrap();
2636
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
2637
    assert!(a.delegate_remove(&key_b).is_err());
2638
    let key_a3 = r.new;
2639
    let res = a.push("origin", false).unwrap();
2640
    assert!(res.iter().all(|x| x.ok), "{res:?}");
2641
2642
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
2643
    // both applied under the old threshold of 1. A grant then needs Bob too.
2644
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
2645
    assert!(a.policy_root_add(id_b.clone()).is_err());
2646
    assert!(a.policy_set_threshold(3).is_err());
2647
    assert!(a.policy_set_threshold(2).unwrap().applied);
2648
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
2649
    b.pull("origin").unwrap();
75167672 Andy McCall 2650
    assert_eq!(
2651
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
2652
        2
2653
    );
2654
    let mut c = Repo::init(&root.join("c"))
2655
        .unwrap()
2656
        .with_home(root.join("home-c"));
2657
    let (key_c, id_c) = c
2658
        .create_identity("Cy", "[email protected]", IdentityScope::User)
2659
        .unwrap();
28fc23d7 Andy McCall ↶ 2660
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
2661
    let proposal = a.policy_grant(id_c, None).unwrap();
2662
    assert!(!proposal.applied && proposal.sigs.len() == 1);
2663
    assert_eq!(proposal.policy.serial, serial_before + 1);
75167672 Andy McCall 2664
    assert_eq!(
2665
        a.current_policy().unwrap().unwrap().1.policy.serial,
2666
        serial_before,
2667
        "a proposal changes nothing yet"
2668
    );
28fc23d7 Andy McCall ↶ 2669
    // Bob signs the proposal, handed over as a file, and it applies for him.
2670
    let bytes = proposal.signed().encode();
75167672 Andy McCall 2671
    let signed = b
2672
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
2673
        .unwrap();
28fc23d7 Andy McCall ↶ 2674
    assert!(signed.applied && signed.sigs.len() == 2);
75167672 Andy McCall 2675
    assert!(b
2676
        .current_policy()
2677
        .unwrap()
2678
        .unwrap()
2679
        .1
2680
        .policy
2681
        .authorizes(&key_c, "main"));
2682
    assert!(
2683
        b.policy_sign(signed.signed()).is_err(),
2684
        "a stale proposal is refused"
2685
    );
28fc23d7 Andy McCall ↶ 2686
    // Bob publishes it and Ada picks it up.
75167672 Andy McCall 2687
    assert!(b
2688
        .push("origin", false)
2689
        .unwrap()
2690
        .iter()
2691
        .any(|x| x.name == "policy" && x.ok));
28fc23d7 Andy McCall ↶ 2692
    a.pull("origin").unwrap();
75167672 Andy McCall 2693
    assert_eq!(
2694
        a.current_policy().unwrap().unwrap().1.policy.serial,
2695
        serial_before + 1
2696
    );
28fc23d7 Andy McCall ↶ 2697
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
2698
    assert!(a.policy_revoke(&key_a3).is_err());
75167672 Andy McCall 2699
    let u = a
2700
        .revoke_identity(&key_c, "left the project")
2701
        .unwrap()
2702
        .unwrap();
28fc23d7 Andy McCall ↶ 2703
    assert!(!u.applied);
2704
    assert!(a.is_revoked(&key_c).unwrap());
2705
    assert!(!b.is_revoked(&key_c).unwrap());
2706
    let u = b.policy_sign(u.signed()).unwrap();
2707
    assert!(u.applied && u.policy.is_revoked(&key_c));
2708
    assert!(b.is_revoked(&key_c).unwrap());
2709
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
75167672 Andy McCall 2710
    assert!(
2711
        b.policy_revoke(&key_a3).is_err(),
2712
        "would leave one root for a threshold of 2"
2713
    );
28fc23d7 Andy McCall ↶ 2714
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
2715
    let key_c_own = c.config.author_key.unwrap();
75167672 Andy McCall 2716
    assert!(c
2717
        .revoke_identity(&key_c_own, "lost laptop")
2718
        .unwrap()
2719
        .is_none());
28fc23d7 Andy McCall ↶ 2720
    assert!(c.is_revoked(&key_c_own).unwrap());
2721
    assert_eq!(key_c_own, key_c);
2722
}
2723
6e723b81 Andy McCall ↶ 2724
#[test]
2725
fn renames_are_detected_and_tracked_as_moves() {
2726
    hermetic();
2727
    let dir = tempfile::tempdir().unwrap();
2728
    let root = dir.path();
2729
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2730
    write(
2731
        root,
2732
        "src/old.rs",
2733
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
2734
    );
6e723b81 Andy McCall ↶ 2735
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
2736
    write(root, "tiny.txt", b"x\n");
2737
    let h1 = repo.commit("base", &[]).unwrap();
2738
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
2739
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
2740
2741
    // Rename with a small edit, a binary moved unchanged, and a rewrite
2742
    // that shares nothing with the removed file.
2743
    fs::remove_file(root.join("src/old.rs")).unwrap();
75167672 Andy McCall 2744
    write(
2745
        root,
2746
        "lib/new.rs",
2747
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
2748
    );
6e723b81 Andy McCall ↶ 2749
    fs::remove_file(root.join("img.bin")).unwrap();
2750
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
2751
    fs::remove_file(root.join("tiny.txt")).unwrap();
2752
    write(root, "other.txt", b"completely different\n");
2753
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 2754
    let statuses: Vec<(&str, ChangeStatus)> = snap
2755
        .statuses
2756
        .iter()
2757
        .map(|s| (s.path.as_str(), s.status))
2758
        .collect();
6e723b81 Andy McCall ↶ 2759
    assert_eq!(
2760
        statuses,
75167672 Andy McCall 2761
        vec![
2762
            ("assets/img.bin", ChangeStatus::Renamed),
2763
            ("lib/new.rs", ChangeStatus::Renamed),
2764
            ("other.txt", ChangeStatus::Added),
2765
            ("src", ChangeStatus::Removed),
2766
            ("tiny.txt", ChangeStatus::Removed)
2767
        ]
6e723b81 Andy McCall ↶ 2768
    );
2769
    let h2 = repo.commit("move things", &[]).unwrap();
2770
    let c = repo.store().get_change(&h2).unwrap();
75167672 Andy McCall 2771
    let moves: Vec<_> = c
2772
        .tree_ops
2773
        .iter()
2774
        .filter(|op| matches!(op, TreeOp::Move { .. }))
2775
        .collect();
6e723b81 Andy McCall ↶ 2776
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
75167672 Andy McCall 2777
    assert!(c.tree_ops.iter().any(
2778
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
2779
    ));
2780
    assert!(c.tree_ops.iter().any(
2781
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
2782
    ));
6e723b81 Andy McCall ↶ 2783
    let snap = repo.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 2784
    assert_eq!(
2785
        snap.files["lib/new.rs"].node, node_old,
2786
        "the node survives the rename"
2787
    );
2788
    assert!(
2789
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
2790
    );
6e723b81 Andy McCall ↶ 2791
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
75167672 Andy McCall 2792
    assert!(render_change(
2793
        &c,
2794
        &repo.load_state(&[h1]).unwrap(),
2795
        &repo.load_state(&[h1]).unwrap().materialize()
2796
    )
0912a033 Andy McCall ↶ 2797
    .contains("R src/old.rs -> lib/new.rs"));
6e723b81 Andy McCall ↶ 2798
    // A fresh checkout reproduces the tree.
2799
    let other = tempfile::tempdir().unwrap();
2800
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
75167672 Andy McCall 2801
    assert_eq!(
2802
        fs::read(other.path().join("lib/new.rs")).unwrap(),
2803
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
2804
    );
6e723b81 Andy McCall ↶ 2805
    assert!(!other.path().join("src").exists());
2806
    assert!(!clone.snapshot("status").unwrap().changed);
2807
    // Similarity is line based, byte weighted.
2808
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
2809
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
2810
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
2811
    assert_eq!(similarity(b"", b"x\n"), 0);
2812
}
2813
30ea9c1e Andy McCall ↶ 2814
#[test]
2815
fn git_fetch_and_push_round_trip() {
2816
    hermetic();
75167672 Andy McCall 2817
    if std::process::Command::new("git")
2818
        .arg("--version")
2819
        .output()
2820
        .is_err()
2821
    {
30ea9c1e Andy McCall ↶ 2822
        eprintln!("git not installed; skipping");
2823
        return;
2824
    }
2825
    let dir = tempfile::tempdir().unwrap();
2826
    let root = dir.path();
2827
    let git_in = |d: &Path, args: &[&str]| -> String {
2828
        let out = std::process::Command::new("git")
2829
            .arg("-C")
2830
            .arg(d)
75167672 Andy McCall 2831
            .args([
2832
                "-c",
2833
                "user.name=Grace",
2834
                "-c",
2835
                "[email protected]",
2836
                "-c",
2837
                "commit.gpgsign=false",
2838
            ])
30ea9c1e Andy McCall ↶ 2839
            .args(args)
2840
            .output()
2841
            .unwrap();
75167672 Andy McCall 2842
        assert!(
2843
            out.status.success(),
2844
            "git {args:?}: {}",
2845
            String::from_utf8_lossy(&out.stderr)
2846
        );
30ea9c1e Andy McCall ↶ 2847
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2848
    };
2849
    // A bare "remote" and a work tree that pushes to it.
2850
    let remote = root.join("remote.git");
2851
    fs::create_dir_all(&remote).unwrap();
2852
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
2853
    let work = root.join("work");
75167672 Andy McCall 2854
    git_in(
2855
        root,
2856
        &[
2857
            "clone",
2858
            "-q",
2859
            remote.to_str().unwrap(),
2860
            work.to_str().unwrap(),
2861
        ],
2862
    );
30ea9c1e Andy McCall ↶ 2863
    git_in(&work, &["checkout", "-q", "-b", "main"]);
2864
    write(&work, "README.md", b"# Project\n");
2865
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
2866
    git_in(&work, &["add", "."]);
2867
    git_in(&work, &["commit", "-q", "-m", "initial"]);
2868
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2869
    git_in(&work, &["commit", "-q", "-am", "second"]);
2870
    git_in(&work, &["push", "-q", "origin", "main"]);
2871
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
2872
2873
    // Fetch into a fresh oxy repository.
2874
    let o = root.join("oxy");
2875
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2876
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
2877
        .unwrap();
30ea9c1e Andy McCall ↶ 2878
    let url = remote.to_string_lossy().to_string();
2879
    let r = repo.git_fetch(&url, "main").unwrap();
2880
    assert_eq!((r.commits, r.heads), (2, 1));
75167672 Andy McCall 2881
    assert_eq!(
2882
        fs::read(o.join("src/lib.rs")).unwrap(),
2883
        b"pub fn a() {}\npub fn b() {}\n"
2884
    );
30ea9c1e Andy McCall ↶ 2885
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 2886
    assert_eq!(
2887
        repo.git_fetch(&url, "main").unwrap().commits,
2888
        0,
2889
        "nothing new"
2890
    );
30ea9c1e Andy McCall ↶ 2891
2892
    // An oxy change, pushed back: one commit on top of the Git tip.
75167672 Andy McCall 2893
    write(
2894
        &o,
2895
        "src/lib.rs",
2896
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2897
    );
30ea9c1e Andy McCall ↶ 2898
    write(&o, "NOTES.md", b"from oxy\n");
2899
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
2900
    let r = repo.git_push(&url, "main").unwrap();
2901
    assert_eq!(r.exported, 1, "{r:?}");
2902
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
75167672 Andy McCall 2903
    assert_eq!(
2904
        git_in(&work, &["log", "--format=%s", "main"]),
2905
        "add c and notes\nsecond\ninitial"
2906
    );
30ea9c1e Andy McCall ↶ 2907
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
2908
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
2909
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
75167672 Andy McCall 2910
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
2911
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
2912
    assert_eq!(
2913
        repo.git_push(&url, "main").unwrap().exported,
2914
        0,
2915
        "already pushed"
2916
    );
30ea9c1e Andy McCall ↶ 2917
2918
    // Git moves on; pushing without fetching is refused, fetching brings
2919
    // the commit in and the working copy follows.
2920
    write(&work, "README.md", b"# Project\n\nMore.\n");
2921
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
2922
    git_in(&work, &["push", "-q", "origin", "main"]);
2923
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
75167672 Andy McCall 2924
    assert!(repo
2925
        .git_push(&url, "main")
2926
        .unwrap_err()
2927
        .to_string()
2928
        .contains("fetch"));
30ea9c1e Andy McCall ↶ 2929
    let r = repo.git_fetch(&url, "main").unwrap();
75167672 Andy McCall 2930
    assert_eq!(
2931
        (r.commits, r.heads),
2932
        (1, 2),
2933
        "the Git change and the oxy change commute"
2934
    );
2935
    assert_eq!(
2936
        fs::read(o.join("README.md")).unwrap(),
2937
        b"# Project\n\nMore.\n"
2938
    );
30ea9c1e Andy McCall ↶ 2939
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
2940
    assert!(!repo.snapshot("status").unwrap().changed);
2941
    // Another oxy change pushes on top of Git's newest commit.
2942
    write(&o, "NOTES.md", b"from oxy\nagain\n");
2943
    repo.commit("notes again", &[]).unwrap();
2944
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
2945
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
2946
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
75167672 Andy McCall 2947
    assert_eq!(
2948
        fs::read(work.join("NOTES.md")).unwrap(),
2949
        b"from oxy\nagain\n"
2950
    );
2951
    assert_eq!(
2952
        git_in(&work, &["log", "--format=%s", "main"])
2953
            .lines()
2954
            .count(),
2955
        5
2956
    );
30ea9c1e Andy McCall ↶ 2957
}
2958
2b872d07 Andy McCall ↶ 2959
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
2960
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
2961
#[test]
2962
#[ignore]
2963
fn bench_one_gibibyte_file() {
2964
    hermetic();
2965
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
2966
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
2967
        Some(d) => tempfile::tempdir_in(d).unwrap(),
2968
        None => tempfile::tempdir().unwrap(),
2969
    };
2970
    let root = dir.path();
75167672 Andy McCall 2971
    let repo = Repo::init(&root.join("r"))
2972
        .unwrap()
2973
        .with_home(root.join("home"));
2b872d07 Andy McCall ↶ 2974
    let size = 1usize << 30;
2975
    let mut data = vec![0u8; size];
2976
    let mut x = 0x9e3779b97f4a7c15u64;
2977
    for chunk in data.chunks_mut(8) {
2978
        x ^= x << 13;
2979
        x ^= x >> 7;
2980
        x ^= x << 17;
2981
        let b = x.to_le_bytes();
2982
        chunk.copy_from_slice(&b[..chunk.len()]);
2983
    }
2984
    let t = std::time::Instant::now();
2985
    write(&root.join("r"), "big.bin", &data);
2986
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
2987
    let t = std::time::Instant::now();
2988
    let h = repo.commit("big", &[]).unwrap();
2989
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
2990
    let t = std::time::Instant::now();
2991
    assert!(!repo.snapshot("status").unwrap().changed);
2992
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
2993
    let t = std::time::Instant::now();
2994
    let objects = repo.store().list().unwrap().len();
2995
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
2996
    let t = std::time::Instant::now();
2997
    let g = repo.gc(true).unwrap();
2998
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
2999
    let t = std::time::Instant::now();
3000
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
3001
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
3002
    let t = std::time::Instant::now();
3003
    let back = fs::read(root.join("c/big.bin")).unwrap();
3004
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
3005
    eprintln!("read back and verify: {:.2?}", t.elapsed());
3006
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
3007
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
75167672 Andy McCall 3008
    eprintln!(
3009
        "store size: {:.1} MiB for 1 GiB of data",
3010
        store_bytes as f64 / (1024.0 * 1024.0)
3011
    );
2b872d07 Andy McCall ↶ 3012
}
3013
3014
fn walkdir_size(p: &Path) -> u64 {
3015
    let mut total = 0;
3016
    if let Ok(rd) = fs::read_dir(p) {
3017
        for e in rd.flatten() {
3018
            let path = e.path();
3019
            if path.is_dir() {
3020
                total += walkdir_size(&path);
3021
            } else if let Ok(m) = fs::metadata(&path) {
3022
                total += m.len();
3023
            }
3024
        }
3025
    }
3026
    total
3027
}
3028
b7f102fc Andy McCall ↶ 3029
/// An opaque file whose size and mtime match the manifest is not read on
3030
/// the next snapshot: its blob comes from the manifest's stat cache.
3031
#[cfg(unix)]
3032
#[test]
3033
fn stat_cache_skips_reading_unchanged_opaque_files() {
3034
    use std::os::unix::fs::PermissionsExt;
3035
    hermetic();
3036
    let dir = tempfile::tempdir().unwrap();
3037
    let root = dir.path();
3038
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3039
    let mut big = vec![0u8; 300 * 1024];
3040
    for (i, b) in big.iter_mut().enumerate() {
3041
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
3042
    }
3043
    big[0] = 0;
3044
    write(root, "big.bin", &big);
3045
    write(root, "a.txt", b"text\n");
3046
    let h1 = repo.commit("base", &[]).unwrap();
3047
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
75167672 Andy McCall 3048
    assert!(
3049
        m.entries["big.bin"].blob.is_some(),
3050
        "opaque files record their blob"
3051
    );
b7f102fc Andy McCall ↶ 3052
    assert!(m.entries["a.txt"].blob.is_none());
3053
    let blob = m.entries["big.bin"].blob.unwrap();
3054
    assert!(repo.store().has(&blob));
3055
3056
    // Files modified within two seconds of the manifest are racy and still
3057
    // read; age the file so the cache applies, then snapshot to record it.
3058
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
75167672 Andy McCall 3059
    fs::File::options()
3060
        .write(true)
3061
        .open(root.join("big.bin"))
3062
        .unwrap()
3063
        .set_modified(old)
3064
        .unwrap();
b7f102fc Andy McCall ↶ 3065
    assert!(!repo.snapshot("status").unwrap().changed);
3066
    // Now the file cannot be read at all; the snapshot succeeds without it.
3067
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
3068
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3069
    assert!(
3070
        !snap.changed && snap.statuses.is_empty(),
3071
        "{:?}",
3072
        snap.statuses
3073
    );
b7f102fc Andy McCall ↶ 3074
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
3075
    // A real change (new mtime, new content) is seen and committed correctly.
3076
    let mut big2 = big.clone();
3077
    big2[10] ^= 0xff;
3078
    write(root, "big.bin", &big2);
3079
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3080
    assert_eq!(
3081
        snap.statuses
3082
            .iter()
3083
            .map(|s| (s.path.as_str(), s.status))
3084
            .collect::<Vec<_>>(),
3085
        vec![("big.bin", ChangeStatus::Modified)]
3086
    );
b7f102fc Andy McCall ↶ 3087
    let h2 = repo.commit("edit", &[]).unwrap();
3088
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 3089
    assert_eq!(
3090
        files["big.bin"].content,
3091
        FileContent::Opaque {
3092
            blobs: vec![Repo::blob_ref(&big2)]
3093
        }
3094
    );
b7f102fc Andy McCall ↶ 3095
    // Checkout writes a manifest with blobs too, so the next status is cached.
3096
    repo.checkout(&[h1], false, "checkout").unwrap();
3097
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
3098
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
3099
    assert!(!repo.snapshot("status").unwrap().changed);
3100
}
3101
50a046e4 Andy McCall ↶ 3102
#[test]
3103
fn status_json_lists_conflicts_with_contributors() {
3104
    hermetic();
3105
    let dir = tempfile::tempdir().unwrap();
3106
    let root = dir.path();
3107
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3108
    write(root, "a.txt", b"one\n");
3109
    let h1 = repo.commit("base", &[]).unwrap();
3110
    write(root, "a.txt", b"one\nleft\n");
3111
    let ha = repo.commit("left", &[]).unwrap();
3112
    repo.checkout(&[h1], true, "checkout").unwrap();
3113
    write(root, "a.txt", b"one\nright\n");
3114
    let hb = repo.commit("right", &[]).unwrap();
3115
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
3116
    let snap = repo.snapshot("status").unwrap();
3117
    assert!(snap.base_snapshot.is_conflicted());
3118
    let json = repo.status_json(&snap).unwrap();
3119
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
3120
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
3121
    assert!(json.contains("\"conflicted\":true"), "{json}");
75167672 Andy McCall 3122
    assert!(
3123
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
3124
        "{json}"
3125
    );
50a046e4 Andy McCall ↶ 3126
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
3127
    assert!(json.contains("\"resolved\":false"), "{json}");
3128
    assert!(json.starts_with('{') && json.ends_with('}'));
3129
    // Resolve and the report says so; a clean copy has no conflicts.
3130
    write(root, "a.txt", b"one\nleft\nright\n");
3131
    let snap = repo.snapshot("status").unwrap();
3132
    let json = repo.status_json(&snap).unwrap();
3133
    assert!(json.contains("\"resolved\":true"), "{json}");
3134
    repo.commit("resolve", &[]).unwrap();
3135
    let snap = repo.snapshot("status").unwrap();
3136
    let json = repo.status_json(&snap).unwrap();
75167672 Andy McCall 3137
    assert!(
3138
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
3139
        "{json}"
3140
    );
50a046e4 Andy McCall ↶ 3141
}
3142
9ac1fbe2 Andy McCall ↶ 3143
#[test]
3144
fn ignore_rules_do_not_untrack_files() {
3145
    hermetic();
3146
    let dir = tempfile::tempdir().unwrap();
3147
    let root = dir.path();
3148
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3149
    write(root, "src.c", b"int x;\n");
3150
    write(root, "build/out.o", b"\0obj");
3151
    write(root, "sub/keep.log", b"keep\n");
3152
    write(root, "sub/junk.log", b"junk\n");
3153
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
3154
    let snap = repo.snapshot("status").unwrap();
3155
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 3156
    assert_eq!(
3157
        added,
3158
        vec![".oxyignore", "src.c", "sub/keep.log"],
3159
        "anchored, glob, and negated rules"
3160
    );
9ac1fbe2 Andy McCall ↶ 3161
    let h1 = repo.commit("base", &[]).unwrap();
3162
    // Ignoring a tracked file changes nothing about it.
3163
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
3164
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3165
    assert_eq!(
3166
        snap.statuses
3167
            .iter()
3168
            .map(|s| s.path.as_str())
3169
            .collect::<Vec<_>>(),
3170
        vec![".oxyignore"]
3171
    );
9ac1fbe2 Andy McCall ↶ 3172
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
75167672 Andy McCall 3173
    assert!(repo
3174
        .load_state(&[h2])
3175
        .unwrap()
3176
        .materialize()
3177
        .files
3178
        .contains_key("src.c"));
9ac1fbe2 Andy McCall ↶ 3179
    // Its edits are still seen, by status and by the prompt.
3180
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
3181
    write(root, "src.c", b"int x, y;\n");
3182
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
3183
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3184
    assert_eq!(
3185
        snap.statuses
3186
            .iter()
3187
            .map(|s| (s.path.as_str(), s.status))
3188
            .collect::<Vec<_>>(),
3189
        vec![("src.c", ChangeStatus::Modified)]
3190
    );
9ac1fbe2 Andy McCall ↶ 3191
    let h3 = repo.commit("edit src.c", &[]).unwrap();
75167672 Andy McCall 3192
    assert!(
3193
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
3194
    );
9ac1fbe2 Andy McCall ↶ 3195
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
3196
    fs::remove_file(root.join("src.c")).unwrap();
3197
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3198
    assert_eq!(
3199
        snap.statuses
3200
            .iter()
3201
            .map(|s| (s.path.as_str(), s.status))
3202
            .collect::<Vec<_>>(),
3203
        vec![("src.c", ChangeStatus::Removed)]
3204
    );
9ac1fbe2 Andy McCall ↶ 3205
    repo.checkout(&[h3], true, "checkout").unwrap();
3206
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
3207
    assert!(!repo.snapshot("status").unwrap().changed);
3208
    let _ = h1;
3209
}
3210
b837d2b5 Andy McCall ↶ 3211
#[test]
3212
fn split_works_on_non_heads_by_node() {
3213
    hermetic();
3214
    let dir = tempfile::tempdir().unwrap();
3215
    let root = dir.path();
3216
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3217
    write(root, "a.txt", b"one\n");
3218
    write(root, "junk/x.lock", b"lock\n");
3219
    let h1 = repo.commit("work plus junk", &[]).unwrap();
3220
    write(root, "a.txt", b"one\ntwo\n");
3221
    let h2 = repo.commit("more work", &[]).unwrap();
3222
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
3223
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3224
    // h1 is not a head: split it by node.
3225
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
3226
    assert_ne!(h1b, h1);
75167672 Andy McCall 3227
    assert_eq!(
3228
        repo.store().get_change(&h1b).unwrap().change_id,
3229
        id1,
3230
        "the rest keeps the ChangeId"
3231
    );
b837d2b5 Andy McCall ↶ 3232
    let junk = repo.store().get_change(&hj).unwrap();
75167672 Andy McCall 3233
    assert!(junk.tree_ops.iter().all(
3234
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
3235
    ));
b837d2b5 Andy McCall ↶ 3236
    let heads = repo.bookmark_heads().unwrap();
75167672 Andy McCall 3237
    assert!(
3238
        heads.contains(&hj),
3239
        "the split-off part is a head of its own"
3240
    );
b837d2b5 Andy McCall ↶ 3241
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 3242
    assert!(
3243
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3244
        "the dependent was rewritten onto the new hash"
3245
    );
b837d2b5 Andy McCall ↶ 3246
    assert!(snap.files.contains_key("junk/x.lock"));
75167672 Andy McCall 3247
    let h2b = heads
3248
        .iter()
3249
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
3250
        .copied()
3251
        .unwrap();
b837d2b5 Andy McCall ↶ 3252
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
3253
    assert!(!repo.snapshot("status").unwrap().changed);
3254
    // Abandoning the split-off head removes the junk from history.
3255
    repo.abandon(&hj).unwrap();
3256
    let heads = repo.bookmark_heads().unwrap();
3257
    let snap = repo.load_state(&heads).unwrap().materialize();
3258
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
3259
    assert!(snap.files.contains_key("a.txt"));
3260
    // A dependent that touches the split-off paths blocks the split.
3261
    write(root, "junk/y.lock", b"y\n");
3262
    let hb = repo.commit("junk base", &[]).unwrap();
3263
    write(root, "junk/y.lock", b"yy\n");
3264
    write(root, "b.txt", b"b\n");
3265
    repo.commit("touches junk", &[]).unwrap();
3266
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
3267
    assert!(err.contains("depends on the split-off paths"), "{err}");
3268
}
3269
7b9809e6 Andy McCall ↶ 3270
#[test]
3271
fn bookmarks_switch_merge_and_push() {
3272
    hermetic();
3273
    let dir = tempfile::tempdir().unwrap();
3274
    let root = dir.path();
3275
    let origin = Repo::init(&root.join("origin")).unwrap();
3276
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3277
    let mut repo = Repo::clone(&url, &root.join("r"))
3278
        .unwrap()
3279
        .with_home(root.join("home"));
7b9809e6 Andy McCall ↶ 3280
    let r = root.join("r");
3281
    write(&r, "a.txt", b"a\n");
3282
    let h_a = repo.commit("a", &[]).unwrap();
3283
    assert!(repo.push("origin", false).unwrap()[0].ok);
3284
3285
    // A bookmark at the working copy's base, then work on it.
3286
    assert!(repo.bookmark_create("bad name..", None).is_err());
3287
    assert!(repo.bookmark_create("-x", None).is_err());
3288
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
3289
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
3290
    repo.bookmark_switch("feature", false).unwrap();
3291
    assert_eq!(repo.config.bookmark, "feature");
3292
    write(&r, "a.txt", b"a\nb\n");
3293
    write(&r, "b.txt", b"b\n");
3294
    let h_b = repo.commit("b on feature", &[]).unwrap();
75167672 Andy McCall 3295
    assert_eq!(
3296
        repo.bookmark_heads().unwrap(),
3297
        vec![h_b],
3298
        "b edits a.txt, so it depends on a"
3299
    );
3300
    assert_eq!(
3301
        repo.resolve_heads("main").unwrap(),
3302
        vec![h_a],
3303
        "main is untouched"
3304
    );
3305
    assert_eq!(
3306
        repo.resolve_change("feature").unwrap(),
3307
        h_b,
3308
        "a one-head bookmark names its change"
3309
    );
7b9809e6 Andy McCall ↶ 3310
    // Reopening keeps the workspace's bookmark.
3311
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
3312
    assert_eq!(reopened.config.bookmark, "feature");
3313
    // Back to main: b.txt goes away; work there.
3314
    repo.bookmark_switch("main", false).unwrap();
3315
    assert!(!r.join("b.txt").exists());
3316
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
3317
    write(&r, "c.txt", b"c\n");
3318
    let h_c = repo.commit("c on main", &[]).unwrap();
3319
    let list = repo.bookmarks().unwrap();
75167672 Andy McCall 3320
    assert_eq!(
3321
        list.iter()
3322
            .map(|b| (b.name.as_str(), b.current))
3323
            .collect::<Vec<_>>(),
3324
        vec![("feature", false), ("main", true)]
3325
    );
3326
    assert_eq!(
3327
        list.iter().find(|b| b.name == "main").unwrap().ahead,
3328
        Some(1),
3329
        "c is not on origin yet"
3330
    );
7b9809e6 Andy McCall ↶ 3331
    // Merge feature into main: the union, both heads, no merge change.
3332
    let m = repo.merge("feature").unwrap();
3333
    assert!(m.changed && m.checked_out);
3334
    let mut want = vec![h_b, h_c];
3335
    want.sort();
3336
    assert_eq!(m.heads, want);
3337
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
3338
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
3339
    assert!(repo.merge("main").is_err());
3340
    // The other bookmark can be pushed by name and appears at origin.
3341
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
3342
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
3343
    assert!(repo.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 3344
    assert_eq!(
3345
        repo.bookmarks()
3346
            .unwrap()
3347
            .iter()
3348
            .find(|b| b.name == "main")
3349
            .unwrap()
3350
            .ahead,
3351
        Some(0)
3352
    );
7b9809e6 Andy McCall ↶ 3353
    // A second workspace inherits the current bookmark and can switch independently.
3354
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
3355
    assert_eq!(ws.config.bookmark, "main");
3356
    let mut ws = ws;
3357
    ws.bookmark_switch("feature", false).unwrap();
75167672 Andy McCall 3358
    assert_eq!(
3359
        Repo::open(&r).unwrap().config.bookmark,
3360
        "main",
3361
        "the first workspace is unaffected"
3362
    );
3363
    assert!(
3364
        repo.bookmark_delete("feature").is_err(),
3365
        "current bookmark of another workspace"
3366
    );
7b9809e6 Andy McCall ↶ 3367
    ws.bookmark_switch("main", false).unwrap();
3368
    // Set and delete.
3369
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
3370
    assert!(repo.bookmark_delete("main").is_err(), "current here");
3371
    repo.bookmark_delete("feature").unwrap();
3372
    assert!(repo.resolve_heads("feature").is_err());
3373
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
75167672 Andy McCall 3374
    assert!(
3375
        repo.checkout(&[h_a], false, "checkout").is_ok(),
3376
        "changes of a deleted bookmark remain"
3377
    );
7b9809e6 Andy McCall ↶ 3378
}
3379
4dee277c Andy McCall ↶ 3380
#[test]
3381
fn oxygen_subrepos_pin_follow_and_update() {
3382
    hermetic();
3383
    let dir = tempfile::tempdir().unwrap();
3384
    let root = dir.path();
3385
    // A library repository with two commits, and a bare-ish origin for it.
3386
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
3387
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
75167672 Andy McCall 3388
    let lib = Repo::clone(&lib_url, &root.join("lib"))
3389
        .unwrap()
3390
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3391
    write(&root.join("lib"), "lib.txt", b"v1\n");
3392
    let l1 = lib.commit("lib v1", &[]).unwrap();
3393
    assert!(lib.push("origin", false).unwrap()[0].ok);
3394
    let _ = lib_origin;
3395
3396
    // The application (a clone of its own origin) adds it as a subrepo.
3397
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
3398
    let app_url = root.join("app-origin").to_string_lossy().to_string();
3399
    let _ = app_origin;
3400
    let app_dir = root.join("app");
75167672 Andy McCall 3401
    let app = Repo::clone(&app_url, &app_dir)
3402
        .unwrap()
3403
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3404
    write(&app_dir, "main.txt", b"app\n");
3405
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
3406
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
3407
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
3408
    let snap = app.snapshot("status").unwrap();
3409
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 3410
    assert_eq!(
3411
        paths,
3412
        vec![".oxymodules", "libs/lib", "main.txt"],
3413
        "the nested files are not walked"
3414
    );
4dee277c Andy McCall ↶ 3415
    let a1 = app.commit("app with lib", &[]).unwrap();
3416
    let files = app.load_state(&[a1]).unwrap().materialize().files;
3417
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
3418
    assert!(!files.contains_key("libs/lib/lib.txt"));
3419
    assert!(!app.snapshot("status").unwrap().changed);
3420
    let subs = app.subrepos().unwrap();
3421
    assert_eq!(subs.len(), 1);
3422
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
3423
3424
    // Advance the nested repository: the parent sees a modified pin.
75167672 Andy McCall 3425
    let nested = Repo::open(&app_dir.join("libs/lib"))
3426
        .unwrap()
3427
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3428
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
3429
    let l2 = nested.commit("lib v2", &[]).unwrap();
3430
    assert!(nested.push("origin", false).unwrap()[0].ok);
3431
    let snap = app.snapshot("status").unwrap();
75167672 Andy McCall 3432
    assert_eq!(
3433
        snap.statuses
3434
            .iter()
3435
            .map(|s| (s.path.as_str(), s.status))
3436
            .collect::<Vec<_>>(),
3437
        vec![("libs/lib", ChangeStatus::Modified)]
3438
    );
4dee277c Andy McCall ↶ 3439
    let a2 = app.commit("bump lib", &[]).unwrap();
1a3b6203 Andy McCall ↶ 3440
    // Checking out the older app state brings the nested working copy back
3441
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4dee277c Andy McCall ↶ 3442
    let r = app.checkout(&[a1], false, "checkout").unwrap();
1a3b6203 Andy McCall ↶ 3443
    assert!(
3444
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
3445
        "{:?}",
3446
        r.notes
3447
    );
4dee277c Andy McCall ↶ 3448
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
1a3b6203 Andy McCall ↶ 3449
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
3450
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
3451
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4dee277c Andy McCall ↶ 3452
    assert!(!app.snapshot("status").unwrap().changed);
3453
    // A dirty nested repository is left alone and reported.
3454
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
3455
    let r = app.checkout(&[a2], false, "checkout").unwrap();
75167672 Andy McCall 3456
    assert!(
3457
        r.notes.iter().any(|n| n.contains("uncommitted")),
3458
        "{:?}",
3459
        r.notes
3460
    );
4dee277c Andy McCall ↶ 3461
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
3462
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
3463
    let r = app.submodule_update(false, &[]).unwrap();
3464
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
3465
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
3466
    let _ = l2;
3467
3468
    // A fresh clone of the app has the pin but no nested repository until update --init.
3469
    assert!(app.push("origin", false).unwrap()[0].ok);
3470
    let clone_dir = root.join("app-clone");
75167672 Andy McCall 3471
    let clone = Repo::clone(&app_url, &clone_dir)
3472
        .unwrap()
3473
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 3474
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
75167672 Andy McCall 3475
    assert_eq!(
3476
        clone.submodule_update(false, &[]).unwrap(),
3477
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
3478
    );
3479
    assert_eq!(
3480
        clone.submodule_update(true, &[]).unwrap(),
3481
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
3482
    );
3483
    assert_eq!(
3484
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
3485
        b"v2\n"
3486
    );
4dee277c Andy McCall ↶ 3487
    assert!(!clone.snapshot("status").unwrap().changed);
3488
    // Removing the subrepo leaves the directory and drops the node.
3489
    clone.submodule_remove("libs/lib").unwrap();
3490
    let snap = clone.snapshot("status").unwrap();
75167672 Andy McCall 3491
    assert!(
3492
        snap.statuses
3493
            .iter()
3494
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
3495
        "{:?}",
3496
        snap.statuses
3497
    );
4dee277c Andy McCall ↶ 3498
    let c = clone.commit("drop lib", &[]).unwrap();
75167672 Andy McCall 3499
    assert!(!clone
3500
        .load_state(&[c])
3501
        .unwrap()
3502
        .materialize()
3503
        .files
3504
        .contains_key("libs/lib"));
4dee277c Andy McCall ↶ 3505
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
75167672 Andy McCall 3506
    assert!(
3507
        !clone.snapshot("status").unwrap().changed,
3508
        "an unregistered nested repository is ignored"
3509
    );
4dee277c Andy McCall ↶ 3510
}
3511
3512
#[test]
3513
fn git_submodules_import_and_export_as_gitlinks() {
3514
    hermetic();
75167672 Andy McCall 3515
    if std::process::Command::new("git")
3516
        .arg("--version")
3517
        .output()
3518
        .is_err()
3519
    {
4dee277c Andy McCall ↶ 3520
        eprintln!("git not installed; skipping");
3521
        return;
3522
    }
3523
    let dir = tempfile::tempdir().unwrap();
3524
    let root = dir.path();
3525
    let git_in = |d: &Path, args: &[&str]| -> String {
3526
        let out = std::process::Command::new("git")
3527
            .arg("-C")
3528
            .arg(d)
75167672 Andy McCall 3529
            .args([
3530
                "-c",
3531
                "user.name=Grace",
3532
                "-c",
3533
                "[email protected]",
3534
                "-c",
3535
                "commit.gpgsign=false",
3536
                "-c",
3537
                "protocol.file.allow=always",
3538
            ])
4dee277c Andy McCall ↶ 3539
            .args(args)
3540
            .output()
3541
            .unwrap();
75167672 Andy McCall 3542
        assert!(
3543
            out.status.success(),
3544
            "git {args:?}: {}",
3545
            String::from_utf8_lossy(&out.stderr)
3546
        );
4dee277c Andy McCall ↶ 3547
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3548
    };
3549
    let sub = root.join("sub");
3550
    fs::create_dir_all(&sub).unwrap();
3551
    git_in(&sub, &["init", "-q", "-b", "main"]);
3552
    write(&sub, "s.txt", b"sub\n");
3553
    git_in(&sub, &["add", "."]);
3554
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
3555
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
3556
    let g = root.join("main.git");
3557
    fs::create_dir_all(&g).unwrap();
3558
    git_in(&g, &["init", "-q", "-b", "main"]);
3559
    write(&g, "README.md", b"# app\n");
3560
    git_in(&g, &["add", "."]);
3561
    git_in(&g, &["commit", "-q", "-m", "initial"]);
75167672 Andy McCall 3562
    git_in(
3563
        &g,
3564
        &[
3565
            "submodule",
3566
            "add",
3567
            "-q",
3568
            sub.to_str().unwrap(),
3569
            "vendor/sub",
3570
        ],
3571
    );
4dee277c Andy McCall ↶ 3572
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
3573
3574
    let dest = root.join("oxy");
3575
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3576
    let rep = repo.import_git(&g, "main").unwrap();
3577
    assert_eq!((rep.commits, rep.submodules), (2, 1));
75167672 Andy McCall 3578
    let files = repo
3579
        .load_state(&repo.bookmark_heads().unwrap())
3580
        .unwrap()
3581
        .materialize()
3582
        .files;
4dee277c Andy McCall ↶ 3583
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
75167672 Andy McCall 3584
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
3585
        panic!()
3586
    };
3587
    assert_eq!(
3588
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
3589
        crate::subrepo::Pin::Git {
3590
            sha: sub_sha.clone(),
3591
            branch: "HEAD".into()
3592
        }
3593
    );
3594
    let modules =
3595
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4dee277c Andy McCall ↶ 3596
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
3597
    assert!(modules.entries["vendor/sub"].git);
75167672 Andy McCall 3598
    assert!(
3599
        files.contains_key(".gitmodules"),
3600
        "the Git file is kept for round trips"
3601
    );
3602
    assert!(
3603
        !dest.join("vendor/sub/.git").exists(),
3604
        "not cloned until update --init"
3605
    );
4dee277c Andy McCall ↶ 3606
    assert!(!repo.snapshot("status").unwrap().changed);
3607
    // update --init clones it at the pinned commit; status is unchanged.
75167672 Andy McCall 3608
    assert_eq!(
3609
        repo.submodule_update(true, &[]).unwrap(),
3610
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
3611
    );
3612
    assert_eq!(
3613
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
3614
        sub_sha
3615
    );
4dee277c Andy McCall ↶ 3616
    assert!(!repo.snapshot("status").unwrap().changed);
3617
    // Export writes the gitlink and .gitmodules back.
3618
    let mirror = root.join("mirror.git");
3619
    let rep = repo.git_export(&mirror).unwrap();
3620
    assert_eq!(rep.skipped_subrepos, 0);
3621
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
75167672 Andy McCall 3622
    assert!(
3623
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
3624
        "{ls}"
3625
    );
3626
    assert_eq!(
3627
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
3628
        ".gitmodules\nREADME.md\nvendor"
3629
    );
4dee277c Andy McCall ↶ 3630
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
75167672 Andy McCall 3631
    assert_eq!(
3632
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
3633
        orig_tree,
3634
        "tree round trip"
3635
    );
4dee277c Andy McCall ↶ 3636
}
3637
957fee30 Andy McCall ↶ 3638
#[test]
3639
fn partial_commits_by_path_and_by_hunk() {
3640
    hermetic();
3641
    let dir = tempfile::tempdir().unwrap();
3642
    let root = dir.path();
3643
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3644
    write(root, "a.txt", b"1\n2\n3\n");
3645
    write(root, "b.txt", b"b\n");
3646
    let h0 = repo.commit("base", &[]).unwrap();
3647
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
3648
    write(root, "b.txt", b"b\nbb\n");
3649
    write(root, "c.txt", b"c\n");
3650
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
75167672 Andy McCall 3651
    let h1 = repo
3652
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
3653
        .unwrap();
957fee30 Andy McCall ↶ 3654
    let c1 = repo.store().get_change(&h1).unwrap();
75167672 Andy McCall 3655
    assert!(
3656
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
3657
        "{:?}",
3658
        c1.tree_ops
3659
    );
957fee30 Andy McCall ↶ 3660
    assert_eq!(c1.deps, vec![h0]);
3661
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
75167672 Andy McCall 3662
    assert!(
3663
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
3664
    );
957fee30 Andy McCall ↶ 3665
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
3666
    assert!(!files.contains_key("c.txt"));
3667
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3668
    assert_eq!(
3669
        snap.statuses
3670
            .iter()
3671
            .map(|s| (s.path.as_str(), s.status))
3672
            .collect::<Vec<_>>(),
3673
        vec![
3674
            ("b.txt", ChangeStatus::Modified),
3675
            ("c.txt", ChangeStatus::Added)
3676
        ]
3677
    );
3678
    assert_eq!(
3679
        fs::read(root.join("b.txt")).unwrap(),
3680
        b"b\nbb\n",
3681
        "disk untouched"
3682
    );
957fee30 Andy McCall ↶ 3683
    // By hunk: pick the b.txt insert; c.txt's addition is left.
3684
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 3685
    let b_hunk = hunks
3686
        .iter()
3687
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
3688
        .unwrap()
3689
        .index;
3690
    let h2 = repo
3691
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
3692
        .unwrap();
957fee30 Andy McCall ↶ 3693
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 3694
    assert!(
3695
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
3696
    );
957fee30 Andy McCall ↶ 3697
    assert!(!files.contains_key("c.txt"));
3698
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 3699
    assert_eq!(
3700
        snap.statuses
3701
            .iter()
3702
            .map(|s| s.path.as_str())
3703
            .collect::<Vec<_>>(),
3704
        vec!["c.txt"]
3705
    );
957fee30 Andy McCall ↶ 3706
    // Choosing only the content hunk of a file in a new directory pulls in
3707
    // the directory and file additions it needs.
3708
    write(root, "d/e.txt", b"e\n");
3709
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 3710
    let e_insert = hunks
3711
        .iter()
3712
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
3713
        .unwrap()
3714
        .index;
3715
    let h3 = repo
3716
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
3717
        .unwrap();
957fee30 Andy McCall ↶ 3718
    let c3 = repo.store().get_change(&h3).unwrap();
3719
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
3720
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
3721
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
d8c086ca Andy McCall ↶ 3722
    // Choosing a new file's addition hunk brings its content along.
3723
    write(root, "f/g.txt", b"g\n");
3724
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 3725
    let g_add = hunks
3726
        .iter()
3727
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
3728
        .unwrap()
3729
        .index;
3730
    let h4 = repo
3731
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
3732
        .unwrap();
d8c086ca Andy McCall ↶ 3733
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
75167672 Andy McCall 3734
    assert!(
3735
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
3736
    );
3737
    assert!(!repo
3738
        .snapshot("status")
3739
        .unwrap()
3740
        .statuses
3741
        .iter()
3742
        .any(|s| s.path == "f/g.txt"));
957fee30 Andy McCall ↶ 3743
    // Everything left commits normally; the working copy is then clean.
3744
    repo.commit("the rest", &[]).unwrap();
3745
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 3746
    let files = repo
3747
        .load_state(&repo.bookmark_heads().unwrap())
3748
        .unwrap()
3749
        .materialize()
3750
        .files;
957fee30 Andy McCall ↶ 3751
    assert!(files.contains_key("c.txt"));
3752
}
3753
3754
#[test]
3755
fn blame_attributes_lines_to_introducing_changes_across_renames() {
3756
    hermetic();
3757
    let dir = tempfile::tempdir().unwrap();
3758
    let root = dir.path();
3759
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3760
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
3761
        .unwrap();
957fee30 Andy McCall ↶ 3762
    write(root, "a.txt", b"one\n");
3763
    let h1 = repo.commit("first", &[]).unwrap();
3764
    write(root, "a.txt", b"one\ntwo\n");
3765
    let h2 = repo.commit("second", &[]).unwrap();
3766
    let b = repo.blame("a.txt").unwrap();
75167672 Andy McCall 3767
    assert_eq!(
3768
        b.iter()
3769
            .map(|l| (l.line, l.hash, l.text.as_slice()))
3770
            .collect::<Vec<_>>(),
3771
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
3772
    );
957fee30 Andy McCall ↶ 3773
    assert!(b.iter().all(|l| l.author == "Ada"));
75167672 Andy McCall 3774
    assert_eq!(
3775
        b[0].change_id,
3776
        repo.store().get_change(&h1).unwrap().change_id
3777
    );
957fee30 Andy McCall ↶ 3778
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
3779
    repo.commit("rename", &[]).unwrap();
3780
    let b = repo.blame("b.txt").unwrap();
75167672 Andy McCall 3781
    assert_eq!(
3782
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
3783
        vec![h1, h2],
3784
        "the node survives the rename"
3785
    );
957fee30 Andy McCall ↶ 3786
    assert!(repo.blame("a.txt").is_err());
3787
}
3788
3789
#[test]
3790
fn bisect_finds_the_first_bad_change() {
3791
    hermetic();
3792
    let dir = tempfile::tempdir().unwrap();
3793
    let root = dir.path();
3794
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3795
    let mut content = String::new();
3796
    let mut hashes = Vec::new();
3797
    for i in 1..=8 {
3798
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
3799
        write(root, "f.txt", content.as_bytes());
3800
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
3801
    }
3802
    // Each step appends after the previous line, so the chain is linear.
3803
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
3804
    repo.bisect_start().unwrap();
75167672 Andy McCall 3805
    assert!(matches!(
3806
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
3807
        BisectStep::NeedMarks { good: 1, bad: 0 }
3808
    ));
957fee30 Andy McCall ↶ 3809
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
75167672 Andy McCall 3810
    assert!(
3811
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
3812
        "{step:?}"
3813
    );
957fee30 Andy McCall ↶ 3814
    // Automated: bad when the bug line is present.
75167672 Andy McCall 3815
    let step = repo
3816
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
3817
        .unwrap();
957fee30 Andy McCall ↶ 3818
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
75167672 Andy McCall 3819
    assert_eq!(
3820
        repo.bisect_status().unwrap(),
3821
        Some(BisectStep::Found { culprit: hashes[4] })
3822
    );
957fee30 Andy McCall ↶ 3823
    repo.bisect_reset().unwrap();
3824
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
3825
    assert!(repo.bisect_status().unwrap().is_none());
3826
    assert!(!repo.snapshot("status").unwrap().changed);
3827
    // Manual marks and a skip.
3828
    repo.bisect_start().unwrap();
3829
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3830
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3831
    let mut skipped_once = false;
3832
    let mut guard = 0;
3833
    while let BisectStep::Testing { .. } = step {
3834
        guard += 1;
3835
        assert!(guard < 20);
3836
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
3837
        if !skipped_once && text.contains("line 6") {
3838
            // An untestable state away from the boundary: the search routes around it.
3839
            skipped_once = true;
3840
            step = repo.bisect_mark(None, &[]).unwrap();
3841
            continue;
3842
        }
3843
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
3844
    }
3845
    assert!(skipped_once);
3846
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
3847
    repo.bisect_reset().unwrap();
3848
    // Skipping the culprit itself leaves it among the candidates reported.
3849
    repo.bisect_start().unwrap();
3850
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
3851
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
3852
    let mut guard = 0;
3853
    while let BisectStep::Testing { heads, .. } = &step {
3854
        guard += 1;
3855
        assert!(guard < 20);
3856
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 3857
        let is_culprit_state =
3858
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
3859
        step = if is_culprit_state {
3860
            repo.bisect_mark(None, &[]).unwrap()
3861
        } else {
3862
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
3863
        };
957fee30 Andy McCall ↶ 3864
    }
3865
    match step {
75167672 Andy McCall 3866
        BisectStep::Inconclusive { candidates } => assert!(
3867
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
3868
            "{candidates:?}"
3869
        ),
957fee30 Andy McCall ↶ 3870
        other => panic!("{other:?}"),
3871
    }
3872
    repo.bisect_reset().unwrap();
3873
}
3874
728da0f9 Andy McCall ↶ 3875
#[test]
3876
fn squash_folds_a_change_into_its_dependency() {
3877
    hermetic();
3878
    let dir = tempfile::tempdir().unwrap();
3879
    let root = dir.path();
3880
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3881
    write(root, "a.txt", b"1\n");
3882
    let a = repo.commit("A", &[]).unwrap();
3883
    write(root, "a.txt", b"1\n2\n");
3884
    let c = repo.commit("C", &[]).unwrap();
3885
    write(root, "a.txt", b"1\n2\n3\n");
3886
    let e = repo.commit("E", &[]).unwrap();
3887
    write(root, "b.txt", b"b\n");
3888
    let b = repo.commit("B", &[]).unwrap();
3889
    let id_a = repo.store().get_change(&a).unwrap().change_id;
3890
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3891
    // E depends on C which A lacks: refused, naming it.
3892
    let err = repo.squash(&e, &a).unwrap_err().to_string();
3893
    assert!(err.contains(&c.short(12)), "{err}");
3894
    // C into A: A' has both, C is gone, E follows and still reads the same.
3895
    let a2 = repo.squash(&c, &a).unwrap();
3896
    let a2c = repo.store().get_change(&a2).unwrap();
3897
    assert_eq!(a2c.change_id, id_a);
3898
    assert!(a2c.deps.is_empty());
3899
    let heads = repo.bookmark_heads().unwrap();
3900
    let st = repo.load_state(&heads).unwrap();
3901
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
75167672 Andy McCall 3902
    let e2 = st
3903
        .changes()
3904
        .find(|(_, m)| m.change_id == id_e)
3905
        .map(|(h, _)| *h)
3906
        .unwrap();
3907
    assert_eq!(
3908
        repo.store().get_change(&e2).unwrap().deps,
3909
        vec![a2],
3910
        "E now depends on A' alone"
3911
    );
728da0f9 Andy McCall ↶ 3912
    let files = st.materialize().files;
75167672 Andy McCall 3913
    assert!(
3914
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
3915
    );
728da0f9 Andy McCall ↶ 3916
    assert!(files.contains_key("b.txt"));
3917
    assert!(st.contains(&b));
3918
    assert!(!repo.snapshot("status").unwrap().changed);
3919
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
3920
    // Undo restores the three original changes.
3921
    repo.undo().unwrap();
3922
    repo.undo().unwrap();
3923
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3924
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
3925
}
3926
3927
#[test]
3928
fn rebase_re_expresses_a_change_against_another_base() {
3929
    hermetic();
3930
    let dir = tempfile::tempdir().unwrap();
3931
    let root = dir.path();
3932
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3933
    write(root, "a.txt", b"1\n2\n");
3934
    let a = repo.commit("A", &[]).unwrap();
3935
    write(root, "a.txt", b"1\n2\n3\n");
3936
    let c = repo.commit("C: append 3", &[]).unwrap();
3937
    write(root, "a.txt", b"1\n2\n3\n4\n");
3938
    let e = repo.commit("E: append 4", &[]).unwrap();
3939
    // A different base: A plus a change that prepends a line.
3940
    repo.checkout(&[a], true, "checkout").unwrap();
3941
    write(root, "a.txt", b"0\n1\n2\n");
3942
    let d = repo.commit("D: prepend 0", &[]).unwrap();
3943
    let id_c = repo.store().get_change(&c).unwrap().change_id;
3944
    let id_e = repo.store().get_change(&e).unwrap().change_id;
3945
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
3946
    let c2 = repo.rebase(&c, &[d]).unwrap();
3947
    let c2c = repo.store().get_change(&c2).unwrap();
3948
    assert_eq!(c2c.change_id, id_c);
3949
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
3950
    let heads = repo.bookmark_heads().unwrap();
3951
    let st = repo.load_state(&heads).unwrap();
3952
    assert!(!st.contains(&c) && st.contains(&d));
75167672 Andy McCall 3953
    let e2 = st
3954
        .changes()
3955
        .find(|(_, m)| m.change_id == id_e)
3956
        .map(|(h, _)| *h)
3957
        .unwrap();
728da0f9 Andy McCall ↶ 3958
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
75167672 Andy McCall 3959
    assert!(
3960
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
3961
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
3962
    );
728da0f9 Andy McCall ↶ 3963
    let files = st.materialize().files;
75167672 Andy McCall 3964
    assert!(
3965
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
3966
        "{:?}",
3967
        files["a.txt"].content
3968
    );
728da0f9 Andy McCall ↶ 3969
    assert!(!files["a.txt"].is_conflicted());
3970
    // Rebasing onto a state that already contains the change is refused.
3971
    assert!(repo.rebase(&c2, &[c2]).is_err());
3972
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
75167672 Andy McCall 3973
    assert!(
3974
        err.contains("lacks dependencies"),
3975
        "E needs C, which D's state does not have: {err}"
3976
    );
728da0f9 Andy McCall ↶ 3977
}
3978
c792033a Andy McCall ↶ 3979
#[test]
3980
fn unsigned_tags_keep_their_message() {
3981
    hermetic();
3982
    let dir = tempfile::tempdir().unwrap();
3983
    let root = dir.path();
3984
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3985
    write(root, "a.txt", b"a\n");
3986
    repo.commit("a", &[]).unwrap();
3987
    assert!(repo.secret_key().unwrap().is_none());
75167672 Andy McCall 3988
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
3989
        .unwrap();
c792033a Andy McCall ↶ 3990
    let tags = repo.tags().unwrap();
75167672 Andy McCall 3991
    assert_eq!(
3992
        (
3993
            tags[0].name.as_str(),
3994
            tags[0].message.as_str(),
3995
            tags[0].signer.as_deref()
3996
        ),
3997
        ("v1", "first release", None)
3998
    );
3999
    assert!(
4000
        repo.tag_refs().unwrap()[0].attestation.is_none(),
4001
        "an unsigned attestation is not advertised"
4002
    );
c792033a Andy McCall ↶ 4003
}
387335ff Andy McCall ↶ 4004
4005
#[test]
4006
fn fsck_passes_a_sound_repository_and_names_each_fault() {
64818938 Andy McCall ↶ 4007
    // Files on disk are what this tests: tampering with them, and the
4008
    // directory store's crash points.
4009
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4010
        return;
4011
    }
387335ff Andy McCall ↶ 4012
    hermetic();
4013
    let dir = tempfile::tempdir().unwrap();
4014
    let root = dir.path();
4015
    let origin_path = root.join("origin");
4016
    let origin = Repo::init(&origin_path).unwrap();
4017
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
4018
        .unwrap()
4019
        .with_home(root.join("home-a"));
4020
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4021
        .unwrap();
4022
    write(&root.join("a"), "f.txt", b"one\n");
4023
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
4024
    let h1 = a.commit("first", &[]).unwrap();
4025
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
4026
    let h2 = a.commit("second", &[]).unwrap();
4027
    a.tag_create("v1", &[h2], "first release").unwrap();
4028
    a.checkpoint().unwrap();
4029
    assert!(a.push("origin", false).unwrap()[0].ok);
4030
4031
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
4032
    for repo in [&a, &origin] {
4033
        let rep = repo.fsck().unwrap();
4034
        assert_eq!(rep.problems, vec![], "{rep:?}");
4035
        // The two commits, plus the working copy's change in `a`.
4036
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
4037
        assert!(rep.ops > 1 && rep.objects > 5);
4038
    }
4039
    assert!(origin.fsck().unwrap().attestations >= 1);
4040
4041
    // A flipped byte in a stored object is corruption, named by hash.
4042
    let c1 = a.store().path_for(&h1);
4043
    let pristine = fs::read(&c1).unwrap();
4044
    let mut bytes = pristine.clone();
4045
    *bytes.last_mut().unwrap() ^= 1;
4046
    fs::write(&c1, &bytes).unwrap();
4047
    let rep = a.fsck().unwrap();
4048
    assert!(rep.errors() >= 1);
4049
    assert!(
4050
        rep.problems
4051
            .iter()
4052
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
4053
        "{rep:?}"
4054
    );
4055
    fs::write(&c1, &pristine).unwrap();
4056
    assert_eq!(a.fsck().unwrap().errors(), 0);
4057
4058
    // A missing change is named with what needed it.
4059
    fs::remove_file(&c1).unwrap();
4060
    let rep = a.fsck().unwrap();
4061
    assert!(
4062
        rep.problems.iter().any(|p| p.severity == Severity::Error
4063
            && p.object == Some(h1)
4064
            && p.what.contains("change missing, needed by change")),
4065
        "{rep:?}"
4066
    );
4067
    fs::write(&c1, &pristine).unwrap();
4068
4069
    // A missing blob is an error in a full clone.
4070
    let c2 = a.store().get_change(&h1).unwrap();
4071
    let blob = c2
4072
        .edits
4073
        .iter()
4074
        .find_map(|e| match e {
4075
            Edit::Replace { new: Some(b), .. } => Some(*b),
4076
            _ => None,
4077
        })
4078
        .expect("the binary file is a blob");
4079
    let bp = a.store().path_for(&blob);
4080
    let blob_bytes = fs::read(&bp).unwrap();
4081
    fs::remove_file(&bp).unwrap();
4082
    let rep = a.fsck().unwrap();
4083
    assert!(
4084
        rep.problems
4085
            .iter()
4086
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
4087
        "{rep:?}"
4088
    );
4089
    fs::write(&bp, &blob_bytes).unwrap();
4090
4091
    // A broken op log head is reported, not a crash.
4092
    let head = root.join("a/.oxy/ops/head");
4093
    let saved = fs::read(&head).unwrap();
4094
    fs::write(&head, b"not a hash").unwrap();
4095
    let rep = a.fsck().unwrap();
4096
    assert!(
4097
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
4098
        "{rep:?}"
4099
    );
4100
    fs::write(&head, saved).unwrap();
4101
    assert_eq!(a.fsck().unwrap().problems, vec![]);
4102
}
4dcb8c09 Andy McCall ↶ 4103
4104
/// Copy a directory tree (for restoring a pristine repository).
4105
fn copy_tree(from: &Path, to: &Path) {
4106
    fs::create_dir_all(to).unwrap();
4107
    for e in fs::read_dir(from).unwrap() {
4108
        let e = e.unwrap();
4109
        let target = to.join(e.file_name());
4110
        if e.file_type().unwrap().is_dir() {
4111
            copy_tree(&e.path(), &target);
4112
        } else {
4113
            fs::copy(e.path(), &target).unwrap();
4114
        }
4115
    }
4116
}
4117
4118
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
4119
/// would, and check that both repositories still open, pass `fsck`, and
4120
/// accept the same operation again.
4121
#[test]
4122
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
64818938 Andy McCall ↶ 4123
    // Files on disk are what this tests: tampering with them, and the
4124
    // directory store's crash points.
4125
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
4126
        return;
4127
    }
4dcb8c09 Andy McCall ↶ 4128
    use crate::durable::failpoint;
4129
    hermetic();
4130
    let dir = tempfile::tempdir().unwrap();
4131
    let pristine = dir.path().join("pristine");
4132
    let origin_path = pristine.join("origin");
4133
    Repo::init(&origin_path).unwrap();
4134
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
4135
        .unwrap()
4136
        .with_home(dir.path().join("home"));
4137
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4138
        .unwrap();
4139
    write(&pristine.join("a"), "f.txt", b"one\n");
4140
    a.commit("first", &[]).unwrap();
4141
    assert!(a.push("origin", false).unwrap()[0].ok);
4142
    drop(a);
4143
4144
    type Op = fn(&Repo) -> Result<()>;
4145
    let edit_and_commit: Op = |r| {
4146
        write(r.root(), "f.txt", b"one\ntwo\n");
4147
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
4148
        r.commit("second", &[]).map(|_| ())
4149
    };
4150
    let push: Op = |r| {
4151
        let res = r.push("origin", false)?;
4152
        if res.iter().all(|x| x.ok) {
4153
            Ok(())
4154
        } else {
4155
            Err(RepoError::Msg(format!("{res:?}")))
4156
        }
4157
    };
4158
4159
    for (name, prepare, op) in [
4160
        ("commit", None, edit_and_commit),
4161
        ("push", Some(edit_and_commit), push),
4162
    ] {
4163
        let mut steps = 0;
4164
        for n in 1.. {
4165
            let run = dir.path().join(format!("{name}-{n}"));
4166
            copy_tree(&pristine, &run);
4167
            // Clones record their remote by path; point it at this copy.
4168
            let open = |p: &Path| {
4169
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
4170
                r.config
4171
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
4172
                    .unwrap();
4173
                r.save_config().unwrap();
4174
                r
4175
            };
4176
            let a = open(&run.join("a"));
4177
            if let Some(prep) = prepare {
4178
                prep(&a).unwrap();
4179
            }
4180
            failpoint::crash_after(n);
4181
            let outcome = op(&a);
4182
            let crashed = failpoint::disarm();
4183
            drop(a);
4184
            if !crashed {
4185
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
4186
                steps = n - 1;
4187
                break;
4188
            }
4189
            assert!(
4190
                outcome.is_err(),
4191
                "{name}: a crash at step {n} was swallowed"
4192
            );
4193
            for repo in ["a", "origin"] {
4194
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
4195
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
4196
                });
4197
                let rep = r.fsck().unwrap();
4198
                assert_eq!(
4199
                    rep.errors(),
4200
                    0,
4201
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
4202
                    rep.problems
4203
                );
4204
            }
4205
            // The interrupted operation can simply be run again.
4206
            let a = open(&run.join("a"));
4207
            // A crash after the commit point leaves the commit done.
4208
            let landed = a
4209
                .bookmark_heads()
4210
                .unwrap()
4211
                .iter()
4212
                .any(|h| a.store().get_change(h).unwrap().message == "second");
4213
            let again = match (name, landed) {
4214
                ("commit", true) => Ok(()),
4215
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
4216
                _ => op(&a),
4217
            };
4218
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
4219
            assert_eq!(a.fsck().unwrap().errors(), 0);
4220
            fs::remove_dir_all(&run).unwrap();
4221
        }
4222
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
4223
    }
4224
}
19555025 Andy McCall ↶ 4225
4226
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
4227
/// running at the same time lose nothing: every commit ends up on the
4228
/// bookmark, locally and on the remote, and the repository passes fsck.
4229
#[test]
4230
fn concurrent_commits_in_two_workspaces_lose_nothing() {
4231
    hermetic();
4232
    let dir = tempfile::tempdir().unwrap();
4233
    let root = dir.path();
4234
    let origin = root.join("origin");
4235
    Repo::init_bare_unbound(&origin).unwrap();
4236
    let main = root.join("main");
4237
    let mut repo = Repo::init(&main).unwrap();
4238
    repo.config
4239
        .set("remote.origin.url", &origin.to_string_lossy())
4240
        .unwrap();
4241
    repo.save_config().unwrap();
4242
    write(&main, "seed.txt", b"seed\n");
4243
    repo.commit("seed", &[]).unwrap();
4244
    let second = root.join("second");
4245
    repo.workspace_add(&second, None).unwrap();
4246
    drop(repo);
4247
4248
    const EACH: usize = 15;
4249
    std::thread::scope(|s| {
4250
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
4251
            s.spawn(move || {
4252
                let r = Repo::open(&dir).unwrap();
4253
                for i in 0..EACH {
4254
                    write(
4255
                        &dir,
4256
                        &format!("{tag}-{i}.txt"),
4257
                        format!("{tag} {i}\n").as_bytes(),
4258
                    );
4259
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
4260
                    if push && i % 5 == 4 {
4261
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
4262
                        let _ = r.push("origin", false);
4263
                    }
4264
                }
4265
            });
4266
        }
4267
    });
4268
4269
    let repo = Repo::open(&main).unwrap();
4270
    let heads = repo.bookmark_heads().unwrap();
4271
    let state = repo.load_state(&heads).unwrap();
4272
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
4273
    for tag in ["a", "b"] {
4274
        for i in 0..EACH {
4275
            assert!(
4276
                messages.contains(&format!("{tag} {i}")),
4277
                "lost commit {tag} {i}; have {messages:?}"
4278
            );
4279
        }
4280
    }
4281
    let rep = repo.fsck().unwrap();
4282
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
4283
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
4284
    let hosted = Repo::open(&origin).unwrap();
4285
    let hosted_heads = hosted.bookmark_heads().unwrap();
4286
    assert_eq!(
4287
        hosted.load_state(&hosted_heads).unwrap().len(),
4288
        state.len(),
4289
        "the remote has every commit"
4290
    );
4291
}
4292
4293
/// Two operations recorded from the same parent (what two processes do
4294
/// when they race) are merged: both bookmarks' heads survive, and a
4295
/// change made on one side only is kept.
4296
#[test]
4297
fn operations_from_the_same_parent_are_merged() {
4298
    hermetic();
4299
    let dir = tempfile::tempdir().unwrap();
4300
    let root = dir.path();
4301
    let repo = Repo::init(root).unwrap();
4302
    write(root, "a.txt", b"a\n");
4303
    let a = repo.commit("a", &[]).unwrap();
4304
    write(root, "b.txt", b"b\n");
4305
    let b = repo.commit("b", &[]).unwrap();
4306
    let (x, op) = repo.head_op().unwrap();
4307
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
4308
4309
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
4310
    let mut one = op.view.clone();
4311
    one.bookmarks.insert("main".into(), state(vec![a]));
4312
    one.bookmarks.insert("topic".into(), state(vec![a]));
4313
    let mut two = op.view.clone();
4314
    two.bookmarks.insert("main".into(), state(vec![b]));
4315
    repo.record_op(&[x], "one", one).unwrap();
4316
    let merged = repo.record_op(&[x], "two", two).unwrap();
4317
4318
    let (head, op) = repo.head_op().unwrap();
4319
    assert_eq!(head, merged);
4320
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
4321
    assert!(op.command.contains("merged with a concurrent operation"));
4322
    let mut main = repo
4323
        .store()
4324
        .get_state(&op.view.bookmarks["main"])
4325
        .unwrap()
4326
        .heads;
4327
    main.sort();
4328
    let mut want = vec![a, b];
4329
    want.sort();
4330
    assert_eq!(main, want, "both sides' heads are kept");
4331
    assert!(
4332
        op.view.bookmarks.contains_key("topic"),
4333
        "a one-sided change survives"
4334
    );
4335
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4336
}
3e5772cc Andy McCall ↶ 4337
4338
#[test]
4339
fn failed_requests_come_with_a_next_step() {
4340
    use crate::protocol::hint_for;
4341
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
4342
        .unwrap()
4343
        .contains("token"));
4344
    assert!(hint_for("…: HTTP 403: forbidden")
4345
        .unwrap()
4346
        .contains("repo:write"));
4347
    assert!(hint_for("…: HTTP 404: no such repository")
4348
        .unwrap()
4349
        .contains("owner and repository name"));
4350
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
4351
        .unwrap()
4352
        .contains("oxyhub-ca.pem"));
4353
    assert!(hint_for("Connect error: Connection refused (os error 111)")
4354
        .unwrap()
4355
        .contains("running"));
4356
    assert!(hint_for("Dns Failed: failed to lookup address information")
4357
        .unwrap()
4358
        .contains("resolve"));
4359
    assert_eq!(hint_for("something else entirely"), None);
4360
}
4361
4362
#[test]
4363
fn doctor_names_problems_and_what_to_do() {
4364
    hermetic();
4365
    let dir = tempfile::tempdir().unwrap();
4366
    let root = dir.path();
4367
    let origin = root.join("origin");
4368
    Repo::init_bare_unbound(&origin).unwrap();
4369
    let mut repo = Repo::init(&root.join("r"))
4370
        .unwrap()
4371
        .with_home(root.join("home"));
4372
    let find = |r: &DoctorReport, area: &str, h: Health| {
4373
        r.checks
4374
            .iter()
4375
            .find(|c| c.area == area && c.health == h)
4376
            .cloned()
4377
    };
4378
4379
    let r = repo.doctor(true);
4380
    assert!(find(&r, "identity", Health::Warn)
4381
        .unwrap()
4382
        .hint
4383
        .unwrap()
4384
        .contains("oxy identity create"));
4385
    assert!(find(&r, "repository", Health::Ok).is_some());
4386
4387
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
4388
        .unwrap();
4389
    repo.config.set("author.name", "Ada").unwrap();
4390
    repo.config.set("author.email", "[email protected]").unwrap();
4391
    repo.config
4392
        .set("remote.origin.url", &origin.to_string_lossy())
4393
        .unwrap();
4394
    repo.config
4395
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
4396
        .unwrap();
4397
    repo.config.set("remote.down.token", "t").unwrap();
4398
    repo.config
4399
        .set("remote.badca.url", "https://example.invalid/a/b")
4400
        .unwrap();
4401
    repo.config
4402
        .set(
4403
            "remote.badca.ca",
4404
            &root.join("missing.pem").to_string_lossy(),
4405
        )
4406
        .unwrap();
4407
    repo.save_config().unwrap();
4408
4409
    let r = repo.doctor(true);
4410
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
4411
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
4412
    assert!(find(&r, "remote origin", Health::Ok)
4413
        .unwrap()
4414
        .message
4415
        .contains("first push binds it"));
4416
    let down = find(&r, "remote down", Health::Fail).unwrap();
4417
    assert!(
4418
        down.hint.as_deref().unwrap_or("").contains("running"),
4419
        "{down:?}"
4420
    );
4421
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
4422
    assert!(
4423
        badca.hint.unwrap().contains("remote.badca.ca"),
4424
        "the remote's own name is in the hint"
4425
    );
4426
    assert_eq!(r.worst(), Health::Fail);
4427
4428
    // Offline, nothing is contacted.
4429
    let r = repo.doctor(false);
4430
    assert!(find(&r, "remote down", Health::Fail).is_none());
4431
    assert!(find(&r, "remote down", Health::Ok)
4432
        .unwrap()
4433
        .message
4434
        .contains("not contacted"));
4435
}
62794ecc Andy McCall ↶ 4436
4437
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
4438
/// after it. Inserting after `b` and then deleting `b`, one commit after
4439
/// the other, must not leave a delete/insert conflict.
4440
#[test]
4441
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
4442
    hermetic();
4443
    let dir = tempfile::tempdir().unwrap();
4444
    let root = dir.path();
4445
    let repo = Repo::init(root).unwrap();
4446
    write(root, "f", b"a\nb\nc\n");
4447
    repo.commit("base", &[]).unwrap();
4448
    write(root, "f", b"a\nb\nx\nc\n");
4449
    let insert = repo.commit("insert x after b", &[]).unwrap();
4450
    write(root, "f", b"a\nx\nc\n");
4451
    let delete = repo.commit("delete b", &[]).unwrap();
4452
    assert!(
4453
        repo.store()
4454
            .get_change(&delete)
4455
            .unwrap()
4456
            .deps
4457
            .contains(&insert),
4458
        "the deletion depends on the insertion below the deleted line"
4459
    );
4460
    let heads = repo.bookmark_heads().unwrap();
4461
    assert_eq!(heads, vec![delete]);
4462
    let snap = repo.load_state(&heads).unwrap().materialize();
4463
    assert!(!snap.is_conflicted());
4464
    assert!(
4465
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
4466
    );
4467
}
4468
4469
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
4470
/// replacement depends on the change that set the blob it replaces.
4471
#[test]
4472
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
4473
    hermetic();
4474
    let dir = tempfile::tempdir().unwrap();
4475
    let root = dir.path();
4476
    let repo = Repo::init(root).unwrap();
4477
    write(root, "bin", b"\0A");
4478
    let v1 = repo.commit("v1", &[]).unwrap();
4479
    write(root, "bin", b"\0B");
4480
    let v2 = repo.commit("v2", &[]).unwrap();
4481
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
4482
    write(root, "bin", b"\0A");
4483
    let v3 = repo.commit("back to A", &[]).unwrap();
4484
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
4485
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
4486
    let state = repo.load_state(&[v3]).unwrap();
4487
    let snap = state.materialize();
4488
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
4489
        panic!("opaque")
4490
    };
4491
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
4492
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
4493
}
4494
4495
/// Spec §23: a binary file changed on two branches and merged in Git to
4496
/// one side's version comes back as that version at the merge, and the
4497
/// import verifies commit by commit.
4498
#[test]
4499
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
4500
    hermetic();
4501
    if std::process::Command::new("git")
4502
        .arg("--version")
4503
        .output()
4504
        .is_err()
4505
    {
4506
        eprintln!("git not installed; skipping");
4507
        return;
4508
    }
4509
    let dir = tempfile::tempdir().unwrap();
4510
    let root = dir.path();
4511
    let g = root.join("src.git");
4512
    fs::create_dir_all(&g).unwrap();
4513
    let git = |args: &[&str]| -> String {
4514
        let out = std::process::Command::new("git")
4515
            .arg("-C")
4516
            .arg(&g)
4517
            .args([
4518
                "-c",
4519
                "user.name=Grace",
4520
                "-c",
4521
                "[email protected]",
4522
                "-c",
4523
                "commit.gpgsign=false",
4524
            ])
4525
            .args(args)
4526
            .output()
4527
            .unwrap();
4528
        assert!(
4529
            out.status.success(),
4530
            "git {args:?}: {}",
4531
            String::from_utf8_lossy(&out.stderr)
4532
        );
4533
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4534
    };
4535
    git(&["init", "-q", "-b", "main"]);
4536
    write(&g, "logo.bin", b"\0base");
4537
    write(&g, "notes.txt", b"a\nb\nc\n");
4538
    git(&["add", "."]);
4539
    git(&["commit", "-qm", "base"]);
4540
    git(&["checkout", "-qb", "side"]);
4541
    write(&g, "logo.bin", b"\0side");
4542
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
4543
    git(&["commit", "-qam", "side"]);
4544
    git(&["checkout", "-q", "main"]);
4545
    write(&g, "logo.bin", b"\0main");
4546
    git(&["commit", "-qam", "main"]);
4547
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
4548
    let _ = std::process::Command::new("git")
4549
        .arg("-C")
4550
        .arg(&g)
4551
        .args([
4552
            "-c",
4553
            "user.name=G",
4554
            "-c",
4555
            "user.email=g@e",
4556
            "merge",
4557
            "-q",
4558
            "side",
4559
        ])
4560
        .output();
4561
    write(&g, "logo.bin", b"\0main");
4562
    git(&["add", "."]);
4563
    git(&["commit", "-qm", "merge side"]);
4564
    // Then a revert of the binary to its first version.
4565
    write(&g, "logo.bin", b"\0base");
4566
    git(&["commit", "-qam", "back to base"]);
4567
4568
    let repo = Repo::init(&root.join("o")).unwrap();
4569
    let rep = repo.import_git(&g, "main").unwrap();
4570
    assert_eq!(rep.merges, 1);
4571
    let v = repo.verify_git_import(&g, "main").unwrap();
4572
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
4573
    assert_eq!(v.commits, 5);
4574
    let snap = repo
4575
        .load_state(&repo.bookmark_heads().unwrap())
4576
        .unwrap()
4577
        .materialize();
4578
    assert!(!snap.is_conflicted());
4579
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
4580
        panic!("opaque")
4581
    };
4582
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
4583
}
c863c7a7 Andy McCall ↶ 4584
4585
/// Spec §7.7 on a file system without executable bits or symlinks: the
4586
/// recorded bit is kept, and a symlink checked out as a plain file holding
4587
/// its target is still that symlink.
4588
#[cfg(unix)]
4589
#[test]
4590
fn windows_file_systems_keep_exec_bits_and_symlinks() {
4591
    use crate::portable::Platform;
4592
    use std::os::unix::fs::PermissionsExt;
4593
    hermetic();
4594
    let dir = tempfile::tempdir().unwrap();
4595
    let root = dir.path();
4596
    let repo = Repo::init(root).unwrap();
4597
    write(root, "run.sh", b"#!/bin/sh\n");
4598
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
4599
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
4600
    repo.commit("script and link", &[]).unwrap();
4601
    drop(repo);
4602
4603
    // What checking out on Windows leaves: no exec bit, the link as a file.
4604
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
4605
    fs::remove_file(root.join("link")).unwrap();
4606
    write(root, "link", b"run.sh");
4607
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
4608
    let s = win.snapshot("oxy status").unwrap();
4609
    assert!(
4610
        s.statuses.is_empty(),
4611
        "nothing changed on Windows: {:?}",
4612
        statuses(&s)
4613
    );
4614
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
4615
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
4616
    write(root, "link", b"other");
4617
    let h = win.commit("edit on Windows", &[]).unwrap();
4618
    let snap = win.load_state(&[h]).unwrap().materialize();
4619
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
4620
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
4621
    // The same working copy read as Linux sees the lost bit and the plain file.
4622
    let linux = Repo::open(root).unwrap();
4623
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
4624
}
4625
4626
/// Paths that collide on case-insensitive or Windows file systems are
4627
/// named at checkout there, and by doctor everywhere.
4628
#[test]
4629
fn paths_other_platforms_cannot_hold_are_reported() {
4630
    use crate::portable::Platform;
4631
    hermetic();
4632
    let dir = tempfile::tempdir().unwrap();
4633
    let root = dir.path();
4634
    let repo = Repo::init(root).unwrap();
4635
    write(root, "README.md", b"a\n");
4636
    write(root, "readme.md", b"b\n");
4637
    write(root, "src/aux.c", b"int x;\n");
4638
    let h = repo.commit("unportable", &[]).unwrap();
4639
    let r = repo.doctor(false);
4640
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
4641
    assert_eq!(port.health, Health::Warn);
4642
    assert!(
4643
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
4644
        "{}",
4645
        port.message
4646
    );
4647
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
4648
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
4649
    assert!(
4650
        rep.notes
4651
            .iter()
4652
            .any(|n| n.contains("README.md and readme.md")),
4653
        "{:?}",
4654
        rep.notes
4655
    );
4656
    assert!(
4657
        !rep.notes.iter().any(|n| n.contains("aux.c")),
4658
        "macOS allows aux.c"
4659
    );
4660
}
bc489b6c Andy McCall ↶ 4661
4662
#[test]
4663
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
4664
    hermetic();
4665
    let dir = tempfile::tempdir().unwrap();
4666
    let repo = Repo::init(dir.path()).unwrap();
4667
    write(dir.path(), "a.txt", b"one\n");
4668
    write(dir.path(), "other.txt", b"x\n");
4669
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
4670
    repo.snapshot("t").unwrap();
4671
    let c1 = repo.commit("first", &[]).unwrap();
4672
    write(dir.path(), "other.txt", b"y\n");
4673
    repo.snapshot("t").unwrap();
4674
    repo.commit("other only", &[]).unwrap();
4675
    write(dir.path(), "a.txt", b"one\ntwo\n");
4676
    repo.snapshot("t").unwrap();
4677
    let c3 = repo.commit("second line", &[]).unwrap();
4678
    write(dir.path(), "other.txt", b"z\n");
4679
    repo.snapshot("t").unwrap();
4680
    repo.commit("other again", &[]).unwrap();
4681
4682
    let heads = repo.bookmark_heads().unwrap();
4683
    let state = repo.load_state(&heads).unwrap();
4684
    let full: Vec<ChangeHash> = repo
4685
        .log_for_path_in("a.txt", &heads)
4686
        .unwrap()
4687
        .iter()
4688
        .map(|e| e.hash)
4689
        .collect();
4690
    assert_eq!(
4691
        full,
4692
        vec![c3, c1],
4693
        "newest first, only changes touching the path"
4694
    );
4695
    let newest: Vec<ChangeHash> = repo
4696
        .log_for_path_of(&state, "a.txt", Some(1))
4697
        .unwrap()
4698
        .iter()
4699
        .map(|e| e.hash)
4700
        .collect();
4701
    assert_eq!(newest, vec![c3], "stops at the first");
4702
    assert_eq!(
4703
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
4704
        2
4705
    );
4706
    assert!(repo
4707
        .log_for_path_of(&state, "missing.txt", Some(1))
4708
        .is_err());
4709
    assert_eq!(
4710
        repo.log_state(&heads).unwrap().len(),
4711
        repo.log_of(&state).len()
4712
    );
4713
4714
    let tree = state.tree().view();
4715
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
4716
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
4717
    assert_eq!(
4718
        via_state
4719
            .iter()
4720
            .map(|l| (l.hash, l.text.clone()))
4721
            .collect::<Vec<_>>(),
4722
        via_heads
4723
            .iter()
4724
            .map(|l| (l.hash, l.text.clone()))
4725
            .collect::<Vec<_>>()
4726
    );
4727
    assert_eq!(
4728
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
4729
        vec![c1, c3]
4730
    );
4731
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
4732
}
696bbf29 Andy McCall ↶ 4733
4734
/// A text file whose stat matches the manifest and whose recorded hash is
4735
/// the base's content is taken from the base without reading it; anything
4736
/// else is read, so no edit is missed (spec §12.3).
4737
#[cfg(unix)]
4738
#[test]
4739
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
4740
    use std::os::unix::fs::PermissionsExt;
4741
    hermetic();
4742
    let dir = tempfile::tempdir().unwrap();
4743
    let root = dir.path();
4744
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4745
    write(root, "a.txt", b"one\ntwo\n");
4746
    write(root, "b.txt", b"bee\n");
4747
    repo.commit("base", &[]).unwrap();
4748
    let age = |p: &str| {
4749
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4750
        fs::File::options()
4751
            .write(true)
4752
            .open(root.join(p))
4753
            .unwrap()
4754
            .set_modified(old)
4755
            .unwrap();
4756
    };
4757
    age("a.txt");
4758
    age("b.txt");
4759
    assert!(
4760
        !repo.snapshot("status").unwrap().changed,
4761
        "records the aged stat"
4762
    );
4763
4764
    // Clean and equal to the base: not read at all.
4765
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4766
    let snap = repo.snapshot("status").unwrap();
4767
    assert!(
4768
        !snap.changed && snap.statuses.is_empty(),
4769
        "{:?}",
4770
        snap.statuses
4771
    );
4772
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4773
4774
    // An uncommitted edit that is older than the manifest: stat-clean, but
4775
    // its hash is not the base's, so it is read and stays visible.
4776
    write(root, "b.txt", b"bee edited\n");
4777
    age("b.txt");
4778
    let first = repo.snapshot("status").unwrap();
4779
    assert_eq!(
4780
        statuses(&first),
4781
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
4782
    );
4783
    let again = repo.snapshot("status").unwrap();
4784
    assert_eq!(
4785
        statuses(&again),
4786
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
4787
        "still seen once stat-clean"
4788
    );
4789
    assert!(!again.changed, "and the working copy hashes the same");
4790
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4791
    assert!(
4792
        repo.snapshot("status").is_err(),
4793
        "an edited file must be read, never taken from the base"
4794
    );
4795
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4796
4797
    // A same-size edit made just now is racy and read.
4798
    write(root, "a.txt", b"one\nTWO\n");
4799
    assert_eq!(
4800
        statuses(&repo.snapshot("status").unwrap()),
4801
        vec![
4802
            ("a.txt".to_string(), ChangeStatus::Modified),
4803
            ("b.txt".to_string(), ChangeStatus::Modified)
4804
        ]
4805
    );
4806
    // Committing makes the edits the base: both are clean and served from it again.
4807
    repo.commit("edits", &[]).unwrap();
4808
    age("a.txt");
4809
    age("b.txt");
4810
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4811
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4812
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
4813
    let snap = repo.snapshot("status").unwrap();
4814
    assert!(!snap.changed && snap.statuses.is_empty());
4815
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4816
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
4817
}
afaba5f1 Andy McCall ↶ 4818
4819
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
4820
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
4821
/// file is unchanged, and loading through the checkpoint equals a full load.
4822
#[test]
4823
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
4824
    hermetic();
4825
    let dir = tempfile::tempdir().unwrap();
4826
    let root = dir.path();
4827
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4828
    let long: String = (0..300)
4829
        .map(|i| format!("line {i} of a long file\n"))
4830
        .collect();
4831
    write(root, "long.txt", long.as_bytes());
4832
    write(root, "short.txt", b"short\n");
4833
    repo.commit("base", &[]).unwrap();
4834
    let (r1, _, _) = repo.checkpoint().unwrap();
4835
    let cp1 = crate::objects::Checkpoint::decode(
4836
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
4837
    )
4838
    .unwrap();
4839
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
4840
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
4841
4842
    // gc keeps the graph blob; fsck finds the checkpoint sound.
4843
    repo.gc(true).unwrap();
4844
    assert!(repo.store().has(&graphs1[0]));
4845
    let report = repo.fsck().unwrap();
4846
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
4847
4848
    // Loading through the checkpoint equals a full load.
4849
    write(root, "short.txt", b"short, edited\n");
4850
    repo.commit("edit the short file", &[]).unwrap();
4851
    let heads = repo.bookmark_heads().unwrap();
4852
    let fast = repo.load_state(&heads).unwrap();
4853
    let full = repo.load_state_full(&heads).unwrap();
4854
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
4855
4856
    // The next checkpoint shares the unchanged long file's graph.
4857
    let (r2, _, _) = repo.checkpoint().unwrap();
4858
    let cp2 = crate::objects::Checkpoint::decode(
4859
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
4860
    )
4861
    .unwrap();
4862
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
4863
4864
    // A shallow clone's bundle carries the graph blob with the checkpoint.
4865
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
4866
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
4867
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
4868
4869
    // A version 1 checkpoint written by an older oxy still loads.
4870
    let state = repo.load_state_full(&heads).unwrap();
4871
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
4872
    let cp_old = crate::objects::Checkpoint {
4873
        heads: cp2.heads.clone(),
4874
        count: cp2.count,
4875
        payload: old,
4876
    };
4877
    let r_old = repo
4878
        .store()
4879
        .put(ObjectType::Checkpoint, &cp_old.encode())
4880
        .unwrap();
4881
    repo.install_checkpoint("main", &r_old).unwrap();
4882
    assert_eq!(
4883
        repo.load_state(&heads).unwrap().checkpoint_payload(),
4884
        full.checkpoint_payload()
4885
    );
4886
    assert_eq!(repo.fsck().unwrap().errors(), 0);
4887
4888
    // A lost graph blob fails the load loudly rather than dropping the
4889
    // file, and fsck reports it (a fresh repository, objects still loose).
4890
    let dir2 = tempfile::tempdir().unwrap();
4891
    let root2 = dir2.path();
4892
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
4893
    write(root2, "long.txt", long.as_bytes());
4894
    repo2.commit("base", &[]).unwrap();
4895
    let (r, _, _) = repo2.checkpoint().unwrap();
4896
    let cp = crate::objects::Checkpoint::decode(
4897
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
4898
    )
4899
    .unwrap();
4900
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
64818938 Andy McCall ↶ 4901
    repo2.store().remove_loose_for_test(&graph).unwrap();
afaba5f1 Andy McCall ↶ 4902
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
4903
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
4904
}
e3d071ce Andy McCall ↶ 4905
4906
/// A new repository has not stored the user's identity yet (that happens
4907
/// at the first signed change); looking it up falls back to the key
4908
/// directory, and a file there that does not hash to the key is refused.
4909
#[test]
4910
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
4911
    hermetic();
4912
    let dir = tempfile::tempdir().unwrap();
4913
    let home = dir.path().join("home");
4914
    let mut first = Repo::init(&dir.path().join("a"))
4915
        .unwrap()
4916
        .with_home(home.clone());
4917
    let (key, _) = first
4918
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4919
        .unwrap();
4920
    let fresh = Repo::init(&dir.path().join("b"))
4921
        .unwrap()
4922
        .with_home(home.clone());
4923
    assert!(!fresh.store().has(&key), "nothing stored yet");
4924
    let id = fresh.identity(&key).unwrap();
4925
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
4926
    // A key file that is not this identity is an error, not a wrong answer.
4927
    let keys = fresh.keys_dir.clone();
4928
    let (other, _) = first
4929
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4930
        .unwrap();
4931
    fs::copy(
4932
        keys.join(format!("{}.identity", other.to_hex())),
4933
        keys.join(format!("{}.identity", key.to_hex())),
4934
    )
4935
    .unwrap();
4936
    assert!(fresh
4937
        .identity(&key)
4938
        .unwrap_err()
4939
        .to_string()
4940
        .contains("does not hold identity"));
4941
}
cc7a0056 Andy McCall ↶ 4942
4943
/// Status snapshots (spec §12.3): a text file whose stat matches the
4944
/// manifest, and whose base graph key is the one the manifest recorded it
4945
/// equal to, is neither read nor rendered; any edit, and any change to the
4946
/// file's graph in the base, brings it back.
4947
#[cfg(unix)]
4948
#[test]
4949
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
4950
    use std::os::unix::fs::PermissionsExt;
4951
    hermetic();
4952
    let dir = tempfile::tempdir().unwrap();
4953
    let root = dir.path();
4954
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4955
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
4956
        write(root, p, c.as_bytes());
4957
    }
4958
    repo.commit("base", &[]).unwrap();
4959
    let age = |p: &str| {
4960
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4961
        fs::File::options()
4962
            .write(true)
4963
            .open(root.join(p))
4964
            .unwrap()
4965
            .set_modified(old)
4966
            .unwrap();
4967
    };
4968
    let lock = |p: &str, mode: u32| {
4969
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
4970
    };
4971
    for p in ["a.txt", "b.txt", "d/c.txt"] {
4972
        age(p);
4973
    }
4974
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
4975
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4976
    assert!(
4977
        m.entries.values().all(|e| e.graph.is_some()),
4978
        "keys recorded"
4979
    );
4980
4981
    // Unreadable files prove they are not read; the status snapshot does
4982
    // not render them either, and its base lacks their graphs.
4983
    lock("a.txt", 0o000);
4984
    lock("b.txt", 0o000);
4985
    let snap = repo.snapshot_status("status").unwrap();
4986
    assert!(!snap.changed && snap.statuses.is_empty());
4987
    assert_eq!(
4988
        snap.base_snapshot
4989
            .unrendered
4990
            .iter()
4991
            .cloned()
4992
            .collect::<Vec<_>>(),
4993
        vec!["a.txt", "b.txt", "d/c.txt"]
4994
    );
4995
    assert!(!snap.base.is_full());
4996
    assert!(!snap.base_snapshot.is_conflicted());
4997
    // A full snapshot does not read them either, but renders everything.
4998
    let full = repo.snapshot("status").unwrap();
4999
    assert!(full.statuses.is_empty() && full.base.is_full());
5000
    assert!(full.base_snapshot.unrendered.is_empty());
5001
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
5002
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
5003
5004
    // An edit is seen; the file is rendered, the others still are not.
5005
    write(root, "d/c.txt", b"sea edited\n");
5006
    let snap = repo.snapshot_status("status").unwrap();
5007
    assert_eq!(
5008
        statuses(&snap),
5009
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
5010
    );
5011
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
5012
    // So is a mode change of an unread file.
5013
    lock("b.txt", 0o100);
5014
    assert_eq!(
5015
        statuses(&repo.snapshot_status("status").unwrap()),
5016
        vec![
5017
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
5018
            ("d/c.txt".to_string(), ChangeStatus::Modified)
5019
        ]
5020
    );
5021
    lock("b.txt", 0o000);
5022
5023
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
5024
    // stays unread, c.txt is read once and then skipped too.
5025
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
5026
        .unwrap();
5027
    age("d/c.txt");
5028
    let snap = repo.snapshot_status("status").unwrap();
5029
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
5030
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
5031
    lock("d/c.txt", 0o000);
5032
    let snap = repo.snapshot_status("status").unwrap();
5033
    assert!(snap.statuses.is_empty());
5034
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
5035
    for p in ["a.txt", "b.txt", "d/c.txt"] {
5036
        lock(p, 0o644);
5037
    }
5038
}
5039
5040
/// Attributes decide how a file compares with the base, so a changed
5041
/// `.oxyattributes` makes every text file be compared again.
5042
#[cfg(unix)]
5043
#[test]
5044
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
5045
    hermetic();
5046
    let dir = tempfile::tempdir().unwrap();
5047
    let root = dir.path();
5048
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5049
    write(root, "a.txt", b"crlf\r\n");
5050
    repo.commit("base", &[]).unwrap();
5051
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5052
    fs::File::options()
5053
        .write(true)
5054
        .open(root.join("a.txt"))
5055
        .unwrap()
5056
        .set_modified(old)
5057
        .unwrap();
5058
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5059
    assert!(repo
5060
        .snapshot_status("status")
5061
        .unwrap()
5062
        .base_snapshot
5063
        .unrendered
5064
        .contains("a.txt"));
5065
    // With eol=lf, a.txt as stored no longer equals the base.
5066
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
5067
    let snap = repo.snapshot_status("status").unwrap();
5068
    assert_eq!(
5069
        statuses(&snap),
5070
        vec![
5071
            (".oxyattributes".to_string(), ChangeStatus::Added),
5072
            ("a.txt".to_string(), ChangeStatus::Modified)
5073
        ]
5074
    );
5075
}
54cd08a1 Andy McCall ↶ 5076
5077
/// Bookmarks with `/` in their names: pushing records their
5078
/// attestations, and checkpoints are kept for them, beside `feature`
5079
/// itself.
5080
#[test]
5081
fn bookmarks_with_slashes_push_and_checkpoint() {
5082
    hermetic();
5083
    let dir = tempfile::tempdir().unwrap();
5084
    let root = dir.path();
5085
    let origin = Repo::init(&root.join("origin")).unwrap();
5086
    let url = root.join("origin").to_string_lossy().to_string();
5087
    let mut repo = Repo::clone(&url, &root.join("r"))
5088
        .unwrap()
5089
        .with_home(root.join("home"));
5090
    // With an identity, pushes carry reference attestations: the case
5091
    // that failed, since the attestation is a file named after the bookmark.
5092
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5093
        .unwrap();
5094
    let r = root.join("r");
5095
    write(&r, "a.txt", b"a\n");
5096
    let h_a = repo.commit("a", &[]).unwrap();
5097
    assert!(repo.push("origin", false).unwrap()[0].ok);
5098
    repo.bookmark_create("feature", None).unwrap();
5099
    repo.bookmark_create("feature/x", None).unwrap();
5100
    repo.bookmark_switch("feature/x", false).unwrap();
5101
    write(&r, "b.txt", b"b\n");
5102
    let h_b = repo.commit("b", &[]).unwrap();
5103
    for name in ["feature", "feature/x"] {
5104
        let res = repo.push_bookmark("origin", name, false).unwrap();
5105
        assert!(res[0].ok, "{name}: {res:?}");
5106
    }
5107
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
5108
    assert_eq!(
5109
        origin.resolve_heads("feature/x").unwrap(),
5110
        repo.resolve_heads("feature/x").unwrap()
5111
    );
5112
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
5113
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
5114
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
5115
5116
    // A checkpoint of feature/x is found again when loading its state.
5117
    let (cp, _, _) = repo.checkpoint().unwrap();
5118
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
5119
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
5120
    let heads = repo.resolve_heads("feature/x").unwrap();
5121
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
f8c69576 Andy McCall ↶ 5122
}
5123
5124
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
5125
/// never the remote's own bookmark, and a bookmark created again later is
5126
/// accepted although the deletion's attestation stays the latest.
5127
#[test]
5128
fn bookmarks_are_deleted_on_a_remote() {
5129
    hermetic();
5130
    let dir = tempfile::tempdir().unwrap();
5131
    let root = dir.path();
5132
    let origin = Repo::init(&root.join("origin")).unwrap();
5133
    let url = root.join("origin").to_string_lossy().to_string();
5134
    let mut repo = Repo::clone(&url, &root.join("r"))
5135
        .unwrap()
5136
        .with_home(root.join("home"));
5137
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5138
        .unwrap();
5139
    let r = root.join("r");
5140
    write(&r, "a.txt", b"a\n");
5141
    repo.commit("a", &[]).unwrap();
5142
    assert!(repo.push("origin", false).unwrap()[0].ok);
5143
    repo.bookmark_create("feature/x", None).unwrap();
5144
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
5145
    assert!(origin.resolve_heads("feature/x").is_ok());
5146
5147
    let res = repo.push_delete("origin", "feature/x").unwrap();
5148
    assert!(res[0].ok, "{res:?}");
5149
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
5150
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
5151
    assert!(
5152
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
5153
        "the deletion is attested"
5154
    );
5155
    assert!(
5156
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
5157
        "the local bookmark stays"
5158
    );
5159
    assert!(!repo
5160
        .view()
5161
        .unwrap()
5162
        .remotes
5163
        .get("origin")
5164
        .is_some_and(|m| m.contains_key("feature/x")));
5165
5166
    // Pushing it again creates it again, past the deletion's serial.
5167
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
5168
    assert!(res[0].ok, "{res:?}");
5169
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
5170
5171
    // Nothing to delete, and never the remote's own bookmark.
5172
    assert!(repo.push_delete("origin", "nope").is_err());
5173
    let res = repo.push_delete("origin", "main").unwrap();
5174
    assert!(
5175
        !res[0].ok && res[0].reason.contains("default bookmark"),
5176
        "{res:?}"
5177
    );
5178
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
54cd08a1 Andy McCall ↶ 5179
}
61e3bce7 Andy McCall ↶ 5180
5181
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
5182
/// when the target has the same versions of the files it touches, and is
5183
/// refused, untouched, when it has others.
5184
#[test]
5185
fn switching_bookmarks_carries_uncommitted_work() {
5186
    hermetic();
5187
    let dir = tempfile::tempdir().unwrap();
5188
    let root = dir.path();
5189
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5190
    write(root, "a.txt", b"a\n");
5191
    write(root, "b.txt", b"b\n");
5192
    write(root, "gone.txt", b"gone\n");
5193
    repo.commit("base", &[]).unwrap();
5194
    repo.bookmark_create("feature", None).unwrap();
5195
    // Started on main, belongs on feature: edit, add, remove.
5196
    write(root, "a.txt", b"a\nmore\n");
5197
    write(root, "new.txt", b"new\n");
5198
    fs::remove_file(root.join("gone.txt")).unwrap();
5199
    let (_, carried) = repo.bookmark_switch_carry("feature").unwrap();
5200
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
5201
    assert_eq!(repo.config.bookmark, "feature");
5202
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
5203
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
5204
    assert!(!root.join("gone.txt").exists());
5205
    let snap = repo.snapshot("status").unwrap();
5206
    assert_eq!(
5207
        statuses(&snap),
5208
        vec![
5209
            ("a.txt".to_string(), ChangeStatus::Modified),
5210
            ("gone.txt".to_string(), ChangeStatus::Removed),
5211
            ("new.txt".to_string(), ChangeStatus::Added)
5212
        ]
5213
    );
5214
    repo.commit("the work", &[]).unwrap();
5215
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
5216
5217
    // main moves b.txt on; work on feature touching b.txt cannot follow.
5218
    repo.bookmark_switch("main", false).unwrap();
5219
    write(root, "b.txt", b"b on main\n");
5220
    repo.commit("b on main", &[]).unwrap();
5221
    repo.bookmark_switch("feature", false).unwrap();
5222
    write(root, "b.txt", b"b edited\n");
5223
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
5224
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
5225
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
5226
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
5227
}
1c2bd9ab Andy McCall ↶ 5228
5229
/// Merging and checking out (feedback 3): a working copy without changes
5230
/// follows a merge whichever state it sat on; a refused checkout names
5231
/// what is in the way; `checkout --carry` takes the work along.
5232
#[test]
5233
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
5234
    hermetic();
5235
    let dir = tempfile::tempdir().unwrap();
5236
    let root = dir.path();
5237
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5238
    write(root, "a.txt", b"a\n");
5239
    let h1 = repo.commit("a", &[]).unwrap();
5240
    write(root, "b.txt", b"b\n");
5241
    repo.commit("b", &[]).unwrap();
5242
    repo.bookmark_create("feature", None).unwrap();
5243
    repo.bookmark_switch("feature", false).unwrap();
5244
    write(root, "c.txt", b"c\n");
5245
    repo.commit("c on feature", &[]).unwrap();
5246
    repo.bookmark_switch("main", false).unwrap();
5247
    // The working copy sits on an older state than main's heads.
5248
    repo.checkout(&[h1], false, "checkout").unwrap();
5249
    assert!(!root.join("b.txt").exists());
5250
    let m = repo.merge("feature").unwrap();
5251
    assert!(m.checked_out, "a clean working copy follows the merge");
5252
    for f in ["a.txt", "b.txt", "c.txt"] {
5253
        assert!(root.join(f).exists(), "{f}");
5254
    }
5255
5256
    // A refusal says which paths are in the way and what to do.
5257
    fs::remove_file(root.join("b.txt")).unwrap();
5258
    write(root, "a.txt", b"a edited\n");
5259
    let err = repo
5260
        .checkout(&[h1], false, "checkout")
5261
        .unwrap_err()
5262
        .to_string();
5263
    assert!(
5264
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
5265
        "{err}"
5266
    );
5267
    // --carry takes them along: h1 has a.txt as the base has it, and no b.txt
5268
    // is carried as absent (h1 has none either, so that is refused).
5269
    let err = repo
5270
        .checkout_carry(&[h1], "the first change", "checkout")
5271
        .unwrap_err()
5272
        .to_string();
5273
    assert!(
5274
        err.contains("b.txt") && err.contains("the first change"),
5275
        "{err}"
5276
    );
5277
    write(root, "b.txt", b"b\n");
5278
    let (_, carried) = repo
5279
        .checkout_carry(&[h1], "the first change", "checkout")
5280
        .unwrap();
5281
    assert_eq!(carried, vec!["a.txt"]);
5282
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
5283
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
5284
}
e7ac6c2e Andy McCall ↶ 5285
5286
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
5287
/// user identity not stored in a new repository yet is fine while its
5288
/// secret key is there; an added subrepo is listed as not committed yet.
5289
#[test]
5290
fn a_new_repository_is_healthy_before_its_first_commit() {
5291
    hermetic();
5292
    let dir = tempfile::tempdir().unwrap();
5293
    let root = dir.path();
5294
    let home = root.join("home");
5295
    let mut first = Repo::init(&root.join("first"))
5296
        .unwrap()
5297
        .with_home(home.clone());
5298
    let (key, _) = first
5299
        .create_identity("Ada", "[email protected]", IdentityScope::User)
5300
        .unwrap();
5301
    let repo = Repo::init(&root.join("second"))
5302
        .unwrap()
5303
        .with_home(home.clone());
5304
    // Only the secret key: no identity object anywhere this repository sees.
5305
    let keys = repo.keys_dir.clone();
5306
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
5307
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
5308
    let r = repo.doctor(true);
5309
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
5310
    assert_eq!(id.health, Health::Ok, "{}", id.message);
5311
    assert!(id.message.contains("first signed change"), "{}", id.message);
5312
5313
    // A subrepo added and not committed yet is listed, pinned where it is.
5314
    let lib = root.join("lib");
5315
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
5316
    write(&lib, "x.txt", b"x\n");
5317
    l.commit("x", &[]).unwrap();
5318
    let second = root.join("second");
5319
    write(&second, "a.txt", b"a\n");
5320
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
5321
        .unwrap();
5322
    let subs = repo.subrepos().unwrap();
5323
    assert_eq!(subs.len(), 1);
5324
    assert_eq!(
5325
        (subs[0].path.as_str(), subs[0].committed),
5326
        ("deps/lib", false)
5327
    );
5328
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5329
    repo.commit("add lib", &[]).unwrap();
5330
    let subs = repo.subrepos().unwrap();
5331
    assert!(subs[0].committed, "committed now");
5332
}
8ab265dc Andy McCall ↶ 5333
5334
/// Commit, diff, hunks and discard use the partial snapshot: a file
5335
/// unchanged since the manifest is neither read nor rendered, and showing
5336
/// a change renders only what it edits, the same as from a full base.
5337
#[cfg(unix)]
5338
#[test]
5339
fn commits_and_diffs_leave_unchanged_files_alone() {
5340
    use std::os::unix::fs::PermissionsExt;
5341
    hermetic();
5342
    let dir = tempfile::tempdir().unwrap();
5343
    let root = dir.path();
5344
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5345
    write(root, "big.txt", b"lots\nof\nlines\n");
5346
    write(root, "a.txt", b"one\ntwo\n");
5347
    repo.commit("base", &[]).unwrap();
5348
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
5349
    for f in ["big.txt", "a.txt"] {
5350
        fs::File::options()
5351
            .write(true)
5352
            .open(root.join(f))
5353
            .unwrap()
5354
            .set_modified(old)
5355
            .unwrap();
5356
    }
5357
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
5358
    // big.txt cannot be read at all from here on.
5359
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
5360
5361
    write(root, "a.txt", b"one\nTWO\nthree\n");
5362
    let diff = repo.diff_files(None).unwrap();
5363
    assert_eq!(
5364
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
5365
        ["a.txt"]
5366
    );
5367
    let (_, hunks) = repo.hunks().unwrap();
5368
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
5369
    let h = repo.commit("edit a", &[]).unwrap();
5370
5371
    // Showing the change needs only a.txt's graph, and renders as a full base does.
5372
    let c = repo.store().get_change(&h).unwrap();
5373
    let full = repo.load_state(&c.deps).unwrap();
5374
    let want = render_change(&c, &full, &full.materialize());
5375
    assert_eq!(repo.describe_change(&h).unwrap(), want);
5376
    let (base, snap) = repo.change_base(&c).unwrap();
5377
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
5378
5379
    // Discarding works the same way.
5380
    write(root, "a.txt", b"scratch\n");
5381
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
5382
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
5383
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
5384
}
f7510b63 Andy McCall ↶ 5385
5386
/// A replace conflict (spec §9.3) is settled by a change that writes one
5387
/// candidate, or new bytes, at the path when the caller names it; a plain
5388
/// snapshot of a checkout never settles it on its own.
5389
#[test]
5390
fn replace_conflicts_are_settled_when_asked() {
5391
    hermetic();
5392
    let dir = tempfile::tempdir().unwrap();
5393
    let root = dir.path();
5394
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5395
    let blob = |n: u8| {
5396
        let mut v = vec![0u8; 64];
5397
        v[1] = n;
5398
        v
5399
    };
5400
    write(root, "img.bin", &blob(1));
5401
    repo.commit("add img", &[]).unwrap();
5402
    repo.bookmark_create("other", None).unwrap();
5403
    write(root, "img.bin", &blob(2));
5404
    repo.commit("img two", &[]).unwrap();
5405
    repo.bookmark_switch("other", false).unwrap();
5406
    write(root, "img.bin", &blob(3));
5407
    repo.commit("img three", &[]).unwrap();
5408
    repo.bookmark_switch("main", false).unwrap();
5409
    repo.merge("other").unwrap();
5410
    let heads = repo.bookmark_heads().unwrap();
5411
    let merged = repo.load_state(&heads).unwrap().materialize();
5412
    assert!(
5413
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
5414
        "a replace conflict"
5415
    );
5416
    // A snapshot of the checkout records nothing.
5417
    assert!(repo
5418
        .snapshot("status")
5419
        .unwrap()
5420
        .statuses
5421
        .iter()
5422
        .all(|s| s.path != "img.bin"));
5423
5424
    // Keeping candidate 3 settles it.
5425
    let author = repo.author();
5426
    let edits = [FileEdit {
5427
        path: "img.bin".into(),
5428
        content: Some(blob(3)),
5429
    }];
5430
    let c = repo
5431
        .build_change(&heads, &edits, "keep three", author)
5432
        .unwrap();
5433
    assert_eq!(c.kind, ChangeKind::Resolution);
5434
    let mut st = repo.load_state(&heads).unwrap();
5435
    for d in &c.deps {
5436
        assert!(st.contains(d));
5437
    }
5438
    assert!(
5439
        heads.iter().all(|h| c.deps.contains(h)),
5440
        "depends on both contributors"
5441
    );
5442
    st.add(c).unwrap();
5443
    let after = st.materialize();
5444
    assert!(!after.is_conflicted());
5445
    assert_eq!(
5446
        after.files["img.bin"].content,
5447
        FileContent::Opaque {
5448
            blobs: vec![Repo::blob_ref(&blob(3))]
5449
        }
5450
    );
5451
5452
    // New bytes settle it too.
5453
    let edits = [FileEdit {
5454
        path: "img.bin".into(),
5455
        content: Some(blob(9)),
5456
    }];
5457
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
5458
    let mut st = repo.load_state(&heads).unwrap();
5459
    st.add(c).unwrap();
5460
    assert_eq!(
5461
        st.materialize().files["img.bin"].content,
5462
        FileContent::Opaque {
5463
            blobs: vec![Repo::blob_ref(&blob(9))]
5464
        }
5465
    );
5466
}
83d61e80 Andy McCall ↶ 5467
5468
/// The history of a range of lines (spec §27): the changes that wrote
5469
/// or deleted its atoms, or deleted atoms from between them; edits outside
5470
/// the range and changes the range's lines survived are not in it.
5471
#[test]
5472
fn line_ranges_have_exact_histories() {
5473
    hermetic();
5474
    let dir = tempfile::tempdir().unwrap();
5475
    let root = dir.path();
5476
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5477
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
5478
    let base = repo.commit("add f", &[]).unwrap();
5479
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
5480
    let outside = repo.commit("change the import", &[]).unwrap();
5481
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
5482
    let inside = repo.commit("edit a line of a", &[]).unwrap();
5483
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
5484
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
5485
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
5486
    let after = repo.commit("add b after a", &[]).unwrap();
5487
    let heads = repo.bookmark_heads().unwrap();
5488
5489
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
5490
    let hist: Vec<ChangeHash> = repo
5491
        .line_history(&heads, "f.rs", 2, 4)
5492
        .unwrap()
5493
        .iter()
5494
        .map(|e| e.hash)
5495
        .collect();
5496
    for (h, what) in [
5497
        (base, "wrote it"),
5498
        (inside, "edited a line"),
5499
        (deleted, "deleted a line from inside"),
5500
    ] {
5501
        assert!(hist.contains(&h), "{what}");
5502
    }
5503
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
5504
        assert!(!hist.contains(&h), "{what}");
5505
    }
5506
    assert_eq!(hist[0], deleted, "newest first");
5507
    // One line: only what touched it.
5508
    let one: Vec<ChangeHash> = repo
5509
        .line_history(&heads, "f.rs", 1, 1)
5510
        .unwrap()
5511
        .iter()
5512
        .map(|e| e.hash)
5513
        .collect();
5514
    assert!(one.contains(&outside) && !one.contains(&inside));
5515
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
5516
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
5517
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
5518
}
fc1a466a Andy McCall ↶ 5519
5520
#[test]
5521
fn receipts_are_kept_with_their_state_and_verified() {
5522
    use crate::receipt::{Receipt, SignedReceipt};
5523
    hermetic();
5524
    let dir = tempfile::tempdir().unwrap();
5525
    let root = dir.path();
5526
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5527
    write(root, "a.txt", b"1\n");
5528
    repo.commit("A", &[]).unwrap();
5529
    let heads = repo.bookmark_heads().unwrap();
5530
    let state = repo
5531
        .store()
5532
        .put_state(&StateObject::new(heads.clone()))
5533
        .unwrap();
5534
    let out = repo.store_blob(b"built\n").unwrap();
5535
    let receipt = Receipt {
5536
        job_name: "build".into(),
5537
        pipeline_hash: ObjectRef([1; 32]),
5538
        scope_tree_hash: ObjectRef([2; 32]),
5539
        inputs: vec![],
5540
        environment: ObjectRef([3; 32]),
5541
        outputs: vec![out],
5542
        exit_code: 0,
5543
        duration_ms: 42,
5544
    };
5545
    let sk = SecretKey::generate();
5546
    let runner = sk.identity("earth-1", "runner@earth", 1);
5547
    let sr = SignedReceipt::sign(
5548
        receipt.clone(),
5549
        repo.id().unwrap(),
5550
        state,
5551
        "demo#1",
5552
        &runner,
5553
        &sk,
5554
    );
5555
5556
    let r = repo.add_receipt(&sr).unwrap();
5557
    let found = repo.receipts(&heads).unwrap();
5558
    assert_eq!(found.len(), 1);
5559
    assert_eq!(found[0].attest, r);
5560
    assert_eq!(found[0].signed, sr);
5561
    assert!(found[0].problem.is_none() && !found[0].revoked);
5562
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
5563
5564
    // Another repository's receipt, or a forged one, is refused.
5565
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
5566
    assert!(repo
5567
        .add_receipt(&elsewhere)
5568
        .unwrap_err()
5569
        .to_string()
5570
        .contains("another repository"));
5571
    let mut forged = sr.clone();
5572
    forged.receipt.exit_code = 1;
5573
    assert!(repo
5574
        .add_receipt(&forged)
5575
        .unwrap_err()
5576
        .to_string()
5577
        .contains("does not verify"));
5578
5579
    // gc keeps the receipt, its runner and its output while the state lives.
5580
    repo.gc(true).unwrap();
5581
    assert_eq!(repo.receipts(&heads).unwrap().len(), 1);
5582
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
5583
    assert!(repo.fsck().unwrap().problems.is_empty());
dfb23a3a Andy McCall ↶ 5584
}
5585
5586
#[test]
5587
fn status_leaves_an_unchanged_manifest_alone() {
5588
    hermetic();
5589
    let dir = tempfile::tempdir().unwrap();
5590
    let root = dir.path();
5591
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5592
    write(root, "a.txt", b"1\n");
5593
    write(root, "b.txt", b"2\n");
5594
    repo.commit("A", &[]).unwrap();
5595
    // Files last touched well outside the racy window.
5596
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
5597
    for f in ["a.txt", "b.txt"] {
5598
        fs::File::options()
5599
            .write(true)
5600
            .open(root.join(f))
5601
            .unwrap()
5602
            .set_modified(old)
5603
            .unwrap();
5604
    }
5605
    repo.snapshot_status("status").unwrap();
5606
    let path = repo.manifest_path();
5607
    let first = fs::read(&path).unwrap();
5608
    repo.snapshot_status("status").unwrap();
5609
    assert_eq!(
5610
        fs::read(&path).unwrap(),
5611
        first,
5612
        "an unchanged tree does not rewrite the manifest"
5613
    );
5614
    // A change rewrites it.
5615
    write(root, "a.txt", b"1\n2\n");
5616
    repo.snapshot_status("status").unwrap();
5617
    assert_ne!(fs::read(&path).unwrap(), first);
fc1a466a Andy McCall ↶ 5618
}
6f8aeb99 Andy McCall ↶ 5619
5620
#[test]
5621
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
5622
    hermetic();
5623
    let dir = tempfile::tempdir().unwrap();
5624
    let root = dir.path();
5625
    let origin_path = root.join("origin");
5626
    Repo::init(&origin_path).unwrap();
5627
    let origin_url = origin_path.to_string_lossy().to_string();
5628
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
5629
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
5630
    write(&root.join("a"), "big.txt", big.as_bytes());
5631
    write(&root.join("a"), "small.txt", b"small\n");
5632
    let h1 = a.commit("large", &[]).unwrap();
5633
    let (_, body) = a.store().get(&h1).unwrap();
5634
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
5635
    assert!(a.push("origin", false).unwrap()[0].ok);
5636
5637
    // A clone reads the text from the blobs that came with the change.
5638
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
5639
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
5640
    // An edit in the middle of the stored insert is an ordinary change.
5641
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
5642
    write(&root.join("b"), "big.txt", edited.as_bytes());
5643
    let h2 = b.commit("edit", &[]).unwrap();
5644
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
5645
    assert!(b.push("origin", false).unwrap()[0].ok);
5646
    assert!(a.pull("origin").unwrap().checked_out);
5647
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
5648
    assert_eq!(
5649
        a.fsck().unwrap().errors(),
5650
        0,
5651
        "{:?}",
5652
        a.fsck().unwrap().problems
5653
    );
5654
5655
    // With zero retention gc keeps the text blobs of every kept change.
5656
    let mut a = Repo::open(&root.join("a")).unwrap();
5657
    a.config.set("core.op-retention", "0").unwrap();
5658
    a.save_config().unwrap();
5659
    let a = Repo::open(&root.join("a")).unwrap();
5660
    a.gc(true).unwrap();
5661
    let a = Repo::open(&root.join("a")).unwrap();
5662
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
5663
    assert_eq!(
5664
        a.fsck().unwrap().errors(),
5665
        0,
5666
        "{:?}",
5667
        a.fsck().unwrap().problems
5668
    );
5669
    // And a clone of the packed repository reads them from its packs.
5670
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
5671
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
5672
    drop(c);
6caacfff Andy McCall ↶ 5673
}
5674
5675
#[test]
5676
fn operations_that_both_replace_a_working_copy_are_not_merged() {
5677
    hermetic();
5678
    let dir = tempfile::tempdir().unwrap();
5679
    let root = dir.path();
5680
    let repo = Repo::init(root).unwrap();
5681
    write(root, "a.txt", b"a\n");
5682
    let a = repo.commit("a", &[]).unwrap();
5683
    write(root, "b.txt", b"b\n");
5684
    repo.commit("b", &[]).unwrap();
5685
    let (x, op) = repo.head_op().unwrap();
5686
    let ws = *op.view.workspaces.keys().next().unwrap();
5687
    let mut one = op.view.clone();
5688
    one.workspaces.insert(ws, a);
5689
    let mut two = op.view.clone();
5690
    two.workspaces.insert(ws, ObjectRef([7; 32]));
5691
    let first = repo.record_op(&[x], "one", one).unwrap();
5692
    let e = repo.record_op(&[x], "two", two).unwrap_err();
5693
    assert!(
5694
        e.to_string()
5695
            .contains("changed this working copy at the same time"),
5696
        "{e}"
5697
    );
5698
    assert_eq!(
5699
        repo.head_op().unwrap().0,
5700
        first,
5701
        "the second is not recorded"
5702
    );
5703
}
5704
5705
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
5706
/// rewrote the working copy recorded the half-written files as edits, and
5707
/// its view replaced the switch's.
5708
#[test]
5709
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
5710
    hermetic();
5711
    let dir = tempfile::tempdir().unwrap();
5712
    let root = dir.path().to_path_buf();
5713
    let mut repo = Repo::init(&root).unwrap();
5714
    write(&root, "keep.txt", b"keep\n");
5715
    repo.commit("base", &[]).unwrap();
5716
    repo.bookmark_create("small", None).unwrap();
5717
    for i in 0..300 {
5718
        write(
5719
            &root,
5720
            &format!("many/f{i}.txt"),
5721
            format!("file {i}\n").as_bytes(),
5722
        );
5723
    }
5724
    repo.commit("many", &[]).unwrap();
5725
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5726
    let watcher = {
5727
        let (root, stop) = (root.clone(), stop.clone());
5728
        std::thread::spawn(move || {
5729
            let r = Repo::open(&root).unwrap();
5730
            let mut ran = 0;
5731
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
5732
                if r.snapshot_status("oxy status").is_ok() {
5733
                    ran += 1;
5734
                }
5735
            }
5736
            ran
5737
        })
5738
    };
5739
    for i in 0..20 {
5740
        let to = if i % 2 == 0 { "small" } else { "main" };
5741
        repo.bookmark_switch(to, false).unwrap();
5742
    }
5743
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
5744
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
5745
    // Back on main, clean, with every file where main has it.
5746
    let repo = Repo::open(&root).unwrap();
5747
    let s = repo.snapshot_status("oxy status").unwrap();
5748
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
5749
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
5750
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
5751
    assert!(root.join("many/f299.txt").exists());
1a3b6203 Andy McCall ↶ 5752
}
5753
5754
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
5755
/// put a subrepo that was ahead of its pin back at the pin and moved the
5756
/// subrepo's own bookmark backwards.
5757
#[test]
5758
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
5759
    hermetic();
5760
    let dir = tempfile::tempdir().unwrap();
5761
    let root = dir.path();
5762
    Repo::init(&root.join("lib-origin")).unwrap();
5763
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5764
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
5765
    write(&root.join("lib"), "lib.txt", b"v1\n");
5766
    lib.commit("lib v1", &[]).unwrap();
5767
    assert!(lib.push("origin", false).unwrap()[0].ok);
5768
5769
    let app_dir = root.join("app");
5770
    let mut app = Repo::init(&app_dir).unwrap();
5771
    write(&app_dir, "main.txt", b"app\n");
5772
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5773
    app.commit("app with lib", &[]).unwrap();
5774
    app.bookmark_create("feature", None).unwrap();
5775
5776
    // New work in the subrepo, not yet pinned by the parent.
5777
    let nested_dir = app_dir.join("libs/lib");
5778
    let nested = Repo::open(&nested_dir).unwrap();
5779
    write(&nested_dir, "new.txt", b"new\n");
5780
    let l2 = nested.commit("lib: new file", &[]).unwrap();
5781
    drop(nested);
5782
5783
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
5784
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
5785
    let nested = Repo::open(&nested_dir).unwrap();
5786
    assert!(
5787
        nested.bookmark_heads().unwrap().contains(&l2),
5788
        "its bookmark kept its work"
5789
    );
5790
    assert!(nested_dir.join("new.txt").exists(), "and its files");
5791
    let s = app.snapshot("status").unwrap();
5792
    assert_eq!(
5793
        statuses(&s),
5794
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
5795
    );
6f8aeb99 Andy McCall ↶ 5796
}
7d9dab13 Andy McCall ↶ 5797
5798
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
5799
/// moving `main` to a change this clone had pushed on another bookmark,
5800
/// the first `pull` said "Already up to date" while `main` was behind.
5801
#[test]
5802
fn pull_takes_a_remote_move_to_changes_already_here() {
5803
    hermetic();
5804
    let dir = tempfile::tempdir().unwrap();
5805
    let root = dir.path();
5806
    let origin_path = root.join("origin");
5807
    let origin = Repo::init(&origin_path).unwrap();
5808
    let url = origin_path.to_string_lossy().to_string();
5809
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
5810
    write(&root.join("b"), "base.txt", b"base\n");
5811
    b.commit("base", &[]).unwrap();
5812
    assert!(b.push("origin", false).unwrap()[0].ok);
5813
5814
    // A feature bookmark with one change, pushed.
5815
    b.bookmark_create("feat", None).unwrap();
5816
    b.bookmark_switch("feat", false).unwrap();
5817
    write(&root.join("b"), "x.txt", b"x\n");
5818
    let x = b.commit("x", &[]).unwrap();
5819
    assert!(b.push("origin", false).unwrap()[0].ok);
5820
    b.bookmark_switch("main", false).unwrap();
5821
5822
    // The remote lands it: its main moves to the feature's state.
5823
    let feat = origin
5824
        .store()
5825
        .get_state(&origin.view().unwrap().bookmarks["feat"])
5826
        .unwrap()
5827
        .heads;
5828
    origin.bookmark_set("main", &feat).unwrap();
5829
5830
    let r = b.pull("origin").unwrap();
5831
    assert!(r.changed, "{r:?}");
5832
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
5833
    let main = b
5834
        .bookmarks()
5835
        .unwrap()
5836
        .into_iter()
5837
        .find(|m| m.name == "main")
5838
        .unwrap();
5839
    assert_eq!(main.behind, Some(0), "{main:?}");
5840
}
86e1824f Andy McCall ↶ 5841
14edbaaf Andy McCall ↶ 5842
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
5843
/// to one only the remote has makes a local bookmark from it; a pull moves
5844
/// every local bookmark the remote has too; a clone checks out the remote's
5845
/// default bookmark.
5846
#[test]
5847
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
5848
    hermetic();
5849
    let dir = tempfile::tempdir().unwrap();
5850
    let root = dir.path();
5851
    let origin_path = root.join("origin");
5852
    let mut origin = Repo::init(&origin_path).unwrap();
5853
    let url = origin_path.to_string_lossy().to_string();
5854
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
5855
    write(&root.join("a"), "base.txt", b"base\n");
5856
    a.commit("base", &[]).unwrap();
5857
    assert!(a.push("origin", false).unwrap()[0].ok);
5858
    a.bookmark_create("develop", None).unwrap();
5859
    a.bookmark_switch("develop", false).unwrap();
5860
    write(&root.join("a"), "base.txt", b"base\nd1\n");
5861
    let d1 = a.commit("d1", &[]).unwrap();
5862
    assert!(a.push("origin", false).unwrap()[0].ok);
5863
5864
    // A clone has main only; origin/develop is a name all the same.
5865
    let c_root = root.join("c");
5866
    let mut c = Repo::clone(&url, &c_root).unwrap();
5867
    assert_eq!(c.config.bookmark, "main");
5868
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
5869
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
5870
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
5871
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
5872
5873
    // Switching makes the local bookmark from origin's.
5874
    c.bookmark_switch("develop", false).unwrap();
5875
    assert_eq!(c.config.bookmark, "develop");
5876
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
5877
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
5878
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
5879
    assert!(c.bookmark_switch("nowhere", false).is_err());
5880
5881
    // Both bookmarks move on the remote; one pull takes both.
5882
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
5883
    let d2 = a.commit("d2", &[]).unwrap();
5884
    assert!(a.push("origin", false).unwrap()[0].ok);
5885
    a.bookmark_switch("main", false).unwrap();
5886
    write(&root.join("a"), "m.txt", b"m\n");
5887
    let m = a.commit("m", &[]).unwrap();
5888
    assert!(a.push("origin", false).unwrap()[0].ok);
5889
    let r = c.pull("origin").unwrap();
5890
    assert!(r.changed && r.checked_out, "{r:?}");
5891
    assert_eq!(r.heads, vec![d2]);
5892
    assert_eq!(r.others, vec!["main".to_string()]);
5893
    assert!(c.resolve_heads("main").unwrap().contains(&m));
5894
    assert_eq!(
5895
        fs::read(c_root.join("base.txt")).unwrap(),
5896
        b"base\nd1\nd2\n"
5897
    );
5898
    let again = c.pull("origin").unwrap();
5899
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
5900
5901
    // A clone checks out the remote's default bookmark.
5902
    origin.config.set("workspace.bookmark", "develop").unwrap();
5903
    origin.save_config().unwrap();
5904
    let e = Repo::clone(&url, &root.join("e")).unwrap();
5905
    assert_eq!(e.config.bookmark, "develop");
5906
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
5907
    let reopened = Repo::open(&root.join("e")).unwrap();
5908
    assert_eq!(reopened.config.bookmark, "develop");
5909
    // REMOTE/NAME names the remote's bookmark to switch to.
5910
    let mut e = reopened;
5911
    e.bookmark_switch("origin/main", false).unwrap();
5912
    assert_eq!(e.config.bookmark, "main");
5913
    assert!(e.bookmark_heads().unwrap().contains(&m));
5914
}
5915
98a1620a Andy McCall ↶ 5916
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
5917
/// op restore goes back to an operation, files included, and undo takes
5918
/// the restore back whole; op revert undoes one operation alone; each
5919
/// operation's changes are described from the views.
5920
#[test]
5921
fn operations_can_be_read_restored_and_reverted() {
5922
    hermetic();
5923
    let dir = tempfile::tempdir().unwrap();
5924
    let root = dir.path();
5925
    let repo = Repo::init(root).unwrap();
5926
    write(root, "a.txt", b"a\n");
5927
    let first = repo.commit("first", &[]).unwrap();
5928
    write(root, "a.txt", b"a\nb\n");
5929
    let second = repo.commit("second", &[]).unwrap();
5930
    let at_second = repo.head_op().unwrap().0.to_hex();
5931
    repo.bookmark_create("keep", None).unwrap();
5932
    let created = repo.head_op().unwrap().0.to_hex();
5933
    write(root, "n.txt", b"n\n");
5934
    let third = repo.commit("third", &[]).unwrap();
5935
5936
    // What each operation changed.
5937
    let ops = repo.op_log().unwrap();
5938
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
5939
    assert!(
5940
        changes
5941
            .iter()
5942
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
5943
        "{changes:?}"
5944
    );
5945
    assert!(changes
5946
        .iter()
5947
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
5948
5949
    // Reading at an earlier operation.
5950
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
5951
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
5952
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
5953
    write(root, "z.txt", b"z\n");
5954
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
5955
    fs::remove_file(root.join("z.txt")).unwrap();
5956
    assert!(repo.resolve_op("zz").is_err());
5957
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
5958
5959
    // Restore goes back, files and all; undo takes it back whole.
5960
    repo.op_restore(&at_second, false).unwrap();
5961
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
5962
    assert!(!root.join("n.txt").exists());
5963
    repo.undo().unwrap();
5964
    let mut heads = repo.bookmark_heads().unwrap();
5965
    heads.sort();
5966
    let mut want = vec![second, third];
5967
    want.sort();
5968
    assert_eq!(heads, want);
5969
    assert!(
5970
        root.join("n.txt").exists(),
5971
        "the files came back with the undo"
5972
    );
5973
5974
    // Revert the bookmark's creation alone: the commit after it stays.
5975
    let r = repo.op_revert(&created).unwrap();
5976
    assert_eq!(r.reverted, vec!["keep".to_string()]);
5977
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
5978
    assert!(repo
5979
        .load_state(&repo.bookmark_heads().unwrap())
5980
        .unwrap()
5981
        .contains(&third));
5982
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
5983
    let _ = first;
5984
}
5985
36041796 Andy McCall ↶ 5986
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
5987
/// from the status cache while every file is as the snapshot left it, and
5988
/// from a snapshot again as soon as one is not.
5989
#[test]
5990
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
5991
    hermetic();
5992
    let dir = tempfile::tempdir().unwrap();
5993
    let root = dir.path();
5994
    let repo = Repo::init(root).unwrap();
5995
    write(root, "a.txt", b"a\n");
5996
    write(root, "b.txt", b"b\n");
5997
    repo.commit("base", &[]).unwrap();
5998
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
5999
6000
    write(root, "a.txt", b"a\nmore\n");
6001
    assert_eq!(
6002
        repo.status_by_manifest().unwrap(),
6003
        None,
6004
        "no snapshot of the edit yet"
6005
    );
6006
    let snap = repo.snapshot_status("oxy status").unwrap();
6007
    assert_eq!(snap.statuses.len(), 1);
6008
    let cached = repo
6009
        .status_by_manifest()
6010
        .unwrap()
6011
        .expect("answered from the cache");
6012
    assert_eq!(cached.len(), 1);
6013
    assert_eq!(
6014
        (cached[0].path.as_str(), cached[0].status),
6015
        ("a.txt", ChangeStatus::Modified)
6016
    );
6017
6018
    // Any further change sends status back to a snapshot.
6019
    write(root, "a.txt", b"a\nmore\nand more\n");
6020
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
6021
    repo.snapshot_status("oxy status").unwrap();
6022
    assert!(repo.status_by_manifest().unwrap().is_some());
6023
    write(root, "new.txt", b"n\n");
6024
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
6025
    fs::remove_file(root.join("new.txt")).unwrap();
6026
    assert!(
6027
        repo.status_by_manifest().unwrap().is_some(),
6028
        "back as it was"
6029
    );
6030
    fs::remove_file(root.join("b.txt")).unwrap();
6031
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
6032
    write(root, "b.txt", b"b\n");
6033
6034
    // A commit leaves nothing uncommitted: clean again, no cache needed.
6035
    repo.snapshot_status("oxy status").unwrap();
6036
    repo.commit("more", &[]).unwrap();
6037
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6038
}
6039
77445673 Andy McCall ↶ 6040
/// oxygen#41: while the status cache holds, the working copy's diff is
6041
/// rendered from the stored working-copy change, and says exactly what a
6042
/// snapshot's diff says.
6043
#[test]
6044
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
6045
    hermetic();
6046
    let dir = tempfile::tempdir().unwrap();
6047
    let root = dir.path();
6048
    let repo = Repo::init(root).unwrap();
6049
    write(root, "a.txt", b"one\ntwo\nthree\n");
6050
    write(root, "gone.txt", b"bye\n");
6051
    repo.commit("base", &[]).unwrap();
6052
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
6053
    write(root, "new.txt", b"hello\n");
6054
    fs::remove_file(root.join("gone.txt")).unwrap();
6055
    let snap = repo.snapshot_status("oxy status").unwrap();
6056
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
6057
    assert!(
6058
        repo.status_by_manifest().unwrap().is_some(),
6059
        "the cache holds"
6060
    );
6061
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
6062
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
6063
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
6064
}
6065
1ec3f008 Andy McCall ↶ 6066
/// oxygen#41: a manifest written from a walk keeps every directory's time;
6067
/// while none has moved, the check stats the tracked files without listing
6068
/// the tree, and a file added or removed anywhere moves its directory's
6069
/// time, so the tree is listed again.
6070
#[test]
6071
fn the_manifest_check_skips_listing_while_no_directory_changed() {
6072
    hermetic();
6073
    let dir = tempfile::tempdir().unwrap();
6074
    let root = dir.path();
6075
    let repo = Repo::init(root).unwrap();
6076
    write(root, "a.txt", b"a\n");
6077
    write(root, "sub/deep/b.txt", b"b\n");
6078
    repo.commit("base", &[]).unwrap();
6079
    // Out of the racy window: every file and directory a minute old.
6080
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6081
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
6082
        fs::File::open(root.join(p))
6083
            .unwrap()
6084
            .set_modified(old)
6085
            .unwrap();
6086
    }
6087
    repo.snapshot_status("oxy status").unwrap();
6088
    repo.write_manifest(false, false).unwrap();
6089
    let m = repo.read_manifest().unwrap().unwrap().2;
6090
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
6091
    assert_eq!(
6092
        repo.disk_differs_by_dirs(&m),
6093
        Some(false),
6094
        "no listing needed"
6095
    );
6096
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
6097
6098
    // A same-size edit with a new time: found by its stat.
6099
    write(root, "sub/deep/b.txt", b"c\n");
6100
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
6101
    write(root, "sub/deep/b.txt", b"b\n");
6102
    fs::File::open(root.join("sub/deep/b.txt"))
6103
        .unwrap()
6104
        .set_modified(old)
6105
        .unwrap();
6106
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
6107
6108
    // A new file moves its directory's time: the tree must be listed.
6109
    write(root, "sub/deep/new.txt", b"n\n");
6110
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6111
    assert_eq!(repo.status_by_manifest().unwrap(), None);
6112
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
6113
    // A removed one too.
6114
    fs::remove_file(root.join("a.txt")).unwrap();
6115
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
6116
}
6117
e226a6cc Andy McCall ↶ 6118
/// oxygen#41: a commit right after a status takes the snapshot the status
6119
/// left (the status cache holds) rather than walking again, and commits
6120
/// exactly what a snapshot would have.
6121
#[test]
6122
fn a_commit_after_a_status_uses_the_cached_snapshot() {
6123
    hermetic();
6124
    let dir = tempfile::tempdir().unwrap();
6125
    let root = dir.path();
6126
    let repo = Repo::init(root).unwrap();
6127
    write(root, "a.txt", b"a\nb\n");
6128
    write(root, ".oxyattributes", b"*.bin binary\n");
6129
    repo.commit("base", &[]).unwrap();
6130
    write(root, "a.txt", b"a\nB\n");
6131
    write(root, "new.txt", b"new\n");
6132
    let snap = repo.snapshot_status("oxy status").unwrap();
6133
    let cached = repo
6134
        .snapshot_from_cache()
6135
        .unwrap()
6136
        .expect("the cache holds");
6137
    assert_eq!(cached.wc_hash, snap.wc_hash);
6138
    assert_eq!(cached.statuses, snap.statuses);
6139
    assert!(
6140
        !cached.attributes.is_empty(),
6141
        "the .oxyattributes file was read"
6142
    );
6143
    let h = repo.commit("edit", &[]).unwrap();
6144
    let c = repo.store().get_change(&h).unwrap();
6145
    assert_eq!(
6146
        c.tree_ops.len() + c.edits.len(),
6147
        snap.wc.tree_ops.len() + snap.wc.edits.len()
6148
    );
6149
    assert_eq!(
6150
        repo.status_by_manifest().unwrap(),
6151
        Some(vec![]),
6152
        "clean after the commit"
6153
    );
6154
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
6155
}
6156
0389c3e8 Andy McCall ↶ 6157
/// oxygen#41: a clean check that verified racy entries restamps the
6158
/// manifest, so later checks can trust them, and a same-size rewrite
6159
/// straight afterwards is still found: entries within two seconds of the
6160
/// new time stay racy.
6161
#[test]
6162
fn a_verified_clean_check_restamps_the_manifest_safely() {
6163
    hermetic();
6164
    let dir = tempfile::tempdir().unwrap();
6165
    let root = dir.path();
6166
    let repo = Repo::init(root).unwrap();
6167
    write(root, "a.txt", b"one\n");
6168
    repo.commit("one", &[]).unwrap();
6169
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
6170
    assert!(repo.clean_by_manifest().unwrap());
6171
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
6172
    assert!(after > before, "restamped");
6173
    write(root, "a.txt", b"two\n");
6174
    assert!(
6175
        !repo.clean_by_manifest().unwrap(),
6176
        "a same-size rewrite is still seen"
6177
    );
6178
}
6179
86e1824f Andy McCall ↶ 6180
/// oxygen#35: a history-only state keeps no inserted text. It reads a
6181
/// stored insert's text blob only when it builds that file's graph, and
6182
/// builds the same graph a full load does.
6183
#[test]
6184
fn history_only_states_read_text_only_for_the_graphs_they_build() {
6185
    hermetic();
6186
    let dir = tempfile::tempdir().unwrap();
6187
    let root = dir.path();
6188
    let repo = Repo::init(root).unwrap();
6189
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
6190
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
6191
    write(root, "big.txt", big.as_bytes());
6192
    write(root, "other.txt", other.as_bytes());
6193
    let h = repo.commit("two large files", &[]).unwrap();
6194
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
6195
    let h2 = repo.commit("append", &[]).unwrap();
6196
6197
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
6198
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
6199
        FileContent::Text { bytes, .. } => bytes.clone(),
6200
        other => panic!("{other:?}"),
6201
    };
6202
    // Built on demand, every graph renders as the full load's.
6203
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6204
    let big_node = full.files["big.txt"].node;
6205
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
6206
    repo.load_all_graphs(&mut hist).unwrap();
6207
    let rendered = hist.materialize();
6208
    for p in ["big.txt", "other.txt"] {
6209
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
6210
    }
6211
6212
    // Without other.txt's text blob, history still loads and big.txt still
6213
    // builds: nothing read the other text.
6214
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6215
    assert_eq!(texts.len(), 2);
6216
    let content = |r: &ObjectRef| -> Vec<u8> {
6217
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
6218
        blob.chunks
6219
            .iter()
6220
            .flat_map(|c| repo.store().get(c).unwrap().1)
6221
            .collect()
6222
    };
6223
    let other_text = texts
6224
        .iter()
a4fad5b0 Andy McCall ↶ 6225
        .filter_map(|t| match t {
0f93f49c Andy McCall ↶ 6226
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
a4fad5b0 Andy McCall ↶ 6227
            _ => None,
6228
        })
86e1824f Andy McCall ↶ 6229
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
6230
        .unwrap();
64818938 Andy McCall ↶ 6231
    repo.store().remove_loose_for_test(&other_text).unwrap();
86e1824f Andy McCall ↶ 6232
    let mut hist = repo.load_state_history(&[h2]).unwrap();
6233
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
6234
    assert!(repo
6235
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
6236
        .is_err());
6237
}
6238
6239
/// oxygen#35: the first status after a commit read and rendered every
6240
/// file (79 s and more than 14 GB on the Linux tree), because the
6241
/// manifest had no graph keys for files the commit added.
6242
#[test]
6243
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
6244
    use std::os::unix::fs::PermissionsExt;
6245
    hermetic();
6246
    let dir = tempfile::tempdir().unwrap();
6247
    let root = dir.path();
6248
    let repo = Repo::init(root).unwrap();
6249
    let files = ["a.txt", "b.txt", "d/c.txt"];
6250
    for p in files {
6251
        write(root, p, format!("{p}\n").as_bytes());
6252
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6253
        fs::File::options()
6254
            .write(true)
6255
            .open(root.join(p))
6256
            .unwrap()
6257
            .set_modified(old)
6258
            .unwrap();
6259
    }
6260
    repo.commit("added", &[]).unwrap();
6261
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6262
    assert!(
6263
        m.entries.values().all(|e| e.graph.is_some()),
6264
        "keys recorded at commit"
6265
    );
6266
    // Unreadable files prove the next status reads none of them.
6267
    for p in files {
6268
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
6269
    }
6270
    let snap = repo.snapshot_status("status").unwrap();
6271
    for p in files {
6272
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
6273
    }
6274
    assert!(!snap.changed && snap.statuses.is_empty());
6275
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
6276
}
c5ce0367 Andy McCall ↶ 6277
6278
/// oxygen#35: a checkout reads, renders and writes only the files whose
6279
/// graphs differ, and renders the rest a batch at a time.
6280
#[test]
6281
fn checkout_touches_only_what_differs_and_renders_in_batches() {
6282
    use std::os::unix::fs::PermissionsExt;
6283
    hermetic();
6284
    let dir = tempfile::tempdir().unwrap();
6285
    let root = dir.path();
6286
    let origin = root.join("origin");
6287
    let mut repo = Repo::init(&origin).unwrap();
6288
    // More files than one batch holds.
6289
    let n = 2100;
6290
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6291
    for i in 0..n {
6292
        let p = format!("f/{i:04}.txt");
6293
        write(&origin, &p, format!("file {i}\n").as_bytes());
6294
        fs::File::options()
6295
            .write(true)
6296
            .open(origin.join(&p))
6297
            .unwrap()
6298
            .set_modified(old)
6299
            .unwrap();
6300
    }
6301
    repo.commit("many", &[]).unwrap();
6302
    repo.bookmark_create("feature", None).unwrap();
6303
    repo.bookmark_switch("feature", false).unwrap();
6304
    write(&origin, "f/0007.txt", b"changed\n");
6305
    repo.commit("one change", &[]).unwrap();
6306
6307
    // Switching back to main must not read the unchanged files.
6308
    for i in 0..n {
6309
        if i != 7 {
6310
            let p = origin.join(format!("f/{i:04}.txt"));
6311
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
6312
        }
6313
    }
6314
    let r = repo.bookmark_switch("main", false).unwrap();
6315
    for i in 0..n {
6316
        let p = origin.join(format!("f/{i:04}.txt"));
6317
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
6318
    }
6319
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
6320
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
6321
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6322
6323
    // A clone renders every file, across batches.
6324
    let c = root.join("clone");
6325
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
6326
    for i in [0, 2047, 2048, n - 1] {
6327
        assert_eq!(
6328
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
6329
            format!("file {i}\n").as_bytes()
6330
        );
6331
    }
6332
    let cloned = Repo::open(&c).unwrap();
6333
    assert!(cloned
6334
        .snapshot_status("status")
6335
        .unwrap()
6336
        .statuses
6337
        .is_empty());
d3cd7ef9 Andy McCall ↶ 6338
}
6339
6340
/// A file written just before the manifest (inside the racy window) is
6341
/// checked by its hash: trusted when equal, caught when edited in place
6342
/// with the same size and time.
6343
#[test]
6344
fn a_racy_manifest_entry_is_checked_by_hash() {
6345
    hermetic();
6346
    let dir = tempfile::tempdir().unwrap();
6347
    let root = dir.path();
6348
    let repo = Repo::init(root).unwrap();
6349
    write(root, "a.txt", b"one\n");
6350
    repo.commit("fresh", &[]).unwrap();
6351
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
6352
    let t = fs::metadata(root.join("a.txt"))
6353
        .unwrap()
6354
        .modified()
6355
        .unwrap();
6356
    write(root, "a.txt", b"two\n");
6357
    fs::File::options()
6358
        .write(true)
6359
        .open(root.join("a.txt"))
6360
        .unwrap()
6361
        .set_modified(t)
6362
        .unwrap();
6363
    assert!(
6364
        !repo.clean_by_manifest().unwrap(),
6365
        "same size and time, other bytes"
6366
    );
6367
    assert_eq!(
6368
        statuses(&repo.snapshot_status("status").unwrap()),
6369
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
6370
    );
c5ce0367 Andy McCall ↶ 6371
}
2c75672f Andy McCall ↶ 6372
6373
/// A fetch on one machine moves changes as stored, text blobs among the
6374
/// objects; a change whose text blob did not come is refused, not stored.
6375
#[test]
6376
fn a_raw_bundle_without_a_changes_text_is_refused() {
6377
    hermetic();
6378
    let dir = tempfile::tempdir().unwrap();
6379
    let root = dir.path();
6380
    let a = Repo::init(&root.join("a")).unwrap();
6381
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6382
    write(&root.join("a"), "big.txt", big.as_bytes());
6383
    let h = a.commit("big", &[]).unwrap();
6384
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
6385
    assert_eq!(bundle.raw_changes.len(), 1);
6386
    assert!(bundle.changes.is_empty());
6387
    let b = Repo::init(&root.join("b")).unwrap();
6388
    let mut without = bundle.clone();
6389
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
6390
    let e = b.import_bundle(&without, false).unwrap_err();
6391
    assert!(e.to_string().contains("came without its text blob"), "{e}");
6392
    assert!(!b.store().has(&h));
6393
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
6394
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
6395
}
a87c7b9d Andy McCall ↶ 6396
6397
/// oxygen#30 (vscode): a directory deleted in one line of history and made
6398
/// again was a second node for one Git path, so a file moved into it on
6399
/// another line, where the first node still stood, ended up in two places.
6400
/// An import now brings the directory back rather than make a new one.
6401
#[test]
6402
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
6403
    hermetic();
6404
    if std::process::Command::new("git")
6405
        .arg("--version")
6406
        .output()
6407
        .is_err()
6408
    {
6409
        eprintln!("git not installed; skipping");
6410
        return;
6411
    }
6412
    let dir = tempfile::tempdir().unwrap();
6413
    let root = dir.path();
6414
    let g = root.join("src.git");
6415
    fs::create_dir_all(&g).unwrap();
6416
    let git = |args: &[&str]| -> String {
6417
        let out = std::process::Command::new("git")
6418
            .arg("-C")
6419
            .arg(&g)
6420
            .args([
6421
                "-c",
6422
                "user.name=Grace",
6423
                "-c",
6424
                "[email protected]",
6425
                "-c",
6426
                "commit.gpgsign=false",
6427
            ])
6428
            .args(args)
6429
            .output()
6430
            .unwrap();
6431
        assert!(
6432
            out.status.success(),
6433
            "git {args:?}: {}",
6434
            String::from_utf8_lossy(&out.stderr)
6435
        );
6436
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6437
    };
6438
    git(&["init", "-q", "-b", "main"]);
6439
    write(&g, "d/a.txt", b"a\n");
6440
    write(&g, "c/x.txt", b"x\n");
6441
    git(&["add", "."]);
6442
    git(&["commit", "-qm", "base"]);
6443
    // One line: move x into d while d still stands.
6444
    git(&["checkout", "-qb", "side"]);
6445
    git(&["mv", "c/x.txt", "d/x.txt"]);
6446
    git(&["commit", "-qm", "x into d"]);
6447
    // The other: d goes, comes back, and x moves into it too.
6448
    git(&["checkout", "-q", "main"]);
6449
    git(&["rm", "-q", "d/a.txt"]);
6450
    git(&["commit", "-qm", "d goes"]);
6451
    write(&g, "d/b.txt", b"b\n");
6452
    git(&["add", "."]);
6453
    git(&["commit", "-qm", "d comes back"]);
6454
    git(&["mv", "c/x.txt", "d/x.txt"]);
6455
    git(&["commit", "-qm", "x into d again"]);
6456
    git(&["merge", "-q", "--no-edit", "side"]);
6457
6458
    let repo = Repo::init(&root.join("o")).unwrap();
6459
    repo.import_git(&g, "main").unwrap();
6460
    let v = repo.verify_git_import(&g, "main").unwrap();
6461
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6462
    let st = repo
6463
        .load_state_history(&repo.bookmark_heads().unwrap())
6464
        .unwrap();
6465
    let view = st.tree().view();
6466
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6467
    // The directory is the one the first commit made.
6468
    // Commits made in one second tie on time: find the first by its message.
6469
    let first = repo
6470
        .log()
6471
        .unwrap()
6472
        .into_iter()
6473
        .find(|e| e.change.message.starts_with("base"))
6474
        .unwrap();
6475
    let base = repo
6476
        .load_state_history(&[first.hash])
6477
        .unwrap()
6478
        .tree()
6479
        .view();
6480
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
6481
}
6482
6483
/// oxygen#30, the rest: a placement left under a directory another line
6484
/// removed is out of sight, so no diff reaches it; the merge that settles
6485
/// where the file is retires it.
6486
#[test]
6487
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
6488
    hermetic();
6489
    if std::process::Command::new("git")
6490
        .arg("--version")
6491
        .output()
6492
        .is_err()
6493
    {
6494
        eprintln!("git not installed; skipping");
6495
        return;
6496
    }
6497
    let dir = tempfile::tempdir().unwrap();
6498
    let root = dir.path();
6499
    let g = root.join("src.git");
6500
    fs::create_dir_all(&g).unwrap();
6501
    let run = |args: &[&str]| {
6502
        std::process::Command::new("git")
6503
            .arg("-C")
6504
            .arg(&g)
6505
            .args([
6506
                "-c",
6507
                "user.name=Grace",
6508
                "-c",
6509
                "[email protected]",
6510
                "-c",
6511
                "commit.gpgsign=false",
6512
            ])
6513
            .args(args)
6514
            .output()
6515
            .unwrap()
6516
    };
6517
    let git = |args: &[&str]| {
6518
        let out = run(args);
6519
        assert!(
6520
            out.status.success(),
6521
            "git {args:?}: {}",
6522
            String::from_utf8_lossy(&out.stderr)
6523
        );
6524
    };
6525
    git(&["init", "-q", "-b", "main"]);
6526
    write(&g, "c/x.txt", b"x\n");
6527
    write(&g, "keep.txt", b"k\n");
6528
    git(&["add", "."]);
6529
    git(&["commit", "-qm", "base"]);
6530
    // One line renames the file within c; the other moves it out of c,
6531
    // which goes.
6532
    git(&["checkout", "-qb", "side"]);
6533
    git(&["mv", "c/x.txt", "c/y.txt"]);
6534
    git(&["commit", "-qm", "rename within c"]);
6535
    git(&["checkout", "-q", "main"]);
6536
    fs::create_dir_all(g.join("n")).unwrap();
6537
    git(&["mv", "c/x.txt", "n/x.txt"]);
6538
    git(&["commit", "-qm", "move out of c"]);
6539
    // Git cannot merge the two renames; the merge keeps n/x.txt.
6540
    let _ = run(&["merge", "-q", "side"]);
6541
    let _ = run(&[
6542
        "rm",
6543
        "-q",
6544
        "--cached",
6545
        "--ignore-unmatch",
6546
        "c/y.txt",
6547
        "c/x.txt",
6548
    ]);
6549
    let _ = std::fs::remove_dir_all(g.join("c"));
6550
    write(&g, "n/x.txt", b"x\n");
6551
    git(&["add", "-A"]);
6552
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
6553
6554
    let repo = Repo::init(&root.join("o")).unwrap();
6555
    repo.import_git(&g, "main").unwrap();
6556
    let v = repo.verify_git_import(&g, "main").unwrap();
6557
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6558
    let st = repo
6559
        .load_state_history(&repo.bookmark_heads().unwrap())
6560
        .unwrap();
6561
    let view = st.tree().view();
6562
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6563
    assert!(view.entries.contains_key("n/x.txt"));
6564
}
6565
6566
/// oxygen#30, orphans: a file added on one line into a directory the other
6567
/// line removed is placed where the tree cannot show it; Git's merge keeps
6568
/// the file, and the import's merge leaves exactly one of it.
6569
#[test]
6570
fn git_import_merge_leaves_no_orphan_behind() {
6571
    hermetic();
6572
    if std::process::Command::new("git")
6573
        .arg("--version")
6574
        .output()
6575
        .is_err()
6576
    {
6577
        eprintln!("git not installed; skipping");
6578
        return;
6579
    }
6580
    let dir = tempfile::tempdir().unwrap();
6581
    let root = dir.path();
6582
    let g = root.join("src.git");
6583
    fs::create_dir_all(&g).unwrap();
6584
    let git = |args: &[&str]| {
6585
        let out = std::process::Command::new("git")
6586
            .arg("-C")
6587
            .arg(&g)
6588
            .args([
6589
                "-c",
6590
                "user.name=Grace",
6591
                "-c",
6592
                "[email protected]",
6593
                "-c",
6594
                "commit.gpgsign=false",
6595
            ])
6596
            .args(args)
6597
            .output()
6598
            .unwrap();
6599
        assert!(
6600
            out.status.success(),
6601
            "git {args:?}: {}",
6602
            String::from_utf8_lossy(&out.stderr)
6603
        );
6604
    };
6605
    git(&["init", "-q", "-b", "main"]);
6606
    write(&g, "d/f.txt", b"f\n");
6607
    write(&g, "keep.txt", b"k\n");
6608
    git(&["add", "."]);
6609
    git(&["commit", "-qm", "base"]);
6610
    git(&["checkout", "-qb", "side"]);
6611
    write(&g, "d/new.txt", b"new\n");
6612
    git(&["add", "."]);
6613
    git(&["commit", "-qm", "add into d"]);
6614
    git(&["checkout", "-q", "main"]);
6615
    git(&["rm", "-q", "d/f.txt"]);
6616
    git(&["commit", "-qm", "d goes"]);
6617
    git(&["merge", "-q", "--no-edit", "side"]);
6618
6619
    let repo = Repo::init(&root.join("o")).unwrap();
6620
    repo.import_git(&g, "main").unwrap();
6621
    let v = repo.verify_git_import(&g, "main").unwrap();
6622
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6623
    let st = repo
6624
        .load_state_history(&repo.bookmark_heads().unwrap())
6625
        .unwrap();
6626
    let view = st.tree().view();
6627
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
6628
    assert!(view.entries.contains_key("d/new.txt"));
6629
}
d77e1702 Andy McCall ↶ 6630
6631
/// fsck checks a change's text as the blobs it is stored in, without
6632
/// decoding it: a missing text blob is an error named for the change.
6633
#[test]
6634
fn fsck_names_a_missing_text_blob() {
6635
    hermetic();
6636
    let dir = tempfile::tempdir().unwrap();
6637
    let root = dir.path();
6638
    let repo = Repo::init(root).unwrap();
6639
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
6640
    write(root, "big.txt", big.as_bytes());
6641
    let h = repo.commit("big", &[]).unwrap();
6642
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6643
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
6644
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
6645
        panic!("a stored text")
6646
    };
64818938 Andy McCall ↶ 6647
    repo.store().remove_loose_for_test(&b).unwrap();
d77e1702 Andy McCall ↶ 6648
    let rep = repo.fsck().unwrap();
6649
    assert!(rep.errors() > 0);
6650
    assert!(
6651
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
6652
        "{:?}",
6653
        rep.problems
6654
    );
6655
}
a07f60a3 Andy McCall ↶ 6656
6657
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
6658
/// reached with that remote's token and CA (a private subrepo then clones
6659
/// for anyone who can read the parent); another hub gets none of them.
6660
#[test]
6661
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
6662
    hermetic();
6663
    let dir = tempfile::tempdir().unwrap();
6664
    let mut repo = Repo::init(dir.path()).unwrap();
6665
    repo.config
6666
        .set(
6667
            "remote.origin.url",
6668
            "https://Hub.example:7343/doomsdayone/metalgear",
6669
        )
6670
        .unwrap();
6671
    repo.config.set("remote.origin.token", "secret").unwrap();
6672
    repo.config
6673
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
6674
        .unwrap();
6675
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
6676
    assert_eq!(same.token.as_deref(), Some("secret"));
6677
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
6678
    for other in [
6679
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
6680
        "https://hub.example/doomsdayone/rstar-api",
6681
        "http://hub.example:7343/doomsdayone/rstar-api",
6682
    ] {
6683
        let o = repo.credentials_for(other);
6684
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
6685
    }
6686
}
ce14f0d6 Andy McCall ↶ 6687
ff1f62fe Andy McCall ↶ 6688
/// oxygen#47: a remote with no token of its own uses the user's credential
6689
/// store for its hub, and a nested checkout finds its parent's remote
6690
/// token there instead of keeping a copy.
ce14f0d6 Andy McCall ↶ 6691
#[test]
ff1f62fe Andy McCall ↶ 6692
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
6693
    hermetic();
6694
    let home = tempfile::tempdir().unwrap();
6695
    let dir = tempfile::tempdir().unwrap();
6696
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
6697
    parent
6698
        .config
6699
        .set("remote.origin.url", "https://hub.example/o/parent")
6700
        .unwrap();
6701
    parent.save_config().unwrap();
6702
    assert_eq!(parent.remote_options("origin").token, None);
6703
    crate::credentials::Credentials::at(home.path())
6704
        .save("https://hub.example", "stored", Some("andy"), None)
6705
        .unwrap();
6706
    assert_eq!(
6707
        parent.remote_options("origin").token.as_deref(),
6708
        Some("stored")
6709
    );
6710
6711
    let empty_home = tempfile::tempdir().unwrap();
6712
    let nested = dir.path().join("deps").join("child");
6713
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
6714
    child
6715
        .config
6716
        .set("remote.origin.url", "https://hub.example/o/child")
6717
        .unwrap();
6718
    child.save_config().unwrap();
6719
    assert_eq!(child.remote_options("origin").token, None);
6720
    parent
6721
        .config
6722
        .set("remote.origin.token", "checkout")
6723
        .unwrap();
6724
    parent.save_config().unwrap();
6725
    assert_eq!(
6726
        child.remote_options("origin").token.as_deref(),
6727
        Some("checkout")
6728
    );
6729
    // Another hub's checkout token is not borrowed.
6730
    child
6731
        .config
6732
        .set("remote.origin.url", "https://other.example/o/child")
6733
        .unwrap();
6734
    assert_eq!(child.remote_options("origin").token, None);
6735
}
6736
6737
#[test]
ce14f0d6 Andy McCall ↶ 6738
fn the_metadata_cache_survives_a_torn_tail() {
6739
    hermetic();
6740
    let dir = tempfile::tempdir().unwrap();
6741
    let root = dir.path();
6742
    let repo = Repo::init(root).unwrap();
6743
    write(root, "a.txt", b"1\n");
6744
    let h = repo.commit("first", &[]).unwrap();
6745
    let meta = repo.store().get_change_meta(&h).unwrap();
6746
    let cache = repo.store().dir().join("metas");
6747
    let len = fs::metadata(&cache).unwrap().len();
6748
    assert!(len > 0, "a change read is cached");
6749
    // A torn record at the end: the cache reads up to it and cuts it off.
6750
    fs::OpenOptions::new()
6751
        .append(true)
6752
        .open(&cache)
6753
        .unwrap()
6754
        .write_all(&[7; 20])
6755
        .unwrap();
6756
    let again = Repo::open(root).unwrap();
6757
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
6758
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
6759
}
f9466021 Andy McCall ↶ 6760
6761
#[test]
6762
fn a_manifest_that_does_not_check_reads_as_none() {
6763
    hermetic();
6764
    let dir = tempfile::tempdir().unwrap();
6765
    let root = dir.path();
6766
    let repo = Repo::init(root).unwrap();
6767
    write(root, "a.txt", b"1\n");
6768
    repo.commit("first", &[]).unwrap();
6769
    let path = repo.manifest_path();
6770
    let mut bytes = fs::read(&path).unwrap();
6771
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
6772
    let last = bytes.len() - 1;
6773
    bytes[last] ^= 1;
6774
    fs::write(&path, &bytes).unwrap();
6775
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
6776
    // The next status reads the files and writes it again.
6777
    let again = Repo::open(root).unwrap();
6778
    assert!(!again.snapshot("status").unwrap().changed);
6779
    assert!(again.read_manifest().unwrap().is_some());
6780
}
6781
6782
#[test]
6783
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
6784
    hermetic();
6785
    let dir = tempfile::tempdir().unwrap();
6786
    let root = dir.path();
6787
    let repo = Repo::init(root).unwrap();
6788
    write(root, "a.txt", b"1\n");
6789
    write(root, "b.txt", b"2\n");
6790
    // b.txt outside the racy window, so snapshots take it as unchanged.
6791
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
6792
    fs::File::options()
6793
        .write(true)
6794
        .open(root.join("b.txt"))
6795
        .unwrap()
6796
        .set_modified(old)
6797
        .unwrap();
6798
    repo.commit("first", &[]).unwrap();
6799
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
6800
    repo.snapshot_status("status").unwrap();
6801
    write(root, "a.txt", b"1\n2\n");
6802
    repo.commit("second", &[]).unwrap();
6803
    assert!(
6804
        repo.clean_by_manifest().unwrap(),
6805
        "after a commit of one file"
6806
    );
6807
    // Edited, seen by a status, edited again, then committed: the status
6808
    // left the first edit's stat, which the commit must not keep.
6809
    write(root, "a.txt", b"1\n2\n3\n");
6810
    repo.snapshot_status("status").unwrap();
6811
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
6812
    repo.commit("third", &[]).unwrap();
6813
    assert!(
6814
        repo.clean_by_manifest().unwrap(),
6815
        "after an edit a status saw"
6816
    );
6817
}
e266b7d4 Andy McCall ↶ 6818
6819
#[test]
6820
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
6821
    hermetic();
6822
    let dir = tempfile::tempdir().unwrap();
6823
    let root = dir.path();
6824
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6825
    write(root, "a.txt", b"1\n2\n");
6826
    let a = repo.commit("A", &[]).unwrap();
6827
    repo.bookmark_create("develop", Some(&[a])).unwrap();
6828
    write(root, "a.txt", b"1\nX\n");
6829
    let c = repo.commit("C: 2 to X", &[]).unwrap();
6830
    repo.bookmark_switch("develop", false).unwrap();
6831
    write(root, "a.txt", b"1\nY\n");
6832
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
6833
    repo.bookmark_switch("main", false).unwrap();
6834
6835
    let err = repo.rebase(&c, &[d]).unwrap_err();
6836
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
6837
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
6838
    assert!(r.changed && r.checked_out);
6839
    let snap = repo.snapshot_status("status").unwrap();
6840
    assert!(
6841
        snap.base_snapshot.is_conflicted(),
6842
        "the conflict is in the working copy"
6843
    );
6844
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
6845
    assert!(text.contains('X') && text.contains('Y'), "{text}");
6846
6847
    write(root, "a.txt", b"1\nXY\n");
6848
    repo.commit("Resolve", &[]).unwrap();
6849
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
6850
    assert!(st.contains(&c) && st.contains(&d));
6851
    let files = st.materialize().files;
6852
    assert!(!files["a.txt"].is_conflicted());
6853
    assert!(
6854
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
6855
    );
6856
6857
    // A change the current bookmark does not hold is refused.
6858
    repo.bookmark_switch("develop", false).unwrap();
6859
    write(root, "b.txt", b"b\n");
6860
    let e = repo.commit("E", &[]).unwrap();
6861
    repo.bookmark_switch("main", false).unwrap();
6862
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
6863
    assert!(
6864
        err.to_string().contains("not on the current bookmark"),
6865
        "{err}"
6866
    );
6867
}
d4dbab97 Andy McCall ↶ 6868
6869
#[test]
6870
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
6871
    hermetic();
6872
    let dir = tempfile::tempdir().unwrap();
6873
    let root = dir.path();
6874
    let repo = Repo::init(root).unwrap();
6875
    write(root, "a.txt", b"a\n");
6876
    write(root, "kept.log", b"tracked\n");
6877
    repo.commit("first", &[]).unwrap();
6878
    write(root, "build.log", b"made\n");
6879
    let snap = repo.snapshot_status("status").unwrap();
6880
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
6881
    // A rule written afterwards leaves the added file out again, while the
6882
    // committed one stays tracked.
6883
    write(root, ".gitignore", b"*.log\n");
6884
    let snap = repo.snapshot_status("status").unwrap();
6885
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
6886
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
6887
    write(root, "kept.log", b"tracked, edited\n");
6888
    let snap = repo.snapshot_status("status").unwrap();
6889
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
6890
}
fd280228 Andy McCall ↶ 6891
6892
#[test]
6893
fn shed_graphs_come_back_the_same() {
6894
    hermetic();
6895
    let dir = tempfile::tempdir().unwrap();
6896
    let root = dir.path();
6897
    let repo = Repo::init(root).unwrap();
6898
    write(root, "a.txt", b"1\n2\n3\n");
6899
    write(root, "b.txt", b"x\n");
6900
    repo.commit("first", &[]).unwrap();
6901
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
6902
    repo.commit("second", &[]).unwrap();
6903
    let heads = repo.bookmark_heads().unwrap();
6904
    let mut st = repo.load_state_history(&heads).unwrap();
6905
    let view = st.tree().view();
6906
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
6907
        .iter()
6908
        .map(|p| view.entries[*p].node)
6909
        .collect();
6910
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6911
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6912
    assert_eq!(st.built_count(), 2);
6913
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
6914
    assert_eq!((shed, st.built_count()), (2, 0));
6915
    // A later change applies on top of the shed history.
6916
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
6917
    let h3 = repo.commit("third", &[]).unwrap();
6918
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
6919
    st.add_known(h3, skeleton, texts);
6920
    repo.load_graphs_of(&mut st, &nodes).unwrap();
6921
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
6922
    assert_eq!(after[1], before[1]);
6923
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
6924
}
360aa74a Andy McCall ↶ 6925
6926
#[test]
6927
fn many_edited_files_diff_in_parallel() {
6928
    // Enough edited files that the builder diffs them in parallel; the
6929
    // commit must hold exactly what is on disk, and a second snapshot
6930
    // must find nothing left to commit.
6931
    hermetic();
6932
    let dir = tempfile::tempdir().unwrap();
6933
    let root = dir.path();
6934
    let repo = Repo::init(root).unwrap();
6935
    let text = |i: usize, round: usize| {
6936
        let mut s = String::new();
6937
        for line in 0..50 {
6938
            if round > 0 && line % 7 == i % 7 {
6939
                s.push_str(&format!("edited {round} {i} {line}\n"));
6940
            } else {
6941
                s.push_str(&format!("file {i} line {line}\n"));
6942
            }
6943
        }
6944
        if round > 0 && i.is_multiple_of(3) {
6945
            s.push_str("appended\n");
6946
        }
6947
        s
6948
    };
6949
    for i in 0..40 {
6950
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
6951
    }
6952
    repo.commit("first", &[]).unwrap();
6953
    for i in 0..40 {
6954
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
6955
    }
6956
    let h = repo.commit("edit every file", &[]).unwrap();
6957
    let snap = repo.load_state(&[h]).unwrap().materialize();
6958
    for i in 0..40 {
6959
        let want = text(i, 1);
6960
        assert!(
6961
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
6962
            "d/f{i}.txt as committed"
6963
        );
6964
    }
6965
    assert!(
6966
        repo.commit("nothing", &[]).is_err(),
6967
        "nothing left to commit"
6968
    );
6969
}
b35df36b Andy McCall ↶ 6970
6971
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
6972
/// is known (fetch printed "up to date" while main was behind), a change
6973
/// only fetched resolves and says where it is, and a checkout whose only
6974
/// remote is not `origin` uses that one.
6975
#[test]
6976
fn a_fetched_change_shows_as_behind_and_resolves() {
6977
    hermetic();
6978
    let dir = tempfile::tempdir().unwrap();
6979
    let root = dir.path();
6980
    let origin = Repo::init(&root.join("origin")).unwrap();
6981
    drop(origin);
6982
    let url = root.join("origin").to_string_lossy().to_string();
6983
    let a = Repo::clone(&url, &root.join("a"))
6984
        .unwrap()
6985
        .with_home(root.join("home-a"));
6986
    write(&root.join("a"), "f.txt", b"one\n");
6987
    a.commit("one", &[]).unwrap();
6988
    a.push("origin", false).unwrap();
6989
    let b = Repo::clone(&url, &root.join("b"))
6990
        .unwrap()
6991
        .with_home(root.join("home-b"));
6992
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
6993
6994
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
6995
    let h2 = a.commit("two", &[]).unwrap();
6996
    a.push("origin", false).unwrap();
6997
    b.fetch("origin").unwrap();
6998
    // Fetched, not pulled: one behind, the change found and placed.
6999
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7000
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
7001
    assert_eq!(
7002
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
7003
            .unwrap(),
7004
        h2
7005
    );
7006
    assert_eq!(
7007
        b.remote_only_location(&h2).unwrap().as_deref(),
7008
        Some("origin/main")
7009
    );
7010
    // Fetching again changes nothing: still behind, which is what the
7011
    // CLI now says rather than "up to date".
7012
    b.fetch("origin").unwrap();
7013
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
7014
    b.pull("origin").unwrap();
7015
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
7016
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
7017
7018
    // One remote, not called origin: it is the default.
7019
    let mut c = Repo::init(&root.join("c")).unwrap();
7020
    assert_eq!(c.default_remote(), "origin");
7021
    c.config.set("remote.earth.url", &url).unwrap();
7022
    assert_eq!(c.default_remote(), "earth");
7023
    c.config.set("remote.origin.url", &url).unwrap();
7024
    assert_eq!(c.default_remote(), "origin");
7025
}
827281ee Andy McCall ↶ 7026
7027
/// oxygen#57: a clone from a relative local path records the remote as an
7028
/// absolute path, so fetch still finds it from inside the clone.
7029
#[test]
7030
fn a_clone_from_a_relative_path_records_it_absolute() {
7031
    hermetic();
7032
    let dir = tempfile::tempdir().unwrap();
7033
    let root = dir.path();
7034
    Repo::init(&root.join("origin")).unwrap();
7035
    let rel = crate::protocol::stored_url("relative/repo");
7036
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
7037
    assert_eq!(
7038
        crate::protocol::stored_url("https://hub.example/o/n"),
7039
        "https://hub.example/o/n"
7040
    );
7041
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8d803563 Andy McCall ↶ 7042
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
7043
    // A bucket is kept as written: it is not a path.
7044
    assert_eq!(
7045
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
7046
        "s3://bucket/prefix?profile=p"
7047
    );
827281ee Andy McCall ↶ 7048
    let url = root.join("origin").to_string_lossy().to_string();
7049
    let b = Repo::clone(&url, &root.join("b")).unwrap();
7050
    assert_eq!(b.config.remotes["origin"], url);
7051
    b.fetch("origin").unwrap();
7052
}
a46f3e4f Andy McCall ↶ 7053
7054
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
7055
/// and gets its subrepos at their pins from this workspace's copies, with
7056
/// their remotes pointing where the subrepos come from.
7057
#[test]
7058
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
7059
    hermetic();
7060
    let dir = tempfile::tempdir().unwrap();
7061
    let root = dir.path();
7062
    Repo::init(&root.join("lib-origin")).unwrap();
7063
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7064
    let lib = Repo::clone(&lib_url, &root.join("lib"))
7065
        .unwrap()
7066
        .with_home(root.join("home"));
7067
    write(&root.join("lib"), "lib.txt", b"v1\n");
7068
    let l1 = lib.commit("lib v1", &[]).unwrap();
7069
    assert!(lib.push("origin", false).unwrap()[0].ok);
7070
7071
    let app_dir = root.join("app");
7072
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
7073
    write(&app_dir, "main.txt", b"app\n");
7074
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7075
    app.commit("app with lib", &[]).unwrap();
7076
    // A second bookmark, and the main workspace on another.
7077
    app.bookmark_create("develop", None).unwrap();
7078
    app.bookmark_create("feature", None).unwrap();
7079
    let mut app = app;
7080
    app.bookmark_switch("feature", false).unwrap();
7081
    assert_eq!(app.config.bookmark, "feature");
7082
7083
    // The library's origin goes away: the subrepo must come from here.
7084
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
7085
    let heads = app.resolve_heads("develop").unwrap();
7086
    let ws = app
7087
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
7088
        .unwrap();
7089
    assert_eq!(
7090
        ws.config.bookmark, "develop",
7091
        "the new workspace is on develop"
7092
    );
7093
    assert_eq!(
7094
        app.config.bookmark, "feature",
7095
        "and this one stays on its own"
7096
    );
7097
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
7098
    assert_eq!(
7099
        sub.config.remotes["origin"], lib_url,
7100
        "its origin is the subrepo's URL"
7101
    );
7102
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
7103
    assert_eq!(
7104
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
7105
        b"v1\n"
7106
    );
7107
}
47ce8b8e Andy McCall ↶ 7108
7109
/// Revsets (docs/revset_query_language.md): symbols, relations, set
7110
/// operators and the predicates, over a small graph with two heads and
7111
/// a rename.
7112
#[test]
7113
fn revsets_select_changes_by_relation_author_text_date_and_path() {
7114
    hermetic();
7115
    let dir = tempfile::tempdir().unwrap();
7116
    let root = dir.path();
7117
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7118
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
7119
        .unwrap();
7120
    write(root, "src/a.rs", b"one\n");
7121
    let a = repo.commit("first: add a", &[]).unwrap();
7122
    write(root, "src/a.rs", b"one\ntwo\n");
7123
    let b = repo.commit("second: grow a", &[]).unwrap();
7124
    // A second head, independent of b: a new file on top of a.
7125
    repo.checkout(&[a], false, "checkout a").unwrap();
7126
    write(root, "docs/notes.md", b"notes\n");
7127
    let c = repo.commit("third: notes", &[]).unwrap();
7128
    // Back to both heads, then rename a.rs: the node keeps its identity.
7129
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
7130
        .unwrap();
7131
    fs::remove_file(root.join("src/a.rs")).unwrap();
7132
    write(root, "src/z.rs", b"one\ntwo\n");
7133
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
7134
    let wc = repo.working_copy().unwrap().0;
7135
    // A saved revset is checked when set.
7136
    repo.set_user_config("revset.mine", "author(me) & ::main")
7137
        .unwrap();
7138
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
7139
    let set = |src: &str| -> Vec<ChangeHash> {
7140
        let mut v = repo.revset(src).unwrap().hashes;
7141
        v.sort();
7142
        v
7143
    };
7144
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
7145
        let mut v = hs.to_vec();
7146
        v.sort();
7147
        v
7148
    };
7149
7150
    // Changes commute: a new file depends on nothing and the rename on the
7151
    // file's creation, so the graph is a, b->a, d->a, c, and the working
7152
    // copy on the three heads b, c, d.
7153
    let heads = sorted(&repo.bookmark_heads().unwrap());
7154
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
7155
    assert!(heads.contains(&d) && heads.contains(&c));
7156
    // Symbols and closures.
7157
    assert_eq!(set("main"), heads);
7158
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
7159
    assert_eq!(set("@"), vec![wc]);
7160
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
7161
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
7162
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
7163
    assert_eq!(
7164
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
7165
        sorted(&[a, b])
7166
    );
7167
    // Ranges: what main has beyond b, and `..` forms.
7168
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
7169
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
7170
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
7171
    // Operators and precedence: ~ binds tighter than &, & than |.
7172
    assert_eq!(
7173
        set(&format!("::main ~ #{}", d.short(12))),
7174
        sorted(&[a, b, c])
7175
    );
7176
    assert_eq!(
7177
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
7178
        sorted(&[b, c])
7179
    );
7180
    assert_eq!(set("all() ~ ::main"), vec![wc]);
7181
    // Relations.
7182
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
7183
    head_deps.sort();
7184
    head_deps.dedup();
7185
    assert_eq!(set("deps(main)"), head_deps);
7186
    let on_a: Vec<ChangeHash> = [b, c, d]
7187
        .into_iter()
7188
        .filter(|h| meta(h).deps.contains(&a))
7189
        .collect();
7190
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
7191
    assert_eq!(set("heads(::main)"), heads);
7192
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
7193
    assert_eq!(
7194
        set(&format!(
7195
            "heads(#{} | #{} | #{})",
7196
            a.short(12),
7197
            b.short(12),
7198
            c.short(12)
7199
        )),
7200
        sorted(&[b, c])
7201
    );
7202
    assert_eq!(set("latest(::main, 1)"), vec![d]);
7203
    assert_eq!(set("kind(working-copy)"), vec![wc]);
7204
    assert_eq!(set("none()"), vec![]);
7205
    // Predicates: author by name, email, key prefix and `me`.
7206
    let key = repo.config.author_key.unwrap();
7207
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
7208
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
7209
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
7210
    assert_eq!(set("author(me) & ::main").len(), 4);
7211
    assert_eq!(set("author(nobody)"), vec![]);
7212
    assert_eq!(set("description(notes)"), vec![c]);
7213
    assert_eq!(set("description(\"rename a\")"), vec![d]);
7214
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
7215
    assert_eq!(set("date(..2000-01-01)"), vec![]);
7216
    // touches follows the node through the rename, in the current state.
7217
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
7218
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
7219
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
7220
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
7221
    // Newest first in the result order.
7222
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
7223
    // The saved revset, and errors that say what is wrong.
7224
    assert_eq!(set("mine()").len(), 4);
7225
    let e = repo.revset("nosuch()").unwrap_err().to_string();
7226
    assert!(e.contains("unknown function nosuch()"), "{e}");
7227
    let e = repo.revset("main &").unwrap_err().to_string();
7228
    assert!(e.contains("at character"), "{e}");
7229
    let e = repo.revset("zzzz").unwrap_err().to_string();
7230
    assert!(e.contains("no change matches"), "{e}");
7231
    let e = repo
7232
        .revset_with_budget("::main", std::time::Duration::ZERO)
7233
        .unwrap_err()
7234
        .to_string();
7235
    assert!(e.contains("budget"), "{e}");
7236
    // The log entries carry the bookmark's heads and the working copy.
7237
    let entries = repo.log_revset("::@").unwrap();
7238
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
2c9ddac3 Andy McCall ↶ 7239
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
7240
    // push); then a signed change, a tag, and a revocation.
7241
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
7242
    assert_eq!(set("signed_by(me)"), vec![]);
7243
    repo.sign_change(&d).unwrap();
7244
    assert_eq!(set("signed_by(me)"), vec![d]);
7245
    assert_eq!(set("signed_by([email protected])"), vec![d]);
7246
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
7247
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
7248
    assert_eq!(set("delegated()"), vec![]);
7249
    assert_eq!(set("revoked()"), vec![]);
7250
    assert_eq!(set("attested(tag)"), vec![]);
7251
    repo.tag_create("v1", &[b], "first").unwrap();
7252
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
7253
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
7254
    assert_eq!(set("attested(receipt)"), vec![]);
7255
    assert_eq!(set("built(test)"), vec![]);
7256
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
7257
    assert!(e.contains("tag, receipt or ref"), "{e}");
7258
    repo.revoke_identity(&key, "test").unwrap();
7259
    assert_eq!(set("revoked()"), vec![d]);
7260
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
543bbf64 Andy McCall ↶ 7261
    // independent(X, IN): what could ship without X. c and d neither
7262
    // depend on b nor are depended on by it; a is below, the working copy
7263
    // above.
7264
    assert_eq!(
7265
        set(&format!("independent(#{}, ::@)", b.short(12))),
7266
        sorted(&[c, d])
7267
    );
7268
    assert_eq!(
7269
        set(&format!("independent(#{}, ::main)", a.short(12))),
7270
        vec![c]
7271
    );
7272
    // conflicts(S): nothing conflicts yet; then two edits of one line.
7273
    assert_eq!(set("conflicts()"), vec![]);
7274
    assert_eq!(set("conflicts(main)"), vec![]);
7275
    // (The saved revset above edited the user config under the root:
7276
    // discard it.)
7277
    repo.checkout(&[a], true, "checkout a").unwrap();
7278
    write(root, "src/a.rs", b"one\nTWO\n");
7279
    let e = repo
7280
        .commit("fifth: the other edit of line two", &[])
7281
        .unwrap();
7282
    repo.checkout(&repo.bookmark_heads().unwrap(), true, "checkout main")
7283
        .unwrap();
7284
    let conflicted = repo.revset("conflicts()").unwrap().hashes;
7285
    assert!(
7286
        conflicted.contains(&e) && conflicted.contains(&b),
7287
        "{conflicted:?} should hold b and e"
7288
    );
7289
    assert!(!conflicted.contains(&c));
7290
    assert_eq!(set("conflicts() & author(nobody)"), vec![]);
47ce8b8e Andy McCall ↶ 7291
}