OXYGENHUB
◆ v0.5.1 oxygen / crates / oxy-core / src / repo / tests.rs
385.2 KiB · Rust · last changed Old clients are not sent tags only a certificate authorizes (closes #131) 16 days ago source blame history raw
98286406 Andy McCall ↶ 1
//! Tests for the repository layer.
2
3
use super::*;
75167672 Andy McCall 4
use crate::protocol::SignedPolicy;
957fee30 Andy McCall ↶ 5
use crate::repo::{BisectStep, Selection};
98286406 Andy McCall ↶ 6
7
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
8
/// test reads or writes the developer's real user configuration or keys.
9
fn hermetic() {
10
    static ONCE: std::sync::Once = std::sync::Once::new();
11
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
12
    ONCE.call_once(|| {
13
        let d = tempfile::tempdir().unwrap();
14
        std::env::set_var("OXY_HOME", d.path());
15
        DIR.set(d).ok();
16
    });
17
}
18
19
fn write(root: &Path, rel: &str, content: &[u8]) {
20
    let p = root.join(rel);
21
    fs::create_dir_all(p.parent().unwrap()).unwrap();
22
    fs::write(p, content).unwrap();
23
}
24
25
fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
75167672 Andy McCall 26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
98286406 Andy McCall ↶ 30
}
31
32
#[test]
33
fn init_snapshot_commit_log_undo() {
34
    hermetic();
35
    let dir = tempfile::tempdir().unwrap();
36
    let root = dir.path();
37
    let repo = Repo::init(root).unwrap();
38
    assert!(Repo::init(root).is_err());
39
    let ops = repo.op_log().unwrap();
40
    assert_eq!(ops.len(), 1);
41
    assert_eq!(ops[0].1.command, "oxy init");
42
43
    // Empty working copy: snapshot records no operation (spec §12.3).
44
    let s = repo.snapshot("oxy status").unwrap();
45
    assert!(!s.changed);
46
    assert_eq!(repo.op_log().unwrap().len(), 1);
47
48
    write(root, "src/main.rs", b"fn main() {}\n");
49
    write(root, "README.md", b"# Hello\n");
50
    write(root, ".oxyignore", b"/target\n");
51
    write(root, "target/junk.o", b"\0\0\0");
52
    let s = repo.snapshot("oxy status").unwrap();
53
    assert!(s.changed);
54
    assert_eq!(
55
        statuses(&s),
56
        vec![
57
            (".oxyignore".into(), ChangeStatus::Added),
58
            ("README.md".into(), ChangeStatus::Added),
59
            ("src/main.rs".into(), ChangeStatus::Added),
60
        ]
61
    );
62
    assert_eq!(repo.op_log().unwrap().len(), 2);
63
    // Snapshotting again with nothing changed records no op.
64
    let s2 = repo.snapshot("oxy status").unwrap();
65
    assert!(!s2.changed);
66
    assert_eq!(s2.wc_hash, s.wc_hash);
67
    assert_eq!(repo.op_log().unwrap().len(), 2);
68
69
    let h1 = repo.commit("Initial import", &[]).unwrap();
70
    let c1 = repo.store().get_change(&h1).unwrap();
71
    assert_eq!(c1.kind, ChangeKind::Normal);
72
    assert!(c1.deps.is_empty(), "first change has nothing to depend on");
73
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
74
    let (wc_hash, wc) = repo.working_copy().unwrap();
75
    assert_eq!(wc.deps, vec![h1]);
76
    assert!(wc.edits.is_empty());
77
    assert!(repo.commit("nothing", &[]).is_err());
78
79
    // Modify one file, remove another, add a binary file.
75167672 Andy McCall 80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
98286406 Andy McCall ↶ 85
    fs::remove_file(root.join("README.md")).unwrap();
86
    write(root, "logo.png", b"\x89PNG\0\0\x01");
87
    let s = repo.snapshot("oxy status").unwrap();
88
    assert_eq!(
89
        statuses(&s),
90
        vec![
91
            ("README.md".into(), ChangeStatus::Removed),
92
            ("logo.png".into(), ChangeStatus::Added),
93
            ("src/main.rs".into(), ChangeStatus::Modified),
94
        ]
95
    );
96
    assert_ne!(s.wc_hash, wc_hash);
97
    // The rewritten working copy keeps its ChangeId and depends on h1.
98
    assert_eq!(s.wc.change_id, wc.change_id);
99
    assert!(s.wc.deps.contains(&h1));
100
101
    let h2 = repo.commit("Second", &[]).unwrap();
102
    let c2 = repo.store().get_change(&h2).unwrap();
75167672 Andy McCall 103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
98286406 Andy McCall ↶ 108
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
109
110
    // The materialized head state matches the working copy.
111
    let st = repo.load_state(&[h2]).unwrap();
112
    let snap = st.materialize();
113
    assert!(!snap.is_conflicted());
75167672 Andy McCall 114
    assert_eq!(
115
        snap.files.keys().cloned().collect::<Vec<_>>(),
116
        [".oxyignore", "logo.png", "src", "src/main.rs"]
117
    );
118
    assert!(
119
        matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n")
120
    );
98286406 Andy McCall ↶ 121
    assert!(snap.files["logo.png"].mode.opaque);
122
    if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
123
        assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
124
    } else {
125
        panic!("logo should be opaque");
126
    }
127
128
    // Log: newest first, working copy included.
129
    let log = repo.log().unwrap();
130
    assert_eq!(log.len(), 3);
131
    assert!(log[0].is_working_copy);
132
    assert_eq!(log[1].hash, h2);
133
    assert!(log[1].is_head);
134
    assert_eq!(log[2].hash, h1);
135
    let d = repo.describe_change(&h2).unwrap();
136
    assert!(d.contains("D README.md"), "{d}");
0912a033 Andy McCall ↶ 137
    assert!(
138
        d.lines()
139
            .any(|l| l.starts_with("M ") && l.ends_with("main.rs")),
140
        "a modified file is in the summary too: {d}"
141
    );
98286406 Andy McCall ↶ 142
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
143
    assert!(d.contains("-fn main() {}"), "{d}");
144
145
    // Resolution by prefix.
146
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
75167672 Andy McCall 147
    assert_eq!(
148
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
149
        h1
150
    );
98286406 Andy McCall ↶ 151
    assert!(repo.resolve_change("zzzz").is_err());
152
153
    // Undo the commit: bookmark and working copy go back.
154
    repo.undo().unwrap();
155
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
156
    let s = repo.snapshot("oxy status").unwrap();
75167672 Andy McCall 157
    assert!(
158
        !s.changed,
159
        "files on disk still match the pre-commit working copy"
160
    );
98286406 Andy McCall ↶ 161
    assert_eq!(s.statuses.len(), 3);
162
}
163
164
/// Make `main` conflicted: two commits on the same base that edit the same line.
165
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
166
    let dir = tempfile::tempdir().unwrap();
167
    let root = dir.path();
168
    let repo = Repo::init(root).unwrap();
169
    write(root, "f.txt", b"a\nb\nc\n");
170
    let h1 = repo.commit("base", &[]).unwrap();
171
    write(root, "f.txt", b"a\nB\nc\n");
172
    let h2 = repo.commit("upper", &[]).unwrap();
173
    repo.checkout(&[h1], false, "checkout").unwrap();
174
    write(root, "f.txt", b"a\nX\nc\n");
175
    let h3 = repo.commit("ex", &[]).unwrap();
176
    (dir, repo, h1, h2, h3)
177
}
178
3652104a Andy McCall ↶ 179
/// oxygen#126: a file whose text includes an example of oxy's markers (as
180
/// the spec's §9.5 does) can still have its conflict resolved; a real
181
/// marker left behind is still caught.
98286406 Andy McCall ↶ 182
#[test]
3652104a Andy McCall ↶ 183
fn marker_like_text_does_not_block_a_resolution() {
184
    hermetic();
185
    let dir = tempfile::tempdir().unwrap();
186
    let root = dir.path();
187
    let repo = Repo::init(root).unwrap();
188
    let example = "```\n<<<<<<< oxy conflict 1 of 2, side 1: change k7m2p9 \"Add retry loop\"\n... lines ...\n======= oxy conflict 1 of 2, side 2: change q3x8w1 \"Refactor client\"\n>>>>>>> oxy conflict 1 of 2 end\n```\n";
189
    write(
190
        root,
191
        "doc.md",
192
        format!("intro\n{example}b\nend\n").as_bytes(),
193
    );
194
    let h1 = repo.commit("base", &[]).unwrap();
195
    write(
196
        root,
197
        "doc.md",
198
        format!("intro\n{example}B\nend\n").as_bytes(),
199
    );
200
    repo.commit("upper", &[]).unwrap();
201
    repo.checkout(&[h1], false, "checkout").unwrap();
202
    write(
203
        root,
204
        "doc.md",
205
        format!("intro\n{example}X\nend\n").as_bytes(),
206
    );
207
    repo.commit("ex", &[]).unwrap();
208
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
209
        .unwrap();
210
    let marked = fs::read_to_string(root.join("doc.md")).unwrap();
211
    assert!(marked.contains("oxy conflict 1 of 1"), "{marked}");
212
    // A real marker left: still caught.
213
    write(root, "doc.md", marked.replace("B\n", "BB\n").as_bytes());
214
    let s = repo.snapshot("status").unwrap();
215
    assert_eq!(
216
        statuses(&s),
217
        vec![("doc.md".into(), ChangeStatus::ConflictEdited)]
218
    );
219
    // Resolved, the example kept: a resolution.
220
    write(
221
        root,
222
        "doc.md",
223
        format!("intro\n{example}X\nend\n").as_bytes(),
224
    );
225
    let s = repo.snapshot("status").unwrap();
226
    assert_eq!(
227
        statuses(&s),
228
        vec![("doc.md".into(), ChangeStatus::Resolved)]
229
    );
230
    let h = repo.commit("resolve", &[]).unwrap();
231
    assert_eq!(
232
        repo.store().get_change(&h).unwrap().kind,
233
        ChangeKind::Resolution
234
    );
235
    assert!(!repo.load_state(&[h]).unwrap().materialize().is_conflicted());
236
}
237
238
#[test]
98286406 Andy McCall ↶ 239
fn concurrent_edits_conflict_and_can_be_resolved() {
240
    hermetic();
241
    let (dir, repo, h1, h2, h3) = conflicted_repo();
242
    let root = dir.path();
243
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
244
    assert_eq!(heads, [h2, h3].into_iter().collect());
245
    let st = repo.load_state(&[h2, h3]).unwrap();
246
    assert!(st.materialize().is_conflicted());
247
248
    // Checking out main writes markers.
75167672 Andy McCall 249
    let r = repo
250
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
251
        .unwrap();
98286406 Andy McCall ↶ 252
    assert!(r.conflicted);
253
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 254
    assert!(
255
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
256
        "{marked}"
257
    );
258
    assert!(
259
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
260
        "{marked}"
261
    );
98286406 Andy McCall ↶ 262
    assert!(has_conflict_markers(marked.as_bytes()));
263
    // Untouched markers: clean working copy; commit has nothing to do.
264
    let s = repo.snapshot("status").unwrap();
265
    assert!(s.statuses.is_empty());
266
    assert!(!s.resolves);
267
268
    // Partially edited file that still has markers cannot be committed.
269
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
270
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 271
    assert_eq!(
272
        statuses(&s),
273
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
274
    );
98286406 Andy McCall ↶ 275
    assert!(repo.commit("no", &[]).is_err());
276
277
    // Resolve by keeping one side and adding a line elsewhere.
278
    write(root, "f.txt", b"a\nX\nc\nd\n");
279
    let s = repo.snapshot("status").unwrap();
280
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
281
    assert!(s.resolves);
282
    let h4 = repo.commit("resolve", &[]).unwrap();
283
    let c4 = repo.store().get_change(&h4).unwrap();
284
    assert_eq!(c4.kind, ChangeKind::Resolution);
285
    let mut want = vec![h1, h2, h3];
286
    want.sort();
75167672 Andy McCall 287
    assert_eq!(
288
        c4.deps, want,
289
        "a resolution depends on exactly the contributors and what it references"
290
    );
98286406 Andy McCall ↶ 291
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
292
    let snap = repo.load_state(&[h4]).unwrap().materialize();
293
    assert!(!snap.is_conflicted());
75167672 Andy McCall 294
    assert!(
295
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
296
    );
98286406 Andy McCall ↶ 297
    assert!(!repo.snapshot("status").unwrap().changed);
298
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
299
    // whatever order the changes arrive in.
300
    let mut st = State::new();
301
    for h in [h4, h3, h1, h2] {
302
        st.add_unchecked(repo.store().get_change(&h).unwrap());
303
    }
304
    st.validate().unwrap();
75167672 Andy McCall 305
    assert!(
306
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
307
    );
98286406 Andy McCall ↶ 308
}
309
69953b50 Andy McCall ↶ 310
/// oxygen#118 (Metal Gear): a resolution commits by paths, leaving other
311
/// work uncommitted, so long as it takes every file it resolves; and
312
/// `amend PATHS` folds only those paths into the head.
98286406 Andy McCall ↶ 313
#[test]
69953b50 Andy McCall ↶ 314
fn resolutions_and_amends_take_paths() {
315
    hermetic();
316
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
317
    let root = dir.path();
318
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
319
        .unwrap();
320
    // The conflict resolved, and other work beside it.
321
    write(root, "f.txt", b"a\nX\nc\n");
322
    write(root, "notes.txt", b"pending\n");
323
    let s = repo.snapshot("status").unwrap();
324
    assert!(s.resolves);
325
    let err = repo
326
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["notes.txt".into()]))
327
        .unwrap_err()
328
        .to_string();
329
    assert!(
330
        err.contains("takes every file it resolves") && err.contains("f.txt"),
331
        "{err}"
332
    );
333
    let (h4, partial) = repo
334
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["f.txt".into()]))
335
        .unwrap();
336
    assert!(partial);
337
    assert_eq!(
338
        repo.store().get_change(&h4).unwrap().kind,
339
        ChangeKind::Resolution
340
    );
341
    assert!(!repo
342
        .load_state(&[h4])
343
        .unwrap()
344
        .materialize()
345
        .is_conflicted());
346
    let s = repo.snapshot("status").unwrap();
347
    assert_eq!(
348
        statuses(&s),
349
        vec![("notes.txt".into(), ChangeStatus::Added)],
350
        "the other work waits"
351
    );
352
353
    // amend PATHS: only those paths join the head; it keeps its ChangeId.
354
    // On the resolution, so the bookmark has one head to amend.
355
    let h5 = repo.commit("notes", &[h4]).unwrap();
356
    let id5 = repo.store().get_change(&h5).unwrap().change_id;
357
    write(root, "notes.txt", b"pending\nmore\n");
358
    write(root, "other.txt", b"later\n");
359
    let h6 = repo
360
        .amend_paths(Some("notes, amended"), &["notes.txt".into()])
361
        .unwrap();
362
    let c6 = repo.store().get_change(&h6).unwrap();
363
    assert_eq!((c6.change_id, c6.message.as_str()), (id5, "notes, amended"));
364
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h6]);
365
    let snap6 = repo.load_state(&[h6]).unwrap().materialize();
366
    assert!(
367
        matches!(&snap6.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"pending\nmore\n")
368
    );
369
    assert!(
370
        !snap6.files.contains_key("other.txt"),
371
        "other.txt stays out"
372
    );
373
    let s = repo.snapshot("status").unwrap();
374
    assert_eq!(
375
        statuses(&s),
376
        vec![("other.txt".into(), ChangeStatus::Added)]
377
    );
378
}
379
380
#[test]
98286406 Andy McCall ↶ 381
fn resolution_may_keep_both_sides_or_neither() {
382
    hermetic();
383
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
384
    let root = dir.path();
75167672 Andy McCall 385
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
386
        .unwrap();
98286406 Andy McCall ↶ 387
    // Keep both sides in a chosen order.
388
    write(root, "f.txt", b"a\nX\nB\nc\n");
389
    let h = repo.commit("both", &[]).unwrap();
390
    let snap = repo.load_state(&[h]).unwrap().materialize();
391
    assert!(!snap.is_conflicted());
75167672 Andy McCall 392
    assert!(
393
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
394
    );
98286406 Andy McCall ↶ 395
    // Undo and instead drop the whole region.
396
    repo.undo().unwrap();
397
    write(root, "f.txt", b"a\nc\n");
398
    let h = repo.commit("neither", &[]).unwrap();
399
    let snap = repo.load_state(&[h]).unwrap().materialize();
400
    assert!(!snap.is_conflicted());
75167672 Andy McCall 401
    assert!(
402
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
403
    );
98286406 Andy McCall ↶ 404
}
405
406
#[test]
407
fn name_conflict_resolved_by_removing_a_candidate() {
408
    hermetic();
409
    let dir = tempfile::tempdir().unwrap();
410
    let root = dir.path();
411
    let repo = Repo::init(root).unwrap();
412
    write(root, "keep.txt", b"k\n");
413
    let h1 = repo.commit("base", &[]).unwrap();
414
    write(root, "new.txt", b"one\n");
415
    repo.commit("one", &[]).unwrap();
416
    repo.checkout(&[h1], false, "checkout").unwrap();
417
    write(root, "new.txt", b"two\n");
418
    repo.commit("two", &[]).unwrap();
75167672 Andy McCall 419
    let r = repo
420
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
421
        .unwrap();
98286406 Andy McCall ↶ 422
    assert!(r.conflicted);
75167672 Andy McCall 423
    assert!(
424
        root.join("new.txt.oxy-conflict-1").exists()
425
            && root.join("new.txt.oxy-conflict-2").exists()
426
    );
98286406 Andy McCall ↶ 427
    assert!(!root.join("new.txt").exists());
428
    // Candidate numbering follows change-hash order, so pick by content:
429
    // keep the "two" candidate under the real name and drop the other.
75167672 Andy McCall 430
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
431
        (1, 2)
432
    } else {
433
        (2, 1)
434
    };
98286406 Andy McCall ↶ 435
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
75167672 Andy McCall 436
    fs::rename(
437
        root.join(format!("new.txt.oxy-conflict-{keep}")),
438
        root.join("new.txt"),
439
    )
440
    .unwrap();
98286406 Andy McCall ↶ 441
    let h = repo.commit("pick two", &[]).unwrap();
75167672 Andy McCall 442
    assert_eq!(
443
        repo.store().get_change(&h).unwrap().kind,
444
        ChangeKind::Resolution
445
    );
98286406 Andy McCall ↶ 446
    // The resolution does not touch keep.txt, so it does not depend on h1;
447
    // the bookmark keeps both as heads and their union is the state.
448
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
449
    assert_eq!(heads, [h1, h].into_iter().collect());
75167672 Andy McCall 450
    let snap = repo
451
        .load_state(&repo.bookmark_heads().unwrap())
452
        .unwrap()
453
        .materialize();
98286406 Andy McCall ↶ 454
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
75167672 Andy McCall 455
    assert_eq!(
456
        snap.files.keys().cloned().collect::<Vec<_>>(),
457
        ["keep.txt", "new.txt"]
458
    );
459
    assert!(
460
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
461
    );
98286406 Andy McCall ↶ 462
}
463
c2e1d090 Andy McCall 464
/// Each of two bookmarks adds `path` (a file written by `side` on each)
465
/// from the same base, and the second is merged into the first. Returns
466
/// the repository on `main`, the merge's heads, and the three changes.
467
fn merged_additions(
468
    side: impl Fn(&Path, bool),
469
) -> (tempfile::TempDir, Repo, Vec<ChangeHash>, [ChangeHash; 3]) {
470
    let dir = tempfile::tempdir().unwrap();
471
    let root = dir.path().to_path_buf();
472
    let mut repo = Repo::init(&root).unwrap();
473
    write(&root, "keep.txt", b"k\n");
474
    let h1 = repo.commit("base", &[]).unwrap();
475
    repo.bookmark_create("side", None).unwrap();
476
    side(&root, false);
477
    let ha = repo.commit("add on main", &[]).unwrap();
478
    repo.bookmark_switch("side", false).unwrap();
479
    side(&root, true);
480
    let hb = repo.commit("add on side", &[]).unwrap();
481
    repo.bookmark_switch("main", false).unwrap();
482
    let m = repo.merge("side").unwrap();
483
    assert!(m.changed && m.checked_out);
484
    (dir, repo, m.heads, [h1, ha, hb])
485
}
486
487
fn conflict_copies(root: &Path) -> Vec<String> {
488
    let mut out: Vec<String> = fs::read_dir(root)
489
        .unwrap()
490
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
491
        .filter(|n| n.contains(".oxy-conflict-"))
492
        .collect();
493
    out.sort();
494
    out
495
}
496
497
/// The same path added on two bookmarks with identical content is one
498
/// file after the merge (oxygen#101): no conflict, nothing to resolve,
499
/// nothing recorded; and editing or removing it later keeps it one.
500
#[test]
501
fn identical_additions_unify_on_merge() {
502
    hermetic();
503
    let (dir, repo, heads, [h1, ha, hb]) =
504
        merged_additions(|root, _| write(root, "x.txt", b"same\nlines\n"));
505
    let root = dir.path();
506
    // The tree graph has the name conflict; every reader sees one file.
507
    let st = repo.load_state(&heads).unwrap();
508
    assert!(st
509
        .tree()
510
        .view()
511
        .conflicts
512
        .iter()
513
        .any(|c| matches!(c, crate::tree::TreeConflict::Name { .. })));
514
    let snap = st.materialize();
515
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
516
    assert_eq!(
517
        snap.files.keys().cloned().collect::<Vec<_>>(),
518
        ["keep.txt", "x.txt"]
519
    );
520
    assert!(
521
        matches!(&snap.files["x.txt"].content, FileContent::Text { bytes, .. } if bytes == b"same\nlines\n")
522
    );
523
    assert_eq!(snap.tree.unified.len(), 1);
524
    // On disk once, the working copy clean, nothing to commit.
525
    assert_eq!(fs::read(root.join("x.txt")).unwrap(), b"same\nlines\n");
526
    assert!(
527
        conflict_copies(root).is_empty(),
528
        "{:?}",
529
        conflict_copies(root)
530
    );
531
    let s = repo.snapshot("status").unwrap();
532
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
533
    assert!(!s.changed && !s.resolves);
534
    assert!(!s.base_snapshot.is_conflicted());
535
    assert!(s.wc.tree_ops.is_empty() && s.wc.edits.is_empty());
536
    let json = repo.status_json(&s).unwrap();
537
    assert!(json.contains("\"conflicted\":false"), "{json}");
538
    assert!(repo.commit("nothing", &[]).is_err());
539
    assert_eq!(repo.file_at("x.txt", None).unwrap(), b"same\nlines\n");
540
    // A peer holding the same changes, added in another order, agrees.
541
    let mut peer = State::new();
542
    for h in [hb, ha, h1] {
543
        peer.add_unchecked(repo.store().get_change(&h).unwrap());
544
    }
545
    peer.validate().unwrap();
546
    let ps = peer.materialize();
547
    assert!(!ps.is_conflicted());
548
    assert_eq!(ps.tree.entries["x.txt"], snap.tree.entries["x.txt"]);
549
    assert_eq!(ps.tree.unified, snap.tree.unified);
550
    // The file's history is both additions.
551
    let log: Vec<ChangeHash> = repo
552
        .log_for_path("x.txt")
553
        .unwrap()
554
        .iter()
555
        .map(|e| e.hash)
556
        .collect();
557
    assert!(log.contains(&ha) && log.contains(&hb), "{log:?}");
558
559
    // Edited and committed: one file still, the duplicate retired with it.
560
    write(root, "x.txt", b"same\nedited\n");
561
    let s = repo.snapshot("status").unwrap();
562
    assert_eq!(statuses(&s), vec![("x.txt".into(), ChangeStatus::Modified)]);
563
    let he = repo.commit("edit x", &[]).unwrap();
564
    let c = repo.store().get_change(&he).unwrap();
565
    assert_eq!(c.kind, ChangeKind::Normal);
566
    let (dup, _) = snap.tree.unified.iter().next().unwrap();
567
    assert!(
568
        c.tree_ops
569
            .iter()
570
            .any(|o| matches!(o, TreeOp::RemoveNode { node, .. } if node == dup)),
571
        "{:?}",
572
        c.tree_ops
573
    );
574
    let d = repo.describe_change(&he).unwrap();
575
    assert!(!d.contains("D x.txt"), "{d}");
576
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
577
    assert!(
578
        st.tree().view().conflicts.is_empty(),
579
        "nothing left to unify"
580
    );
581
    let snap = st.materialize();
582
    assert!(!snap.is_conflicted());
583
    assert!(
584
        matches!(&snap.files["x.txt"].content, FileContent::Text { bytes, .. } if bytes == b"same\nedited\n")
585
    );
586
    assert!(!repo.snapshot("status").unwrap().changed);
587
588
    // Removed and committed: gone.
589
    fs::remove_file(root.join("x.txt")).unwrap();
590
    repo.commit("drop x", &[]).unwrap();
591
    let snap = repo
592
        .load_state(&repo.bookmark_heads().unwrap())
593
        .unwrap()
594
        .materialize();
595
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
596
    assert_eq!(snap.files.keys().cloned().collect::<Vec<_>>(), ["keep.txt"]);
597
    assert!(!root.join("x.txt").exists());
598
}
599
600
/// Removing, renaming, or committing just the path of a unified file
601
/// retires its duplicate with it, so the conflict never comes back.
602
#[test]
603
fn unified_additions_stay_one_when_removed_renamed_or_committed_alone() {
604
    hermetic();
605
    let add = |root: &Path, _: bool| write(root, "x.txt", b"same\n");
606
    for how in ["remove", "rename", "path", "hunk"] {
607
        let (dir, repo, _, _) = merged_additions(add);
608
        let root = dir.path();
609
        match how {
610
            "remove" => fs::remove_file(root.join("x.txt")).unwrap(),
611
            "rename" => fs::rename(root.join("x.txt"), root.join("y.txt")).unwrap(),
612
            _ => {
613
                write(root, "x.txt", b"same\nmore\n");
614
                write(root, "other.txt", b"o\n");
615
            }
616
        }
617
        let s = repo.snapshot("status").unwrap();
618
        let h = match how {
619
            "path" => repo
620
                .commit_selection("x alone", &[], &Selection::Paths(vec!["x.txt".into()]))
621
                .unwrap(),
622
            "hunk" => {
623
                let (_, hunks) = repo.hunks().unwrap();
624
                // The duplicate's retirement is no hunk of its own.
625
                assert!(hunks.iter().all(|h| !h.text.starts_with("D ")), "{hunks:?}");
626
                let x: Vec<usize> = hunks
627
                    .iter()
628
                    .filter(|h| h.path == "x.txt")
629
                    .map(|h| h.index)
630
                    .collect();
631
                assert!(!x.is_empty());
632
                repo.commit_selection("x hunks", &[], &Selection::Hunks(x))
633
                    .unwrap()
634
            }
635
            _ => repo.commit(how, &[]).unwrap(),
636
        };
637
        assert!(!s.base_snapshot.is_conflicted());
638
        let heads = repo.bookmark_heads().unwrap();
639
        assert!(heads.contains(&h));
640
        let snap = repo.load_state(&heads).unwrap().materialize();
641
        assert!(!snap.is_conflicted(), "{how}: {:?}", snap.tree.conflicts);
642
        let want: &[&str] = match how {
643
            "remove" => &["keep.txt"],
644
            "rename" => &["keep.txt", "y.txt"],
645
            _ => &["keep.txt", "x.txt"],
646
        };
647
        assert_eq!(
648
            snap.files.keys().cloned().collect::<Vec<_>>(),
649
            want,
650
            "{how}"
651
        );
652
        assert!(conflict_copies(root).is_empty(), "{how}");
653
    }
654
}
655
656
/// The same path added with different content, or a different mode, is a
657
/// name conflict as before.
658
#[test]
659
fn additions_that_differ_still_conflict() {
660
    hermetic();
661
    #[cfg(unix)]
662
    use std::os::unix::fs::PermissionsExt;
663
    let content =
664
        |root: &Path, side: bool| write(root, "x.txt", if side { b"two\n" } else { b"one\n" });
665
    let mode = |root: &Path, side: bool| {
666
        write(root, "x.txt", b"same\n");
667
        #[cfg(unix)]
668
        if side {
669
            fs::set_permissions(root.join("x.txt"), fs::Permissions::from_mode(0o755)).unwrap();
670
        }
671
    };
672
    let check = |what: &str, side: &dyn Fn(&Path, bool)| {
673
        let (dir, repo, heads, _) = merged_additions(side);
674
        let snap = repo.load_state(&heads).unwrap().materialize();
675
        assert!(snap.tree.unified.is_empty(), "{what}");
676
        assert!(
677
            snap.tree.conflicts.iter().any(
678
                |c| matches!(c, crate::tree::TreeConflict::Name { name, .. } if name == "x.txt")
679
            ),
680
            "{what}: {:?}",
681
            snap.tree.conflicts
682
        );
683
        assert_eq!(
684
            conflict_copies(dir.path()),
685
            ["x.txt.oxy-conflict-1", "x.txt.oxy-conflict-2"],
686
            "{what}"
687
        );
688
        assert!(!dir.path().join("x.txt").exists(), "{what}");
689
    };
690
    check("content", &content);
691
    #[cfg(unix)]
692
    check("mode", &mode);
693
    #[cfg(not(unix))]
694
    let _ = mode;
695
}
696
697
/// The same subrepo at the same pin, added on two bookmarks, is one
698
/// subrepo after the merge (oxygen#101), as is the identical
699
/// `.oxymodules` beside it.
700
#[test]
701
fn the_same_subrepo_added_on_two_bookmarks_unifies() {
702
    hermetic();
703
    let dir = tempfile::tempdir().unwrap();
704
    let root = dir.path();
705
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
706
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
707
    let lib = Repo::clone(&lib_url, &root.join("lib"))
708
        .unwrap()
709
        .with_home(root.join("home"));
710
    write(&root.join("lib"), "lib.txt", b"v1\n");
711
    lib.commit("lib v1", &[]).unwrap();
712
    assert!(lib.push("origin", false).unwrap()[0].ok);
713
    let _ = lib_origin;
714
715
    let app_dir = root.join("app");
716
    let mut app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
717
    write(&app_dir, "main.txt", b"app\n");
718
    app.commit("base", &[]).unwrap();
719
    app.bookmark_create("side", None).unwrap();
720
    app.submodule_add(&lib_url, "rstar-api", None).unwrap();
721
    let modules = fs::read(app_dir.join(".oxymodules")).unwrap();
722
    app.commit("rstar-api on main", &[]).unwrap();
723
    // On the other bookmark the nested repository is still there (it is
724
    // never deleted); registering it again adds it at the same pin.
725
    app.bookmark_switch("side", false).unwrap();
726
    assert!(app_dir.join("rstar-api/.oxy").is_dir());
727
    write(&app_dir, ".oxymodules", &modules);
728
    let s = app.snapshot("status").unwrap();
729
    assert_eq!(
730
        statuses(&s),
731
        vec![
732
            (".oxymodules".into(), ChangeStatus::Added),
733
            ("rstar-api".into(), ChangeStatus::Added)
734
        ]
735
    );
736
    app.commit("rstar-api on side", &[]).unwrap();
737
    app.bookmark_switch("main", false).unwrap();
738
739
    let m = app.merge("side").unwrap();
740
    assert!(m.changed && m.checked_out);
741
    let snap = app.load_state(&m.heads).unwrap().materialize();
742
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
743
    assert_eq!(snap.tree.unified.len(), 2);
744
    assert_eq!(snap.files["rstar-api"].kind, NodeKind::Subrepo);
745
    assert!(conflict_copies(&app_dir).is_empty());
746
    let s = app.snapshot("status").unwrap();
747
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
748
    assert!(!s.base_snapshot.is_conflicted());
749
    assert_eq!(
750
        fs::read_to_string(app_dir.join("rstar-api/lib.txt")).unwrap(),
751
        "v1\n"
752
    );
753
}
754
98286406 Andy McCall ↶ 755
#[test]
756
fn identities_and_signed_commits() {
757
    hermetic();
758
    let dir = tempfile::tempdir().unwrap();
759
    let root = dir.path();
760
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
761
    write(root, "a.txt", b"a\n");
762
    let h0 = repo.commit("unsigned", &[]).unwrap();
763
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
75167672 Andy McCall 764
    assert_eq!(
765
        repo.store().get_change(&h0).unwrap().author,
766
        ObjectRef::ZERO
767
    );
98286406 Andy McCall ↶ 768
75167672 Andy McCall 769
    let (key, id) = repo
770
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
771
        .unwrap();
98286406 Andy McCall ↶ 772
    assert_eq!(id.hash(), key);
773
    assert_eq!(repo.config.author_key, Some(key));
774
    // Config survives reopen; the secret key is found again.
775
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
776
    assert_eq!(reopened.config.author_key, Some(key));
777
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
778
779
    // Default core.sign = seal: commits carry the author but no signature.
780
    write(root, "a.txt", b"a\nb\n");
781
    let h1 = repo.commit("authored", &[]).unwrap();
782
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
783
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
784
    // Signing later works too.
785
    repo.sign_change(&h1).unwrap();
75167672 Andy McCall 786
    assert!(
787
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
788
    );
98286406 Andy McCall ↶ 789
790
    repo.config.set("core.sign", "change").unwrap();
791
    repo.save_config().unwrap();
792
    write(root, "a.txt", b"a\nb\nc\n");
793
    let h2 = repo.commit("signed", &[]).unwrap();
75167672 Andy McCall 794
    assert_eq!(
795
        repo.verify_change(&h2).unwrap(),
796
        SignatureStatus::Valid {
797
            key,
798
            name: "Ada".into(),
799
            email: "[email protected]".into(),
800
            sealed: false,
801
            revoked: false
802
        }
803
    );
98286406 Andy McCall ↶ 804
05e71ed6 Andy McCall ↶ 805
    // A signature by a key that is not the author or a delegate is rejected
806
    // when the change names an author; an anonymous change (made before any
807
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
98286406 Andy McCall ↶ 808
    let other = SecretKey::generate();
809
    let other_id = other.identity("Mallory", "[email protected]", 0);
810
    let other_key = repo.store().put_identity(&other_id).unwrap();
05e71ed6 Andy McCall ↶ 811
    write(root, "a.txt", b"a\nb\nc\nd\n");
812
    repo.config.set("core.sign", "seal").unwrap();
813
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
814
    let forged = other.sign(Domain::Change, &other_key, &h3);
815
    repo.store().put_signature(&h3, &forged).unwrap();
75167672 Andy McCall 816
    assert!(
05e71ed6 Andy McCall ↶ 817
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
75167672 Andy McCall 818
    );
05e71ed6 Andy McCall ↶ 819
    let adopted = other.sign(Domain::Change, &other_key, &h0);
820
    repo.store().put_signature(&h0, &adopted).unwrap();
821
    assert!(
822
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
823
    );
98286406 Andy McCall ↶ 824
825
    // Tampering with the stored signature invalidates it.
826
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
827
    sig.ed[0] ^= 1;
828
    repo.store().put_signature(&h2, &sig).unwrap();
75167672 Andy McCall 829
    assert!(matches!(
830
        repo.verify_change(&h2).unwrap(),
831
        SignatureStatus::Invalid(_)
832
    ));
98286406 Andy McCall ↶ 833
834
    // Without the secret key, signing at commit fails cleanly.
835
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
836
    write(root, "a.txt", b"z\n");
837
    assert!(no_keys.commit("cannot sign", &[]).is_err());
838
}
839
840
#[test]
841
fn checkout_moves_the_working_copy() {
842
    hermetic();
843
    let dir = tempfile::tempdir().unwrap();
844
    let root = dir.path();
845
    let repo = Repo::init(root).unwrap();
846
    write(root, "a.txt", b"one\n");
847
    write(root, "sub/deep/b.txt", b"b\n");
848
    let h1 = repo.commit("first", &[]).unwrap();
849
    write(root, "a.txt", b"two\n");
850
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
851
    write(root, "bin.dat", &[0, 1, 2, 3]);
852
    let h2 = repo.commit("second", &[]).unwrap();
853
854
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
75167672 Andy McCall 855
    assert_eq!(
856
        r,
857
        CheckoutReport {
858
            written: 2,
859
            removed: 1,
9b723f69 Andy McCall ↶ 860
            removed_paths: vec!["bin.dat".into()],
75167672 Andy McCall 861
            conflicted: false,
d3cd7ef9 Andy McCall ↶ 862
            notes: vec![],
863
            lacks: 1,
75167672 Andy McCall 864
        }
865
    );
98286406 Andy McCall ↶ 866
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
867
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
868
    assert!(!root.join("bin.dat").exists());
869
    let (_, wc) = repo.working_copy().unwrap();
870
    assert_eq!(wc.deps, vec![h1]);
75167672 Andy McCall 871
    assert!(
872
        !repo.snapshot("status").unwrap().changed,
873
        "checkout leaves a clean working copy"
874
    );
98286406 Andy McCall ↶ 875
    // The bookmark still points at h2.
876
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
877
878
    // Dirty working copy refuses without --discard.
879
    write(root, "a.txt", b"dirty\n");
880
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
75167672 Andy McCall 881
    let r = repo
882
        .checkout(&[h2], true, "oxy checkout --discard")
883
        .unwrap();
98286406 Andy McCall ↶ 884
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
885
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
886
    assert!(!root.join("sub").exists(), "empty directories are pruned");
887
    assert_eq!(r.removed, 1);
888
    assert!(!repo.snapshot("status").unwrap().changed);
889
890
    // Refuses to write through a symlinked directory.
891
    #[cfg(unix)]
892
    {
893
        fs::remove_dir_all(root.join("sub")).ok();
894
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
895
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
896
    }
897
}
898
899
#[test]
900
fn large_files_are_chunked_and_read_back() {
901
    hermetic();
902
    let dir = tempfile::tempdir().unwrap();
903
    let repo = Repo::init(dir.path()).unwrap();
904
    let mut big = vec![0u8; 700 * 1024];
905
    for (i, b) in big.iter_mut().enumerate() {
906
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
907
    }
908
    let r = repo.store_blob(&big).unwrap();
909
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
910
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
911
    assert_eq!(repo.read_blob(&r).unwrap(), big);
912
    assert_eq!(Repo::blob_ref(&big), r);
913
}
914
915
#[test]
916
fn clone_push_pull_with_seals_and_attestations() {
917
    hermetic();
918
    let dir = tempfile::tempdir().unwrap();
919
    let root = dir.path();
920
    let origin_path = root.join("origin");
921
    let origin = Repo::init(&origin_path).unwrap();
922
    let origin_url = origin_path.to_string_lossy().to_string();
923
924
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
75167672 Andy McCall 925
    let mut a = Repo::clone(&origin_url, &root.join("a"))
926
        .unwrap()
927
        .with_home(root.join("home-a"));
98286406 Andy McCall ↶ 928
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
75167672 Andy McCall 929
    let (key_a, _) = a
930
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
931
        .unwrap();
98286406 Andy McCall ↶ 932
    write(&root.join("a"), "f.txt", b"a\n");
933
    let h1 = a.commit("first", &[]).unwrap();
934
    let results = a.push("origin", false).unwrap();
767ac6cd Andy McCall 935
    origin.refresh().unwrap();
98286406 Andy McCall ↶ 936
    assert!(results[0].ok, "{}", results[0].reason);
937
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
938
    // The change was sealed at push and the reference attested.
75167672 Andy McCall 939
    assert!(
940
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
941
    );
942
    assert_eq!(
943
        origin.verify_change(&h1).unwrap(),
944
        SignatureStatus::Unsigned
945
    );
f8c69576 Andy McCall ↶ 946
    let serial_of = |att: &SignedAttest| match att.attest.body {
947
        AttestBody::Ref { serial, .. } => serial,
948
        _ => unreachable!(),
949
    };
98286406 Andy McCall ↶ 950
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 951
    // A bookmark new to the remote starts at the clock (past any deleted
952
    // namesake's serial); later updates count up from there.
953
    let first = serial_of(&att);
954
    assert!(first > 1_000_000_000_000, "{first}");
98286406 Andy McCall ↶ 955
    let again = a.push("origin", false).unwrap();
767ac6cd Andy McCall 956
    origin.refresh().unwrap();
98286406 Andy McCall ↶ 957
    assert!(again[0].ok && again[0].reason.contains("up to date"));
958
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 959
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
98286406 Andy McCall ↶ 960
961
    // B clones and sees the file and the seal.
962
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
963
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
964
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
75167672 Andy McCall 965
    assert!(matches!(
966
        b.authenticate_change(&h1).unwrap(),
967
        SignatureStatus::Valid { sealed: true, .. }
968
    ));
98286406 Andy McCall ↶ 969
970
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
971
    write(&root.join("b"), "f.txt", b"a\nb\n");
972
    let h2 = b.commit("second", &[]).unwrap();
973
    assert!(b.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 974
    origin.refresh().unwrap();
98286406 Andy McCall ↶ 975
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
976
977
    // A commits an independent change; push is refused until A pulls.
978
    write(&root.join("a"), "g.txt", b"g\n");
979
    let h3 = a.commit("third", &[]).unwrap();
980
    assert!(a.push("origin", false).is_err());
981
    let pr = a.pull("origin").unwrap();
982
    assert!(pr.changed && pr.checked_out);
983
    let mut want = vec![h2, h3];
984
    want.sort();
985
    assert_eq!(pr.heads, want);
986
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
987
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
988
    let results = a.push("origin", false).unwrap();
767ac6cd Andy McCall 989
    origin.refresh().unwrap();
98286406 Andy McCall ↶ 990
    assert!(results[0].ok, "{}", results[0].reason);
991
    let mut origin_heads = origin.bookmark_heads().unwrap();
992
    origin_heads.sort();
993
    assert_eq!(origin_heads, want);
994
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
f8c69576 Andy McCall ↶ 995
    assert_eq!(serial_of(&att), first + 1);
98286406 Andy McCall ↶ 996
997
    // B pulls and ends up identical.
998
    let pr = b.pull("origin").unwrap();
999
    assert_eq!(pr.heads, want);
1000
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
1001
    assert!(!b.snapshot("status").unwrap().changed);
1002
1003
    // Concurrent edits of the same line: the union is a reified conflict.
1004
    write(&root.join("a"), "f.txt", b"a\nA\n");
1005
    a.commit("a-edit", &[]).unwrap();
1006
    a.push("origin", false).unwrap();
767ac6cd Andy McCall 1007
    origin.refresh().unwrap();
98286406 Andy McCall ↶ 1008
    write(&root.join("b"), "f.txt", b"a\nB\n");
1009
    b.commit("b-edit", &[]).unwrap();
1010
    let pr = b.pull("origin").unwrap();
1011
    assert!(pr.changed && pr.checked_out);
1012
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
1013
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
1014
    write(&root.join("b"), "f.txt", b"a\nAB\n");
1015
    let hr = b.commit("resolve", &[]).unwrap();
75167672 Andy McCall 1016
    assert_eq!(
1017
        b.store().get_change(&hr).unwrap().kind,
1018
        ChangeKind::Resolution
1019
    );
98286406 Andy McCall ↶ 1020
    assert!(b.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 1021
    origin.refresh().unwrap();
98286406 Andy McCall ↶ 1022
    a.pull("origin").unwrap();
1023
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
1024
    // The resolution depends on the conflicting edits, but nothing depends
1025
    // on "third" (it only added g.txt), so it stays a head beside it.
1026
    let mut want = vec![hr, h3];
1027
    want.sort();
1028
    assert_eq!(a.bookmark_heads().unwrap(), want);
1029
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
1030
}
1031
1032
#[test]
1033
fn receive_push_rejects_bad_updates() {
1034
    hermetic();
1035
    let dir = tempfile::tempdir().unwrap();
1036
    let root = dir.path();
1037
    let origin = Repo::init(&root.join("origin")).unwrap();
1038
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 1039
    let mut a = Repo::clone(&url, &root.join("a"))
1040
        .unwrap()
1041
        .with_home(root.join("home"));
1042
    let (key, _) = a
1043
        .create_identity("Ada", "a@b", IdentityScope::Repo)
1044
        .unwrap();
98286406 Andy McCall ↶ 1045
    write(&root.join("a"), "f.txt", b"x\n");
1046
    let h1 = a.commit("one", &[]).unwrap();
1047
    assert!(a.push("origin", false).unwrap()[0].ok);
1048
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
75167672 Andy McCall 1049
    let s1 = origin
1050
        .store()
1051
        .put_state(&StateObject::new(vec![h1]))
1052
        .unwrap();
98286406 Andy McCall ↶ 1053
1054
    // Missing head.
75167672 Andy McCall 1055
    let ghost = origin
1056
        .store()
1057
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
1058
        .unwrap();
1059
    let r = origin
1060
        .receive_push(
1061
            Bundle::default(),
1062
            vec![RefUpdate {
1063
                name: "main".into(),
1064
                old_state: s1,
1065
                new_state: ghost,
1066
                force: false,
1067
                attestation: None,
1068
            }],
1069
            None,
1070
            vec![],
1071
        )
1072
        .unwrap();
1073
    assert!(
1074
        !r[0].ok && r[0].reason.contains("missing"),
1075
        "{}",
1076
        r[0].reason
1077
    );
98286406 Andy McCall ↶ 1078
1079
    // Stale old_state.
75167672 Andy McCall 1080
    let r = origin
1081
        .receive_push(
1082
            Bundle::default(),
1083
            vec![RefUpdate {
1084
                name: "main".into(),
1085
                old_state: empty,
1086
                new_state: s1,
1087
                force: false,
1088
                attestation: None,
1089
            }],
1090
            None,
1091
            vec![],
1092
        )
1093
        .unwrap();
98286406 Andy McCall ↶ 1094
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
1095
1096
    // Non-fast-forward without force is refused; with force it passes.
75167672 Andy McCall 1097
    let r = origin
1098
        .receive_push(
1099
            Bundle::default(),
1100
            vec![RefUpdate {
1101
                name: "main".into(),
1102
                old_state: s1,
1103
                new_state: empty,
1104
                force: false,
1105
                attestation: None,
1106
            }],
1107
            None,
1108
            vec![],
1109
        )
1110
        .unwrap();
1111
    assert!(
1112
        !r[0].ok && r[0].reason.contains("fast-forward"),
1113
        "{}",
1114
        r[0].reason
1115
    );
1116
    let r = origin
1117
        .receive_push(
1118
            Bundle::default(),
1119
            vec![RefUpdate {
1120
                name: "main".into(),
1121
                old_state: s1,
1122
                new_state: empty,
1123
                force: true,
1124
                attestation: None,
1125
            }],
1126
            None,
1127
            vec![],
1128
        )
1129
        .unwrap();
98286406 Andy McCall ↶ 1130
    assert!(r[0].ok);
1131
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
1132
1133
    // Attestation with a stale serial is a rollback and is refused.
75167672 Andy McCall 1134
    let sa = a
1135
        .sign_attest(&Attest {
1136
            repo: a.id().unwrap(),
1137
            hlc: Hlc::now(),
1138
            body: AttestBody::Ref {
1139
                name: "main".into(),
1140
                old_state: empty,
1141
                new_state: s1,
1142
                serial: 1,
1143
            },
1144
        })
1145
        .unwrap();
1146
    let r = origin
1147
        .receive_push(
1148
            Bundle::default(),
1149
            vec![RefUpdate {
1150
                name: "main".into(),
1151
                old_state: empty,
1152
                new_state: s1,
1153
                force: false,
1154
                attestation: Some(sa.clone()),
1155
            }],
1156
            None,
1157
            vec![],
1158
        )
1159
        .unwrap();
1160
    assert!(
1161
        !r[0].ok && r[0].reason.contains("serial"),
1162
        "{}",
1163
        r[0].reason
1164
    );
98286406 Andy McCall ↶ 1165
    // An attestation for a different update is refused too.
75167672 Andy McCall 1166
    let sa2 = a
1167
        .sign_attest(&Attest {
1168
            repo: a.id().unwrap(),
1169
            hlc: Hlc::now(),
1170
            body: AttestBody::Ref {
1171
                name: "main".into(),
1172
                old_state: s1,
1173
                new_state: empty,
1174
                serial: 5,
1175
            },
1176
        })
1177
        .unwrap();
1178
    let r = origin
1179
        .receive_push(
1180
            Bundle::default(),
1181
            vec![RefUpdate {
1182
                name: "main".into(),
1183
                old_state: empty,
1184
                new_state: s1,
1185
                force: false,
1186
                attestation: Some(sa2),
1187
            }],
1188
            None,
1189
            vec![],
1190
        )
1191
        .unwrap();
1192
    assert!(
1193
        !r[0].ok && r[0].reason.contains("describe"),
1194
        "{}",
1195
        r[0].reason
1196
    );
98286406 Andy McCall ↶ 1197
    let _ = key;
1198
}
1199
1200
#[test]
1201
fn user_config_supplies_defaults_and_clones_sign() {
1202
    hermetic();
1203
    let dir = tempfile::tempdir().unwrap();
1204
    let root = dir.path();
1205
    let home = root.join("home");
1206
    let origin = Repo::init(&root.join("origin")).unwrap();
1207
    let url = root.join("origin").to_string_lossy().to_string();
1208
1209
    // Identity at user scope: the repository file stays free of author keys.
1210
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
75167672 Andy McCall 1211
    let (key, _) = a
1212
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1213
        .unwrap();
98286406 Andy McCall ↶ 1214
    assert!(!a.config.repo_layer().contains_key("author.key"));
1215
    assert_eq!(a.config.author_key, Some(key));
1216
    assert!(home.join("config.toml").exists());
1217
    a.set_user_config("core.sign", "change").unwrap();
1218
    assert!(a.config.sign_changes);
1219
1220
    // Repository settings override user settings and are the only ones saved.
1221
    a.config.set("core.sign", "seal").unwrap();
1222
    a.save_config().unwrap();
1223
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
1224
    assert!(!again.config.sign_changes);
1225
    assert_eq!(again.config.author_key, Some(key));
75167672 Andy McCall 1226
    assert_eq!(
1227
        read_config_file(&root.join("a/.oxy/config"))
1228
            .unwrap()
1229
            .get("core.sign")
1230
            .map(String::as_str),
1231
        Some("seal")
1232
    );
98286406 Andy McCall ↶ 1233
1234
    // A fresh clone made by this user signs with the user-level identity,
1235
    // even though the clone's store has never seen the identity object.
1236
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
1237
    assert!(b.config.sign_changes);
1238
    write(&root.join("b"), "f.txt", b"f\n");
1239
    let h = b.commit("signed from a clone", &[]).unwrap();
75167672 Andy McCall 1240
    assert!(
1241
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
1242
    );
98286406 Andy McCall ↶ 1243
    assert!(b.push("origin", false).unwrap()[0].ok);
75167672 Andy McCall 1244
    assert!(matches!(
1245
        origin.verify_change(&h).unwrap(),
1246
        SignatureStatus::Valid { .. }
1247
    ));
98286406 Andy McCall ↶ 1248
}
1249
1250
#[test]
1251
fn format1_repositories_are_migrated_on_open() {
1252
    hermetic();
1253
    use crate::oplog::{Format1Op, Format1View};
1254
    let dir = tempfile::tempdir().unwrap();
1255
    let root = dir.path();
1256
    let repo = Repo::init(root).unwrap();
1257
    write(root, "a.txt", b"a\n");
1258
    let h1 = repo.commit("one", &[]).unwrap();
1259
    let (wc_hash, _) = repo.working_copy().unwrap();
1260
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
1261
    let mut v1 = Format1View::default();
1262
    v1.bookmarks.insert("main".into(), vec![]);
1263
    v1.workspaces.insert(repo.workspace(), wc_hash);
75167672 Andy McCall 1264
    let init = Format1Op {
1265
        parents: vec![],
1266
        hlc: Hlc::default(),
1267
        command: "oxy init".into(),
1268
        view: v1.clone(),
1269
    };
98286406 Andy McCall ↶ 1270
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
1271
    v1.bookmarks.insert("main".into(), vec![h1]);
75167672 Andy McCall 1272
    let commit = Format1Op {
1273
        parents: vec![init_ref],
1274
        hlc: Hlc::default(),
1275
        command: "oxy commit".into(),
1276
        view: v1,
1277
    };
98286406 Andy McCall ↶ 1278
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
1279
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
1280
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
1281
    drop(repo);
1282
1283
    let repo = Repo::open(root).unwrap();
75167672 Andy McCall 1284
    assert_eq!(
1285
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
1286
        FORMAT_LINE
1287
    );
98286406 Andy McCall ↶ 1288
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
1289
    let ops = repo.op_log().unwrap();
75167672 Andy McCall 1290
    assert_eq!(
1291
        ops.iter()
1292
            .map(|(_, o)| o.command.as_str())
1293
            .collect::<Vec<_>>(),
1294
        ["oxy commit", "oxy init"]
1295
    );
98286406 Andy McCall ↶ 1296
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
1297
    assert!(!repo.snapshot("status").unwrap().changed);
1298
    // Reopening again is a no-op.
1299
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
1300
}
1301
1302
#[test]
1303
fn undo_skips_snapshot_operations() {
1304
    hermetic();
1305
    let dir = tempfile::tempdir().unwrap();
1306
    let root = dir.path();
1307
    let repo = Repo::init(root).unwrap();
1308
    write(root, "a.txt", b"a\n");
1309
    let h1 = repo.commit("a", &[]).unwrap();
1310
    // A later command snapshots new edits on top of the commit.
1311
    write(root, "b.txt", b"b\n");
1312
    let s = repo.snapshot("oxy status").unwrap();
1313
    assert!(s.changed);
1314
    assert!(repo.head_op().unwrap().1.is_snapshot());
1315
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
1316
    // Undo must undo the commit, not the snapshot.
1317
    repo.undo().unwrap();
1318
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
1319
    let s = repo.snapshot("oxy status").unwrap();
1320
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
75167672 Andy McCall 1321
    assert_eq!(
1322
        paths,
1323
        ["a.txt", "b.txt"],
1324
        "both files are back in the working copy"
1325
    );
98286406 Andy McCall ↶ 1326
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
1327
    // Only snapshots remain above `init`, so there is nothing left to undo.
1328
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
1329
    assert!(repo.undo().is_err());
1330
}
1331
1332
#[test]
1333
fn independent_changes_commute_and_make_multiple_heads() {
1334
    hermetic();
1335
    let dir = tempfile::tempdir().unwrap();
1336
    let root = dir.path();
1337
    let repo = Repo::init(root).unwrap();
1338
    write(root, "a.txt", b"a\n");
1339
    let h1 = repo.commit("a", &[]).unwrap();
1340
    write(root, "b.txt", b"b\n");
1341
    let h2 = repo.commit("b", &[]).unwrap();
1342
    let c2 = repo.store().get_change(&h2).unwrap();
1343
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
1344
    let mut heads = repo.bookmark_heads().unwrap();
1345
    heads.sort();
1346
    let mut want = vec![h1, h2];
1347
    want.sort();
1348
    assert_eq!(heads, want);
1349
    // Editing a.txt depends on h1 only.
1350
    write(root, "a.txt", b"a\na2\n");
1351
    let h3 = repo.commit("a2", &[]).unwrap();
1352
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
1353
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1354
    assert_eq!(heads, [h2, h3].into_iter().collect());
1355
    // Explicit dependency.
1356
    write(root, "c.txt", b"c\n");
1357
    let h4 = repo.commit("c", &[h2]).unwrap();
1358
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
1359
}
1360
1361
#[test]
1362
fn mode_change_and_text_binary_switch() {
1363
    hermetic();
1364
    let dir = tempfile::tempdir().unwrap();
1365
    let root = dir.path();
1366
    let repo = Repo::init(root).unwrap();
1367
    write(root, "run.sh", b"#!/bin/sh\n");
1368
    repo.commit("add script", &[]).unwrap();
1369
    #[cfg(unix)]
1370
    {
1371
        use std::os::unix::fs::PermissionsExt;
1372
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1373
        let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 1374
        assert_eq!(
1375
            statuses(&s),
1376
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
1377
        );
98286406 Andy McCall ↶ 1378
        let h = repo.commit("exec", &[]).unwrap();
1379
        let snap = repo.load_state(&[h]).unwrap().materialize();
1380
        assert!(snap.files["run.sh"].mode.exec);
1381
    }
1382
    // Text → binary → text.
1383
    write(root, "run.sh", b"\0binary");
1384
    let h = repo.commit("binary", &[]).unwrap();
1385
    let snap = repo.load_state(&[h]).unwrap().materialize();
1386
    assert!(snap.files["run.sh"].mode.opaque);
1387
    write(root, "run.sh", b"text again\n");
1388
    let h = repo.commit("text", &[]).unwrap();
1389
    let snap = repo.load_state(&[h]).unwrap().materialize();
1390
    assert!(!snap.files["run.sh"].mode.opaque);
75167672 Andy McCall 1391
    assert!(
1392
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
1393
    );
98286406 Andy McCall ↶ 1394
    assert!(!snap.is_conflicted());
1395
}
83e0677b Andy McCall ↶ 1396
6eae06b6 Andy McCall ↶ 1397
/// oxygen#87: a binary file given new contents and the executable bit in
1398
/// one commit kept the contents and lost the bit.
1399
#[cfg(unix)]
1400
#[test]
1401
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
1402
    use std::os::unix::fs::PermissionsExt;
1403
    hermetic();
1404
    let dir = tempfile::tempdir().unwrap();
1405
    let root = dir.path();
1406
    let repo = Repo::init(root).unwrap();
1407
    write(root, "tool.exe", b"MZ\0one");
1408
    repo.commit("add", &[]).unwrap();
1409
    write(root, "tool.exe", b"MZ\0two");
1410
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
1411
    let h = repo.commit("update and +x", &[]).unwrap();
1412
    let snap = repo.load_state(&[h]).unwrap().materialize();
1413
    let f = &snap.files["tool.exe"];
1414
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
1415
    assert!(
1416
        repo.snapshot("status").unwrap().statuses.is_empty(),
1417
        "nothing left to commit"
1418
    );
1419
}
1420
f0a517d2 Andy McCall ↶ 1421
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
1422
/// key whose certificate an issuer gave pushes when the policy grants its
1423
/// subject, and a fetch accepts what it attested; an expired certificate,
1424
/// or a subject the policy does not grant, may not move the bookmark.
83e0677b Andy McCall ↶ 1425
#[test]
f0a517d2 Andy McCall ↶ 1426
fn a_certified_key_pushes_under_a_subject_grant() {
1427
    use crate::cert::{Certificate, SignedCertificate};
1428
    use crate::identity::Scope;
1429
    hermetic();
1430
    let dir = tempfile::tempdir().unwrap();
1431
    let root = dir.path();
1432
    let _origin = Repo::init(&root.join("origin")).unwrap();
1433
    let url = root.join("origin").to_string_lossy().to_string();
1434
    let mut a = Repo::clone(&url, &root.join("a"))
1435
        .unwrap()
1436
        .with_home(root.join("home-a"));
1437
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1438
        .unwrap();
1439
    write(&root.join("a"), "a.txt", b"a\n");
1440
    a.commit("a", &[]).unwrap();
1441
    a.policy_init().unwrap();
1442
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1443
    let hub_sk = SecretKey::generate();
1444
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1445
    a.policy_grant_subject(
1446
        "agent:claude@ada",
1447
        hub.clone(),
1448
        Scope::CHANGES | Scope::REFS,
1449
        None,
1450
    )
1451
    .unwrap();
1452
    assert!(a
1453
        .push("origin", false)
1454
        .unwrap()
1455
        .iter()
1456
        .any(|r| r.name == "policy" && r.ok));
1457
1458
    let now = Hlc::now().wall_ms;
1459
    // An agent repository whose key the hub certified for `subject`, from
1460
    // `from` to `to`.
1461
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1462
        let mut r = Repo::clone(&url, &root.join(name))
1463
            .unwrap()
1464
            .with_home(root.join(format!("home-{name}")));
1465
        let (_, id) = r
1466
            .create_identity(name, "[email protected]", IdentityScope::User)
1467
            .unwrap();
1468
        let cert = SignedCertificate::sign(
1469
            Certificate {
1470
                key: id,
1471
                issuer: hub.hash(),
1472
                subject: subject.into(),
1473
                claims: vec![],
1474
                scope: Scope::CHANGES | Scope::REFS,
1475
                not_before: from,
1476
                expires: to,
a2387d54 Andy McCall ↶ 1477
                grant: None,
f0a517d2 Andy McCall ↶ 1478
            },
1479
            &hub,
1480
            &hub_sk,
1481
        );
1482
        r.store().put_identity(&hub).unwrap();
1483
        r.store().put_certificate(&cert).unwrap();
1484
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1485
        r.commit("work", &[]).unwrap();
1486
        r
1487
    };
1488
1489
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1490
    let r = claude.push("origin", false).unwrap();
1491
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1492
    // Ada's fetch accepts the bookmark the certified key attested.
1493
    a.pull("origin").unwrap();
1494
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1495
        .store()
1496
        .get_change(h)
1497
        .map(|c| c.message == "work")
1498
        .unwrap_or(false)));
1499
f53cbe7a Andy McCall ↶ 1500
    // Step 4c: a host with an acceptor key records when it accepted the
1501
    // certified update and serves it; a fetch checks the certificate at
1502
    // that time only when the certificate's issuer signed it for exactly
1503
    // this attestation, else at the attestation's own time.
1504
    let host = Repo::open(&root.join("origin"))
1505
        .unwrap()
1506
        .with_acceptor(hub.clone(), hub_sk.clone());
1507
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1508
    host.record_acceptance(&attest_ref).unwrap();
1509
    let served = host.remote_refs().unwrap();
1510
    let acc = served
1511
        .refs
1512
        .iter()
1513
        .find(|r| r.name == "main")
1514
        .unwrap()
1515
        .accepted
1516
        .clone()
1517
        .expect("served with the refs");
1518
    let signer = sa.sigs[0].key;
1519
    assert_eq!(
1520
        a.certified_time(&signer, &sa, Some(&acc)),
1521
        acc.attest.hlc.wall_ms
1522
    );
1523
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1524
    let stranger_sk = SecretKey::generate();
1525
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1526
    let mut forged = acc.clone();
1527
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1528
    assert_eq!(
1529
        a.certified_time(&signer, &sa, Some(&forged)),
1530
        sa.attest.hlc.wall_ms,
1531
        "not the issuer's"
1532
    );
1533
    let mut elsewhere = acc.clone();
1534
    elsewhere.attest.body = AttestBody::Accepted {
1535
        attest: ObjectRef([7; 32]),
1536
    };
1537
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1538
    assert_eq!(
1539
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1540
        sa.attest.hlc.wall_ms,
1541
        "another attestation's"
1542
    );
1543
    a.pull("origin").unwrap();
1544
    // gc keeps the acceptance with the attestation.
1545
    host.gc(true).unwrap();
1546
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1547
f0a517d2 Andy McCall ↶ 1548
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1549
    let r = late.push("origin", false).unwrap();
1550
    assert!(
1551
        !r[0].ok && r[0].reason.contains("may not update"),
1552
        "an expired certificate: {r:?}"
1553
    );
1554
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1555
    let r = other.push("origin", false).unwrap();
1556
    assert!(
1557
        !r[0].ok && r[0].reason.contains("may not update"),
1558
        "a subject not granted: {r:?}"
1559
    );
1560
}
1561
d8524a9f Andy McCall ↶ 1562
/// A tag made under one short-lived key and pushed under another: its
1563
/// signer travels with the push (identity and certificate), so a receiver
1564
/// that has never seen that key accepts it. A tag-only push by a keyless
1565
/// agent was refused "unknown key" (found releasing OxygenFlow 0.2.0).
1566
#[test]
1567
fn a_tag_signed_by_an_earlier_short_lived_key_is_pushed() {
1568
    use crate::cert::{Certificate, SignedCertificate};
1569
    use crate::identity::Scope;
1570
    hermetic();
1571
    let dir = tempfile::tempdir().unwrap();
1572
    let root = dir.path();
1573
    let _origin = Repo::init(&root.join("origin")).unwrap();
1574
    let url = root.join("origin").to_string_lossy().to_string();
1575
    let mut a = Repo::clone(&url, &root.join("a"))
1576
        .unwrap()
1577
        .with_home(root.join("home-a"));
1578
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1579
        .unwrap();
1580
    write(&root.join("a"), "a.txt", b"a\n");
1581
    a.commit("a", &[]).unwrap();
1582
    a.policy_init().unwrap();
1583
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1584
    let hub_sk = SecretKey::generate();
1585
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1586
    a.policy_grant_subject(
1587
        "agent:claude@ada",
1588
        hub.clone(),
1589
        Scope::CHANGES | Scope::REFS,
1590
        Some("*"),
1591
    )
1592
    .unwrap();
1593
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1594
1595
    let now = Hlc::now().wall_ms;
1596
    let mut agent = Repo::clone(&url, &root.join("agent"))
1597
        .unwrap()
1598
        .with_home(root.join("home-agent"));
1599
    agent.store().put_identity(&hub).unwrap();
1600
    let certify = |agent: &Repo, id| {
1601
        let cert = SignedCertificate::sign(
1602
            Certificate {
1603
                key: id,
1604
                issuer: hub.hash(),
1605
                subject: "agent:claude@ada".into(),
1606
                claims: vec![],
1607
                scope: Scope::CHANGES | Scope::REFS,
1608
                not_before: now - 60_000,
1609
                expires: now + 600_000,
1610
                grant: None,
1611
            },
1612
            &hub,
1613
            &hub_sk,
1614
        );
1615
        agent.store().put_certificate(&cert).unwrap();
1616
    };
1617
    // The tag, under the first short-lived key.
1618
    let (first, first_id) = agent
1619
        .create_identity("claude", "[email protected]", IdentityScope::User)
1620
        .unwrap();
1621
    certify(&agent, first_id);
1622
    let heads = agent.bookmark_heads().unwrap();
1623
    agent.tag_create("v1", &heads, "first").unwrap();
1624
    // The push, under a second one (a later process's ten-minute key).
1625
    let (second, second_id) = agent
1626
        .create_identity("claude", "[email protected]", IdentityScope::User)
1627
        .unwrap();
1628
    assert_ne!(first, second);
1629
    certify(&agent, second_id);
1630
    agent
1631
        .set_user_config("author.signer", &second.to_hex())
1632
        .unwrap();
1633
    let host = Repo::open(&root.join("origin")).unwrap();
1ec6fdbc Andy McCall ↶ 1634
    assert!(
1635
        host.store().get_identity(&first).is_err(),
1636
        "the host has never seen the tag's key"
1637
    );
d8524a9f Andy McCall ↶ 1638
    let r = agent.push("origin", false).unwrap();
1ec6fdbc Andy McCall ↶ 1639
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1640
    let host = Repo::open(&root.join("origin")).unwrap();
1641
    assert!(
1642
        host.tag_refs().unwrap().iter().any(|t| t.name == "v1"),
1643
        "the tag arrived"
1644
    );
1645
}
1646
1647
/// oxygen#129: a short-lived key's tag is checked on a fetch at a time its
1648
/// signer did not choose, its issuer's acceptance, never at the time it
1649
/// claims nor at the fetch's (when the ten-minute certificate has long
1650
/// expired). Without an acceptance it is left out and said so; with one
1651
/// inside the certificate's window it is fetched however much later, and
1652
/// a host it is pushed on to keeps and serves the acceptance.
1653
#[test]
1654
fn a_short_lived_key_s_tag_is_fetched_at_its_issuer_s_acceptance() {
1655
    use crate::cert::{Certificate, SignedCertificate};
1656
    use crate::identity::Scope;
1657
    hermetic();
1658
    let dir = tempfile::tempdir().unwrap();
1659
    let root = dir.path();
1660
    let _origin = Repo::init(&root.join("origin")).unwrap();
1661
    let url = root.join("origin").to_string_lossy().to_string();
1662
    let mut a = Repo::clone(&url, &root.join("a"))
1663
        .unwrap()
1664
        .with_home(root.join("home-a"));
1665
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1666
        .unwrap();
1667
    write(&root.join("a"), "a.txt", b"a\n");
1668
    a.commit("a", &[]).unwrap();
1669
    a.policy_init().unwrap();
1670
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1671
    let hub_sk = SecretKey::generate();
1672
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1673
    a.policy_grant_subject(
1674
        "agent:claude@ada",
1675
        hub.clone(),
1676
        Scope::CHANGES | Scope::REFS,
1677
        Some("*"),
1678
    )
1679
    .unwrap();
1680
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1681
1682
    let now = Hlc::now().wall_ms;
1683
    // An agent whose key the hub certified from `from` to `to`.
1684
    let agent = |name: &str, from: u64, to: u64| {
1685
        let mut r = Repo::clone(&url, &root.join(name))
1686
            .unwrap()
1687
            .with_home(root.join(format!("home-{name}")));
1688
        r.store().put_identity(&hub).unwrap();
1689
        let (_, id) = r
1690
            .create_identity(name, "[email protected]", IdentityScope::User)
1691
            .unwrap();
1692
        let cert = SignedCertificate::sign(
1693
            Certificate {
1694
                key: id,
1695
                issuer: hub.hash(),
1696
                subject: "agent:claude@ada".into(),
1697
                claims: vec![],
1698
                scope: Scope::CHANGES | Scope::REFS,
1699
                not_before: from,
1700
                expires: to,
1701
                grant: None,
1702
            },
1703
            &hub,
1704
            &hub_sk,
1705
        );
1706
        r.store().put_certificate(&cert).unwrap();
1707
        r
1708
    };
1709
1710
    // A tag by a key certified now, pushed to a host that records no
1711
    // acceptance (a path on disk): it lands, but a fetch has no time to
1712
    // check its certificate at, so it is left out and the fetch goes on.
1713
    let claude = agent("claude", now - 60_000, now + 600_000);
1714
    let heads = claude.bookmark_heads().unwrap();
1715
    claude.tag_create("v1", &heads, "one").unwrap();
1716
    let r = claude.push("origin", false).unwrap();
d8524a9f Andy McCall ↶ 1717
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1ec6fdbc Andy McCall ↶ 1718
    let b = Repo::clone(&url, &root.join("b"))
1719
        .unwrap()
1720
        .with_home(root.join("home-b"));
1721
    let rep = b.fetch("origin").unwrap();
1722
    assert!(
1723
        rep.skipped
1724
            .iter()
1725
            .any(|(n, why)| n == "tags/v1" && why.contains("no time to check its certificate at")),
1726
        "{rep:?}"
1727
    );
1728
    assert_eq!(b.tag_heads("v1").unwrap(), None);
1729
1730
    // The host's acceptance, signed by the certificate's issuer, served
1731
    // with the tag: fetched.
1732
    let host = Repo::open(&root.join("origin"))
1733
        .unwrap()
1734
        .with_acceptor(hub.clone(), hub_sk.clone());
1735
    let (v1, _) = host.tag_attest("v1").unwrap().unwrap();
1736
    host.record_acceptance(&v1).unwrap();
1737
    let served = host.tag_refs().unwrap();
1738
    assert!(served
1739
        .iter()
1740
        .any(|t| t.name == "v1" && t.accepted.is_some()));
1741
    let rep = b.fetch("origin").unwrap();
1742
    assert!(rep.skipped.is_empty(), "{rep:?}");
1743
    assert_eq!(b.tag_heads("v1").unwrap(), Some(heads.clone()));
1744
    // gc keeps the acceptance with the tag.
1745
    host.gc(true).unwrap();
1746
    assert!(host.acceptance_of(&v1).unwrap().is_some());
1747
1748
    // Long after: a key whose certificate expired an hour ago may not
1749
    // create a tag now.
1750
    let late = agent("late", now - 7_200_000, now - 3_600_000);
1751
    late.tag_create("v2", &heads, "two").unwrap();
1752
    let r = late.push("origin", false).unwrap();
1753
    assert!(
1754
        r.iter()
1755
            .any(|x| x.name == "tags/v2" && !x.ok && x.reason.contains("may not create")),
1756
        "{r:?}"
1757
    );
1758
    // With its issuer's acceptance from inside the window (as a hub gave
1759
    // it then, passed on to another host), it is taken at that time: by
1760
    // the host it is pushed to, which keeps it, and by a fresh clone.
1761
    let (v2, _) = late.tag_attest("v2").unwrap().unwrap();
1762
    let acc = Attest {
1763
        repo: late.id().unwrap(),
1764
        hlc: Hlc {
1765
            wall_ms: now - 5_400_000,
1766
            logical: 0,
1767
        },
1768
        body: AttestBody::Accepted { attest: v2 },
1769
    };
1770
    let sig = hub_sk.sign(Domain::Attest, &hub.hash(), &acc.hash());
1771
    // One by any other key gives no time.
1772
    let stranger_sk = SecretKey::generate();
1773
    let stranger = stranger_sk.identity("stranger", "[email protected]", 1);
1774
    let forged = stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.hash());
1775
    late.keep_acceptance(
1776
        &v2,
1777
        &SignedAttest {
1778
            attest: acc.clone(),
1779
            sigs: vec![forged],
1780
        },
1781
    )
1782
    .unwrap();
1783
    let r = late.push("origin", false).unwrap();
1784
    assert!(
1785
        r.iter().any(|x| x.name == "tags/v2" && !x.ok),
1786
        "not the issuer's: {r:?}"
1787
    );
1788
    let theirs = SignedAttest {
1789
        attest: acc,
1790
        sigs: vec![sig],
1791
    };
1792
    // Kept beside the stranger's: the issuer's is the one sent.
1793
    late.keep_acceptance(&v2, &theirs).unwrap();
1794
    let r = late.push("origin", false).unwrap();
1795
    // (Its re-attestation of main is refused: an expired key moves no
1796
    // bookmark.)
1797
    assert!(r.iter().any(|x| x.name == "tags/v2" && x.ok), "{r:?}");
d8524a9f Andy McCall ↶ 1798
    let host = Repo::open(&root.join("origin")).unwrap();
1ec6fdbc Andy McCall ↶ 1799
    let (hv2, _) = host.tag_attest("v2").unwrap().unwrap();
1800
    assert_eq!(hv2, v2);
1801
    assert!(host
1802
        .store()
1803
        .index_get_pub("accepted", &v2)
1804
        .unwrap()
1805
        .contains(&theirs.attest.hash()));
1806
    let c = Repo::clone(&url, &root.join("c"))
1807
        .unwrap()
1808
        .with_home(root.join("home-c"));
1809
    assert_eq!(c.tag_heads("v2").unwrap(), Some(heads.clone()));
1810
    assert_eq!(c.tag_heads("v1").unwrap(), Some(heads));
d8524a9f Andy McCall ↶ 1811
}
1812
d36ba2f7 Andy McCall ↶ 1813
/// oxygenhub#266: a short-lived key its issuer certified moves a bookmark
1814
/// and signs no change (a keyless agent naming a bookmark). A third
1815
/// party's clone gets the key's identity, its certificate and the
1816
/// issuer's identity with the fetch, so the policy's subject grant
1817
/// authorizes the move and the signature verifies.
1818
#[test]
1819
fn a_bookmark_moved_by_a_certified_key_alone_is_fetched() {
1820
    use crate::cert::{Certificate, SignedCertificate};
1821
    use crate::identity::Scope;
1822
    hermetic();
1823
    let dir = tempfile::tempdir().unwrap();
1824
    let root = dir.path();
1825
    let _origin = Repo::init(&root.join("origin")).unwrap();
1826
    let url = root.join("origin").to_string_lossy().to_string();
1827
    let mut a = Repo::clone(&url, &root.join("a"))
1828
        .unwrap()
1829
        .with_home(root.join("home-a"));
1830
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1831
        .unwrap();
1832
    write(&root.join("a"), "a.txt", b"a\n");
1833
    a.commit("a", &[]).unwrap();
1834
    a.policy_init().unwrap();
1835
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1836
    let hub_sk = SecretKey::generate();
1837
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1838
    a.policy_grant_subject(
1839
        "agent:claude@ada",
1840
        hub.clone(),
1841
        Scope::CHANGES | Scope::REFS,
1842
        None,
1843
    )
1844
    .unwrap();
1845
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1846
1847
    let now = Hlc::now().wall_ms;
1848
    let mut agent = Repo::clone(&url, &root.join("agent"))
1849
        .unwrap()
1850
        .with_home(root.join("home-agent"));
1851
    let (key, id) = agent
1852
        .create_identity("claude", "[email protected]", IdentityScope::User)
1853
        .unwrap();
1854
    let cert = SignedCertificate::sign(
1855
        Certificate {
1856
            key: id,
1857
            issuer: hub.hash(),
1858
            subject: "agent:claude@ada".into(),
1859
            claims: vec![],
1860
            scope: Scope::CHANGES | Scope::REFS,
1861
            not_before: now - 60_000,
1862
            expires: now + 600_000,
1863
            grant: None,
1864
        },
1865
        &hub,
1866
        &hub_sk,
1867
    );
1868
    agent.store().put_identity(&hub).unwrap();
1869
    agent.store().put_certificate(&cert).unwrap();
1870
    let heads = agent.bookmark_heads().unwrap();
1871
    agent.bookmark_create("agent-work", Some(&heads)).unwrap();
1872
    let r = agent.push_bookmark("origin", "agent-work", false).unwrap();
1873
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1874
    let host = Repo::open(&root.join("origin")).unwrap();
1875
    let (_, sa) = host.latest_ref_attest("agent-work").unwrap().unwrap();
1876
    assert_eq!(sa.sigs[0].key, key, "the certified key alone moved it");
1877
1878
    // A fetch naming no change brings the certificate and both identities.
1879
    let bundle = host.bundle_raw_for(&[], None).unwrap();
1880
    assert!(bundle.changes.is_empty() && bundle.raw_changes.is_empty());
1881
    assert_eq!(bundle.certificates.len(), 1);
1882
    for k in [key, hub.hash()] {
1883
        assert!(bundle
1884
            .objects
1885
            .iter()
1886
            .any(|(t, b)| *t == ObjectType::Identity && hash_object(*t, b) == k));
1887
    }
1888
1889
    let c = Repo::clone(&url, &root.join("c")).unwrap();
1890
    let tracked = c.view().unwrap().remotes["origin"].clone();
1891
    assert_eq!(
1892
        tracked.get("agent-work"),
1893
        host.view().unwrap().bookmarks.get("agent-work")
1894
    );
1895
    assert!(c.store().certificate_of(&key).unwrap().is_some());
1896
}
1897
028545df Andy McCall ↶ 1898
/// Trusted time (oxygenhub#240, spec §14.8): a fetched attestation by a
1899
/// short-lived key is judged at its integrated time, the earliest time a
1900
/// pinned witness cosigned a checkpoint holding it. A certificate valid
1901
/// then but expired now passes; a witness this user does not trust gives
1902
/// no time (the earlier rule, said so); a backdated attestation is noted;
1903
/// an answer without the new fields is judged as before.
1904
#[test]
1905
fn a_fetched_attestation_is_judged_at_its_integrated_time() {
1906
    use super::transparency::LogCheck;
1907
    use crate::cert::{Certificate, SignedCertificate};
1908
    use crate::identity::Scope;
1909
    use crate::protocol::{Integration, Logged, RefsResponse, RemoteRef};
1910
    use crate::tlog::{self, Checkpoint, Entry, Hash, Integrated, Note};
1911
    hermetic();
1912
    let dir = tempfile::tempdir().unwrap();
1913
    let root = dir.path();
1914
    let mut a = Repo::init(&root.join("a"))
1915
        .unwrap()
1916
        .with_home(root.join("home-a"));
1917
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1918
        .unwrap();
1919
    write(&root.join("a"), "a.txt", b"a\n");
1920
    a.commit("a", &[]).unwrap();
1921
    a.policy_init().unwrap();
1922
    let issuer_sk = SecretKey::generate();
1923
    let issuer = issuer_sk.identity("hub", "[email protected]", 1);
1924
    a.policy_grant_subject(
1925
        "agent:claude@ada",
1926
        issuer.clone(),
1927
        Scope::CHANGES | Scope::REFS,
1928
        None,
1929
    )
1930
    .unwrap();
1931
    let p = a.current_policy().unwrap().unwrap().1.policy;
1932
1933
    // An agent key the issuer certified for ten minutes two hours ago.
1934
    let now = Hlc::now().wall_ms;
1935
    let t0 = now - 2 * 3_600_000;
1936
    let agent_sk = SecretKey::generate();
1937
    let agent = agent_sk.identity("claude", "[email protected]", t0);
1938
    let cert = SignedCertificate::sign(
1939
        Certificate {
1940
            key: agent.clone(),
1941
            issuer: issuer.hash(),
1942
            subject: "agent:claude@ada".into(),
1943
            claims: vec![],
1944
            scope: Scope::CHANGES | Scope::REFS,
1945
            not_before: t0,
1946
            expires: t0 + 600_000,
1947
            grant: None,
1948
        },
1949
        &issuer,
1950
        &issuer_sk,
1951
    );
1952
    a.store().put_identity(&agent).unwrap();
1953
    a.store().put_certificate(&cert).unwrap();
1954
    let signer = agent.hash();
1955
    let attested = |claimed: u64| {
1956
        let attest = Attest {
1957
            repo: a.id().unwrap(),
1958
            hlc: Hlc {
1959
                wall_ms: claimed,
1960
                logical: 0,
1961
            },
1962
            body: AttestBody::Ref {
1963
                name: "main".into(),
1964
                old_state: ObjectRef([1; 32]),
1965
                new_state: ObjectRef([2; 32]),
1966
                serial: 1,
1967
            },
1968
        };
1969
        let sig = agent_sk.sign(Domain::Attest, &signer, &attest.hash());
1970
        SignedAttest {
1971
            attest,
1972
            sigs: vec![sig],
1973
        }
1974
    };
1975
1976
    // The hub's log: eight entries, the attestation's at 3, the latest
1977
    // checkpoint of 8, and one of 4 that witnesses cosigned.
1978
    let log_sk = SecretKey::generate();
1979
    let log_key = log_sk.identity("hub.example", "[email protected]", 1);
1980
    let origin = "hub.example/log";
1981
    let hub = "https://hub.example";
1982
    let url = "https://hub.example/ada/a";
1983
    let w_sk = SecretKey::generate();
1984
    let w = w_sk.identity("w", "[email protected]", 1);
1985
    let stranger_sk = SecretKey::generate();
1986
    let stranger = stranger_sk.identity("s", "[email protected]", 1);
1987
    let sa = attested(t0 + 300_000);
1988
    let entry_of = |i: u64| {
1989
        let (kind, object) = if i == 3 {
1990
            ("ref", sa.attest.hash())
1991
        } else {
1992
            ("seal", ObjectRef([i as u8; 32]))
1993
        };
1994
        Entry {
1995
            kind: kind.into(),
1996
            repo: sa.attest.repo,
1997
            object,
1998
            signers: vec![signer],
1999
            received: t0 + 300_000,
2000
        }
2001
        .encode()
2002
    };
2003
    let mut stored: Vec<Hash> = Vec::new();
2004
    for i in 0..8 {
2005
        let add = tlog::stored_hashes_for_leaf(i, tlog::leaf_hash(&entry_of(i)), &stored).unwrap();
2006
        stored.extend(add);
2007
    }
2008
    let note_of = |n: u64, cosigners: &[(&str, &Identity, &SecretKey, u64)]| {
2009
        let mut note = Checkpoint {
2010
            origin: origin.into(),
2011
            size: n,
2012
            root: tlog::tree_hash(n, &stored).unwrap(),
2013
            extensions: vec![],
2014
        }
2015
        .sign(&log_key, &log_sk)
2016
        .unwrap();
2017
        for (name, id, sk, t) in cosigners {
2018
            note.sigs
2019
                .extend(tlog::cosign(&note.text, name, id, sk, *t).unwrap());
2020
        }
2021
        note.encode()
2022
    };
2023
    let latest = note_of(8, &[]);
2024
    let witnessed_at = (t0 + 360_000) / 1000;
2025
    let cosigned = note_of(
2026
        4,
2027
        &[
2028
            ("w.example", &w, &w_sk, witnessed_at),
2029
            ("s.example", &stranger, &stranger_sk, 1),
2030
        ],
2031
    );
2032
    let answer = |integration: Vec<Integration>, witnesses: Vec<(String, Vec<u8>)>| RefsResponse {
2033
        refs: vec![RemoteRef {
2034
            name: "main".into(),
2035
            state: ObjectRef([2; 32]),
2036
            heads: vec![],
2037
            attestation: Some(sa.clone()),
2038
            last_serial: None,
2039
            accepted: None,
2040
            logged: Some(Logged {
2041
                index: 3,
2042
                entry: entry_of(3),
2043
                proof: tlog::prove_inclusion(8, 3, &stored).unwrap(),
2044
            }),
2045
            integration,
2046
        }],
2047
        log: Some(latest.clone()),
2048
        witnesses,
2049
        ..RefsResponse::default()
2050
    };
2051
    let proof4 = tlog::prove_inclusion(4, 3, &stored).unwrap();
2052
    let served = vec![Integration {
2053
        note: cosigned.clone(),
2054
        proof: proof4.clone(),
2055
    }];
2056
    let listed = vec![("w.example".to_string(), w.encode())];
2057
    // This user saw the hub's log before (pinned, so nothing is fetched).
2058
    a.remember_log(hub, &log_key, &Note::parse(&latest).unwrap())
2059
        .unwrap();
2060
2061
    // The witness is pinned on first sight, silently; the stranger's
2062
    // earlier cosignature counts for nothing.
2063
    let resp = answer(served.clone(), listed.clone());
2064
    let lc = a.check_log(url, None, &resp).unwrap();
2065
    assert!(lc.notes.is_empty(), "{:?}", lc.notes);
2066
    let t = lc.time_of("main").unwrap();
2067
    assert_eq!((t.time, t.witness.as_str()), (witnessed_at, "w.example"));
2068
    // The certificate expired an hour and fifty minutes ago, but covered
2069
    // the integrated time: accepted, and nothing to say.
2070
    assert!(cert.cert.expires < now);
2071
    let mut notes = Vec::new();
2072
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
2073
        .unwrap();
2074
    assert!(notes.is_empty(), "{notes:?}");
2075
2076
    // Only the stranger cosigned: no witnessed time, so the earlier rule
2077
    // (the attestation's own time, inside the window), said so.
2078
    let lonely = vec![Integration {
2079
        note: note_of(4, &[("s.example", &stranger, &stranger_sk, 1)]),
2080
        proof: proof4.clone(),
2081
    }];
2082
    let resp = answer(lonely, vec![]);
2083
    let lc = a.check_log(url, None, &resp).unwrap();
2084
    assert!(lc
2085
        .time_of("main")
2086
        .unwrap_err()
2087
        .contains("no witness this user trusts"));
2088
    let mut notes = Vec::new();
2089
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
2090
        .unwrap();
2091
    assert!(
2092
        notes.len() == 1 && notes[0].contains("not at a witnessed time"),
2093
        "{notes:?}"
2094
    );
2095
2096
    // A witness listed later under the pinned name with another key is
2097
    // pinned with a note, as a new log key is.
2098
    let resp = answer(
2099
        served.clone(),
2100
        vec![("w.example".into(), stranger.encode())],
2101
    );
2102
    let lc = a.check_log(url, None, &resp).unwrap();
2103
    assert!(
2104
        lc.notes.iter().any(|n| n.contains("another key")),
2105
        "{:?}",
2106
        lc.notes
2107
    );
2108
    assert!(
2109
        lc.time_of("main").is_err(),
2110
        "w's cosignature is by its old key"
2111
    );
2112
    a.check_log(url, None, &answer(served.clone(), listed.clone()))
2113
        .unwrap();
2114
2115
    // An old peer's answer: no log, no witnesses, no integration. Judged
2116
    // as before, silently.
2117
    let mut old = answer(vec![], vec![]);
2118
    old.log = None;
2119
    old.refs[0].logged = None;
2120
    let lc = a.check_log(url, None, &old).unwrap();
2121
    assert!(!lc.kept && lc.notes.is_empty());
2122
    let mut notes = Vec::new();
2123
    a.authorize_in_time(&p, "origin", &old.refs[0], &sa, &signer, &lc, &mut notes)
2124
        .unwrap();
2125
    assert!(notes.is_empty(), "{notes:?}");
2126
2127
    // Judged at given integrated times.
2128
    let at = |secs_after_t0: u64| {
2129
        let mut times = std::collections::HashMap::new();
2130
        times.insert(
2131
            "main".to_string(),
2132
            Ok(Integrated {
2133
                time: (t0 + secs_after_t0 * 1000) / 1000,
2134
                witness: "w.example".into(),
2135
                size: 4,
2136
            }),
2137
        );
2138
        LogCheck {
2139
            kept: true,
2140
            times,
2141
            ..LogCheck::default()
2142
        }
2143
    };
2144
    let judged = |sa: &SignedAttest, lc: &LogCheck| {
2145
        let mut notes = Vec::new();
2146
        a.authorize_in_time(&p, "origin", &old.refs[0], sa, &signer, lc, &mut notes)
2147
            .map(|_| notes)
2148
    };
2149
    // Claimed inside the window, first witnessed an hour later, after
2150
    // the certificate expired: backdated, or held back. Accepted by the
2151
    // earlier rule while logs are new, with both said.
2152
    let notes = judged(&sa, &at(3600)).unwrap();
2153
    assert!(
2154
        notes
2155
            .iter()
2156
            .any(|n| n.contains("had lapsed when witness w.example"))
2157
            && notes
2158
                .iter()
2159
                .any(|n| n.contains("55 minutes before witness")),
2160
        "{notes:?}"
2161
    );
2162
    // Claimed after the certificate expired, but witnessed inside its
2163
    // window: the clock the signer did not choose decides. The gap is
2164
    // still noted.
2165
    let fast = attested(now);
2166
    let notes = judged(&fast, &at(400)).unwrap();
2167
    assert!(
2168
        notes.len() == 1 && notes[0].contains("after witness w.example saw it"),
2169
        "{notes:?}"
2170
    );
2171
    // Claimed and witnessed after it expired: refused, as before.
2172
    assert!(judged(&fast, &at(3600)).is_err());
2173
    // A gap within ten minutes is nothing to note.
2174
    assert!(judged(&sa, &at(500)).unwrap().is_empty());
2175
}
2176
a2387d54 Andy McCall ↶ 2177
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
2178
/// subject the author granted, seals changes in the author's name; with
2179
/// no grant, a stranger's, or one that had ended, it is neither the
2180
/// author nor a delegate.
f0a517d2 Andy McCall ↶ 2181
#[test]
a2387d54 Andy McCall ↶ 2182
fn a_certified_key_acts_for_its_author_under_a_grant() {
2183
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
2184
    use crate::identity::{Identity, Scope};
2185
    hermetic();
2186
    let dir = tempfile::tempdir().unwrap();
2187
    let root = dir.path();
2188
    let _origin = Repo::init(&root.join("origin")).unwrap();
2189
    let url = root.join("origin").to_string_lossy().to_string();
2190
    let mut a = Repo::clone(&url, &root.join("a"))
2191
        .unwrap()
2192
        .with_home(root.join("home-a"));
2193
    let (ada, _) = a
2194
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2195
        .unwrap();
2196
    write(&root.join("a"), "a.txt", b"a\n");
2197
    a.commit("a", &[]).unwrap();
2198
    a.policy_init().unwrap();
2199
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2200
    let hub_sk = SecretKey::generate();
2201
    let hub = hub_sk.identity("hub", "[email protected]", 1);
2202
    a.policy_grant_subject(
2203
        "agent:claude@ada",
2204
        hub.clone(),
2205
        Scope::CHANGES | Scope::REFS,
2206
        None,
2207
    )
2208
    .unwrap();
2209
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2210
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
2211
    let ada_id = a.identity(&ada).unwrap();
2212
2213
    let now = Hlc::now().wall_ms;
2214
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
2215
        SignedGrant::sign(
2216
            Grant {
2217
                grantor: by.hash(),
2218
                subject: "agent:claude@ada".into(),
2219
                issuer: hub.hash(),
2220
                scope: Scope::CHANGES | Scope::SEAL,
2221
                not_before: from,
2222
                expires: to,
2223
            },
2224
            by,
2225
            sk,
2226
        )
2227
    };
2228
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
2229
    // certified (with `g` inside) the signer.
2230
    let agent = |name: &str, g: Option<SignedGrant>| {
2231
        let mut r = Repo::clone(&url, &root.join(name))
2232
            .unwrap()
2233
            .with_home(root.join(format!("home-{name}")));
2234
        let (key, id) = r
2235
            .create_identity(name, "[email protected]", IdentityScope::User)
2236
            .unwrap();
2237
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
2238
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
2239
        let cert = SignedCertificate::sign(
2240
            Certificate {
2241
                key: id,
2242
                issuer: hub.hash(),
2243
                subject: "agent:claude@ada".into(),
2244
                claims: vec![],
2245
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
2246
                not_before: now - 60_000,
2247
                expires: now + 600_000,
2248
                grant: g,
2249
            },
2250
            &hub,
2251
            &hub_sk,
2252
        );
2253
        r.store().put_identity(&hub).unwrap();
2254
        r.store().put_certificate(&cert).unwrap();
2255
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
2256
        let h = r.commit("work", &[]).unwrap();
2257
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
2258
        (r, key, h)
2259
    };
2260
2261
    let (claude, key, h) = agent(
2262
        "claude",
2263
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
2264
    );
2265
    let r = claude.push("origin", false).unwrap();
2266
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2267
    let host = Repo::open(&root.join("origin")).unwrap();
68dcf21f Andy McCall ↶ 2268
    assert!(
2269
        matches!(
2270
            host.authenticate_change(&h).unwrap(),
2271
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
2272
        ),
2273
        "named by its certificate's subject"
2274
    );
a2387d54 Andy McCall ↶ 2275
    a.pull("origin").unwrap();
2276
    assert!(matches!(
2277
        a.authenticate_change(&h).unwrap(),
2278
        SignatureStatus::Valid { key: k, .. } if k == key
2279
    ));
2280
2281
    let (none, _, _) = agent("none", None);
2282
    let r = none.push("origin", false).unwrap();
2283
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
2284
    let mallory_sk = SecretKey::generate();
2285
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
2286
    let (stranger, _, _) = agent(
2287
        "stranger",
2288
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
2289
    );
2290
    let r = stranger.push("origin", false).unwrap();
2291
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
2292
    let (ended, _, eh) = agent(
2293
        "ended",
2294
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
2295
    );
2296
    let r = ended.push("origin", false).unwrap();
2297
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
2298
    assert!(matches!(
2299
        ended.authenticate_change(&eh).unwrap(),
2300
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
2301
    ));
2302
}
2303
2304
#[test]
83e0677b Andy McCall ↶ 2305
fn trust_policy_governs_pushes_and_fetches() {
2306
    hermetic();
2307
    let dir = tempfile::tempdir().unwrap();
2308
    let root = dir.path();
2309
    let origin = Repo::init(&root.join("origin")).unwrap();
2310
    let url = root.join("origin").to_string_lossy().to_string();
2311
2312
    // A is the root. Before the policy, an unsigned push from B is fine.
75167672 Andy McCall 2313
    let mut a = Repo::clone(&url, &root.join("a"))
2314
        .unwrap()
2315
        .with_home(root.join("home-a"));
2316
    let (key_a, _) = a
2317
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2318
        .unwrap();
2319
    let mut b = Repo::clone(&url, &root.join("b"))
2320
        .unwrap()
2321
        .with_home(root.join("home-b"));
83e0677b Andy McCall ↶ 2322
    write(&root.join("b"), "b.txt", b"b\n");
2323
    b.commit("unsigned before policy", &[]).unwrap();
2324
    assert!(b.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 2325
    origin.refresh().unwrap();
83e0677b Andy McCall ↶ 2326
2327
    // A creates the policy and pushes it; origin now enforces it.
2328
    write(&root.join("a"), "a.txt", b"a\n");
2329
    a.commit("a", &[]).unwrap();
2330
    let sp = a.policy_init().unwrap();
2331
    assert_eq!(sp.policy.serial, 1);
2332
    a.pull("origin").unwrap();
2333
    let results = a.push("origin", false).unwrap();
767ac6cd Andy McCall 2334
    origin.refresh().unwrap();
83e0677b Andy McCall ↶ 2335
    assert!(results.iter().all(|r| r.ok), "{results:?}");
2336
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
2337
2338
    // B pulls the policy. Without an identity B cannot push at all.
2339
    b.pull("origin").unwrap();
75167672 Andy McCall 2340
    assert!(
2341
        b.current_policy().unwrap().is_some(),
2342
        "the policy arrived with the fetch"
2343
    );
83e0677b Andy McCall ↶ 2344
    assert!(b.push("origin", false).is_err());
2345
    // With an identity the policy does not list, the push is rejected by origin.
75167672 Andy McCall 2346
    let (key_b, id_b) = b
2347
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2348
        .unwrap();
83e0677b Andy McCall ↶ 2349
    write(&root.join("b"), "b.txt", b"b2\n");
2350
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
2351
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
2352
    let r = b.push("origin", false).unwrap();
767ac6cd Andy McCall 2353
    origin.refresh().unwrap();
75167672 Andy McCall 2354
    assert!(
2355
        !r[0].ok && r[0].reason.contains("may not update"),
2356
        "{:?}",
2357
        r
2358
    );
83e0677b Andy McCall ↶ 2359
2360
    // A grants B (identity handed over as a file) and publishes the policy.
2361
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
2362
    assert_eq!(sp.policy.serial, 2);
2363
    let r = a.push("origin", false).unwrap();
767ac6cd Andy McCall 2364
    origin.refresh().unwrap();
83e0677b Andy McCall ↶ 2365
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2366
    // B must fetch the new policy before pushing.
75167672 Andy McCall 2367
    assert!(b
2368
        .push("origin", false)
2369
        .unwrap_or_else(|e| vec![RefResult {
2370
            name: "main".into(),
2371
            ok: false,
2372
            reason: e.to_string()
2373
        }])
2374
        .iter()
2375
        .all(|x| !x.ok));
83e0677b Andy McCall ↶ 2376
    b.pull("origin").unwrap();
2377
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
2378
    let r = b.push("origin", false).unwrap();
767ac6cd Andy McCall 2379
    origin.refresh().unwrap();
83e0677b Andy McCall ↶ 2380
    assert!(r[0].ok, "{:?}", r);
2381
    // Origin verified B's change under the policy.
2382
    let heads = origin.bookmark_heads().unwrap();
2383
    for h in &heads {
2384
        let c = origin.store().get_change(h).unwrap();
2385
        if c.author == key_b {
75167672 Andy McCall 2386
            origin
2387
                .change_allowed(
2388
                    h,
2389
                    &origin.current_policy().unwrap().unwrap().1.policy,
2390
                    "main",
2391
                )
2392
                .unwrap();
83e0677b Andy McCall ↶ 2393
        }
2394
    }
2395
2396
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
2397
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
2398
    forged.serial = 3;
2399
    forged.roots = vec![key_b];
2400
    let fh = forged.hash();
2401
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 2402
    let forged = SignedPolicy {
2403
        policy: forged,
2404
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
2405
    };
2406
    let r = origin
2407
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
2408
        .unwrap();
83e0677b Andy McCall ↶ 2409
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
2410
    let stale = a.current_policy().unwrap().unwrap().1;
2411
    let mut old = stale.clone();
2412
    old.policy.serial = 1;
75167672 Andy McCall 2413
    let r = origin
2414
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
2415
        .unwrap();
83e0677b Andy McCall ↶ 2416
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
2417
2418
    // A revokes B; after B pulls the policy, B's pushes are refused again.
2419
    a.pull("origin").unwrap();
2420
    a.policy_revoke(&key_b).unwrap();
2421
    let r = a.push("origin", false).unwrap();
767ac6cd Andy McCall 2422
    origin.refresh().unwrap();
83e0677b Andy McCall ↶ 2423
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2424
    b.pull("origin").unwrap();
2425
    write(&root.join("b"), "b.txt", b"b3\n");
2426
    b.commit("b3", &[]).unwrap();
2427
    let r = b.push("origin", false).unwrap();
767ac6cd Andy McCall 2428
    origin.refresh().unwrap();
83e0677b Andy McCall ↶ 2429
    assert!(!r[0].ok, "{:?}", r);
2430
2431
    // A clone by a third party receives and verifies everything.
75167672 Andy McCall 2432
    let c = Repo::clone(&url, &root.join("c"))
2433
        .unwrap()
2434
        .with_home(root.join("home-c"));
83e0677b Andy McCall ↶ 2435
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
75167672 Andy McCall 2436
    assert!(c
2437
        .current_policy()
2438
        .unwrap()
2439
        .unwrap()
2440
        .1
2441
        .policy
2442
        .roots
2443
        .contains(&key_a));
83e0677b Andy McCall ↶ 2444
    assert!(!c.snapshot("status").unwrap().changed);
2445
}
d02e545d Andy McCall ↶ 2446
9ae4d15a Andy McCall ↶ 2447
/// oxygen#66: a gc says what it is doing, phase by phase.
d02e545d Andy McCall ↶ 2448
#[test]
9ae4d15a Andy McCall ↶ 2449
fn gc_reports_its_phases() {
2450
    hermetic();
2451
    let dir = tempfile::tempdir().unwrap();
2452
    let repo = Repo::init(dir.path()).unwrap();
2453
    for i in 0..3 {
2454
        write(
2455
            dir.path(),
2456
            &format!("f{i}.txt"),
2457
            format!("{i}\n").as_bytes(),
2458
        );
2459
        repo.commit(&format!("c{i}"), &[]).unwrap();
2460
    }
2461
    let mut phases = Vec::new();
2462
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
2463
        .unwrap();
2464
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
2465
    assert!(
2466
        phases.iter().any(|p| p.starts_with("pruning")),
2467
        "{phases:?}"
2468
    );
2469
    assert!(
2470
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
2471
        "{phases:?}"
2472
    );
2473
    assert!(
2474
        phases
2475
            .iter()
2476
            .any(|p| p.starts_with("writing the index of ")),
2477
        "{phases:?}"
2478
    );
2479
}
2480
2481
#[test]
d02e545d Andy McCall ↶ 2482
fn gc_packs_objects_and_history_still_works() {
2483
    hermetic();
2484
    let dir = tempfile::tempdir().unwrap();
2485
    let root = dir.path();
2486
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2487
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2488
        .unwrap();
d02e545d Andy McCall ↶ 2489
    repo.set_user_config("core.sign", "change").unwrap();
2490
    write(root, "a.txt", b"one\n");
2491
    let h1 = repo.commit("one", &[]).unwrap();
2492
    write(root, "a.txt", b"two\n");
2493
    write(root, "big.bin", &vec![0u8; 100_000]);
2494
    let h2 = repo.commit("two", &[]).unwrap();
ba160f60 Andy McCall ↶ 2495
    // Several snapshots leave superseded working-copy versions behind.
2496
    for i in 0..5 {
2497
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
2498
        repo.snapshot("status").unwrap();
2499
    }
2500
    write(root, "a.txt", b"two\n");
2501
    repo.snapshot("status").unwrap();
d02e545d Andy McCall ↶ 2502
    let before = repo.store().list().unwrap();
2503
    assert!(repo.store().loose_count().unwrap() > 0);
ba160f60 Andy McCall ↶ 2504
2505
    // With the default retention every operation's view is a root: nothing prunes.
2506
    let r = repo.gc(true).unwrap();
2507
    assert_eq!(r.packed.objects, before.len());
2508
    assert_eq!(r.pruned.objects, 0);
d02e545d Andy McCall ↶ 2509
    assert_eq!(repo.store().loose_count().unwrap(), 0);
2510
    assert_eq!(repo.store().list().unwrap(), before);
ba160f60 Andy McCall ↶ 2511
2512
    // With zero retention only the current view is a root: superseded
2513
    // working copies go, everything reachable stays.
2514
    repo.config.set("core.op-retention", "0").unwrap();
2515
    repo.save_config().unwrap();
21b2aec2 Andy McCall ↶ 2516
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
ba160f60 Andy McCall ↶ 2517
    let r = repo.gc(true).unwrap();
2518
    assert!(r.pruned.objects >= 5, "{r:?}");
2519
    let after = repo.store().list().unwrap();
2520
    assert!(after.len() < before.len());
2521
    assert!(after.contains(&h1) && after.contains(&h2));
2522
    for (_, op) in repo.op_log().unwrap() {
2523
        assert!(!op.command.is_empty(), "operation objects are all kept");
2524
    }
2525
    // Everything still works from the pruned, packed store.
d02e545d Andy McCall ↶ 2526
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
75167672 Andy McCall 2527
    assert!(matches!(
2528
        repo.verify_change(&h2).unwrap(),
2529
        SignatureStatus::Valid { .. }
2530
    ));
d02e545d Andy McCall ↶ 2531
    assert_eq!(repo.log().unwrap().len(), 3);
2532
    repo.checkout(&[h1], false, "checkout").unwrap();
2533
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
2534
    repo.checkout(&[h2], false, "checkout").unwrap();
2535
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
2536
    assert!(!repo.snapshot("status").unwrap().changed);
ba160f60 Andy McCall ↶ 2537
    // Grace period defers pruning of young garbage.
d02e545d Andy McCall ↶ 2538
    write(root, "a.txt", b"three\n");
2539
    repo.commit("three", &[]).unwrap();
ba160f60 Andy McCall ↶ 2540
    let r = repo.gc(false).unwrap();
2541
    assert_eq!(r.pruned.objects, 0);
2542
    assert!(r.pruned.deferred > 0);
2543
    let r = repo.gc(true).unwrap();
2544
    assert!(r.pruned.objects > 0);
2545
    assert_eq!(repo.log().unwrap().len(), 4);
21b2aec2 Andy McCall ↶ 2546
    // Restoring the default retention makes the old views roots again; the
2547
    // working copies they name were pruned, which gc tolerates.
2548
    repo.config.set("core.op-retention", "90").unwrap();
2549
    repo.save_config().unwrap();
2550
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2551
    let r = repo.gc(false).unwrap();
2552
    assert_eq!(r.pruned.objects, 0);
2553
    assert_eq!(repo.log().unwrap().len(), 4);
d02e545d Andy McCall ↶ 2554
}
614541c3 Andy McCall ↶ 2555
2556
#[test]
2557
fn describe_amend_abandon_heads() {
2558
    hermetic();
2559
    let dir = tempfile::tempdir().unwrap();
2560
    let root = dir.path();
2561
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 2562
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2563
        .unwrap();
614541c3 Andy McCall ↶ 2564
    repo.set_user_config("core.sign", "change").unwrap();
2565
    write(root, "a.txt", b"one\n");
2566
    let h1 = repo.commit("first", &[]).unwrap();
2567
    write(root, "a.txt", b"one\ntwo\n");
2568
    let h2 = repo.commit("secnod", &[]).unwrap();
2569
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
2570
2571
    // describe: same ChangeId, new hash, bookmark and working copy follow.
2572
    let h2b = repo.describe(&h2, "second").unwrap();
2573
    assert_ne!(h2b, h2);
2574
    let c = repo.store().get_change(&h2b).unwrap();
75167672 Andy McCall 2575
    assert_eq!(
2576
        (c.change_id, c.message.as_str(), c.deps.clone()),
2577
        (id2, "second", vec![h1])
2578
    );
614541c3 Andy McCall ↶ 2579
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
75167672 Andy McCall 2580
    assert!(matches!(
2581
        repo.verify_change(&h2b).unwrap(),
2582
        SignatureStatus::Valid { .. }
2583
    ));
614541c3 Andy McCall ↶ 2584
    let s = repo.snapshot("status").unwrap();
2585
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
75167672 Andy McCall 2586
    assert_eq!(
2587
        repo.resolve_change(&id2.short(8)).unwrap(),
2588
        h2b,
2589
        "the old object is no longer reachable from the log"
2590
    );
c07e0e7d Andy McCall ↶ 2591
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
2592
    let h1b = repo.describe(&h1, "first, described").unwrap();
2593
    assert_ne!(h1b, h1);
2594
    let heads = repo.bookmark_heads().unwrap();
2595
    assert_eq!(heads.len(), 1);
2596
    let top = repo.store().get_change(&heads[0]).unwrap();
2597
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
75167672 Andy McCall 2598
    assert!(
2599
        matches!(
2600
            repo.verify_change(&heads[0]).unwrap(),
2601
            SignatureStatus::Valid { .. }
2602
        ),
2603
        "rewritten own change is re-signed"
2604
    );
c07e0e7d Andy McCall ↶ 2605
    let (_, wc) = repo.working_copy().unwrap();
75167672 Andy McCall 2606
    assert_eq!(
2607
        wc.deps,
2608
        vec![heads[0]],
2609
        "the working copy follows the rewrite"
2610
    );
c07e0e7d Andy McCall ↶ 2611
    assert!(!repo.snapshot("status").unwrap().changed);
2612
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 2613
    assert!(
2614
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
2615
    );
614541c3 Andy McCall ↶ 2616
2617
    // amend: fold an edit into the head; the result is one change from h1.
2618
    write(root, "a.txt", b"one\ntwo\nthree\n");
2619
    write(root, "b.txt", b"b\n");
2620
    let h2c = repo.amend(None).unwrap();
2621
    let c = repo.store().get_change(&h2c).unwrap();
2622
    assert_eq!(c.change_id, id2);
2623
    assert_eq!(c.message, "second");
2624
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
75167672 Andy McCall 2625
    assert_eq!(
2626
        repo.log().unwrap().len(),
2627
        3,
2628
        "working copy, amended head, first"
2629
    );
614541c3 Andy McCall ↶ 2630
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
75167672 Andy McCall 2631
    assert!(
2632
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
2633
    );
614541c3 Andy McCall ↶ 2634
    assert!(snap.files.contains_key("b.txt"));
2635
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 2636
    assert!(
2637
        repo.amend(None).is_err(),
2638
        "clean working copy and no message"
2639
    );
614541c3 Andy McCall ↶ 2640
    let h2d = repo.amend(Some("second, amended")).unwrap();
75167672 Andy McCall 2641
    assert_eq!(
2642
        repo.store().get_change(&h2d).unwrap().message,
2643
        "second, amended"
2644
    );
614541c3 Andy McCall ↶ 2645
2646
    // abandon: the head goes, its content stays as uncommitted work.
2647
    repo.abandon(&h2d).unwrap();
75167672 Andy McCall 2648
    assert_eq!(
2649
        repo.bookmark_heads().unwrap(),
2650
        vec![h1b],
2651
        "the described first change is the head again"
2652
    );
614541c3 Andy McCall ↶ 2653
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 2654
    let paths: Vec<_> = s
2655
        .statuses
2656
        .iter()
2657
        .map(|p| (p.path.as_str(), p.status))
2658
        .collect();
2659
    assert_eq!(
2660
        paths,
2661
        vec![
2662
            ("a.txt", ChangeStatus::Modified),
2663
            ("b.txt", ChangeStatus::Added)
2664
        ]
2665
    );
614541c3 Andy McCall ↶ 2666
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
2667
    let h3 = repo.commit("recommitted", &[]).unwrap();
2668
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
2669
    // undo brings the abandoned head back.
2670
    repo.undo().unwrap();
2671
    repo.undo().unwrap();
2672
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
c07e0e7d Andy McCall ↶ 2673
6706bdcf Andy McCall ↶ 2674
    // Abandoning a non-head whose dependent references its atoms reifies
2675
    // the references (here: a.txt vanishes with it, so the dependent's edit
2676
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
c07e0e7d Andy McCall ↶ 2677
    let base = repo.bookmark_heads().unwrap()[0];
2678
    let base_change = repo.store().get_change(&base).unwrap();
2679
    let h1_now = base_change.deps[0];
6706bdcf Andy McCall ↶ 2680
    let notes = repo.abandon(&h1_now).unwrap();
75167672 Andy McCall 2681
    assert!(
2682
        !notes.is_empty(),
2683
        "the dependent's edit of a.txt was reified"
2684
    );
6706bdcf Andy McCall ↶ 2685
    let heads = repo.bookmark_heads().unwrap();
2686
    let after = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 2687
    assert!(
2688
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
2689
        "{:?}",
2690
        after.files.keys()
2691
    );
6706bdcf Andy McCall ↶ 2692
    repo.undo().unwrap();
2693
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
c07e0e7d Andy McCall ↶ 2694
    write(root, "c.txt", b"c\n");
2695
    let hc = repo.commit("c", &[]).unwrap();
2696
    write(root, "d.txt", b"d\n");
2697
    let hd = repo.commit("d", &[hc]).unwrap();
2698
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
2699
    repo.abandon(&hc).unwrap();
2700
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2701
    assert!(!heads.contains(&hc));
75167672 Andy McCall 2702
    let d_now = heads
2703
        .iter()
2704
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
2705
        .copied()
2706
        .unwrap();
2707
    assert!(
2708
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
2709
        "d inherited c's (empty) dependencies"
2710
    );
c07e0e7d Andy McCall ↶ 2711
    let s = repo.snapshot("status").unwrap();
75167672 Andy McCall 2712
    assert_eq!(
2713
        s.statuses
2714
            .iter()
2715
            .map(|p| p.path.as_str())
2716
            .collect::<Vec<_>>(),
2717
        vec!["c.txt"],
2718
        "c's content is now uncommitted work"
2719
    );
614541c3 Andy McCall ↶ 2720
}
79ab8528 Andy McCall ↶ 2721
2722
#[test]
2723
fn git_export_mirrors_history() {
2724
    hermetic();
75167672 Andy McCall 2725
    if std::process::Command::new("git")
2726
        .arg("--version")
2727
        .output()
2728
        .is_err()
2729
    {
79ab8528 Andy McCall ↶ 2730
        eprintln!("git not installed; skipping");
2731
        return;
2732
    }
2733
    let dir = tempfile::tempdir().unwrap();
2734
    let root = dir.path();
75167672 Andy McCall 2735
    let mut repo = Repo::init(&root.join("r"))
2736
        .unwrap()
2737
        .with_home(root.join("home"));
2738
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
2739
        .unwrap();
79ab8528 Andy McCall ↶ 2740
    let r = root.join("r");
2741
    write(&r, "README.md", b"hello\n");
2742
    write(&r, "src/main.rs", b"fn main() {}\n");
2743
    let h1 = repo.commit("first", &[]).unwrap();
2744
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
2745
    write(&r, "logo.png", b"\x89PNG\0\0");
2746
    let h2 = repo.commit("second", &[]).unwrap();
2747
2748
    let git_dir = root.join("mirror.git");
2749
    let rep = repo.git_export(&git_dir).unwrap();
2750
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
2751
    let git = |args: &[&str]| -> String {
75167672 Andy McCall 2752
        let out = std::process::Command::new("git")
2753
            .arg("-C")
2754
            .arg(&git_dir)
2755
            .args(args)
2756
            .output()
2757
            .unwrap();
2758
        assert!(
2759
            out.status.success(),
2760
            "{}",
2761
            String::from_utf8_lossy(&out.stderr)
2762
        );
79ab8528 Andy McCall ↶ 2763
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2764
    };
2765
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
2766
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2767
    assert_eq!(git(&["show", "main:README.md"]), "hello");
2768
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 2769
    assert!(
2770
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
2771
        "{body}"
2772
    );
79ab8528 Andy McCall ↶ 2773
    assert!(body.contains("Change-Id: "), "{body}");
75167672 Andy McCall 2774
    assert_eq!(
2775
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
2776
        "Ada Lovelace <[email protected]>"
2777
    );
2778
    assert_eq!(
2779
        git(&["ls-tree", "--name-only", "main"]),
2780
        "README.md\nlogo.png\nsrc"
2781
    );
79ab8528 Andy McCall ↶ 2782
2783
    // Re-export is incremental.
2784
    let rep = repo.git_export(&git_dir).unwrap();
2785
    assert_eq!((rep.exported, rep.skipped), (0, 2));
2786
2787
    // An independent change makes two heads; the next state is one more
2788
    // commit on the linear branch whose tree is the union.
2789
    repo.checkout(&[h1], false, "checkout").unwrap();
2790
    write(&r, "other.txt", b"o\n");
2791
    let h3 = repo.commit("third", &[]).unwrap();
2792
    let rep = repo.git_export(&git_dir).unwrap();
2793
    assert_eq!((rep.exported, rep.heads), (1, 2));
2794
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
2795
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
2796
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
2797
    assert_eq!(git(&["show", "main:other.txt"]), "o");
2798
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
75167672 Andy McCall 2799
    assert_eq!(
2800
        git(&["ls-tree", "--name-only", "main"]),
2801
        "README.md\nlogo.png\nother.txt\nsrc"
2802
    );
79ab8528 Andy McCall ↶ 2803
    let body = git(&["log", "-1", "--format=%B", "main"]);
75167672 Andy McCall 2804
    assert!(
2805
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
2806
        "{body}"
2807
    );
79ab8528 Andy McCall ↶ 2808
    // A rewrite is a new state whose one new change is the rewritten one.
2809
    repo.describe(&h3, "third, described").unwrap();
2810
    let rep = repo.git_export(&git_dir).unwrap();
2811
    assert_eq!(rep.exported, 1);
75167672 Andy McCall 2812
    assert_eq!(
2813
        git(&["log", "-1", "--format=%s", "main"]),
2814
        "third, described"
2815
    );
79ab8528 Andy McCall ↶ 2816
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
2817
    let _ = h2;
2818
}
c3069537 Andy McCall ↶ 2819
2820
#[test]
2821
fn git_import_reproduces_trees() {
c3d2ef61 Andy McCall ↶ 2822
    git_import_reproduces_trees_with(None);
2823
}
2824
2825
/// The same import with every merge rendered in batches of one file
2826
/// (oxygen#25): what a merge onto a base of thousands of files takes.
2827
#[test]
2828
fn git_import_reproduces_trees_in_batches() {
2829
    git_import_reproduces_trees_with(Some(1));
2830
}
2831
2832
fn git_import_reproduces_trees_with(batch: Option<usize>) {
2833
    crate::repo::git::set_merge_batch_for_tests(batch);
c3069537 Andy McCall ↶ 2834
    hermetic();
75167672 Andy McCall 2835
    if std::process::Command::new("git")
2836
        .arg("--version")
2837
        .output()
2838
        .is_err()
2839
    {
c3069537 Andy McCall ↶ 2840
        eprintln!("git not installed; skipping");
2841
        return;
2842
    }
2843
    let dir = tempfile::tempdir().unwrap();
2844
    let root = dir.path();
2845
    let g = root.join("src.git");
2846
    fs::create_dir_all(&g).unwrap();
2847
    let git = |args: &[&str]| -> String {
2848
        let out = std::process::Command::new("git")
2849
            .arg("-C")
2850
            .arg(&g)
75167672 Andy McCall 2851
            .args([
2852
                "-c",
2853
                "user.name=Grace",
2854
                "-c",
2855
                "[email protected]",
2856
                "-c",
2857
                "commit.gpgsign=false",
2858
            ])
c3069537 Andy McCall ↶ 2859
            .args(args)
2860
            .output()
2861
            .unwrap();
75167672 Andy McCall 2862
        assert!(
2863
            out.status.success(),
2864
            "git {args:?}: {}",
2865
            String::from_utf8_lossy(&out.stderr)
2866
        );
c3069537 Andy McCall ↶ 2867
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2868
    };
2869
    git(&["init", "-q", "-b", "main"]);
2870
    write(&g, "README.md", b"# Hi\n");
2871
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
2872
    git(&["add", "."]);
2873
    git(&["commit", "-q", "-m", "initial"]);
2874
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2875
    write(&g, "run.sh", b"#!/bin/sh\n");
2876
    #[cfg(unix)]
2877
    {
2878
        use std::os::unix::fs::PermissionsExt;
2879
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
2880
    }
2881
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
2882
    git(&["add", "."]);
75167672 Andy McCall 2883
    git(&[
2884
        "commit",
2885
        "-q",
2886
        "-m",
2887
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
2888
    ]);
c3069537 Andy McCall ↶ 2889
    // A branch that edits README, merged back with a conflict-free merge.
2890
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
2891
    write(&g, "README.md", b"# Hi\n\nMore.\n");
2892
    git(&["commit", "-q", "-am", "readme"]);
2893
    git(&["checkout", "-q", "main"]);
2894
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
2895
    // A branch from the initial commit inserting at the same place as
2896
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
2897
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
2898
    git(&["checkout", "-q", "-b", "clash", &initial]);
2899
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
2900
    git(&["commit", "-q", "-am", "clash"]);
2901
    git(&["checkout", "-q", "main"]);
7df9007b Andy McCall ↶ 2902
    // Expected to stop at the conflict, so its status is ignored; the
2903
    // identity is passed as for every other git call here, or a machine
2904
    // without one refuses to start the merge at all.
75167672 Andy McCall 2905
    let _ = std::process::Command::new("git")
2906
        .arg("-C")
2907
        .arg(&g)
7df9007b Andy McCall ↶ 2908
        .args([
2909
            "-c",
2910
            "user.name=Grace",
2911
            "-c",
2912
            "[email protected]",
2913
            "merge",
2914
            "-q",
2915
            "clash",
2916
        ])
75167672 Andy McCall 2917
        .output();
7df9007b Andy McCall ↶ 2918
    assert!(
2919
        g.join(".git/MERGE_HEAD").exists(),
2920
        "the clash merge stopped at its conflict"
2921
    );
75167672 Andy McCall 2922
    write(
2923
        &g,
2924
        "src/lib.rs",
2925
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2926
    );
c3069537 Andy McCall ↶ 2927
    git(&["add", "."]);
2928
    git(&["commit", "-q", "-m", "resolve clash"]);
2929
    git(&["rm", "-q", "logo.png"]);
2930
    git(&["commit", "-q", "-m", "drop logo"]);
6e723b81 Andy McCall ↶ 2931
    // A rename with a small edit is imported as a move of the same node.
2932
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
75167672 Andy McCall 2933
    write(
2934
        &g,
2935
        "src/lib2.rs",
2936
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
2937
    );
6e723b81 Andy McCall ↶ 2938
    git(&["add", "."]);
2939
    git(&["commit", "-q", "-m", "rename lib"]);
958fb27d Andy McCall ↶ 2940
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
2941
    // run.sh is the same as in the first parent's tree, but the merged
2942
    // change touched it, so the importer must compare it, not skip it.
2943
    git(&["checkout", "-q", "-b", "discarded"]);
2944
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
2945
    git(&["commit", "-q", "-am", "discarded edit"]);
2946
    git(&["checkout", "-q", "main"]);
314db9b4 Andy McCall ↶ 2947
    git(&[
2948
        "merge",
2949
        "-q",
2950
        "-s",
2951
        "ours",
2952
        "-m",
2953
        "merge discarded, keeping ours",
2954
        "discarded",
2955
    ]);
c3069537 Andy McCall ↶ 2956
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
2957
2958
    let dest = root.join("oxy");
2959
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
2960
    let rep = repo.import_git(&g, "main").unwrap();
2961
    assert_eq!(rep.commits, expected_count);
958fb27d Andy McCall ↶ 2962
    assert_eq!(rep.merges, 3);
314db9b4 Andy McCall ↶ 2963
    assert_eq!(
2964
        fs::read(dest.join("run.sh")).unwrap(),
2965
        b"#!/bin/sh\n",
2966
        "the ours merge kept main's run.sh"
2967
    );
958fb27d Andy McCall ↶ 2968
    let v = repo.verify_git_import(&g, "main").unwrap();
2969
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
2970
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
c3069537 Andy McCall ↶ 2971
    // The working copy equals the Git tree at main.
75167672 Andy McCall 2972
    assert_eq!(
2973
        fs::read(dest.join("src/lib2.rs")).unwrap(),
2974
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2975
    );
6e723b81 Andy McCall ↶ 2976
    assert!(!dest.join("src/lib.rs").exists());
75167672 Andy McCall 2977
    assert_eq!(
2978
        fs::read(dest.join("README.md")).unwrap(),
2979
        b"# Hi\n\nMore.\n"
2980
    );
c3069537 Andy McCall ↶ 2981
    assert!(!dest.join("logo.png").exists());
2982
    #[cfg(unix)]
2983
    {
2984
        use std::os::unix::fs::PermissionsExt;
75167672 Andy McCall 2985
        assert!(
2986
            fs::metadata(dest.join("run.sh"))
2987
                .unwrap()
2988
                .permissions()
2989
                .mode()
2990
                & 0o111
2991
                != 0
2992
        );
c3069537 Andy McCall ↶ 2993
    }
75167672 Andy McCall 2994
    assert!(
2995
        !repo.snapshot("status").unwrap().changed,
2996
        "clean after import"
2997
    );
c3069537 Andy McCall ↶ 2998
    let heads = repo.bookmark_heads().unwrap();
2999
    let st = repo.load_state(&heads).unwrap();
3000
    assert!(!st.materialize().is_conflicted());
3001
    assert_eq!(st.len(), expected_count);
75167672 Andy McCall 3002
    let tip = repo
3003
        .log()
3004
        .unwrap()
3005
        .into_iter()
3006
        .find(|e| e.change.message.starts_with("rename lib"))
3007
        .unwrap();
6e723b81 Andy McCall ↶ 3008
    let c = repo.store().get_change(&tip.hash).unwrap();
75167672 Andy McCall 3009
    assert!(
3010
        c.tree_ops
3011
            .iter()
3012
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
3013
        "{:?}",
3014
        c.tree_ops
3015
    );
3016
    assert!(!c
3017
        .tree_ops
3018
        .iter()
3019
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
c3069537 Andy McCall ↶ 3020
    // Messages carry Git trailers; the Change-Id trailer was honoured.
3021
    let log = repo.log().unwrap();
75167672 Andy McCall 3022
    let second = log
3023
        .iter()
3024
        .find(|e| e.change.message.starts_with("second"))
3025
        .unwrap();
3026
    assert_eq!(
3027
        second.change.change_id,
3028
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
3029
    );
3030
    assert!(second
3031
        .change
3032
        .message
3033
        .contains("Git-Author: Grace <[email protected]>"));
3034
    let resolve = log
3035
        .iter()
3036
        .find(|e| e.change.message.starts_with("resolve clash"))
3037
        .unwrap();
3038
    assert_eq!(
3039
        resolve.change.kind,
3040
        ChangeKind::Resolution,
3041
        "a conflicting Git merge becomes a resolution"
3042
    );
c3069537 Andy McCall ↶ 3043
    // Re-importing into another fresh repository gives the same ChangeIds.
75167672 Andy McCall 3044
    let repo2 = Repo::init(&root.join("oxy2"))
3045
        .unwrap()
3046
        .with_home(root.join("home"));
c3069537 Andy McCall ↶ 3047
    repo2.import_git(&g, "main").unwrap();
dfb23a3a Andy McCall ↶ 3048
    // New nodes' identifiers derive from the commit (spec §23), so the
3049
    // re-import is not just the same ChangeIds but the same changes.
3050
    assert_eq!(
3051
        repo2.bookmark_heads().unwrap(),
3052
        repo.bookmark_heads().unwrap()
3053
    );
75167672 Andy McCall 3054
    let ids: BTreeSet<ChangeId> = repo
3055
        .log()
3056
        .unwrap()
3057
        .iter()
3058
        .filter(|e| !e.is_working_copy)
3059
        .map(|e| e.change.change_id)
3060
        .collect();
3061
    let ids2: BTreeSet<ChangeId> = repo2
3062
        .log()
3063
        .unwrap()
3064
        .iter()
3065
        .filter(|e| !e.is_working_copy)
3066
        .map(|e| e.change.change_id)
3067
        .collect();
c3069537 Andy McCall ↶ 3068
    assert_eq!(ids, ids2);
3069
    // Round trip back out to Git reproduces the tip tree.
3070
    let mirror = root.join("mirror.git");
3071
    repo.git_export(&mirror).unwrap();
75167672 Andy McCall 3072
    let out = std::process::Command::new("git")
3073
        .arg("-C")
3074
        .arg(&mirror)
3075
        .args(["show", "main:src/lib2.rs"])
3076
        .output()
3077
        .unwrap();
3078
    assert_eq!(
3079
        String::from_utf8_lossy(&out.stdout),
3080
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
3081
    );
3082
    let out = std::process::Command::new("git")
3083
        .arg("-C")
3084
        .arg(&mirror)
3085
        .args(["show", "main:src/lib.rs"])
3086
        .output()
3087
        .unwrap();
3088
    assert!(
3089
        !out.status.success(),
3090
        "the old path is gone from the export"
3091
    );
c3069537 Andy McCall ↶ 3092
}
252e8cb2 Andy McCall ↶ 3093
3094
#[test]
3095
fn checkpoints_accelerate_loading_and_stay_correct() {
3096
    hermetic();
3097
    let dir = tempfile::tempdir().unwrap();
3098
    let root = dir.path();
3099
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3100
    repo.config.set("core.checkpoint-interval", "5").unwrap();
3101
    repo.save_config().unwrap();
3102
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
3103
    let mut hashes = Vec::new();
3104
    for i in 0..12 {
75167672 Andy McCall 3105
        write(
3106
            root,
3107
            "a.txt",
3108
            format!(
3109
                "{}\n",
3110
                (0..=i)
3111
                    .map(|k| k.to_string())
3112
                    .collect::<Vec<_>>()
3113
                    .join("\n")
3114
            )
3115
            .as_bytes(),
3116
        );
252e8cb2 Andy McCall ↶ 3117
        write(root, &format!("f{i}.txt"), b"x\n");
3118
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
3119
    }
75167672 Andy McCall 3120
    let (_, cp) = repo
3121
        .latest_checkpoint("main")
3122
        .unwrap()
3123
        .expect("automatic checkpoint");
252e8cb2 Andy McCall ↶ 3124
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
3125
    // Loading through the checkpoint equals loading everything.
3126
    let heads = repo.bookmark_heads().unwrap();
3127
    let fast = repo.load_state(&heads).unwrap();
3128
    let full = repo.load_state_full(&heads).unwrap();
3129
    assert_eq!(fast.len(), full.len());
3130
    assert_eq!(fast.heads(), full.heads());
3131
    let (a, b) = (fast.materialize(), full.materialize());
75167672 Andy McCall 3132
    assert_eq!(
3133
        a.files.keys().collect::<Vec<_>>(),
3134
        b.files.keys().collect::<Vec<_>>()
3135
    );
252e8cb2 Andy McCall ↶ 3136
    for (p, f) in &a.files {
3137
        assert_eq!(f.content, b.files[p].content, "{p}");
3138
    }
3139
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
3140
    // A head set that does not contain the checkpoint's heads falls back.
75167672 Andy McCall 3141
    assert!(repo
3142
        .load_state_checkpointed(&[hashes[0]])
3143
        .unwrap()
3144
        .is_none());
252e8cb2 Andy McCall ↶ 3145
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
3146
    // Everything else keeps working on top of the checkpoint.
3147
    assert!(!repo.snapshot("status").unwrap().changed);
3148
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
3149
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
3150
    let (r, n, bytes) = repo.checkpoint().unwrap();
3151
    assert!(n >= 12 && bytes > 0);
3152
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
3153
    write(root, "a.txt", b"after\n");
3154
    let h_after = repo.commit("after", &[]).unwrap();
3155
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3156
    assert!(st.contains(&h_after));
75167672 Andy McCall 3157
    assert!(
3158
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
3159
    );
252e8cb2 Andy McCall ↶ 3160
    assert_eq!(repo.log().unwrap().len(), 14);
3161
    // Checkpoints survive gc.
3162
    repo.gc(true).unwrap();
3163
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
75167672 Andy McCall 3164
    assert!(repo
3165
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
3166
        .unwrap()
3167
        .is_some());
252e8cb2 Andy McCall ↶ 3168
}
135212de Andy McCall ↶ 3169
3170
#[test]
3171
fn quick_status_for_prompts() {
3172
    hermetic();
3173
    let dir = tempfile::tempdir().unwrap();
3174
    let root = dir.path();
3175
    let origin = Repo::init(&root.join("origin")).unwrap();
3176
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3177
    let a = Repo::clone(&url, &root.join("a"))
3178
        .unwrap()
3179
        .with_home(root.join("home"));
135212de Andy McCall ↶ 3180
    let ops_before = a.op_log().unwrap().len();
3181
    let info = a.quick_status().unwrap();
75167672 Andy McCall 3182
    assert_eq!(
3183
        (
3184
            info.bookmark.as_str(),
3185
            info.heads,
3186
            info.dirty,
3187
            info.conflicted,
3188
            info.ahead,
3189
            info.behind
3190
        ),
3191
        ("main", 0, false, false, Some(0), Some(0))
3192
    );
135212de Andy McCall ↶ 3193
    write(&root.join("a"), "f.txt", b"f\n");
3194
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
75167672 Andy McCall 3195
    assert_eq!(
3196
        a.op_log().unwrap().len(),
3197
        ops_before,
3198
        "quick_status records nothing"
3199
    );
135212de Andy McCall ↶ 3200
    // A snapshotted but uncommitted change is still dirty.
3201
    a.snapshot("status").unwrap();
3202
    assert!(a.quick_status().unwrap().dirty);
3203
    a.commit("f", &[]).unwrap();
3204
    let info = a.quick_status().unwrap();
3205
    assert!(!info.dirty, "clean right after a commit");
3206
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
75167672 Andy McCall 3207
    assert_eq!(
3208
        info.format("%b %c%d%x%A%D"),
3209
        format!("main {}+1", info.change_id)
3210
    );
135212de Andy McCall ↶ 3211
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
3212
    // Touching a file without changing it is not dirty; changing content of
3213
    // the same size is.
3214
    let p = root.join("a/f.txt");
3215
    let content = fs::read(&p).unwrap();
3216
    fs::write(&p, &content).unwrap();
3217
    assert!(!a.quick_status().unwrap().dirty);
3218
    fs::write(&p, b"g\n").unwrap();
3219
    assert!(a.quick_status().unwrap().dirty);
3220
    fs::write(&p, b"f\n").unwrap();
3221
    // Push, then a second clone commits and pushes: we are behind.
3222
    assert!(a.push("origin", false).unwrap()[0].ok);
3223
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
75167672 Andy McCall 3224
    let b = Repo::clone(&url, &root.join("b"))
3225
        .unwrap()
3226
        .with_home(root.join("home-b"));
135212de Andy McCall ↶ 3227
    write(&root.join("b"), "g.txt", b"g\n");
3228
    b.commit("g", &[]).unwrap();
3229
    b.push("origin", false).unwrap();
3230
    a.fetch("origin").unwrap();
3231
    let info = a.quick_status().unwrap();
3232
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
3233
    assert_eq!(info.format("%A%D"), "-1");
3234
    let _ = origin;
3235
}
b3c5a59a Andy McCall ↶ 3236
3237
#[test]
3238
fn lazy_blobs_are_fetched_on_first_read() {
3239
    hermetic();
3240
    let dir = tempfile::tempdir().unwrap();
3241
    let root = dir.path();
3242
    let origin_dir = root.join("origin");
75167672 Andy McCall 3243
    let origin = Repo::init(&origin_dir)
3244
        .unwrap()
3245
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 3246
    let url = origin_dir.to_string_lossy().to_string();
3247
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
3248
    write(&origin_dir, "big.bin", &big);
3249
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
3250
    write(&origin_dir, "t.txt", b"t\n");
3251
    let h = origin.commit("blobs", &[]).unwrap();
3252
    let big_ref = Repo::blob_ref(&big);
3253
3254
    // Fetch only (no checkout) with a filter: the big blob stays absent.
75167672 Andy McCall 3255
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
3256
        .unwrap()
3257
        .with_home(root.join("home"));
b3c5a59a Andy McCall ↶ 3258
    let a = {
3259
        let mut a = a;
3260
        a.config.set("remote.origin.url", &url).unwrap();
3261
        a.config.set("filter.max-blob", "100K").unwrap();
3262
        a.save_config().unwrap();
3263
        a
3264
    };
3265
    assert_eq!(a.config.max_blob, Some(100 * 1024));
3266
    a.fetch("origin").unwrap();
3267
    assert!(a.store().has(&h));
3268
    assert!(!a.store().has(&big_ref), "withheld");
75167672 Andy McCall 3269
    assert!(
3270
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
3271
        "small blob came along"
3272
    );
b3c5a59a Andy McCall ↶ 3273
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
3274
3275
    // status and commit do not need it: adopt the state, edit a text file, commit.
3276
    let (op_ref, op) = a.head_op().unwrap();
3277
    let mut view = op.view.clone();
75167672 Andy McCall 3278
    view.bookmarks.insert(
3279
        "main".into(),
3280
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
3281
    );
b3c5a59a Andy McCall ↶ 3282
    a.record_op(&[op_ref], "adopt", view).unwrap();
3283
    // Checkout reads the blob lazily, which fetches it.
3284
    a.checkout(&[h], true, "checkout").unwrap();
3285
    assert!(a.store().has(&big_ref), "fetched on first read");
3286
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
3287
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
3288
    write(&root.join("a"), "t.txt", b"t2\n");
3289
    a.commit("text edit", &[]).unwrap();
3290
3291
    // clone --max-blob records the filter; the checkout fetches lazily.
7421309f Andy McCall ↶ 3292
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
b3c5a59a Andy McCall ↶ 3293
    assert_eq!(b.config.max_blob, Some(1024));
3294
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
3295
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
3296
    assert!(parse_size("lots").is_err());
3297
}
7421309f Andy McCall ↶ 3298
3299
#[test]
3300
fn sparse_checkout_materializes_only_chosen_paths() {
3301
    hermetic();
3302
    let dir = tempfile::tempdir().unwrap();
3303
    let root = dir.path();
3304
    let origin_dir = root.join("origin");
75167672 Andy McCall 3305
    let origin = Repo::init(&origin_dir)
3306
        .unwrap()
3307
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 3308
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
3309
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
3310
    write(&origin_dir, "docs/guide.md", b"# guide\n");
3311
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
3312
    write(&origin_dir, "docs/logo.png", &logo);
3313
    write(&origin_dir, "README.md", b"# top\n");
3314
    let h1 = origin.commit("tree", &[]).unwrap();
3315
    let url = origin_dir.to_string_lossy().to_string();
3316
75167672 Andy McCall 3317
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
3318
        .unwrap()
3319
        .with_home(root.join("home"));
7421309f Andy McCall ↶ 3320
    assert_eq!(a.config.sparse_paths, vec!["src"]);
3321
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
3322
    assert!(root.join("a/src/main.rs").exists());
3323
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
75167672 Andy McCall 3324
    assert!(
3325
        !a.store().has(&Repo::blob_ref(&logo)),
3326
        "out-of-scope blob never fetched"
3327
    );
3328
    assert!(
3329
        !a.snapshot("status").unwrap().changed,
3330
        "out-of-scope files are not removals"
3331
    );
05e71ed6 Andy McCall ↶ 3332
    assert!(!a.quick_status().unwrap().dirty);
7421309f Andy McCall ↶ 3333
3334
    // Edits in scope commit normally and keep the rest of the tree intact.
75167672 Andy McCall 3335
    write(
3336
        &root.join("a"),
3337
        "src/lib.rs",
3338
        b"pub fn a() {}\npub fn b() {}\n",
3339
    );
7421309f Andy McCall ↶ 3340
    let h2 = a.commit("edit lib", &[]).unwrap();
3341
    let st = a.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 3342
    assert!(
3343
        st.files.contains_key("docs/guide.md"),
3344
        "the state still has everything"
3345
    );
7421309f Andy McCall ↶ 3346
    assert!(a.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 3347
    origin.refresh().unwrap();
7421309f Andy McCall ↶ 3348
    // Files created outside the scope are ignored by status.
3349
    write(&root.join("a"), "docs/new.md", b"ignored\n");
3350
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
3351
3352
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
3353
    let mut a = a;
3354
    a.config.set("filter.paths", "src,docs").unwrap();
3355
    a.save_config().unwrap();
75167672 Andy McCall 3356
    let r = a
3357
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
3358
        .unwrap();
7421309f Andy McCall ↶ 3359
    assert!(r.written >= 2);
75167672 Andy McCall 3360
    assert_eq!(
3361
        fs::read(root.join("a/docs/logo.png")).unwrap(),
3362
        logo,
3363
        "now fetched lazily"
3364
    );
7421309f Andy McCall ↶ 3365
    assert!(!root.join("a/README.md").exists());
3366
    // Origin sees the change made under a sparse checkout with the full tree intact.
3367
    origin.pull("origin").err();
75167672 Andy McCall 3368
    let full = origin
3369
        .load_state(&origin.bookmark_heads().unwrap())
3370
        .unwrap()
3371
        .materialize();
3372
    assert!(
3373
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
3374
    );
7421309f Andy McCall ↶ 3375
    assert!(full.files.contains_key("README.md"));
3376
    let _ = h1;
3377
}
2863456a Andy McCall ↶ 3378
3379
#[test]
3380
fn shallow_clone_and_deepen() {
3381
    hermetic();
3382
    let dir = tempfile::tempdir().unwrap();
3383
    let root = dir.path();
3384
    let origin_dir = root.join("origin");
75167672 Andy McCall 3385
    let origin = Repo::init(&origin_dir)
3386
        .unwrap()
3387
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 3388
    let mut hashes = Vec::new();
3389
    for i in 0..8 {
75167672 Andy McCall 3390
        write(
3391
            &origin_dir,
3392
            "a.txt",
3393
            format!(
3394
                "{}\n",
3395
                (0..=i)
3396
                    .map(|k| k.to_string())
3397
                    .collect::<Vec<_>>()
3398
                    .join("\n")
3399
            )
3400
            .as_bytes(),
3401
        );
2863456a Andy McCall ↶ 3402
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
3403
    }
3404
    let url = origin_dir.to_string_lossy().to_string();
75167672 Andy McCall 3405
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
3406
        .unwrap()
3407
        .with_home(root.join("home"));
2863456a Andy McCall ↶ 3408
    assert!(a.is_shallow());
75167672 Andy McCall 3409
    assert_eq!(
3410
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
3411
        "0\n1\n2\n3\n4\n5\n6\n7\n"
3412
    );
3413
    assert!(
3414
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
3415
        "three levels present"
3416
    );
2863456a Andy McCall ↶ 3417
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
3418
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
75167672 Andy McCall 3419
    assert_eq!(
3420
        a.log().unwrap().len(),
3421
        9,
3422
        "the log shows every change from the checkpoint's metadata"
3423
    );
2863456a Andy McCall ↶ 3424
    assert!(!a.snapshot("status").unwrap().changed);
3425
    assert_eq!(a.quick_status().unwrap().heads, 1);
3426
3427
    // Work continues on top of the shallow history and pushes back.
3428
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
3429
    let h_new = a.commit("c8", &[]).unwrap();
3430
    assert!(a.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 3431
    origin.refresh().unwrap();
2863456a Andy McCall ↶ 3432
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
3433
    // Fetching new work from origin into the shallow clone works too.
3434
    write(&origin_dir, "b.txt", b"b\n");
3435
    origin.pull("origin").err();
3436
    let (_, wc) = origin.working_copy().unwrap();
3437
    let _ = wc;
75167672 Andy McCall 3438
    origin
3439
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
3440
        .unwrap();
2863456a Andy McCall ↶ 3441
    write(&origin_dir, "b.txt", b"b\n");
3442
    let h_b = origin.commit("b", &[]).unwrap();
3443
    let pr = a.pull("origin").unwrap();
3444
    assert!(pr.changed);
3445
    assert!(a.store().has(&h_b));
3446
    assert!(root.join("a/b.txt").exists());
3447
3448
    // Deepening fetches older history until the boundary is gone.
3449
    // Every commit also depends on the change that created the file, so two
3450
    // levels below the boundary hold h4, h3, and the root.
3451
    assert!(a.deepen("origin", 2).unwrap() >= 2);
3452
    assert!(a.store().has(&hashes[3]));
3453
    assert!(a.is_shallow());
3454
    a.deepen("origin", 100).unwrap();
3455
    assert!(!a.is_shallow(), "boundary reached the root");
3456
    assert!(a.store().has(&hashes[0]));
75167672 Andy McCall 3457
    assert_eq!(
3458
        a.load_state_full(&a.bookmark_heads().unwrap())
3459
            .unwrap()
3460
            .len(),
3461
        10
3462
    );
2863456a Andy McCall ↶ 3463
}
132b884b Andy McCall ↶ 3464
3465
#[test]
3466
fn tags_are_immutable_named_states_and_travel() {
3467
    hermetic();
3468
    let dir = tempfile::tempdir().unwrap();
3469
    let root = dir.path();
3470
    let origin = Repo::init(&root.join("origin")).unwrap();
3471
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3472
    let mut a = Repo::clone(&url, &root.join("a"))
3473
        .unwrap()
3474
        .with_home(root.join("home-a"));
3475
    let (key_a, _) = a
3476
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3477
        .unwrap();
132b884b Andy McCall ↶ 3478
    write(&root.join("a"), "f.txt", b"1\n");
3479
    let h1 = a.commit("one", &[]).unwrap();
3480
    write(&root.join("a"), "f.txt", b"1\n2\n");
3481
    let h2 = a.commit("two", &[]).unwrap();
3482
3483
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
75167672 Andy McCall 3484
    assert_eq!(
3485
        (t.heads.clone(), t.signer.as_deref()),
3486
        (vec![h1], Some("Ada"))
3487
    );
132b884b Andy McCall ↶ 3488
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
3489
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
3490
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
3491
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
3492
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
3493
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
3494
    assert_eq!(sa.sigs[0].key, key_a);
ee130dd9 Andy McCall ↶ 3495
    // Without a policy every client is sent every tag, whatever features
3496
    // it declares (oxygen#131).
3497
    let mut refs = a.remote_refs().unwrap();
3498
    a.refs_for_client(&mut refs, None);
3499
    assert_eq!(refs.tags.len(), 1);
132b884b Andy McCall ↶ 3500
    // Checkout by tag.
75167672 Andy McCall 3501
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
3502
        .unwrap();
132b884b Andy McCall ↶ 3503
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
75167672 Andy McCall 3504
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
3505
        .unwrap();
132b884b Andy McCall ↶ 3506
3507
    // Push carries the tag; a second attestation for the name is refused.
3508
    let r = a.push("origin", false).unwrap();
767ac6cd Andy McCall 3509
    origin.refresh().unwrap();
132b884b Andy McCall ↶ 3510
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
3511
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
75167672 Andy McCall 3512
    let mut forged = a
3513
        .tag_refs()
3514
        .unwrap()
3515
        .into_iter()
3516
        .find(|t| t.name == "v1")
3517
        .unwrap();
3518
    forged.state = origin
3519
        .store()
3520
        .put_state(&StateObject::new(vec![h2]))
3521
        .unwrap();
132b884b Andy McCall ↶ 3522
    forged.heads = vec![h2];
3523
    forged.attestation = None;
75167672 Andy McCall 3524
    let r = origin
3525
        .receive_push(Bundle::default(), vec![], None, vec![forged])
3526
        .unwrap();
132b884b Andy McCall ↶ 3527
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
3528
3529
    // A clone gets the tag; a later tag arrives on fetch.
75167672 Andy McCall 3530
    let b = Repo::clone(&url, &root.join("b"))
3531
        .unwrap()
3532
        .with_home(root.join("home-b"));
132b884b Andy McCall ↶ 3533
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3534
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
3535
    a.tag_create("v2", &[h2], "second").unwrap();
3536
    a.push("origin", false).unwrap();
767ac6cd Andy McCall 3537
    origin.refresh().unwrap();
132b884b Andy McCall ↶ 3538
    let rep = b.fetch("origin").unwrap();
3539
    assert_eq!(rep.new_tags, 1);
3540
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
3541
3542
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
3543
    a.policy_init().unwrap();
3544
    a.push("origin", false).unwrap();
767ac6cd Andy McCall 3545
    origin.refresh().unwrap();
1ec6fdbc Andy McCall ↶ 3546
    let unattested = crate::protocol::TagRef::new(
3547
        "v3".into(),
3548
        origin
75167672 Andy McCall 3549
            .store()
3550
            .put_state(&StateObject::new(vec![h2]))
3551
            .unwrap(),
1ec6fdbc Andy McCall ↶ 3552
        vec![h2],
3553
        None,
3554
    );
75167672 Andy McCall 3555
    let r = origin
3556
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
3557
        .unwrap();
132b884b Andy McCall ↶ 3558
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
3559
    a.tag_create("v3", &[h2], "").unwrap();
3560
    let r = a.push("origin", false).unwrap();
767ac6cd Andy McCall 3561
    origin.refresh().unwrap();
132b884b Andy McCall ↶ 3562
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
3563
    assert!(a.gc(true).is_ok());
3564
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
e5d9b051 Andy McCall ↶ 3565
3566
    // After a rotation the policy names only the new key, yet a fresh clone
3567
    // still takes the tags the old key made before it; the old key makes
3568
    // nothing new.
3569
    let rot = a.rotate_identity().unwrap();
3570
    let r = a.push("origin", false).unwrap();
767ac6cd Andy McCall 3571
    origin.refresh().unwrap();
e5d9b051 Andy McCall ↶ 3572
    assert!(r.iter().all(|x| x.ok), "{r:?}");
3573
    let c = Repo::clone(&url, &root.join("c"))
3574
        .unwrap()
3575
        .with_home(root.join("home-c"));
3576
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
3577
    let (_, sp) = c.current_policy().unwrap().unwrap();
3578
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
3579
    let made = c.identity(&rot.new).unwrap().created;
3580
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
3581
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
3582
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
132b884b Andy McCall ↶ 3583
}
4e88e774 Andy McCall ↶ 3584
3585
#[test]
3586
fn multiple_workspaces_share_a_repository() {
3587
    hermetic();
3588
    let dir = tempfile::tempdir().unwrap();
3589
    let root = dir.path();
3590
    let main_dir = root.join("main");
3591
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
3592
    write(&main_dir, "a.txt", b"a\n");
3593
    let h1 = repo.commit("a", &[]).unwrap();
3594
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3595
3596
    // A second workspace elsewhere, checked out on the bookmark.
3597
    let ws_dir = root.join("ws2");
3598
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
3599
    assert!(ws_dir.join(".oxy").is_file());
3600
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
3601
    assert_ne!(ws.workspace(), repo.workspace());
3602
    let list = repo.workspaces().unwrap();
3603
    assert_eq!(list.len(), 2);
75167672 Andy McCall 3604
    assert!(list
3605
        .iter()
3606
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
4e88e774 Andy McCall ↶ 3607
    assert!(!ws.snapshot("status").unwrap().changed);
3608
3609
    // Work in the second workspace: its own working copy, shared bookmark.
3610
    write(&ws_dir, "b.txt", b"b\n");
3611
    let s = ws.snapshot("status").unwrap();
3612
    assert_eq!(s.statuses.len(), 1);
75167672 Andy McCall 3613
    assert!(
3614
        !repo.snapshot("status").unwrap().changed,
3615
        "the first workspace is untouched"
3616
    );
4e88e774 Andy McCall ↶ 3617
    let h2 = ws.commit("b from ws2", &[]).unwrap();
767ac6cd Andy McCall 3618
    repo.refresh().unwrap();
4e88e774 Andy McCall ↶ 3619
    let mut heads = repo.bookmark_heads().unwrap();
3620
    heads.sort();
3621
    let mut want = vec![h1, h2];
3622
    want.sort();
3623
    assert_eq!(heads, want, "both workspaces see the bookmark move");
3624
    assert!(!main_dir.join("b.txt").exists());
75167672 Andy McCall 3625
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
3626
        .unwrap();
4e88e774 Andy McCall ↶ 3627
    assert!(main_dir.join("b.txt").exists());
3628
3629
    // Reopening from inside the second workspace finds the shared repository.
3630
    let reopened = Repo::open(&ws_dir).unwrap();
3631
    assert_eq!(reopened.workspace(), ws.workspace());
3632
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
3633
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
3634
3635
    // Workspaces cannot nest; forget drops one from the view but keeps files.
3636
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
3637
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
3638
    repo.workspace_forget(&ws.workspace()).unwrap();
3639
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3640
    assert!(ws_dir.join("b.txt").exists());
75167672 Andy McCall 3641
    assert!(
3642
        ws.snapshot("status").is_err(),
3643
        "a forgotten workspace is no longer in the view"
3644
    );
4e88e774 Andy McCall ↶ 3645
6caacfff Andy McCall ↶ 3646
    // The working-copy lock: re-entrant in a thread; a lock whose process
3647
    // is gone is taken over, and a live process's is not, however old.
4e88e774 Andy McCall ↶ 3648
    let lock = repo.lock_snapshot().unwrap();
6caacfff Andy McCall ↶ 3649
    let again = repo.lock_working_copy().unwrap();
3650
    drop(again);
4e88e774 Andy McCall ↶ 3651
    drop(lock);
75167672 Andy McCall 3652
    let lock_path = main_dir
3653
        .join(".oxy/workspaces")
3654
        .join(repo.workspace().to_hex())
3655
        .join("lock");
4e88e774 Andy McCall ↶ 3656
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
6caacfff Andy McCall ↶ 3657
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
3658
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
3659
    age(&lock_path);
3660
    assert!(
3661
        !super::workspace::lock_is_stale(&lock_path),
3662
        "a live process keeps its lock"
3663
    );
3664
    fs::write(&lock_path, "4294967295").unwrap();
3665
    age(&lock_path);
4e88e774 Andy McCall ↶ 3666
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
3667
}
cdb5beba Andy McCall ↶ 3668
3669
#[test]
3670
fn attributes_binary_eol_nocompress_lockable() {
3671
    hermetic();
3672
    let dir = tempfile::tempdir().unwrap();
3673
    let root = dir.path();
3674
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3675
    write(
3676
        root,
3677
        ".oxyattributes",
3678
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
3679
    );
cdb5beba Andy McCall ↶ 3680
    write(root, "plain.dat", b"no nul bytes here\n");
3681
    write(root, "notes.txt", b"one\r\ntwo\r\n");
3682
    write(root, "assets/model.bin", b"\0model");
3683
    let h = repo.commit("attrs", &[]).unwrap();
3684
    let snap = repo.load_state(&[h]).unwrap().materialize();
75167672 Andy McCall 3685
    assert!(
3686
        snap.files["plain.dat"].mode.opaque,
3687
        "binary attribute forces opaque without NUL bytes"
3688
    );
3689
    assert!(
3690
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3691
        "stored with LF"
3692
    );
3693
    assert!(
3694
        !repo.snapshot("status").unwrap().changed,
3695
        "CRLF on disk equals LF in the state"
3696
    );
cdb5beba Andy McCall ↶ 3697
    // nocompress chunks pack raw.
3698
    let r = repo.gc(true).unwrap();
3699
    assert!(r.packed.objects > 0);
3700
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
3701
    fs::remove_file(root.join("notes.txt")).unwrap();
3702
    repo.checkout(&[h], true, "co").unwrap();
3703
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
75167672 Andy McCall 3704
    assert!(fs::metadata(root.join("assets/model.bin"))
3705
        .unwrap()
3706
        .permissions()
3707
        .readonly());
cdb5beba Andy McCall ↶ 3708
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
3709
    repo.lock_path("assets/model.bin").unwrap();
75167672 Andy McCall 3710
    assert!(!fs::metadata(root.join("assets/model.bin"))
3711
        .unwrap()
3712
        .permissions()
3713
        .readonly());
cdb5beba Andy McCall ↶ 3714
    assert!(repo.is_locked("assets/model.bin"));
3715
    write(root, "assets/model.bin", b"\0model2");
3716
    repo.commit("edit model", &[]).unwrap();
3717
    repo.unlock_path("assets/model.bin").unwrap();
75167672 Andy McCall 3718
    assert!(fs::metadata(root.join("assets/model.bin"))
3719
        .unwrap()
3720
        .permissions()
3721
        .readonly());
cdb5beba Andy McCall ↶ 3722
    // A later checkout can still overwrite a read-only lockable file.
3723
    repo.checkout(&[h], true, "co").unwrap();
3724
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
3725
}
6d3eefbc Andy McCall ↶ 3726
3727
#[cfg(unix)]
3728
#[test]
3729
fn hooks_can_veto_observe_and_add_dependencies() {
3730
    use std::os::unix::fs::PermissionsExt;
3731
    hermetic();
3732
    let dir = tempfile::tempdir().unwrap();
3733
    let root = dir.path();
3734
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3735
    let hooks = root.join(".oxy/hooks");
3736
    fs::create_dir_all(&hooks).unwrap();
3737
    let hook = |name: &str, body: &str| {
3738
        let p = hooks.join(name);
3739
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
3740
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
3741
    };
3742
    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");
3743
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
3744
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
3745
    hook("pre-push", "echo pushing blocked >&2; exit 3");
3746
    write(root, ".oxyignore", b".last-*\n");
3747
    write(root, "a.txt", b"a\n");
3748
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
3749
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
3750
    let h1 = repo.commit("first", &[]).unwrap();
3751
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
75167672 Andy McCall 3752
    assert!(
3753
        pre.contains("\"event\":\"pre-commit\"")
3754
            && pre.contains("\"path\":\"a.txt\"")
3755
            && pre.contains("\"message\":\"first\""),
3756
        "{pre}"
3757
    );
6d3eefbc Andy McCall ↶ 3758
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
3759
    assert!(post.contains(&h1.to_hex()), "{post}");
3760
    repo.checkout(&[h1], false, "co").unwrap();
75167672 Andy McCall 3761
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
3762
        .unwrap()
3763
        .contains("post-checkout"));
6d3eefbc Andy McCall ↶ 3764
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
3765
    repo.save_config().unwrap();
3766
    let err = repo.push("origin", false).unwrap_err().to_string();
3767
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
3768
3769
    // semantic-deps: only when enabled; adds an explicit dependency.
3770
    write(root, "b.txt", b"b\n");
75167672 Andy McCall 3771
    hook(
3772
        "semantic-deps",
3773
        &format!(
3774
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
3775
            h1.to_hex()
3776
        ),
3777
    );
6d3eefbc Andy McCall ↶ 3778
    let h2 = repo.commit("b without hook", &[]).unwrap();
75167672 Andy McCall 3779
    assert!(
3780
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
3781
        "hook disabled by default"
3782
    );
6d3eefbc Andy McCall ↶ 3783
    repo.config.set("hooks.semantic-deps", "true").unwrap();
3784
    repo.save_config().unwrap();
3785
    write(root, "c.txt", b"c\n");
3786
    let h3 = repo.commit("c with hook", &[]).unwrap();
3787
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
3788
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
75167672 Andy McCall 3789
    assert!(
3790
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
3791
        "{sem}"
3792
    );
6d3eefbc Andy McCall ↶ 3793
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
3794
}
23b217d7 Andy McCall ↶ 3795
3796
#[test]
3797
fn amend_into_older_change_and_split() {
3798
    hermetic();
3799
    let dir = tempfile::tempdir().unwrap();
3800
    let root = dir.path();
3801
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 3802
    repo.create_identity("Ada", "a@b", IdentityScope::User)
3803
        .unwrap();
23b217d7 Andy McCall ↶ 3804
    repo.set_user_config("core.sign", "change").unwrap();
3805
    write(root, "a.txt", b"one\ntwo\n");
3806
    let h0 = repo.commit("base", &[]).unwrap();
3807
    write(root, "a.txt", b"one\nTWO\n");
3808
    let h1 = repo.commit("edit two", &[]).unwrap();
3809
    write(root, "a.txt", b"one\nTWO\nthree\n");
3810
    let h2 = repo.commit("add three", &[]).unwrap();
3811
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3812
3813
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
3814
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3815
    let h1b = repo.amend_into(&h1, None).unwrap();
3816
    assert_ne!(h1b, h1);
3817
    let c1b = repo.store().get_change(&h1b).unwrap();
3818
    assert_eq!(c1b.change_id, id1);
3819
    assert_eq!(c1b.deps, vec![h0]);
75167672 Andy McCall 3820
    assert!(matches!(
3821
        repo.verify_change(&h1b).unwrap(),
3822
        SignatureStatus::Valid { .. }
3823
    ));
23b217d7 Andy McCall ↶ 3824
    let heads = repo.bookmark_heads().unwrap();
3825
    assert_eq!(heads.len(), 1);
3826
    let top = repo.store().get_change(&heads[0]).unwrap();
3827
    assert_eq!(top.message, "add three");
75167672 Andy McCall 3828
    assert_eq!(
3829
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
3830
        [h0, h1b].into_iter().collect(),
3831
        "depends on the file's creator and the rewritten line"
3832
    );
23b217d7 Andy McCall ↶ 3833
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 3834
    assert!(
3835
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
3836
    );
3837
    assert!(
3838
        !repo.snapshot("status").unwrap().changed,
3839
        "the working copy is clean after folding"
3840
    );
23b217d7 Andy McCall ↶ 3841
    // Only h1b's own state shows the fix without "three".
3842
    let only = repo.load_state(&[h1b]).unwrap().materialize();
75167672 Andy McCall 3843
    assert!(
3844
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
3845
    );
23b217d7 Andy McCall ↶ 3846
    assert_eq!(repo.log().unwrap().len(), 4);
3847
3848
    // An edit to a line introduced by h2 cannot fold into h1.
3849
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
3850
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
3851
    assert!(err.contains("introduced after"), "{err}");
75167672 Andy McCall 3852
    assert!(
3853
        repo.snapshot("status").unwrap().statuses.len() == 1,
3854
        "nothing was changed by the refusal"
3855
    );
23b217d7 Andy McCall ↶ 3856
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3857
3858
    // Split the head that touches two files.
3859
    write(root, "b.txt", b"b\n");
3860
    write(root, "c.txt", b"c\n");
3861
    let h3 = repo.commit("b and c", &[]).unwrap();
3862
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
3863
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
3864
    let c_1 = repo.store().get_change(&p1).unwrap();
3865
    let c_2 = repo.store().get_change(&p2).unwrap();
3866
    assert!(c_1.message.contains("part 1: b.txt"));
3867
    assert_eq!(c_2.change_id, id3);
3868
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
75167672 Andy McCall 3869
    assert!(
3870
        heads.contains(&p1) && heads.contains(&p2),
3871
        "independent parts are both heads"
3872
    );
3873
    let snap = repo
3874
        .load_state(&repo.bookmark_heads().unwrap())
3875
        .unwrap()
3876
        .materialize();
23b217d7 Andy McCall ↶ 3877
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
3878
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
3879
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
3880
    assert!(!repo.snapshot("status").unwrap().changed);
3881
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
3882
    let _ = h2;
3883
}
28fc23d7 Andy McCall ↶ 3884
3885
#[test]
3886
fn identity_lifecycle() {
3887
    hermetic();
3888
    let dir = tempfile::tempdir().unwrap();
3889
    let root = dir.path();
3890
    let origin = Repo::init(&root.join("origin")).unwrap();
3891
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 3892
    let mut a = Repo::clone(&url, &root.join("a"))
3893
        .unwrap()
3894
        .with_home(root.join("home-a"));
28fc23d7 Andy McCall ↶ 3895
    a.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 3896
    let (key_a, _) = a
3897
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3898
        .unwrap();
28fc23d7 Andy McCall ↶ 3899
    write(&root.join("a"), "a.txt", b"a\n");
3900
    let h1 = a.commit("one", &[]).unwrap();
3901
    assert!(a.policy_init().unwrap().applied);
3902
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
767ac6cd Andy McCall 3903
    origin.refresh().unwrap();
28fc23d7 Andy McCall ↶ 3904
3905
    // Expiry: an identity that had expired when the change was made does not authenticate it.
75167672 Andy McCall 3906
    let mut e = Repo::init(&root.join("e"))
3907
        .unwrap()
3908
        .with_home(root.join("home-e"));
28fc23d7 Andy McCall ↶ 3909
    e.set_user_config("core.sign", "change").unwrap();
75167672 Andy McCall 3910
    e.create_identity_with(
3911
        "Eve",
3912
        "[email protected]",
3913
        IdentityScope::User,
3914
        Some(Hlc::now().wall_ms - 1),
3915
    )
3916
    .unwrap();
28fc23d7 Andy McCall ↶ 3917
    write(&root.join("e"), "e.txt", b"e\n");
3918
    let he = e.commit("late", &[]).unwrap();
75167672 Andy McCall 3919
    assert!(
3920
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
3921
    );
28fc23d7 Andy McCall ↶ 3922
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
75167672 Andy McCall 3923
    let r = e
3924
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
3925
        .unwrap();
28fc23d7 Andy McCall ↶ 3926
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
3927
    write(&root.join("e"), "e.txt", b"e2\n");
3928
    let he2 = e.commit("in time", &[]).unwrap();
75167672 Andy McCall 3929
    assert!(
3930
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
3931
    );
28fc23d7 Andy McCall ↶ 3932
3933
    // Rotation: a fresh key; the old change still verifies; the policy follows.
3934
    let r = a.rotate_identity().unwrap();
3935
    assert_eq!(r.old, key_a);
3936
    assert_eq!(a.config.author_key, Some(r.new));
3937
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
3938
    assert!(r.policy.as_ref().unwrap().applied);
3939
    let (_, sp) = a.current_policy().unwrap().unwrap();
75167672 Andy McCall 3940
    assert_eq!(
3941
        (sp.policy.serial, sp.policy.roots.clone()),
3942
        (2, vec![r.new])
3943
    );
3944
    assert!(
3945
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
3946
        "superseded, not revoked"
3947
    );
28fc23d7 Andy McCall ↶ 3948
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
75167672 Andy McCall 3949
    assert!(
3950
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
3951
    );
28fc23d7 Andy McCall ↶ 3952
    write(&root.join("a"), "a.txt", b"a2\n");
3953
    let h2 = a.commit("two", &[]).unwrap();
75167672 Andy McCall 3954
    assert!(
3955
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
3956
    );
28fc23d7 Andy McCall ↶ 3957
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
3958
    let res = a.push("origin", false).unwrap();
767ac6cd Andy McCall 3959
    origin.refresh().unwrap();
28fc23d7 Andy McCall ↶ 3960
    assert!(res.iter().all(|x| x.ok), "{res:?}");
3961
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
3962
    let key_a = r.new;
3963
3964
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
3965
    // identity object, so Ada's KeyId changes while her keys stay the same.
75167672 Andy McCall 3966
    let mut b = Repo::clone(&url, &root.join("b"))
3967
        .unwrap()
3968
        .with_home(root.join("home-b"));
3969
    let (key_b, id_b) = b
3970
        .create_identity("Bob", "[email protected]", IdentityScope::User)
3971
        .unwrap();
7ba155f2 Andy McCall ↶ 3972
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
28fc23d7 Andy McCall ↶ 3973
    assert_eq!(r.old, key_a);
3974
    let key_a2 = r.new;
75167672 Andy McCall 3975
    assert_eq!(
7ba155f2 Andy McCall ↶ 3976
        a.identity(&key_a2).unwrap().delegates,
3977
        vec![Delegate::full(key_b)]
3978
    );
3979
    assert_eq!(
75167672 Andy McCall 3980
        a.identity(&key_a2).unwrap().ed25519_pk,
3981
        a.identity(&key_a).unwrap().ed25519_pk
7ba155f2 Andy McCall ↶ 3982
    );
3983
    assert!(
3984
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
3985
        "already a delegate"
75167672 Andy McCall 3986
    );
28fc23d7 Andy McCall ↶ 3987
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
767ac6cd Andy McCall 3988
    origin.refresh().unwrap();
28fc23d7 Andy McCall ↶ 3989
    write(&root.join("a"), "a.txt", b"a3\n");
3990
    let h3 = a.commit("three", &[]).unwrap();
75167672 Andy McCall 3991
    assert!(
3992
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
3993
        "the same secret signs under the new KeyId"
3994
    );
28fc23d7 Andy McCall ↶ 3995
    // A change authored by Ada but signed only by Bob verifies through the delegation.
3996
    a.set_user_config("core.sign", "seal").unwrap();
3997
    write(&root.join("a"), "a.txt", b"a4\n");
3998
    let h4 = a.commit("four", &[]).unwrap();
3999
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
4000
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
75167672 Andy McCall 4001
    a.store()
4002
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
4003
        .unwrap();
4004
    assert!(
4005
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
4006
    );
28fc23d7 Andy McCall ↶ 4007
    a.set_user_config("core.sign", "change").unwrap();
4008
    // Withdrawing the delegation re-issues the identity again.
4009
    let r = a.delegate_remove(&key_b).unwrap();
4010
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
4011
    assert!(a.delegate_remove(&key_b).is_err());
4012
    let key_a3 = r.new;
4013
    let res = a.push("origin", false).unwrap();
767ac6cd Andy McCall 4014
    origin.refresh().unwrap();
28fc23d7 Andy McCall ↶ 4015
    assert!(res.iter().all(|x| x.ok), "{res:?}");
4016
4017
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
4018
    // both applied under the old threshold of 1. A grant then needs Bob too.
4019
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
4020
    assert!(a.policy_root_add(id_b.clone()).is_err());
4021
    assert!(a.policy_set_threshold(3).is_err());
4022
    assert!(a.policy_set_threshold(2).unwrap().applied);
4023
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
767ac6cd Andy McCall 4024
    origin.refresh().unwrap();
28fc23d7 Andy McCall ↶ 4025
    b.pull("origin").unwrap();
75167672 Andy McCall 4026
    assert_eq!(
4027
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
4028
        2
4029
    );
4030
    let mut c = Repo::init(&root.join("c"))
4031
        .unwrap()
4032
        .with_home(root.join("home-c"));
4033
    let (key_c, id_c) = c
4034
        .create_identity("Cy", "[email protected]", IdentityScope::User)
4035
        .unwrap();
28fc23d7 Andy McCall ↶ 4036
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
4037
    let proposal = a.policy_grant(id_c, None).unwrap();
4038
    assert!(!proposal.applied && proposal.sigs.len() == 1);
4039
    assert_eq!(proposal.policy.serial, serial_before + 1);
75167672 Andy McCall 4040
    assert_eq!(
4041
        a.current_policy().unwrap().unwrap().1.policy.serial,
4042
        serial_before,
4043
        "a proposal changes nothing yet"
4044
    );
28fc23d7 Andy McCall ↶ 4045
    // Bob signs the proposal, handed over as a file, and it applies for him.
4046
    let bytes = proposal.signed().encode();
75167672 Andy McCall 4047
    let signed = b
4048
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
4049
        .unwrap();
28fc23d7 Andy McCall ↶ 4050
    assert!(signed.applied && signed.sigs.len() == 2);
75167672 Andy McCall 4051
    assert!(b
4052
        .current_policy()
4053
        .unwrap()
4054
        .unwrap()
4055
        .1
4056
        .policy
4057
        .authorizes(&key_c, "main"));
4058
    assert!(
4059
        b.policy_sign(signed.signed()).is_err(),
4060
        "a stale proposal is refused"
4061
    );
28fc23d7 Andy McCall ↶ 4062
    // Bob publishes it and Ada picks it up.
75167672 Andy McCall 4063
    assert!(b
4064
        .push("origin", false)
4065
        .unwrap()
4066
        .iter()
4067
        .any(|x| x.name == "policy" && x.ok));
767ac6cd Andy McCall 4068
    origin.refresh().unwrap();
28fc23d7 Andy McCall ↶ 4069
    a.pull("origin").unwrap();
75167672 Andy McCall 4070
    assert_eq!(
4071
        a.current_policy().unwrap().unwrap().1.policy.serial,
4072
        serial_before + 1
4073
    );
28fc23d7 Andy McCall ↶ 4074
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
4075
    assert!(a.policy_revoke(&key_a3).is_err());
75167672 Andy McCall 4076
    let u = a
4077
        .revoke_identity(&key_c, "left the project")
4078
        .unwrap()
4079
        .unwrap();
28fc23d7 Andy McCall ↶ 4080
    assert!(!u.applied);
4081
    assert!(a.is_revoked(&key_c).unwrap());
4082
    assert!(!b.is_revoked(&key_c).unwrap());
4083
    let u = b.policy_sign(u.signed()).unwrap();
4084
    assert!(u.applied && u.policy.is_revoked(&key_c));
4085
    assert!(b.is_revoked(&key_c).unwrap());
4086
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
75167672 Andy McCall 4087
    assert!(
4088
        b.policy_revoke(&key_a3).is_err(),
4089
        "would leave one root for a threshold of 2"
4090
    );
28fc23d7 Andy McCall ↶ 4091
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
4092
    let key_c_own = c.config.author_key.unwrap();
75167672 Andy McCall 4093
    assert!(c
4094
        .revoke_identity(&key_c_own, "lost laptop")
4095
        .unwrap()
4096
        .is_none());
28fc23d7 Andy McCall ↶ 4097
    assert!(c.is_revoked(&key_c_own).unwrap());
4098
    assert_eq!(key_c_own, key_c);
4099
}
4100
6e723b81 Andy McCall ↶ 4101
#[test]
4102
fn renames_are_detected_and_tracked_as_moves() {
4103
    hermetic();
4104
    let dir = tempfile::tempdir().unwrap();
4105
    let root = dir.path();
4106
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 4107
    write(
4108
        root,
4109
        "src/old.rs",
4110
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
4111
    );
6e723b81 Andy McCall ↶ 4112
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
4113
    write(root, "tiny.txt", b"x\n");
4114
    let h1 = repo.commit("base", &[]).unwrap();
4115
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
4116
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
4117
4118
    // Rename with a small edit, a binary moved unchanged, and a rewrite
4119
    // that shares nothing with the removed file.
4120
    fs::remove_file(root.join("src/old.rs")).unwrap();
75167672 Andy McCall 4121
    write(
4122
        root,
4123
        "lib/new.rs",
4124
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
4125
    );
6e723b81 Andy McCall ↶ 4126
    fs::remove_file(root.join("img.bin")).unwrap();
4127
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
4128
    fs::remove_file(root.join("tiny.txt")).unwrap();
4129
    write(root, "other.txt", b"completely different\n");
4130
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4131
    let statuses: Vec<(&str, ChangeStatus)> = snap
4132
        .statuses
4133
        .iter()
4134
        .map(|s| (s.path.as_str(), s.status))
4135
        .collect();
6e723b81 Andy McCall ↶ 4136
    assert_eq!(
4137
        statuses,
75167672 Andy McCall 4138
        vec![
4139
            ("assets/img.bin", ChangeStatus::Renamed),
4140
            ("lib/new.rs", ChangeStatus::Renamed),
4141
            ("other.txt", ChangeStatus::Added),
4142
            ("src", ChangeStatus::Removed),
4143
            ("tiny.txt", ChangeStatus::Removed)
4144
        ]
6e723b81 Andy McCall ↶ 4145
    );
4146
    let h2 = repo.commit("move things", &[]).unwrap();
4147
    let c = repo.store().get_change(&h2).unwrap();
75167672 Andy McCall 4148
    let moves: Vec<_> = c
4149
        .tree_ops
4150
        .iter()
4151
        .filter(|op| matches!(op, TreeOp::Move { .. }))
4152
        .collect();
6e723b81 Andy McCall ↶ 4153
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
75167672 Andy McCall 4154
    assert!(c.tree_ops.iter().any(
4155
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
4156
    ));
4157
    assert!(c.tree_ops.iter().any(
4158
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
4159
    ));
6e723b81 Andy McCall ↶ 4160
    let snap = repo.load_state(&[h2]).unwrap().materialize();
75167672 Andy McCall 4161
    assert_eq!(
4162
        snap.files["lib/new.rs"].node, node_old,
4163
        "the node survives the rename"
4164
    );
4165
    assert!(
4166
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
4167
    );
6e723b81 Andy McCall ↶ 4168
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
75167672 Andy McCall 4169
    assert!(render_change(
4170
        &c,
4171
        &repo.load_state(&[h1]).unwrap(),
4172
        &repo.load_state(&[h1]).unwrap().materialize()
4173
    )
0912a033 Andy McCall ↶ 4174
    .contains("R src/old.rs -> lib/new.rs"));
6e723b81 Andy McCall ↶ 4175
    // A fresh checkout reproduces the tree.
4176
    let other = tempfile::tempdir().unwrap();
4177
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
75167672 Andy McCall 4178
    assert_eq!(
4179
        fs::read(other.path().join("lib/new.rs")).unwrap(),
4180
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
4181
    );
6e723b81 Andy McCall ↶ 4182
    assert!(!other.path().join("src").exists());
4183
    assert!(!clone.snapshot("status").unwrap().changed);
4184
    // Similarity is line based, byte weighted.
4185
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
4186
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
4187
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
4188
    assert_eq!(similarity(b"", b"x\n"), 0);
4189
}
4190
30ea9c1e Andy McCall ↶ 4191
#[test]
4192
fn git_fetch_and_push_round_trip() {
4193
    hermetic();
75167672 Andy McCall 4194
    if std::process::Command::new("git")
4195
        .arg("--version")
4196
        .output()
4197
        .is_err()
4198
    {
30ea9c1e Andy McCall ↶ 4199
        eprintln!("git not installed; skipping");
4200
        return;
4201
    }
4202
    let dir = tempfile::tempdir().unwrap();
4203
    let root = dir.path();
4204
    let git_in = |d: &Path, args: &[&str]| -> String {
4205
        let out = std::process::Command::new("git")
4206
            .arg("-C")
4207
            .arg(d)
75167672 Andy McCall 4208
            .args([
4209
                "-c",
4210
                "user.name=Grace",
4211
                "-c",
4212
                "[email protected]",
4213
                "-c",
4214
                "commit.gpgsign=false",
4215
            ])
30ea9c1e Andy McCall ↶ 4216
            .args(args)
4217
            .output()
4218
            .unwrap();
75167672 Andy McCall 4219
        assert!(
4220
            out.status.success(),
4221
            "git {args:?}: {}",
4222
            String::from_utf8_lossy(&out.stderr)
4223
        );
30ea9c1e Andy McCall ↶ 4224
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4225
    };
4226
    // A bare "remote" and a work tree that pushes to it.
4227
    let remote = root.join("remote.git");
4228
    fs::create_dir_all(&remote).unwrap();
4229
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
4230
    let work = root.join("work");
75167672 Andy McCall 4231
    git_in(
4232
        root,
4233
        &[
4234
            "clone",
4235
            "-q",
4236
            remote.to_str().unwrap(),
4237
            work.to_str().unwrap(),
4238
        ],
4239
    );
30ea9c1e Andy McCall ↶ 4240
    git_in(&work, &["checkout", "-q", "-b", "main"]);
4241
    write(&work, "README.md", b"# Project\n");
4242
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
4243
    git_in(&work, &["add", "."]);
4244
    git_in(&work, &["commit", "-q", "-m", "initial"]);
4245
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
4246
    git_in(&work, &["commit", "-q", "-am", "second"]);
4247
    git_in(&work, &["push", "-q", "origin", "main"]);
4248
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
4249
4250
    // Fetch into a fresh oxy repository.
4251
    let o = root.join("oxy");
4252
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
75167672 Andy McCall 4253
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4254
        .unwrap();
30ea9c1e Andy McCall ↶ 4255
    let url = remote.to_string_lossy().to_string();
4256
    let r = repo.git_fetch(&url, "main").unwrap();
4257
    assert_eq!((r.commits, r.heads), (2, 1));
75167672 Andy McCall 4258
    assert_eq!(
4259
        fs::read(o.join("src/lib.rs")).unwrap(),
4260
        b"pub fn a() {}\npub fn b() {}\n"
4261
    );
30ea9c1e Andy McCall ↶ 4262
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 4263
    assert_eq!(
4264
        repo.git_fetch(&url, "main").unwrap().commits,
4265
        0,
4266
        "nothing new"
4267
    );
30ea9c1e Andy McCall ↶ 4268
4269
    // An oxy change, pushed back: one commit on top of the Git tip.
75167672 Andy McCall 4270
    write(
4271
        &o,
4272
        "src/lib.rs",
4273
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
4274
    );
30ea9c1e Andy McCall ↶ 4275
    write(&o, "NOTES.md", b"from oxy\n");
4276
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
4277
    let r = repo.git_push(&url, "main").unwrap();
4278
    assert_eq!(r.exported, 1, "{r:?}");
4279
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
75167672 Andy McCall 4280
    assert_eq!(
4281
        git_in(&work, &["log", "--format=%s", "main"]),
4282
        "add c and notes\nsecond\ninitial"
4283
    );
30ea9c1e Andy McCall ↶ 4284
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
4285
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
4286
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
75167672 Andy McCall 4287
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
4288
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
4289
    assert_eq!(
4290
        repo.git_push(&url, "main").unwrap().exported,
4291
        0,
4292
        "already pushed"
4293
    );
30ea9c1e Andy McCall ↶ 4294
4295
    // Git moves on; pushing without fetching is refused, fetching brings
4296
    // the commit in and the working copy follows.
4297
    write(&work, "README.md", b"# Project\n\nMore.\n");
4298
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
4299
    git_in(&work, &["push", "-q", "origin", "main"]);
4300
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
75167672 Andy McCall 4301
    assert!(repo
4302
        .git_push(&url, "main")
4303
        .unwrap_err()
4304
        .to_string()
4305
        .contains("fetch"));
30ea9c1e Andy McCall ↶ 4306
    let r = repo.git_fetch(&url, "main").unwrap();
75167672 Andy McCall 4307
    assert_eq!(
4308
        (r.commits, r.heads),
4309
        (1, 2),
4310
        "the Git change and the oxy change commute"
4311
    );
4312
    assert_eq!(
4313
        fs::read(o.join("README.md")).unwrap(),
4314
        b"# Project\n\nMore.\n"
4315
    );
30ea9c1e Andy McCall ↶ 4316
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
4317
    assert!(!repo.snapshot("status").unwrap().changed);
4318
    // Another oxy change pushes on top of Git's newest commit.
4319
    write(&o, "NOTES.md", b"from oxy\nagain\n");
4320
    repo.commit("notes again", &[]).unwrap();
4321
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
4322
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
4323
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
75167672 Andy McCall 4324
    assert_eq!(
4325
        fs::read(work.join("NOTES.md")).unwrap(),
4326
        b"from oxy\nagain\n"
4327
    );
4328
    assert_eq!(
4329
        git_in(&work, &["log", "--format=%s", "main"])
4330
            .lines()
4331
            .count(),
4332
        5
4333
    );
30ea9c1e Andy McCall ↶ 4334
}
4335
2b872d07 Andy McCall ↶ 4336
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
4337
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
4338
#[test]
4339
#[ignore]
4340
fn bench_one_gibibyte_file() {
4341
    hermetic();
4342
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
4343
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
4344
        Some(d) => tempfile::tempdir_in(d).unwrap(),
4345
        None => tempfile::tempdir().unwrap(),
4346
    };
4347
    let root = dir.path();
75167672 Andy McCall 4348
    let repo = Repo::init(&root.join("r"))
4349
        .unwrap()
4350
        .with_home(root.join("home"));
2b872d07 Andy McCall ↶ 4351
    let size = 1usize << 30;
4352
    let mut data = vec![0u8; size];
4353
    let mut x = 0x9e3779b97f4a7c15u64;
4354
    for chunk in data.chunks_mut(8) {
4355
        x ^= x << 13;
4356
        x ^= x >> 7;
4357
        x ^= x << 17;
4358
        let b = x.to_le_bytes();
4359
        chunk.copy_from_slice(&b[..chunk.len()]);
4360
    }
4361
    let t = std::time::Instant::now();
4362
    write(&root.join("r"), "big.bin", &data);
4363
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
4364
    let t = std::time::Instant::now();
4365
    let h = repo.commit("big", &[]).unwrap();
4366
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
4367
    let t = std::time::Instant::now();
4368
    assert!(!repo.snapshot("status").unwrap().changed);
4369
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
4370
    let t = std::time::Instant::now();
4371
    let objects = repo.store().list().unwrap().len();
4372
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
4373
    let t = std::time::Instant::now();
4374
    let g = repo.gc(true).unwrap();
4375
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
4376
    let t = std::time::Instant::now();
4377
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
4378
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
4379
    let t = std::time::Instant::now();
4380
    let back = fs::read(root.join("c/big.bin")).unwrap();
4381
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
4382
    eprintln!("read back and verify: {:.2?}", t.elapsed());
4383
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
4384
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
75167672 Andy McCall 4385
    eprintln!(
4386
        "store size: {:.1} MiB for 1 GiB of data",
4387
        store_bytes as f64 / (1024.0 * 1024.0)
4388
    );
2b872d07 Andy McCall ↶ 4389
}
4390
4391
fn walkdir_size(p: &Path) -> u64 {
4392
    let mut total = 0;
4393
    if let Ok(rd) = fs::read_dir(p) {
4394
        for e in rd.flatten() {
4395
            let path = e.path();
4396
            if path.is_dir() {
4397
                total += walkdir_size(&path);
4398
            } else if let Ok(m) = fs::metadata(&path) {
4399
                total += m.len();
4400
            }
4401
        }
4402
    }
4403
    total
4404
}
4405
b7f102fc Andy McCall ↶ 4406
/// An opaque file whose size and mtime match the manifest is not read on
4407
/// the next snapshot: its blob comes from the manifest's stat cache.
4408
#[cfg(unix)]
4409
#[test]
4410
fn stat_cache_skips_reading_unchanged_opaque_files() {
4411
    use std::os::unix::fs::PermissionsExt;
4412
    hermetic();
4413
    let dir = tempfile::tempdir().unwrap();
4414
    let root = dir.path();
4415
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4416
    let mut big = vec![0u8; 300 * 1024];
4417
    for (i, b) in big.iter_mut().enumerate() {
4418
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
4419
    }
4420
    big[0] = 0;
4421
    write(root, "big.bin", &big);
4422
    write(root, "a.txt", b"text\n");
4423
    let h1 = repo.commit("base", &[]).unwrap();
4424
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
75167672 Andy McCall 4425
    assert!(
4426
        m.entries["big.bin"].blob.is_some(),
4427
        "opaque files record their blob"
4428
    );
b7f102fc Andy McCall ↶ 4429
    assert!(m.entries["a.txt"].blob.is_none());
4430
    let blob = m.entries["big.bin"].blob.unwrap();
4431
    assert!(repo.store().has(&blob));
4432
4433
    // Files modified within two seconds of the manifest are racy and still
4434
    // read; age the file so the cache applies, then snapshot to record it.
4435
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
75167672 Andy McCall 4436
    fs::File::options()
4437
        .write(true)
4438
        .open(root.join("big.bin"))
4439
        .unwrap()
4440
        .set_modified(old)
4441
        .unwrap();
b7f102fc Andy McCall ↶ 4442
    assert!(!repo.snapshot("status").unwrap().changed);
4443
    // Now the file cannot be read at all; the snapshot succeeds without it.
4444
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
4445
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4446
    assert!(
4447
        !snap.changed && snap.statuses.is_empty(),
4448
        "{:?}",
4449
        snap.statuses
4450
    );
b7f102fc Andy McCall ↶ 4451
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
4452
    // A real change (new mtime, new content) is seen and committed correctly.
4453
    let mut big2 = big.clone();
4454
    big2[10] ^= 0xff;
4455
    write(root, "big.bin", &big2);
4456
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4457
    assert_eq!(
4458
        snap.statuses
4459
            .iter()
4460
            .map(|s| (s.path.as_str(), s.status))
4461
            .collect::<Vec<_>>(),
4462
        vec![("big.bin", ChangeStatus::Modified)]
4463
    );
b7f102fc Andy McCall ↶ 4464
    let h2 = repo.commit("edit", &[]).unwrap();
4465
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 4466
    assert_eq!(
4467
        files["big.bin"].content,
4468
        FileContent::Opaque {
4469
            blobs: vec![Repo::blob_ref(&big2)]
4470
        }
4471
    );
b7f102fc Andy McCall ↶ 4472
    // Checkout writes a manifest with blobs too, so the next status is cached.
4473
    repo.checkout(&[h1], false, "checkout").unwrap();
4474
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4475
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
4476
    assert!(!repo.snapshot("status").unwrap().changed);
4477
}
4478
50a046e4 Andy McCall ↶ 4479
#[test]
4480
fn status_json_lists_conflicts_with_contributors() {
4481
    hermetic();
4482
    let dir = tempfile::tempdir().unwrap();
4483
    let root = dir.path();
4484
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4485
    write(root, "a.txt", b"one\n");
4486
    let h1 = repo.commit("base", &[]).unwrap();
4487
    write(root, "a.txt", b"one\nleft\n");
4488
    let ha = repo.commit("left", &[]).unwrap();
4489
    repo.checkout(&[h1], true, "checkout").unwrap();
4490
    write(root, "a.txt", b"one\nright\n");
4491
    let hb = repo.commit("right", &[]).unwrap();
4492
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
4493
    let snap = repo.snapshot("status").unwrap();
4494
    assert!(snap.base_snapshot.is_conflicted());
4495
    let json = repo.status_json(&snap).unwrap();
4496
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
4497
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
4498
    assert!(json.contains("\"conflicted\":true"), "{json}");
75167672 Andy McCall 4499
    assert!(
4500
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
4501
        "{json}"
4502
    );
50a046e4 Andy McCall ↶ 4503
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
4504
    assert!(json.contains("\"resolved\":false"), "{json}");
4505
    assert!(json.starts_with('{') && json.ends_with('}'));
4506
    // Resolve and the report says so; a clean copy has no conflicts.
4507
    write(root, "a.txt", b"one\nleft\nright\n");
4508
    let snap = repo.snapshot("status").unwrap();
4509
    let json = repo.status_json(&snap).unwrap();
4510
    assert!(json.contains("\"resolved\":true"), "{json}");
4511
    repo.commit("resolve", &[]).unwrap();
4512
    let snap = repo.snapshot("status").unwrap();
4513
    let json = repo.status_json(&snap).unwrap();
75167672 Andy McCall 4514
    assert!(
4515
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
4516
        "{json}"
4517
    );
50a046e4 Andy McCall ↶ 4518
}
4519
9ac1fbe2 Andy McCall ↶ 4520
#[test]
4521
fn ignore_rules_do_not_untrack_files() {
4522
    hermetic();
4523
    let dir = tempfile::tempdir().unwrap();
4524
    let root = dir.path();
4525
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4526
    write(root, "src.c", b"int x;\n");
4527
    write(root, "build/out.o", b"\0obj");
4528
    write(root, "sub/keep.log", b"keep\n");
4529
    write(root, "sub/junk.log", b"junk\n");
4530
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
4531
    let snap = repo.snapshot("status").unwrap();
4532
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 4533
    assert_eq!(
4534
        added,
4535
        vec![".oxyignore", "src.c", "sub/keep.log"],
4536
        "anchored, glob, and negated rules"
4537
    );
9ac1fbe2 Andy McCall ↶ 4538
    let h1 = repo.commit("base", &[]).unwrap();
4539
    // Ignoring a tracked file changes nothing about it.
4540
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
4541
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4542
    assert_eq!(
4543
        snap.statuses
4544
            .iter()
4545
            .map(|s| s.path.as_str())
4546
            .collect::<Vec<_>>(),
4547
        vec![".oxyignore"]
4548
    );
9ac1fbe2 Andy McCall ↶ 4549
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
75167672 Andy McCall 4550
    assert!(repo
4551
        .load_state(&[h2])
4552
        .unwrap()
4553
        .materialize()
4554
        .files
4555
        .contains_key("src.c"));
9ac1fbe2 Andy McCall ↶ 4556
    // Its edits are still seen, by status and by the prompt.
4557
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
4558
    write(root, "src.c", b"int x, y;\n");
4559
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
4560
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4561
    assert_eq!(
4562
        snap.statuses
4563
            .iter()
4564
            .map(|s| (s.path.as_str(), s.status))
4565
            .collect::<Vec<_>>(),
4566
        vec![("src.c", ChangeStatus::Modified)]
4567
    );
9ac1fbe2 Andy McCall ↶ 4568
    let h3 = repo.commit("edit src.c", &[]).unwrap();
75167672 Andy McCall 4569
    assert!(
4570
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
4571
    );
9ac1fbe2 Andy McCall ↶ 4572
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
4573
    fs::remove_file(root.join("src.c")).unwrap();
4574
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 4575
    assert_eq!(
4576
        snap.statuses
4577
            .iter()
4578
            .map(|s| (s.path.as_str(), s.status))
4579
            .collect::<Vec<_>>(),
4580
        vec![("src.c", ChangeStatus::Removed)]
4581
    );
9ac1fbe2 Andy McCall ↶ 4582
    repo.checkout(&[h3], true, "checkout").unwrap();
4583
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
4584
    assert!(!repo.snapshot("status").unwrap().changed);
4585
    let _ = h1;
4586
}
4587
b837d2b5 Andy McCall ↶ 4588
#[test]
4589
fn split_works_on_non_heads_by_node() {
4590
    hermetic();
4591
    let dir = tempfile::tempdir().unwrap();
4592
    let root = dir.path();
4593
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4594
    write(root, "a.txt", b"one\n");
4595
    write(root, "junk/x.lock", b"lock\n");
4596
    let h1 = repo.commit("work plus junk", &[]).unwrap();
4597
    write(root, "a.txt", b"one\ntwo\n");
4598
    let h2 = repo.commit("more work", &[]).unwrap();
4599
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
4600
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
4601
    // h1 is not a head: split it by node.
4602
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
4603
    assert_ne!(h1b, h1);
75167672 Andy McCall 4604
    assert_eq!(
4605
        repo.store().get_change(&h1b).unwrap().change_id,
4606
        id1,
4607
        "the rest keeps the ChangeId"
4608
    );
b837d2b5 Andy McCall ↶ 4609
    let junk = repo.store().get_change(&hj).unwrap();
75167672 Andy McCall 4610
    assert!(junk.tree_ops.iter().all(
4611
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
4612
    ));
b837d2b5 Andy McCall ↶ 4613
    let heads = repo.bookmark_heads().unwrap();
75167672 Andy McCall 4614
    assert!(
4615
        heads.contains(&hj),
4616
        "the split-off part is a head of its own"
4617
    );
b837d2b5 Andy McCall ↶ 4618
    let snap = repo.load_state(&heads).unwrap().materialize();
75167672 Andy McCall 4619
    assert!(
4620
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
4621
        "the dependent was rewritten onto the new hash"
4622
    );
b837d2b5 Andy McCall ↶ 4623
    assert!(snap.files.contains_key("junk/x.lock"));
75167672 Andy McCall 4624
    let h2b = heads
4625
        .iter()
4626
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
4627
        .copied()
4628
        .unwrap();
b837d2b5 Andy McCall ↶ 4629
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
4630
    assert!(!repo.snapshot("status").unwrap().changed);
4631
    // Abandoning the split-off head removes the junk from history.
4632
    repo.abandon(&hj).unwrap();
4633
    let heads = repo.bookmark_heads().unwrap();
4634
    let snap = repo.load_state(&heads).unwrap().materialize();
4635
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
4636
    assert!(snap.files.contains_key("a.txt"));
4637
    // A dependent that touches the split-off paths blocks the split.
4638
    write(root, "junk/y.lock", b"y\n");
4639
    let hb = repo.commit("junk base", &[]).unwrap();
4640
    write(root, "junk/y.lock", b"yy\n");
4641
    write(root, "b.txt", b"b\n");
4642
    repo.commit("touches junk", &[]).unwrap();
4643
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
4644
    assert!(err.contains("depends on the split-off paths"), "{err}");
4645
}
4646
7b9809e6 Andy McCall ↶ 4647
#[test]
4648
fn bookmarks_switch_merge_and_push() {
4649
    hermetic();
4650
    let dir = tempfile::tempdir().unwrap();
4651
    let root = dir.path();
4652
    let origin = Repo::init(&root.join("origin")).unwrap();
4653
    let url = root.join("origin").to_string_lossy().to_string();
75167672 Andy McCall 4654
    let mut repo = Repo::clone(&url, &root.join("r"))
4655
        .unwrap()
4656
        .with_home(root.join("home"));
7b9809e6 Andy McCall ↶ 4657
    let r = root.join("r");
4658
    write(&r, "a.txt", b"a\n");
4659
    let h_a = repo.commit("a", &[]).unwrap();
4660
    assert!(repo.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 4661
    origin.refresh().unwrap();
7b9809e6 Andy McCall ↶ 4662
4663
    // A bookmark at the working copy's base, then work on it.
4664
    assert!(repo.bookmark_create("bad name..", None).is_err());
4665
    assert!(repo.bookmark_create("-x", None).is_err());
4666
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
4667
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
4668
    repo.bookmark_switch("feature", false).unwrap();
4669
    assert_eq!(repo.config.bookmark, "feature");
4670
    write(&r, "a.txt", b"a\nb\n");
4671
    write(&r, "b.txt", b"b\n");
4672
    let h_b = repo.commit("b on feature", &[]).unwrap();
75167672 Andy McCall 4673
    assert_eq!(
4674
        repo.bookmark_heads().unwrap(),
4675
        vec![h_b],
4676
        "b edits a.txt, so it depends on a"
4677
    );
4678
    assert_eq!(
4679
        repo.resolve_heads("main").unwrap(),
4680
        vec![h_a],
4681
        "main is untouched"
4682
    );
4683
    assert_eq!(
4684
        repo.resolve_change("feature").unwrap(),
4685
        h_b,
4686
        "a one-head bookmark names its change"
4687
    );
7b9809e6 Andy McCall ↶ 4688
    // Reopening keeps the workspace's bookmark.
4689
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
4690
    assert_eq!(reopened.config.bookmark, "feature");
4691
    // Back to main: b.txt goes away; work there.
4692
    repo.bookmark_switch("main", false).unwrap();
4693
    assert!(!r.join("b.txt").exists());
4694
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
4695
    write(&r, "c.txt", b"c\n");
4696
    let h_c = repo.commit("c on main", &[]).unwrap();
4697
    let list = repo.bookmarks().unwrap();
75167672 Andy McCall 4698
    assert_eq!(
4699
        list.iter()
4700
            .map(|b| (b.name.as_str(), b.current))
4701
            .collect::<Vec<_>>(),
4702
        vec![("feature", false), ("main", true)]
4703
    );
4704
    assert_eq!(
4705
        list.iter().find(|b| b.name == "main").unwrap().ahead,
4706
        Some(1),
4707
        "c is not on origin yet"
4708
    );
7b9809e6 Andy McCall ↶ 4709
    // Merge feature into main: the union, both heads, no merge change.
4710
    let m = repo.merge("feature").unwrap();
4711
    assert!(m.changed && m.checked_out);
4712
    let mut want = vec![h_b, h_c];
4713
    want.sort();
4714
    assert_eq!(m.heads, want);
4715
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
4716
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
4717
    assert!(repo.merge("main").is_err());
4718
    // The other bookmark can be pushed by name and appears at origin.
4719
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
767ac6cd Andy McCall 4720
    origin.refresh().unwrap();
7b9809e6 Andy McCall ↶ 4721
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
4722
    assert!(repo.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 4723
    origin.refresh().unwrap();
75167672 Andy McCall 4724
    assert_eq!(
4725
        repo.bookmarks()
4726
            .unwrap()
4727
            .iter()
4728
            .find(|b| b.name == "main")
4729
            .unwrap()
4730
            .ahead,
4731
        Some(0)
4732
    );
7b9809e6 Andy McCall ↶ 4733
    // A second workspace inherits the current bookmark and can switch independently.
4734
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
4735
    assert_eq!(ws.config.bookmark, "main");
4736
    let mut ws = ws;
4737
    ws.bookmark_switch("feature", false).unwrap();
75167672 Andy McCall 4738
    assert_eq!(
4739
        Repo::open(&r).unwrap().config.bookmark,
4740
        "main",
4741
        "the first workspace is unaffected"
4742
    );
4743
    assert!(
4744
        repo.bookmark_delete("feature").is_err(),
4745
        "current bookmark of another workspace"
4746
    );
7b9809e6 Andy McCall ↶ 4747
    ws.bookmark_switch("main", false).unwrap();
4748
    // Set and delete.
4749
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
4750
    assert!(repo.bookmark_delete("main").is_err(), "current here");
4751
    repo.bookmark_delete("feature").unwrap();
4752
    assert!(repo.resolve_heads("feature").is_err());
4753
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
75167672 Andy McCall 4754
    assert!(
4755
        repo.checkout(&[h_a], false, "checkout").is_ok(),
4756
        "changes of a deleted bookmark remain"
4757
    );
7b9809e6 Andy McCall ↶ 4758
}
4759
4dee277c Andy McCall ↶ 4760
#[test]
4761
fn oxygen_subrepos_pin_follow_and_update() {
4762
    hermetic();
4763
    let dir = tempfile::tempdir().unwrap();
4764
    let root = dir.path();
4765
    // A library repository with two commits, and a bare-ish origin for it.
4766
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
4767
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
75167672 Andy McCall 4768
    let lib = Repo::clone(&lib_url, &root.join("lib"))
4769
        .unwrap()
4770
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 4771
    write(&root.join("lib"), "lib.txt", b"v1\n");
4772
    let l1 = lib.commit("lib v1", &[]).unwrap();
4773
    assert!(lib.push("origin", false).unwrap()[0].ok);
4774
    let _ = lib_origin;
4775
4776
    // The application (a clone of its own origin) adds it as a subrepo.
4777
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
4778
    let app_url = root.join("app-origin").to_string_lossy().to_string();
4779
    let _ = app_origin;
4780
    let app_dir = root.join("app");
75167672 Andy McCall 4781
    let app = Repo::clone(&app_url, &app_dir)
4782
        .unwrap()
4783
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 4784
    write(&app_dir, "main.txt", b"app\n");
4785
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
4786
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
4787
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
4788
    let snap = app.snapshot("status").unwrap();
4789
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
75167672 Andy McCall 4790
    assert_eq!(
4791
        paths,
4792
        vec![".oxymodules", "libs/lib", "main.txt"],
4793
        "the nested files are not walked"
4794
    );
4dee277c Andy McCall ↶ 4795
    let a1 = app.commit("app with lib", &[]).unwrap();
4796
    let files = app.load_state(&[a1]).unwrap().materialize().files;
4797
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
4798
    assert!(!files.contains_key("libs/lib/lib.txt"));
4799
    assert!(!app.snapshot("status").unwrap().changed);
4800
    let subs = app.subrepos().unwrap();
4801
    assert_eq!(subs.len(), 1);
4802
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
4803
4804
    // Advance the nested repository: the parent sees a modified pin.
75167672 Andy McCall 4805
    let nested = Repo::open(&app_dir.join("libs/lib"))
4806
        .unwrap()
4807
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 4808
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
4809
    let l2 = nested.commit("lib v2", &[]).unwrap();
4810
    assert!(nested.push("origin", false).unwrap()[0].ok);
4811
    let snap = app.snapshot("status").unwrap();
75167672 Andy McCall 4812
    assert_eq!(
4813
        snap.statuses
4814
            .iter()
4815
            .map(|s| (s.path.as_str(), s.status))
4816
            .collect::<Vec<_>>(),
4817
        vec![("libs/lib", ChangeStatus::Modified)]
4818
    );
4dee277c Andy McCall ↶ 4819
    let a2 = app.commit("bump lib", &[]).unwrap();
1a3b6203 Andy McCall ↶ 4820
    // Checking out the older app state brings the nested working copy back
4821
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4dee277c Andy McCall ↶ 4822
    let r = app.checkout(&[a1], false, "checkout").unwrap();
1a3b6203 Andy McCall ↶ 4823
    assert!(
4824
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
4825
        "{:?}",
4826
        r.notes
4827
    );
4dee277c Andy McCall ↶ 4828
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
1a3b6203 Andy McCall ↶ 4829
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
4830
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
4831
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4dee277c Andy McCall ↶ 4832
    assert!(!app.snapshot("status").unwrap().changed);
4833
    // A dirty nested repository is left alone and reported.
4834
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
4835
    let r = app.checkout(&[a2], false, "checkout").unwrap();
75167672 Andy McCall 4836
    assert!(
4837
        r.notes.iter().any(|n| n.contains("uncommitted")),
4838
        "{:?}",
4839
        r.notes
4840
    );
4dee277c Andy McCall ↶ 4841
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4842
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
4843
    let r = app.submodule_update(false, &[]).unwrap();
4844
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
4845
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
4846
    let _ = l2;
4847
4848
    // A fresh clone of the app has the pin but no nested repository until update --init.
4849
    assert!(app.push("origin", false).unwrap()[0].ok);
4850
    let clone_dir = root.join("app-clone");
75167672 Andy McCall 4851
    let clone = Repo::clone(&app_url, &clone_dir)
4852
        .unwrap()
4853
        .with_home(root.join("home"));
4dee277c Andy McCall ↶ 4854
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
75167672 Andy McCall 4855
    assert_eq!(
4856
        clone.submodule_update(false, &[]).unwrap(),
4857
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
4858
    );
4859
    assert_eq!(
4860
        clone.submodule_update(true, &[]).unwrap(),
4861
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
4862
    );
4863
    assert_eq!(
4864
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
4865
        b"v2\n"
4866
    );
4dee277c Andy McCall ↶ 4867
    assert!(!clone.snapshot("status").unwrap().changed);
4868
    // Removing the subrepo leaves the directory and drops the node.
4869
    clone.submodule_remove("libs/lib").unwrap();
4870
    let snap = clone.snapshot("status").unwrap();
75167672 Andy McCall 4871
    assert!(
4872
        snap.statuses
4873
            .iter()
4874
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
4875
        "{:?}",
4876
        snap.statuses
4877
    );
4dee277c Andy McCall ↶ 4878
    let c = clone.commit("drop lib", &[]).unwrap();
75167672 Andy McCall 4879
    assert!(!clone
4880
        .load_state(&[c])
4881
        .unwrap()
4882
        .materialize()
4883
        .files
4884
        .contains_key("libs/lib"));
4dee277c Andy McCall ↶ 4885
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
75167672 Andy McCall 4886
    assert!(
4887
        !clone.snapshot("status").unwrap().changed,
4888
        "an unregistered nested repository is ignored"
4889
    );
4dee277c Andy McCall ↶ 4890
}
4891
4892
#[test]
4893
fn git_submodules_import_and_export_as_gitlinks() {
4894
    hermetic();
75167672 Andy McCall 4895
    if std::process::Command::new("git")
4896
        .arg("--version")
4897
        .output()
4898
        .is_err()
4899
    {
4dee277c Andy McCall ↶ 4900
        eprintln!("git not installed; skipping");
4901
        return;
4902
    }
4903
    let dir = tempfile::tempdir().unwrap();
4904
    let root = dir.path();
4905
    let git_in = |d: &Path, args: &[&str]| -> String {
4906
        let out = std::process::Command::new("git")
4907
            .arg("-C")
4908
            .arg(d)
75167672 Andy McCall 4909
            .args([
4910
                "-c",
4911
                "user.name=Grace",
4912
                "-c",
4913
                "[email protected]",
4914
                "-c",
4915
                "commit.gpgsign=false",
4916
                "-c",
4917
                "protocol.file.allow=always",
4918
            ])
4dee277c Andy McCall ↶ 4919
            .args(args)
4920
            .output()
4921
            .unwrap();
75167672 Andy McCall 4922
        assert!(
4923
            out.status.success(),
4924
            "git {args:?}: {}",
4925
            String::from_utf8_lossy(&out.stderr)
4926
        );
4dee277c Andy McCall ↶ 4927
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4928
    };
4929
    let sub = root.join("sub");
4930
    fs::create_dir_all(&sub).unwrap();
4931
    git_in(&sub, &["init", "-q", "-b", "main"]);
4932
    write(&sub, "s.txt", b"sub\n");
4933
    git_in(&sub, &["add", "."]);
4934
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
4935
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
4936
    let g = root.join("main.git");
4937
    fs::create_dir_all(&g).unwrap();
4938
    git_in(&g, &["init", "-q", "-b", "main"]);
4939
    write(&g, "README.md", b"# app\n");
4940
    git_in(&g, &["add", "."]);
4941
    git_in(&g, &["commit", "-q", "-m", "initial"]);
75167672 Andy McCall 4942
    git_in(
4943
        &g,
4944
        &[
4945
            "submodule",
4946
            "add",
4947
            "-q",
4948
            sub.to_str().unwrap(),
4949
            "vendor/sub",
4950
        ],
4951
    );
4dee277c Andy McCall ↶ 4952
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
4953
4954
    let dest = root.join("oxy");
4955
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
4956
    let rep = repo.import_git(&g, "main").unwrap();
4957
    assert_eq!((rep.commits, rep.submodules), (2, 1));
75167672 Andy McCall 4958
    let files = repo
4959
        .load_state(&repo.bookmark_heads().unwrap())
4960
        .unwrap()
4961
        .materialize()
4962
        .files;
4dee277c Andy McCall ↶ 4963
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
75167672 Andy McCall 4964
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
4965
        panic!()
4966
    };
4967
    assert_eq!(
4968
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
4969
        crate::subrepo::Pin::Git {
4970
            sha: sub_sha.clone(),
4971
            branch: "HEAD".into()
4972
        }
4973
    );
4974
    let modules =
4975
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
4dee277c Andy McCall ↶ 4976
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
4977
    assert!(modules.entries["vendor/sub"].git);
75167672 Andy McCall 4978
    assert!(
4979
        files.contains_key(".gitmodules"),
4980
        "the Git file is kept for round trips"
4981
    );
4982
    assert!(
4983
        !dest.join("vendor/sub/.git").exists(),
4984
        "not cloned until update --init"
4985
    );
4dee277c Andy McCall ↶ 4986
    assert!(!repo.snapshot("status").unwrap().changed);
4987
    // update --init clones it at the pinned commit; status is unchanged.
75167672 Andy McCall 4988
    assert_eq!(
4989
        repo.submodule_update(true, &[]).unwrap(),
4990
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
4991
    );
4992
    assert_eq!(
4993
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
4994
        sub_sha
4995
    );
4dee277c Andy McCall ↶ 4996
    assert!(!repo.snapshot("status").unwrap().changed);
4997
    // Export writes the gitlink and .gitmodules back.
4998
    let mirror = root.join("mirror.git");
4999
    let rep = repo.git_export(&mirror).unwrap();
5000
    assert_eq!(rep.skipped_subrepos, 0);
5001
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
75167672 Andy McCall 5002
    assert!(
5003
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
5004
        "{ls}"
5005
    );
5006
    assert_eq!(
5007
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
5008
        ".gitmodules\nREADME.md\nvendor"
5009
    );
4dee277c Andy McCall ↶ 5010
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
75167672 Andy McCall 5011
    assert_eq!(
5012
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
5013
        orig_tree,
5014
        "tree round trip"
5015
    );
4dee277c Andy McCall ↶ 5016
}
5017
957fee30 Andy McCall ↶ 5018
#[test]
5019
fn partial_commits_by_path_and_by_hunk() {
5020
    hermetic();
5021
    let dir = tempfile::tempdir().unwrap();
5022
    let root = dir.path();
5023
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5024
    write(root, "a.txt", b"1\n2\n3\n");
5025
    write(root, "b.txt", b"b\n");
5026
    let h0 = repo.commit("base", &[]).unwrap();
5027
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
5028
    write(root, "b.txt", b"b\nbb\n");
5029
    write(root, "c.txt", b"c\n");
5030
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
75167672 Andy McCall 5031
    let h1 = repo
5032
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
5033
        .unwrap();
957fee30 Andy McCall ↶ 5034
    let c1 = repo.store().get_change(&h1).unwrap();
75167672 Andy McCall 5035
    assert!(
5036
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
5037
        "{:?}",
5038
        c1.tree_ops
5039
    );
957fee30 Andy McCall ↶ 5040
    assert_eq!(c1.deps, vec![h0]);
5041
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
75167672 Andy McCall 5042
    assert!(
5043
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
5044
    );
957fee30 Andy McCall ↶ 5045
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
5046
    assert!(!files.contains_key("c.txt"));
5047
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 5048
    assert_eq!(
5049
        snap.statuses
5050
            .iter()
5051
            .map(|s| (s.path.as_str(), s.status))
5052
            .collect::<Vec<_>>(),
5053
        vec![
5054
            ("b.txt", ChangeStatus::Modified),
5055
            ("c.txt", ChangeStatus::Added)
5056
        ]
5057
    );
5058
    assert_eq!(
5059
        fs::read(root.join("b.txt")).unwrap(),
5060
        b"b\nbb\n",
5061
        "disk untouched"
5062
    );
957fee30 Andy McCall ↶ 5063
    // By hunk: pick the b.txt insert; c.txt's addition is left.
5064
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 5065
    let b_hunk = hunks
5066
        .iter()
5067
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
5068
        .unwrap()
5069
        .index;
5070
    let h2 = repo
5071
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
5072
        .unwrap();
957fee30 Andy McCall ↶ 5073
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
75167672 Andy McCall 5074
    assert!(
5075
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
5076
    );
957fee30 Andy McCall ↶ 5077
    assert!(!files.contains_key("c.txt"));
5078
    let snap = repo.snapshot("status").unwrap();
75167672 Andy McCall 5079
    assert_eq!(
5080
        snap.statuses
5081
            .iter()
5082
            .map(|s| s.path.as_str())
5083
            .collect::<Vec<_>>(),
5084
        vec!["c.txt"]
5085
    );
957fee30 Andy McCall ↶ 5086
    // Choosing only the content hunk of a file in a new directory pulls in
5087
    // the directory and file additions it needs.
5088
    write(root, "d/e.txt", b"e\n");
5089
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 5090
    let e_insert = hunks
5091
        .iter()
5092
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
5093
        .unwrap()
5094
        .index;
5095
    let h3 = repo
5096
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
5097
        .unwrap();
957fee30 Andy McCall ↶ 5098
    let c3 = repo.store().get_change(&h3).unwrap();
5099
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
5100
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
5101
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
d8c086ca Andy McCall ↶ 5102
    // Choosing a new file's addition hunk brings its content along.
5103
    write(root, "f/g.txt", b"g\n");
5104
    let (_, hunks) = repo.hunks().unwrap();
75167672 Andy McCall 5105
    let g_add = hunks
5106
        .iter()
5107
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
5108
        .unwrap()
5109
        .index;
5110
    let h4 = repo
5111
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
5112
        .unwrap();
d8c086ca Andy McCall ↶ 5113
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
75167672 Andy McCall 5114
    assert!(
5115
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
5116
    );
5117
    assert!(!repo
5118
        .snapshot("status")
5119
        .unwrap()
5120
        .statuses
5121
        .iter()
5122
        .any(|s| s.path == "f/g.txt"));
957fee30 Andy McCall ↶ 5123
    // Everything left commits normally; the working copy is then clean.
5124
    repo.commit("the rest", &[]).unwrap();
5125
    assert!(!repo.snapshot("status").unwrap().changed);
75167672 Andy McCall 5126
    let files = repo
5127
        .load_state(&repo.bookmark_heads().unwrap())
5128
        .unwrap()
5129
        .materialize()
5130
        .files;
957fee30 Andy McCall ↶ 5131
    assert!(files.contains_key("c.txt"));
5132
}
5133
5134
#[test]
5135
fn blame_attributes_lines_to_introducing_changes_across_renames() {
5136
    hermetic();
5137
    let dir = tempfile::tempdir().unwrap();
5138
    let root = dir.path();
5139
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
75167672 Andy McCall 5140
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
5141
        .unwrap();
957fee30 Andy McCall ↶ 5142
    write(root, "a.txt", b"one\n");
5143
    let h1 = repo.commit("first", &[]).unwrap();
5144
    write(root, "a.txt", b"one\ntwo\n");
5145
    let h2 = repo.commit("second", &[]).unwrap();
5146
    let b = repo.blame("a.txt").unwrap();
75167672 Andy McCall 5147
    assert_eq!(
5148
        b.iter()
5149
            .map(|l| (l.line, l.hash, l.text.as_slice()))
5150
            .collect::<Vec<_>>(),
5151
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
5152
    );
957fee30 Andy McCall ↶ 5153
    assert!(b.iter().all(|l| l.author == "Ada"));
75167672 Andy McCall 5154
    assert_eq!(
5155
        b[0].change_id,
5156
        repo.store().get_change(&h1).unwrap().change_id
5157
    );
957fee30 Andy McCall ↶ 5158
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
5159
    repo.commit("rename", &[]).unwrap();
5160
    let b = repo.blame("b.txt").unwrap();
75167672 Andy McCall 5161
    assert_eq!(
5162
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
5163
        vec![h1, h2],
5164
        "the node survives the rename"
5165
    );
957fee30 Andy McCall ↶ 5166
    assert!(repo.blame("a.txt").is_err());
5167
}
5168
5169
#[test]
5170
fn bisect_finds_the_first_bad_change() {
5171
    hermetic();
5172
    let dir = tempfile::tempdir().unwrap();
5173
    let root = dir.path();
5174
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5175
    let mut content = String::new();
5176
    let mut hashes = Vec::new();
5177
    for i in 1..=8 {
5178
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
5179
        write(root, "f.txt", content.as_bytes());
5180
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
5181
    }
5182
    // Each step appends after the previous line, so the chain is linear.
5183
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
5184
    repo.bisect_start().unwrap();
75167672 Andy McCall 5185
    assert!(matches!(
5186
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
5187
        BisectStep::NeedMarks { good: 1, bad: 0 }
5188
    ));
957fee30 Andy McCall ↶ 5189
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
75167672 Andy McCall 5190
    assert!(
5191
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
5192
        "{step:?}"
5193
    );
957fee30 Andy McCall ↶ 5194
    // Automated: bad when the bug line is present.
75167672 Andy McCall 5195
    let step = repo
5196
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
5197
        .unwrap();
957fee30 Andy McCall ↶ 5198
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
75167672 Andy McCall 5199
    assert_eq!(
5200
        repo.bisect_status().unwrap(),
5201
        Some(BisectStep::Found { culprit: hashes[4] })
5202
    );
957fee30 Andy McCall ↶ 5203
    repo.bisect_reset().unwrap();
5204
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
5205
    assert!(repo.bisect_status().unwrap().is_none());
5206
    assert!(!repo.snapshot("status").unwrap().changed);
5207
    // Manual marks and a skip.
5208
    repo.bisect_start().unwrap();
5209
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
5210
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5211
    let mut skipped_once = false;
5212
    let mut guard = 0;
5213
    while let BisectStep::Testing { .. } = step {
5214
        guard += 1;
5215
        assert!(guard < 20);
5216
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
5217
        if !skipped_once && text.contains("line 6") {
5218
            // An untestable state away from the boundary: the search routes around it.
5219
            skipped_once = true;
5220
            step = repo.bisect_mark(None, &[]).unwrap();
5221
            continue;
5222
        }
5223
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
5224
    }
5225
    assert!(skipped_once);
5226
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
5227
    repo.bisect_reset().unwrap();
5228
    // Skipping the culprit itself leaves it among the candidates reported.
5229
    repo.bisect_start().unwrap();
5230
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
5231
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5232
    let mut guard = 0;
5233
    while let BisectStep::Testing { heads, .. } = &step {
5234
        guard += 1;
5235
        assert!(guard < 20);
5236
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
75167672 Andy McCall 5237
        let is_culprit_state =
5238
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
5239
        step = if is_culprit_state {
5240
            repo.bisect_mark(None, &[]).unwrap()
5241
        } else {
5242
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
5243
        };
957fee30 Andy McCall ↶ 5244
    }
5245
    match step {
75167672 Andy McCall 5246
        BisectStep::Inconclusive { candidates } => assert!(
5247
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
5248
            "{candidates:?}"
5249
        ),
957fee30 Andy McCall ↶ 5250
        other => panic!("{other:?}"),
5251
    }
5252
    repo.bisect_reset().unwrap();
5253
}
5254
728da0f9 Andy McCall ↶ 5255
#[test]
5256
fn squash_folds_a_change_into_its_dependency() {
5257
    hermetic();
5258
    let dir = tempfile::tempdir().unwrap();
5259
    let root = dir.path();
5260
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5261
    write(root, "a.txt", b"1\n");
5262
    let a = repo.commit("A", &[]).unwrap();
5263
    write(root, "a.txt", b"1\n2\n");
5264
    let c = repo.commit("C", &[]).unwrap();
5265
    write(root, "a.txt", b"1\n2\n3\n");
5266
    let e = repo.commit("E", &[]).unwrap();
5267
    write(root, "b.txt", b"b\n");
5268
    let b = repo.commit("B", &[]).unwrap();
5269
    let id_a = repo.store().get_change(&a).unwrap().change_id;
5270
    let id_e = repo.store().get_change(&e).unwrap().change_id;
5271
    // E depends on C which A lacks: refused, naming it.
5272
    let err = repo.squash(&e, &a).unwrap_err().to_string();
5273
    assert!(err.contains(&c.short(12)), "{err}");
5274
    // C into A: A' has both, C is gone, E follows and still reads the same.
5275
    let a2 = repo.squash(&c, &a).unwrap();
5276
    let a2c = repo.store().get_change(&a2).unwrap();
5277
    assert_eq!(a2c.change_id, id_a);
5278
    assert!(a2c.deps.is_empty());
5279
    let heads = repo.bookmark_heads().unwrap();
5280
    let st = repo.load_state(&heads).unwrap();
5281
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
75167672 Andy McCall 5282
    let e2 = st
5283
        .changes()
5284
        .find(|(_, m)| m.change_id == id_e)
5285
        .map(|(h, _)| *h)
5286
        .unwrap();
5287
    assert_eq!(
5288
        repo.store().get_change(&e2).unwrap().deps,
5289
        vec![a2],
5290
        "E now depends on A' alone"
5291
    );
728da0f9 Andy McCall ↶ 5292
    let files = st.materialize().files;
75167672 Andy McCall 5293
    assert!(
5294
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
5295
    );
728da0f9 Andy McCall ↶ 5296
    assert!(files.contains_key("b.txt"));
5297
    assert!(st.contains(&b));
5298
    assert!(!repo.snapshot("status").unwrap().changed);
5299
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
5300
    // Undo restores the three original changes.
5301
    repo.undo().unwrap();
5302
    repo.undo().unwrap();
5303
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
5304
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
5305
}
5306
5307
#[test]
5308
fn rebase_re_expresses_a_change_against_another_base() {
5309
    hermetic();
5310
    let dir = tempfile::tempdir().unwrap();
5311
    let root = dir.path();
5312
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5313
    write(root, "a.txt", b"1\n2\n");
5314
    let a = repo.commit("A", &[]).unwrap();
5315
    write(root, "a.txt", b"1\n2\n3\n");
5316
    let c = repo.commit("C: append 3", &[]).unwrap();
5317
    write(root, "a.txt", b"1\n2\n3\n4\n");
5318
    let e = repo.commit("E: append 4", &[]).unwrap();
5319
    // A different base: A plus a change that prepends a line.
5320
    repo.checkout(&[a], true, "checkout").unwrap();
5321
    write(root, "a.txt", b"0\n1\n2\n");
5322
    let d = repo.commit("D: prepend 0", &[]).unwrap();
5323
    let id_c = repo.store().get_change(&c).unwrap().change_id;
5324
    let id_e = repo.store().get_change(&e).unwrap().change_id;
5325
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
5326
    let c2 = repo.rebase(&c, &[d]).unwrap();
5327
    let c2c = repo.store().get_change(&c2).unwrap();
5328
    assert_eq!(c2c.change_id, id_c);
5329
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
5330
    let heads = repo.bookmark_heads().unwrap();
5331
    let st = repo.load_state(&heads).unwrap();
5332
    assert!(!st.contains(&c) && st.contains(&d));
75167672 Andy McCall 5333
    let e2 = st
5334
        .changes()
5335
        .find(|(_, m)| m.change_id == id_e)
5336
        .map(|(h, _)| *h)
5337
        .unwrap();
728da0f9 Andy McCall ↶ 5338
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
75167672 Andy McCall 5339
    assert!(
5340
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
5341
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
5342
    );
728da0f9 Andy McCall ↶ 5343
    let files = st.materialize().files;
75167672 Andy McCall 5344
    assert!(
5345
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
5346
        "{:?}",
5347
        files["a.txt"].content
5348
    );
728da0f9 Andy McCall ↶ 5349
    assert!(!files["a.txt"].is_conflicted());
5350
    // Rebasing onto a state that already contains the change is refused.
5351
    assert!(repo.rebase(&c2, &[c2]).is_err());
5352
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
75167672 Andy McCall 5353
    assert!(
5354
        err.contains("lacks dependencies"),
5355
        "E needs C, which D's state does not have: {err}"
5356
    );
728da0f9 Andy McCall ↶ 5357
}
5358
c792033a Andy McCall ↶ 5359
#[test]
5360
fn unsigned_tags_keep_their_message() {
5361
    hermetic();
5362
    let dir = tempfile::tempdir().unwrap();
5363
    let root = dir.path();
5364
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5365
    write(root, "a.txt", b"a\n");
5366
    repo.commit("a", &[]).unwrap();
5367
    assert!(repo.secret_key().unwrap().is_none());
75167672 Andy McCall 5368
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
5369
        .unwrap();
c792033a Andy McCall ↶ 5370
    let tags = repo.tags().unwrap();
75167672 Andy McCall 5371
    assert_eq!(
5372
        (
5373
            tags[0].name.as_str(),
5374
            tags[0].message.as_str(),
5375
            tags[0].signer.as_deref()
5376
        ),
5377
        ("v1", "first release", None)
5378
    );
5379
    assert!(
5380
        repo.tag_refs().unwrap()[0].attestation.is_none(),
5381
        "an unsigned attestation is not advertised"
5382
    );
c792033a Andy McCall ↶ 5383
}
387335ff Andy McCall ↶ 5384
5385
#[test]
5386
fn fsck_passes_a_sound_repository_and_names_each_fault() {
64818938 Andy McCall ↶ 5387
    // Files on disk are what this tests: tampering with them, and the
5388
    // directory store's crash points.
5389
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5390
        return;
5391
    }
387335ff Andy McCall ↶ 5392
    hermetic();
5393
    let dir = tempfile::tempdir().unwrap();
5394
    let root = dir.path();
5395
    let origin_path = root.join("origin");
5396
    let origin = Repo::init(&origin_path).unwrap();
5397
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
5398
        .unwrap()
5399
        .with_home(root.join("home-a"));
5400
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5401
        .unwrap();
5402
    write(&root.join("a"), "f.txt", b"one\n");
5403
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
5404
    let h1 = a.commit("first", &[]).unwrap();
5405
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
5406
    let h2 = a.commit("second", &[]).unwrap();
5407
    a.tag_create("v1", &[h2], "first release").unwrap();
5408
    a.checkpoint().unwrap();
5409
    assert!(a.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 5410
    origin.refresh().unwrap();
387335ff Andy McCall ↶ 5411
5412
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
5413
    for repo in [&a, &origin] {
5414
        let rep = repo.fsck().unwrap();
5415
        assert_eq!(rep.problems, vec![], "{rep:?}");
5416
        // The two commits, plus the working copy's change in `a`.
5417
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
5418
        assert!(rep.ops > 1 && rep.objects > 5);
5419
    }
5420
    assert!(origin.fsck().unwrap().attestations >= 1);
5421
5422
    // A flipped byte in a stored object is corruption, named by hash.
5423
    let c1 = a.store().path_for(&h1);
5424
    let pristine = fs::read(&c1).unwrap();
5425
    let mut bytes = pristine.clone();
5426
    *bytes.last_mut().unwrap() ^= 1;
5427
    fs::write(&c1, &bytes).unwrap();
5428
    let rep = a.fsck().unwrap();
5429
    assert!(rep.errors() >= 1);
5430
    assert!(
5431
        rep.problems
5432
            .iter()
5433
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
5434
        "{rep:?}"
5435
    );
5436
    fs::write(&c1, &pristine).unwrap();
5437
    assert_eq!(a.fsck().unwrap().errors(), 0);
5438
5439
    // A missing change is named with what needed it.
5440
    fs::remove_file(&c1).unwrap();
5441
    let rep = a.fsck().unwrap();
5442
    assert!(
5443
        rep.problems.iter().any(|p| p.severity == Severity::Error
5444
            && p.object == Some(h1)
5445
            && p.what.contains("change missing, needed by change")),
5446
        "{rep:?}"
5447
    );
5448
    fs::write(&c1, &pristine).unwrap();
5449
5450
    // A missing blob is an error in a full clone.
5451
    let c2 = a.store().get_change(&h1).unwrap();
5452
    let blob = c2
5453
        .edits
5454
        .iter()
5455
        .find_map(|e| match e {
5456
            Edit::Replace { new: Some(b), .. } => Some(*b),
5457
            _ => None,
5458
        })
5459
        .expect("the binary file is a blob");
5460
    let bp = a.store().path_for(&blob);
5461
    let blob_bytes = fs::read(&bp).unwrap();
5462
    fs::remove_file(&bp).unwrap();
5463
    let rep = a.fsck().unwrap();
5464
    assert!(
5465
        rep.problems
5466
            .iter()
5467
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
5468
        "{rep:?}"
5469
    );
5470
    fs::write(&bp, &blob_bytes).unwrap();
5471
5472
    // A broken op log head is reported, not a crash.
5473
    let head = root.join("a/.oxy/ops/head");
5474
    let saved = fs::read(&head).unwrap();
5475
    fs::write(&head, b"not a hash").unwrap();
5476
    let rep = a.fsck().unwrap();
5477
    assert!(
5478
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
5479
        "{rep:?}"
5480
    );
5481
    fs::write(&head, saved).unwrap();
5482
    assert_eq!(a.fsck().unwrap().problems, vec![]);
5483
}
4dcb8c09 Andy McCall ↶ 5484
5485
/// Copy a directory tree (for restoring a pristine repository).
5486
fn copy_tree(from: &Path, to: &Path) {
5487
    fs::create_dir_all(to).unwrap();
5488
    for e in fs::read_dir(from).unwrap() {
5489
        let e = e.unwrap();
5490
        let target = to.join(e.file_name());
5491
        if e.file_type().unwrap().is_dir() {
5492
            copy_tree(&e.path(), &target);
5493
        } else {
5494
            fs::copy(e.path(), &target).unwrap();
5495
        }
5496
    }
5497
}
5498
5499
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
5500
/// would, and check that both repositories still open, pass `fsck`, and
5501
/// accept the same operation again.
5502
#[test]
5503
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
64818938 Andy McCall ↶ 5504
    // Files on disk are what this tests: tampering with them, and the
5505
    // directory store's crash points.
5506
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5507
        return;
5508
    }
4dcb8c09 Andy McCall ↶ 5509
    use crate::durable::failpoint;
5510
    hermetic();
5511
    let dir = tempfile::tempdir().unwrap();
5512
    let pristine = dir.path().join("pristine");
5513
    let origin_path = pristine.join("origin");
5514
    Repo::init(&origin_path).unwrap();
5515
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
5516
        .unwrap()
5517
        .with_home(dir.path().join("home"));
5518
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5519
        .unwrap();
5520
    write(&pristine.join("a"), "f.txt", b"one\n");
5521
    a.commit("first", &[]).unwrap();
5522
    assert!(a.push("origin", false).unwrap()[0].ok);
5523
    drop(a);
5524
5525
    type Op = fn(&Repo) -> Result<()>;
5526
    let edit_and_commit: Op = |r| {
5527
        write(r.root(), "f.txt", b"one\ntwo\n");
5528
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
5529
        r.commit("second", &[]).map(|_| ())
5530
    };
5531
    let push: Op = |r| {
5532
        let res = r.push("origin", false)?;
5533
        if res.iter().all(|x| x.ok) {
5534
            Ok(())
5535
        } else {
5536
            Err(RepoError::Msg(format!("{res:?}")))
5537
        }
5538
    };
5539
5540
    for (name, prepare, op) in [
5541
        ("commit", None, edit_and_commit),
5542
        ("push", Some(edit_and_commit), push),
5543
    ] {
5544
        let mut steps = 0;
5545
        for n in 1.. {
5546
            let run = dir.path().join(format!("{name}-{n}"));
5547
            copy_tree(&pristine, &run);
5548
            // Clones record their remote by path; point it at this copy.
5549
            let open = |p: &Path| {
5550
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
5551
                r.config
5552
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
5553
                    .unwrap();
5554
                r.save_config().unwrap();
5555
                r
5556
            };
5557
            let a = open(&run.join("a"));
5558
            if let Some(prep) = prepare {
5559
                prep(&a).unwrap();
5560
            }
5561
            failpoint::crash_after(n);
5562
            let outcome = op(&a);
5563
            let crashed = failpoint::disarm();
5564
            drop(a);
5565
            if !crashed {
5566
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
5567
                steps = n - 1;
5568
                break;
5569
            }
5570
            assert!(
5571
                outcome.is_err(),
5572
                "{name}: a crash at step {n} was swallowed"
5573
            );
5574
            for repo in ["a", "origin"] {
5575
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
5576
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
5577
                });
5578
                let rep = r.fsck().unwrap();
5579
                assert_eq!(
5580
                    rep.errors(),
5581
                    0,
5582
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
5583
                    rep.problems
5584
                );
5585
            }
5586
            // The interrupted operation can simply be run again.
5587
            let a = open(&run.join("a"));
5588
            // A crash after the commit point leaves the commit done.
5589
            let landed = a
5590
                .bookmark_heads()
5591
                .unwrap()
5592
                .iter()
5593
                .any(|h| a.store().get_change(h).unwrap().message == "second");
5594
            let again = match (name, landed) {
5595
                ("commit", true) => Ok(()),
5596
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
5597
                _ => op(&a),
5598
            };
5599
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
5600
            assert_eq!(a.fsck().unwrap().errors(), 0);
5601
            fs::remove_dir_all(&run).unwrap();
5602
        }
5603
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
5604
    }
5605
}
19555025 Andy McCall ↶ 5606
5607
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
5608
/// running at the same time lose nothing: every commit ends up on the
5609
/// bookmark, locally and on the remote, and the repository passes fsck.
5610
#[test]
5611
fn concurrent_commits_in_two_workspaces_lose_nothing() {
5612
    hermetic();
5613
    let dir = tempfile::tempdir().unwrap();
5614
    let root = dir.path();
5615
    let origin = root.join("origin");
5616
    Repo::init_bare_unbound(&origin).unwrap();
5617
    let main = root.join("main");
5618
    let mut repo = Repo::init(&main).unwrap();
5619
    repo.config
5620
        .set("remote.origin.url", &origin.to_string_lossy())
5621
        .unwrap();
5622
    repo.save_config().unwrap();
5623
    write(&main, "seed.txt", b"seed\n");
5624
    repo.commit("seed", &[]).unwrap();
5625
    let second = root.join("second");
5626
    repo.workspace_add(&second, None).unwrap();
5627
    drop(repo);
5628
5629
    const EACH: usize = 15;
5630
    std::thread::scope(|s| {
5631
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
5632
            s.spawn(move || {
5633
                let r = Repo::open(&dir).unwrap();
5634
                for i in 0..EACH {
5635
                    write(
5636
                        &dir,
5637
                        &format!("{tag}-{i}.txt"),
5638
                        format!("{tag} {i}\n").as_bytes(),
5639
                    );
5640
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
5641
                    if push && i % 5 == 4 {
5642
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
5643
                        let _ = r.push("origin", false);
5644
                    }
5645
                }
5646
            });
5647
        }
5648
    });
5649
5650
    let repo = Repo::open(&main).unwrap();
5651
    let heads = repo.bookmark_heads().unwrap();
5652
    let state = repo.load_state(&heads).unwrap();
5653
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
5654
    for tag in ["a", "b"] {
5655
        for i in 0..EACH {
5656
            assert!(
5657
                messages.contains(&format!("{tag} {i}")),
5658
                "lost commit {tag} {i}; have {messages:?}"
5659
            );
5660
        }
5661
    }
5662
    let rep = repo.fsck().unwrap();
5663
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
5664
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
5665
    let hosted = Repo::open(&origin).unwrap();
5666
    let hosted_heads = hosted.bookmark_heads().unwrap();
5667
    assert_eq!(
5668
        hosted.load_state(&hosted_heads).unwrap().len(),
5669
        state.len(),
5670
        "the remote has every commit"
5671
    );
5672
}
5673
5674
/// Two operations recorded from the same parent (what two processes do
5675
/// when they race) are merged: both bookmarks' heads survive, and a
5676
/// change made on one side only is kept.
5677
#[test]
5678
fn operations_from_the_same_parent_are_merged() {
5679
    hermetic();
5680
    let dir = tempfile::tempdir().unwrap();
5681
    let root = dir.path();
5682
    let repo = Repo::init(root).unwrap();
5683
    write(root, "a.txt", b"a\n");
5684
    let a = repo.commit("a", &[]).unwrap();
5685
    write(root, "b.txt", b"b\n");
5686
    let b = repo.commit("b", &[]).unwrap();
5687
    let (x, op) = repo.head_op().unwrap();
5688
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
5689
5690
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
5691
    let mut one = op.view.clone();
5692
    one.bookmarks.insert("main".into(), state(vec![a]));
5693
    one.bookmarks.insert("topic".into(), state(vec![a]));
5694
    let mut two = op.view.clone();
5695
    two.bookmarks.insert("main".into(), state(vec![b]));
5696
    repo.record_op(&[x], "one", one).unwrap();
5697
    let merged = repo.record_op(&[x], "two", two).unwrap();
5698
5699
    let (head, op) = repo.head_op().unwrap();
5700
    assert_eq!(head, merged);
5701
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
5702
    assert!(op.command.contains("merged with a concurrent operation"));
5703
    let mut main = repo
5704
        .store()
5705
        .get_state(&op.view.bookmarks["main"])
5706
        .unwrap()
5707
        .heads;
5708
    main.sort();
5709
    let mut want = vec![a, b];
5710
    want.sort();
5711
    assert_eq!(main, want, "both sides' heads are kept");
5712
    assert!(
5713
        op.view.bookmarks.contains_key("topic"),
5714
        "a one-sided change survives"
5715
    );
5716
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5717
}
3e5772cc Andy McCall ↶ 5718
5719
#[test]
5720
fn failed_requests_come_with_a_next_step() {
5721
    use crate::protocol::hint_for;
5722
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
5723
        .unwrap()
5724
        .contains("token"));
5725
    assert!(hint_for("…: HTTP 403: forbidden")
5726
        .unwrap()
5727
        .contains("repo:write"));
5728
    assert!(hint_for("…: HTTP 404: no such repository")
5729
        .unwrap()
5730
        .contains("owner and repository name"));
5731
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
5732
        .unwrap()
5733
        .contains("oxyhub-ca.pem"));
5734
    assert!(hint_for("Connect error: Connection refused (os error 111)")
5735
        .unwrap()
5736
        .contains("running"));
5737
    assert!(hint_for("Dns Failed: failed to lookup address information")
5738
        .unwrap()
5739
        .contains("resolve"));
5740
    assert_eq!(hint_for("something else entirely"), None);
5741
}
5742
5743
#[test]
5744
fn doctor_names_problems_and_what_to_do() {
5745
    hermetic();
5746
    let dir = tempfile::tempdir().unwrap();
5747
    let root = dir.path();
5748
    let origin = root.join("origin");
5749
    Repo::init_bare_unbound(&origin).unwrap();
5750
    let mut repo = Repo::init(&root.join("r"))
5751
        .unwrap()
5752
        .with_home(root.join("home"));
5753
    let find = |r: &DoctorReport, area: &str, h: Health| {
5754
        r.checks
5755
            .iter()
5756
            .find(|c| c.area == area && c.health == h)
5757
            .cloned()
5758
    };
5759
5760
    let r = repo.doctor(true);
5761
    assert!(find(&r, "identity", Health::Warn)
5762
        .unwrap()
5763
        .hint
5764
        .unwrap()
5765
        .contains("oxy identity create"));
5766
    assert!(find(&r, "repository", Health::Ok).is_some());
ad2496f7 Andy McCall ↶ 5767
    // oxygen#127: no policy is said, with who sets one.
5768
    assert!(find(&r, "trust", Health::Warn)
5769
        .unwrap()
5770
        .hint
5771
        .unwrap()
5772
        .contains("oxy policy init"));
3e5772cc Andy McCall ↶ 5773
5774
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5775
        .unwrap();
ad2496f7 Andy McCall ↶ 5776
    repo.policy_init().unwrap();
5777
    let r = repo.doctor(false);
5778
    let trust = find(&r, "trust", Health::Ok).expect("a fresh policy is fine");
5779
    assert!(
5780
        trust.message.contains("serial 1") && trust.message.contains("1 root"),
5781
        "{trust:?}"
5782
    );
3e5772cc Andy McCall ↶ 5783
    repo.config.set("author.name", "Ada").unwrap();
5784
    repo.config.set("author.email", "[email protected]").unwrap();
5785
    repo.config
5786
        .set("remote.origin.url", &origin.to_string_lossy())
5787
        .unwrap();
5788
    repo.config
5789
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
5790
        .unwrap();
5791
    repo.config.set("remote.down.token", "t").unwrap();
5792
    repo.config
5793
        .set("remote.badca.url", "https://example.invalid/a/b")
5794
        .unwrap();
5795
    repo.config
5796
        .set(
5797
            "remote.badca.ca",
5798
            &root.join("missing.pem").to_string_lossy(),
5799
        )
5800
        .unwrap();
5801
    repo.save_config().unwrap();
5802
5803
    let r = repo.doctor(true);
5804
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
5805
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
5806
    assert!(find(&r, "remote origin", Health::Ok)
5807
        .unwrap()
5808
        .message
5809
        .contains("first push binds it"));
5810
    let down = find(&r, "remote down", Health::Fail).unwrap();
5811
    assert!(
5812
        down.hint.as_deref().unwrap_or("").contains("running"),
5813
        "{down:?}"
5814
    );
5815
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
5816
    assert!(
5817
        badca.hint.unwrap().contains("remote.badca.ca"),
5818
        "the remote's own name is in the hint"
5819
    );
5820
    assert_eq!(r.worst(), Health::Fail);
5821
5822
    // Offline, nothing is contacted.
5823
    let r = repo.doctor(false);
5824
    assert!(find(&r, "remote down", Health::Fail).is_none());
5825
    assert!(find(&r, "remote down", Health::Ok)
5826
        .unwrap()
5827
        .message
5828
        .contains("not contacted"));
5829
}
62794ecc Andy McCall ↶ 5830
5831
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
5832
/// after it. Inserting after `b` and then deleting `b`, one commit after
5833
/// the other, must not leave a delete/insert conflict.
5834
#[test]
5835
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
5836
    hermetic();
5837
    let dir = tempfile::tempdir().unwrap();
5838
    let root = dir.path();
5839
    let repo = Repo::init(root).unwrap();
5840
    write(root, "f", b"a\nb\nc\n");
5841
    repo.commit("base", &[]).unwrap();
5842
    write(root, "f", b"a\nb\nx\nc\n");
5843
    let insert = repo.commit("insert x after b", &[]).unwrap();
5844
    write(root, "f", b"a\nx\nc\n");
5845
    let delete = repo.commit("delete b", &[]).unwrap();
5846
    assert!(
5847
        repo.store()
5848
            .get_change(&delete)
5849
            .unwrap()
5850
            .deps
5851
            .contains(&insert),
5852
        "the deletion depends on the insertion below the deleted line"
5853
    );
5854
    let heads = repo.bookmark_heads().unwrap();
5855
    assert_eq!(heads, vec![delete]);
5856
    let snap = repo.load_state(&heads).unwrap().materialize();
5857
    assert!(!snap.is_conflicted());
5858
    assert!(
5859
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
5860
    );
5861
}
5862
5863
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
5864
/// replacement depends on the change that set the blob it replaces.
5865
#[test]
5866
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
5867
    hermetic();
5868
    let dir = tempfile::tempdir().unwrap();
5869
    let root = dir.path();
5870
    let repo = Repo::init(root).unwrap();
5871
    write(root, "bin", b"\0A");
5872
    let v1 = repo.commit("v1", &[]).unwrap();
5873
    write(root, "bin", b"\0B");
5874
    let v2 = repo.commit("v2", &[]).unwrap();
5875
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
5876
    write(root, "bin", b"\0A");
5877
    let v3 = repo.commit("back to A", &[]).unwrap();
5878
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
5879
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
5880
    let state = repo.load_state(&[v3]).unwrap();
5881
    let snap = state.materialize();
5882
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
5883
        panic!("opaque")
5884
    };
5885
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
5886
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
5887
}
5888
5889
/// Spec §23: a binary file changed on two branches and merged in Git to
5890
/// one side's version comes back as that version at the merge, and the
5891
/// import verifies commit by commit.
5892
#[test]
5893
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
5894
    hermetic();
5895
    if std::process::Command::new("git")
5896
        .arg("--version")
5897
        .output()
5898
        .is_err()
5899
    {
5900
        eprintln!("git not installed; skipping");
5901
        return;
5902
    }
5903
    let dir = tempfile::tempdir().unwrap();
5904
    let root = dir.path();
5905
    let g = root.join("src.git");
5906
    fs::create_dir_all(&g).unwrap();
5907
    let git = |args: &[&str]| -> String {
5908
        let out = std::process::Command::new("git")
5909
            .arg("-C")
5910
            .arg(&g)
5911
            .args([
5912
                "-c",
5913
                "user.name=Grace",
5914
                "-c",
5915
                "[email protected]",
5916
                "-c",
5917
                "commit.gpgsign=false",
5918
            ])
5919
            .args(args)
5920
            .output()
5921
            .unwrap();
5922
        assert!(
5923
            out.status.success(),
5924
            "git {args:?}: {}",
5925
            String::from_utf8_lossy(&out.stderr)
5926
        );
5927
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5928
    };
5929
    git(&["init", "-q", "-b", "main"]);
5930
    write(&g, "logo.bin", b"\0base");
5931
    write(&g, "notes.txt", b"a\nb\nc\n");
5932
    git(&["add", "."]);
5933
    git(&["commit", "-qm", "base"]);
5934
    git(&["checkout", "-qb", "side"]);
5935
    write(&g, "logo.bin", b"\0side");
5936
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
5937
    git(&["commit", "-qam", "side"]);
5938
    git(&["checkout", "-q", "main"]);
5939
    write(&g, "logo.bin", b"\0main");
5940
    git(&["commit", "-qam", "main"]);
5941
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
5942
    let _ = std::process::Command::new("git")
5943
        .arg("-C")
5944
        .arg(&g)
5945
        .args([
5946
            "-c",
5947
            "user.name=G",
5948
            "-c",
5949
            "user.email=g@e",
5950
            "merge",
5951
            "-q",
5952
            "side",
5953
        ])
5954
        .output();
5955
    write(&g, "logo.bin", b"\0main");
5956
    git(&["add", "."]);
5957
    git(&["commit", "-qm", "merge side"]);
5958
    // Then a revert of the binary to its first version.
5959
    write(&g, "logo.bin", b"\0base");
5960
    git(&["commit", "-qam", "back to base"]);
5961
5962
    let repo = Repo::init(&root.join("o")).unwrap();
5963
    let rep = repo.import_git(&g, "main").unwrap();
5964
    assert_eq!(rep.merges, 1);
5965
    let v = repo.verify_git_import(&g, "main").unwrap();
5966
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
5967
    assert_eq!(v.commits, 5);
5968
    let snap = repo
5969
        .load_state(&repo.bookmark_heads().unwrap())
5970
        .unwrap()
5971
        .materialize();
5972
    assert!(!snap.is_conflicted());
5973
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
5974
        panic!("opaque")
5975
    };
5976
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
5977
}
c863c7a7 Andy McCall ↶ 5978
5979
/// Spec §7.7 on a file system without executable bits or symlinks: the
5980
/// recorded bit is kept, and a symlink checked out as a plain file holding
5981
/// its target is still that symlink.
5982
#[cfg(unix)]
5983
#[test]
5984
fn windows_file_systems_keep_exec_bits_and_symlinks() {
5985
    use crate::portable::Platform;
5986
    use std::os::unix::fs::PermissionsExt;
5987
    hermetic();
5988
    let dir = tempfile::tempdir().unwrap();
5989
    let root = dir.path();
5990
    let repo = Repo::init(root).unwrap();
5991
    write(root, "run.sh", b"#!/bin/sh\n");
5992
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
5993
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
5994
    repo.commit("script and link", &[]).unwrap();
5995
    drop(repo);
5996
5997
    // What checking out on Windows leaves: no exec bit, the link as a file.
5998
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
5999
    fs::remove_file(root.join("link")).unwrap();
6000
    write(root, "link", b"run.sh");
6001
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
6002
    let s = win.snapshot("oxy status").unwrap();
6003
    assert!(
6004
        s.statuses.is_empty(),
6005
        "nothing changed on Windows: {:?}",
6006
        statuses(&s)
6007
    );
6008
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
6009
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
6010
    write(root, "link", b"other");
6011
    let h = win.commit("edit on Windows", &[]).unwrap();
6012
    let snap = win.load_state(&[h]).unwrap().materialize();
6013
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
6014
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
6015
    // The same working copy read as Linux sees the lost bit and the plain file.
6016
    let linux = Repo::open(root).unwrap();
6017
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
6018
}
6019
6020
/// Paths that collide on case-insensitive or Windows file systems are
6021
/// named at checkout there, and by doctor everywhere.
6022
#[test]
6023
fn paths_other_platforms_cannot_hold_are_reported() {
6024
    use crate::portable::Platform;
6025
    hermetic();
6026
    let dir = tempfile::tempdir().unwrap();
6027
    let root = dir.path();
6028
    let repo = Repo::init(root).unwrap();
6029
    write(root, "README.md", b"a\n");
6030
    write(root, "readme.md", b"b\n");
6031
    write(root, "src/aux.c", b"int x;\n");
6032
    let h = repo.commit("unportable", &[]).unwrap();
6033
    let r = repo.doctor(false);
6034
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
6035
    assert_eq!(port.health, Health::Warn);
6036
    assert!(
6037
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
6038
        "{}",
6039
        port.message
6040
    );
6041
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
6042
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
6043
    assert!(
6044
        rep.notes
6045
            .iter()
6046
            .any(|n| n.contains("README.md and readme.md")),
6047
        "{:?}",
6048
        rep.notes
6049
    );
6050
    assert!(
6051
        !rep.notes.iter().any(|n| n.contains("aux.c")),
6052
        "macOS allows aux.c"
6053
    );
6054
}
bc489b6c Andy McCall ↶ 6055
6056
#[test]
6057
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
6058
    hermetic();
6059
    let dir = tempfile::tempdir().unwrap();
6060
    let repo = Repo::init(dir.path()).unwrap();
6061
    write(dir.path(), "a.txt", b"one\n");
6062
    write(dir.path(), "other.txt", b"x\n");
6063
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
6064
    repo.snapshot("t").unwrap();
6065
    let c1 = repo.commit("first", &[]).unwrap();
6066
    write(dir.path(), "other.txt", b"y\n");
6067
    repo.snapshot("t").unwrap();
6068
    repo.commit("other only", &[]).unwrap();
6069
    write(dir.path(), "a.txt", b"one\ntwo\n");
6070
    repo.snapshot("t").unwrap();
6071
    let c3 = repo.commit("second line", &[]).unwrap();
6072
    write(dir.path(), "other.txt", b"z\n");
6073
    repo.snapshot("t").unwrap();
6074
    repo.commit("other again", &[]).unwrap();
6075
6076
    let heads = repo.bookmark_heads().unwrap();
6077
    let state = repo.load_state(&heads).unwrap();
6078
    let full: Vec<ChangeHash> = repo
6079
        .log_for_path_in("a.txt", &heads)
6080
        .unwrap()
6081
        .iter()
6082
        .map(|e| e.hash)
6083
        .collect();
6084
    assert_eq!(
6085
        full,
6086
        vec![c3, c1],
6087
        "newest first, only changes touching the path"
6088
    );
6089
    let newest: Vec<ChangeHash> = repo
6090
        .log_for_path_of(&state, "a.txt", Some(1))
6091
        .unwrap()
6092
        .iter()
6093
        .map(|e| e.hash)
6094
        .collect();
6095
    assert_eq!(newest, vec![c3], "stops at the first");
6096
    assert_eq!(
6097
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
6098
        2
6099
    );
6100
    assert!(repo
6101
        .log_for_path_of(&state, "missing.txt", Some(1))
6102
        .is_err());
6103
    assert_eq!(
6104
        repo.log_state(&heads).unwrap().len(),
6105
        repo.log_of(&state).len()
6106
    );
6107
6108
    let tree = state.tree().view();
6109
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
6110
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
6111
    assert_eq!(
6112
        via_state
6113
            .iter()
6114
            .map(|l| (l.hash, l.text.clone()))
6115
            .collect::<Vec<_>>(),
6116
        via_heads
6117
            .iter()
6118
            .map(|l| (l.hash, l.text.clone()))
6119
            .collect::<Vec<_>>()
6120
    );
6121
    assert_eq!(
6122
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
6123
        vec![c1, c3]
6124
    );
6125
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
6126
}
696bbf29 Andy McCall ↶ 6127
6128
/// A text file whose stat matches the manifest and whose recorded hash is
6129
/// the base's content is taken from the base without reading it; anything
6130
/// else is read, so no edit is missed (spec §12.3).
6131
#[cfg(unix)]
6132
#[test]
6133
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
6134
    use std::os::unix::fs::PermissionsExt;
6135
    hermetic();
6136
    let dir = tempfile::tempdir().unwrap();
6137
    let root = dir.path();
6138
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6139
    write(root, "a.txt", b"one\ntwo\n");
6140
    write(root, "b.txt", b"bee\n");
6141
    repo.commit("base", &[]).unwrap();
6142
    let age = |p: &str| {
6143
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6144
        fs::File::options()
6145
            .write(true)
6146
            .open(root.join(p))
6147
            .unwrap()
6148
            .set_modified(old)
6149
            .unwrap();
6150
    };
6151
    age("a.txt");
6152
    age("b.txt");
6153
    assert!(
6154
        !repo.snapshot("status").unwrap().changed,
6155
        "records the aged stat"
6156
    );
6157
6158
    // Clean and equal to the base: not read at all.
6159
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6160
    let snap = repo.snapshot("status").unwrap();
6161
    assert!(
6162
        !snap.changed && snap.statuses.is_empty(),
6163
        "{:?}",
6164
        snap.statuses
6165
    );
6166
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6167
6168
    // An uncommitted edit that is older than the manifest: stat-clean, but
6169
    // its hash is not the base's, so it is read and stays visible.
6170
    write(root, "b.txt", b"bee edited\n");
6171
    age("b.txt");
6172
    let first = repo.snapshot("status").unwrap();
6173
    assert_eq!(
6174
        statuses(&first),
6175
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
6176
    );
6177
    let again = repo.snapshot("status").unwrap();
6178
    assert_eq!(
6179
        statuses(&again),
6180
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
6181
        "still seen once stat-clean"
6182
    );
6183
    assert!(!again.changed, "and the working copy hashes the same");
6184
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6185
    assert!(
6186
        repo.snapshot("status").is_err(),
6187
        "an edited file must be read, never taken from the base"
6188
    );
6189
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6190
6191
    // A same-size edit made just now is racy and read.
6192
    write(root, "a.txt", b"one\nTWO\n");
6193
    assert_eq!(
6194
        statuses(&repo.snapshot("status").unwrap()),
6195
        vec![
6196
            ("a.txt".to_string(), ChangeStatus::Modified),
6197
            ("b.txt".to_string(), ChangeStatus::Modified)
6198
        ]
6199
    );
6200
    // Committing makes the edits the base: both are clean and served from it again.
6201
    repo.commit("edits", &[]).unwrap();
6202
    age("a.txt");
6203
    age("b.txt");
6204
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6205
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6206
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6207
    let snap = repo.snapshot("status").unwrap();
6208
    assert!(!snap.changed && snap.statuses.is_empty());
6209
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6210
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6211
}
afaba5f1 Andy McCall ↶ 6212
6213
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
6214
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
6215
/// file is unchanged, and loading through the checkpoint equals a full load.
6216
#[test]
6217
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
6218
    hermetic();
6219
    let dir = tempfile::tempdir().unwrap();
6220
    let root = dir.path();
6221
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6222
    let long: String = (0..300)
6223
        .map(|i| format!("line {i} of a long file\n"))
6224
        .collect();
6225
    write(root, "long.txt", long.as_bytes());
6226
    write(root, "short.txt", b"short\n");
6227
    repo.commit("base", &[]).unwrap();
6228
    let (r1, _, _) = repo.checkpoint().unwrap();
6229
    let cp1 = crate::objects::Checkpoint::decode(
6230
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
6231
    )
6232
    .unwrap();
6233
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
6234
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
6235
6236
    // gc keeps the graph blob; fsck finds the checkpoint sound.
6237
    repo.gc(true).unwrap();
6238
    assert!(repo.store().has(&graphs1[0]));
6239
    let report = repo.fsck().unwrap();
6240
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
6241
6242
    // Loading through the checkpoint equals a full load.
6243
    write(root, "short.txt", b"short, edited\n");
6244
    repo.commit("edit the short file", &[]).unwrap();
6245
    let heads = repo.bookmark_heads().unwrap();
6246
    let fast = repo.load_state(&heads).unwrap();
6247
    let full = repo.load_state_full(&heads).unwrap();
6248
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
6249
6250
    // The next checkpoint shares the unchanged long file's graph.
6251
    let (r2, _, _) = repo.checkpoint().unwrap();
6252
    let cp2 = crate::objects::Checkpoint::decode(
6253
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
6254
    )
6255
    .unwrap();
6256
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
6257
6258
    // A shallow clone's bundle carries the graph blob with the checkpoint.
6259
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
6260
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
6261
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
6262
6263
    // A version 1 checkpoint written by an older oxy still loads.
6264
    let state = repo.load_state_full(&heads).unwrap();
6265
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
6266
    let cp_old = crate::objects::Checkpoint {
6267
        heads: cp2.heads.clone(),
6268
        count: cp2.count,
6269
        payload: old,
6270
    };
6271
    let r_old = repo
6272
        .store()
6273
        .put(ObjectType::Checkpoint, &cp_old.encode())
6274
        .unwrap();
6275
    repo.install_checkpoint("main", &r_old).unwrap();
6276
    assert_eq!(
6277
        repo.load_state(&heads).unwrap().checkpoint_payload(),
6278
        full.checkpoint_payload()
6279
    );
6280
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6281
6282
    // A lost graph blob fails the load loudly rather than dropping the
6283
    // file, and fsck reports it (a fresh repository, objects still loose).
6284
    let dir2 = tempfile::tempdir().unwrap();
6285
    let root2 = dir2.path();
6286
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
6287
    write(root2, "long.txt", long.as_bytes());
6288
    repo2.commit("base", &[]).unwrap();
6289
    let (r, _, _) = repo2.checkpoint().unwrap();
6290
    let cp = crate::objects::Checkpoint::decode(
6291
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
6292
    )
6293
    .unwrap();
6294
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
64818938 Andy McCall ↶ 6295
    repo2.store().remove_loose_for_test(&graph).unwrap();
afaba5f1 Andy McCall ↶ 6296
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
6297
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
6298
}
e3d071ce Andy McCall ↶ 6299
6300
/// A new repository has not stored the user's identity yet (that happens
6301
/// at the first signed change); looking it up falls back to the key
6302
/// directory, and a file there that does not hash to the key is refused.
6303
#[test]
6304
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
6305
    hermetic();
6306
    let dir = tempfile::tempdir().unwrap();
6307
    let home = dir.path().join("home");
6308
    let mut first = Repo::init(&dir.path().join("a"))
6309
        .unwrap()
6310
        .with_home(home.clone());
6311
    let (key, _) = first
6312
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6313
        .unwrap();
6314
    let fresh = Repo::init(&dir.path().join("b"))
6315
        .unwrap()
6316
        .with_home(home.clone());
6317
    assert!(!fresh.store().has(&key), "nothing stored yet");
6318
    let id = fresh.identity(&key).unwrap();
6319
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
6320
    // A key file that is not this identity is an error, not a wrong answer.
6321
    let keys = fresh.keys_dir.clone();
6322
    let (other, _) = first
6323
        .create_identity("Bob", "[email protected]", IdentityScope::User)
6324
        .unwrap();
6325
    fs::copy(
6326
        keys.join(format!("{}.identity", other.to_hex())),
6327
        keys.join(format!("{}.identity", key.to_hex())),
6328
    )
6329
    .unwrap();
6330
    assert!(fresh
6331
        .identity(&key)
6332
        .unwrap_err()
6333
        .to_string()
6334
        .contains("does not hold identity"));
6335
}
cc7a0056 Andy McCall ↶ 6336
6337
/// Status snapshots (spec §12.3): a text file whose stat matches the
6338
/// manifest, and whose base graph key is the one the manifest recorded it
6339
/// equal to, is neither read nor rendered; any edit, and any change to the
6340
/// file's graph in the base, brings it back.
6341
#[cfg(unix)]
6342
#[test]
6343
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
6344
    use std::os::unix::fs::PermissionsExt;
6345
    hermetic();
6346
    let dir = tempfile::tempdir().unwrap();
6347
    let root = dir.path();
6348
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6349
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
6350
        write(root, p, c.as_bytes());
6351
    }
6352
    repo.commit("base", &[]).unwrap();
6353
    let age = |p: &str| {
6354
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6355
        fs::File::options()
6356
            .write(true)
6357
            .open(root.join(p))
6358
            .unwrap()
6359
            .set_modified(old)
6360
            .unwrap();
6361
    };
6362
    let lock = |p: &str, mode: u32| {
6363
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
6364
    };
6365
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6366
        age(p);
6367
    }
6368
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6369
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6370
    assert!(
6371
        m.entries.values().all(|e| e.graph.is_some()),
6372
        "keys recorded"
6373
    );
6374
6375
    // Unreadable files prove they are not read; the status snapshot does
6376
    // not render them either, and its base lacks their graphs.
6377
    lock("a.txt", 0o000);
6378
    lock("b.txt", 0o000);
6379
    let snap = repo.snapshot_status("status").unwrap();
6380
    assert!(!snap.changed && snap.statuses.is_empty());
6381
    assert_eq!(
6382
        snap.base_snapshot
6383
            .unrendered
6384
            .iter()
6385
            .cloned()
6386
            .collect::<Vec<_>>(),
6387
        vec!["a.txt", "b.txt", "d/c.txt"]
6388
    );
6389
    assert!(!snap.base.is_full());
6390
    assert!(!snap.base_snapshot.is_conflicted());
6391
    // A full snapshot does not read them either, but renders everything.
6392
    let full = repo.snapshot("status").unwrap();
6393
    assert!(full.statuses.is_empty() && full.base.is_full());
6394
    assert!(full.base_snapshot.unrendered.is_empty());
6395
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
6396
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
6397
6398
    // An edit is seen; the file is rendered, the others still are not.
6399
    write(root, "d/c.txt", b"sea edited\n");
6400
    let snap = repo.snapshot_status("status").unwrap();
6401
    assert_eq!(
6402
        statuses(&snap),
6403
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
6404
    );
6405
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
6406
    // So is a mode change of an unread file.
6407
    lock("b.txt", 0o100);
6408
    assert_eq!(
6409
        statuses(&repo.snapshot_status("status").unwrap()),
6410
        vec![
6411
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
6412
            ("d/c.txt".to_string(), ChangeStatus::Modified)
6413
        ]
6414
    );
6415
    lock("b.txt", 0o000);
6416
6417
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
6418
    // stays unread, c.txt is read once and then skipped too.
6419
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
6420
        .unwrap();
6421
    age("d/c.txt");
6422
    let snap = repo.snapshot_status("status").unwrap();
6423
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
6424
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
6425
    lock("d/c.txt", 0o000);
6426
    let snap = repo.snapshot_status("status").unwrap();
6427
    assert!(snap.statuses.is_empty());
6428
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
6429
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6430
        lock(p, 0o644);
6431
    }
6432
}
6433
6434
/// Attributes decide how a file compares with the base, so a changed
6435
/// `.oxyattributes` makes every text file be compared again.
6436
#[cfg(unix)]
6437
#[test]
6438
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
6439
    hermetic();
6440
    let dir = tempfile::tempdir().unwrap();
6441
    let root = dir.path();
6442
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6443
    write(root, "a.txt", b"crlf\r\n");
6444
    repo.commit("base", &[]).unwrap();
6445
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6446
    fs::File::options()
6447
        .write(true)
6448
        .open(root.join("a.txt"))
6449
        .unwrap()
6450
        .set_modified(old)
6451
        .unwrap();
6452
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6453
    assert!(repo
6454
        .snapshot_status("status")
6455
        .unwrap()
6456
        .base_snapshot
6457
        .unrendered
6458
        .contains("a.txt"));
6459
    // With eol=lf, a.txt as stored no longer equals the base.
6460
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
6461
    let snap = repo.snapshot_status("status").unwrap();
6462
    assert_eq!(
6463
        statuses(&snap),
6464
        vec![
6465
            (".oxyattributes".to_string(), ChangeStatus::Added),
6466
            ("a.txt".to_string(), ChangeStatus::Modified)
6467
        ]
6468
    );
6469
}
54cd08a1 Andy McCall ↶ 6470
6471
/// Bookmarks with `/` in their names: pushing records their
6472
/// attestations, and checkpoints are kept for them, beside `feature`
6473
/// itself.
6474
#[test]
6475
fn bookmarks_with_slashes_push_and_checkpoint() {
6476
    hermetic();
6477
    let dir = tempfile::tempdir().unwrap();
6478
    let root = dir.path();
6479
    let origin = Repo::init(&root.join("origin")).unwrap();
6480
    let url = root.join("origin").to_string_lossy().to_string();
6481
    let mut repo = Repo::clone(&url, &root.join("r"))
6482
        .unwrap()
6483
        .with_home(root.join("home"));
6484
    // With an identity, pushes carry reference attestations: the case
6485
    // that failed, since the attestation is a file named after the bookmark.
6486
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6487
        .unwrap();
6488
    let r = root.join("r");
6489
    write(&r, "a.txt", b"a\n");
6490
    let h_a = repo.commit("a", &[]).unwrap();
6491
    assert!(repo.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 6492
    origin.refresh().unwrap();
54cd08a1 Andy McCall ↶ 6493
    repo.bookmark_create("feature", None).unwrap();
6494
    repo.bookmark_create("feature/x", None).unwrap();
6495
    repo.bookmark_switch("feature/x", false).unwrap();
6496
    write(&r, "b.txt", b"b\n");
6497
    let h_b = repo.commit("b", &[]).unwrap();
6498
    for name in ["feature", "feature/x"] {
6499
        let res = repo.push_bookmark("origin", name, false).unwrap();
767ac6cd Andy McCall 6500
        origin.refresh().unwrap();
54cd08a1 Andy McCall ↶ 6501
        assert!(res[0].ok, "{name}: {res:?}");
6502
    }
6503
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
6504
    assert_eq!(
6505
        origin.resolve_heads("feature/x").unwrap(),
6506
        repo.resolve_heads("feature/x").unwrap()
6507
    );
6508
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
6509
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
6510
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
6511
6512
    // A checkpoint of feature/x is found again when loading its state.
6513
    let (cp, _, _) = repo.checkpoint().unwrap();
6514
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
6515
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
6516
    let heads = repo.resolve_heads("feature/x").unwrap();
6517
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
f8c69576 Andy McCall ↶ 6518
}
6519
6520
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
6521
/// never the remote's own bookmark, and a bookmark created again later is
6522
/// accepted although the deletion's attestation stays the latest.
6523
#[test]
6524
fn bookmarks_are_deleted_on_a_remote() {
6525
    hermetic();
6526
    let dir = tempfile::tempdir().unwrap();
6527
    let root = dir.path();
6528
    let origin = Repo::init(&root.join("origin")).unwrap();
6529
    let url = root.join("origin").to_string_lossy().to_string();
6530
    let mut repo = Repo::clone(&url, &root.join("r"))
6531
        .unwrap()
6532
        .with_home(root.join("home"));
6533
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6534
        .unwrap();
6535
    let r = root.join("r");
6536
    write(&r, "a.txt", b"a\n");
6537
    repo.commit("a", &[]).unwrap();
6538
    assert!(repo.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 6539
    origin.refresh().unwrap();
f8c69576 Andy McCall ↶ 6540
    repo.bookmark_create("feature/x", None).unwrap();
6541
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
767ac6cd Andy McCall 6542
    origin.refresh().unwrap();
f8c69576 Andy McCall ↶ 6543
    assert!(origin.resolve_heads("feature/x").is_ok());
6544
6545
    let res = repo.push_delete("origin", "feature/x").unwrap();
767ac6cd Andy McCall 6546
    origin.refresh().unwrap();
f8c69576 Andy McCall ↶ 6547
    assert!(res[0].ok, "{res:?}");
6548
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
6549
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
6550
    assert!(
6551
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
6552
        "the deletion is attested"
6553
    );
6554
    assert!(
6555
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
6556
        "the local bookmark stays"
6557
    );
6558
    assert!(!repo
6559
        .view()
6560
        .unwrap()
6561
        .remotes
6562
        .get("origin")
6563
        .is_some_and(|m| m.contains_key("feature/x")));
6564
6565
    // Pushing it again creates it again, past the deletion's serial.
6566
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
767ac6cd Andy McCall 6567
    origin.refresh().unwrap();
f8c69576 Andy McCall ↶ 6568
    assert!(res[0].ok, "{res:?}");
6569
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
6570
6571
    // Nothing to delete, and never the remote's own bookmark.
6572
    assert!(repo.push_delete("origin", "nope").is_err());
6573
    let res = repo.push_delete("origin", "main").unwrap();
767ac6cd Andy McCall 6574
    origin.refresh().unwrap();
f8c69576 Andy McCall ↶ 6575
    assert!(
6576
        !res[0].ok && res[0].reason.contains("default bookmark"),
6577
        "{res:?}"
6578
    );
6579
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
54cd08a1 Andy McCall ↶ 6580
}
61e3bce7 Andy McCall ↶ 6581
6582
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
6583
/// when the target has the same versions of the files it touches, and is
6584
/// refused, untouched, when it has others.
6585
#[test]
6586
fn switching_bookmarks_carries_uncommitted_work() {
6587
    hermetic();
6588
    let dir = tempfile::tempdir().unwrap();
6589
    let root = dir.path();
6590
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6591
    write(root, "a.txt", b"a\n");
6592
    write(root, "b.txt", b"b\n");
6593
    write(root, "gone.txt", b"gone\n");
6594
    repo.commit("base", &[]).unwrap();
6595
    repo.bookmark_create("feature", None).unwrap();
6596
    // Started on main, belongs on feature: edit, add, remove.
6597
    write(root, "a.txt", b"a\nmore\n");
6598
    write(root, "new.txt", b"new\n");
6599
    fs::remove_file(root.join("gone.txt")).unwrap();
44f1ebe7 Andy McCall ↶ 6600
    let (report, carried) = repo.bookmark_switch_carry("feature").unwrap();
61e3bce7 Andy McCall ↶ 6601
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
44f1ebe7 Andy McCall ↶ 6602
    // oxygen#120: the new file was carried, not removed.
6603
    assert_eq!(
6604
        (report.removed, report.removed_paths.len()),
6605
        (0, 0),
6606
        "{report:?}"
6607
    );
61e3bce7 Andy McCall ↶ 6608
    assert_eq!(repo.config.bookmark, "feature");
6609
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
6610
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
6611
    assert!(!root.join("gone.txt").exists());
6612
    let snap = repo.snapshot("status").unwrap();
6613
    assert_eq!(
6614
        statuses(&snap),
6615
        vec![
6616
            ("a.txt".to_string(), ChangeStatus::Modified),
6617
            ("gone.txt".to_string(), ChangeStatus::Removed),
6618
            ("new.txt".to_string(), ChangeStatus::Added)
6619
        ]
6620
    );
6621
    repo.commit("the work", &[]).unwrap();
6622
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
6623
6624
    // main moves b.txt on; work on feature touching b.txt cannot follow.
6625
    repo.bookmark_switch("main", false).unwrap();
6626
    write(root, "b.txt", b"b on main\n");
6627
    repo.commit("b on main", &[]).unwrap();
6628
    repo.bookmark_switch("feature", false).unwrap();
6629
    write(root, "b.txt", b"b edited\n");
6630
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
6631
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
6632
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
6633
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
6634
}
1c2bd9ab Andy McCall ↶ 6635
6636
/// Merging and checking out (feedback 3): a working copy without changes
6637
/// follows a merge whichever state it sat on; a refused checkout names
6638
/// what is in the way; `checkout --carry` takes the work along.
6639
#[test]
6640
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
6641
    hermetic();
6642
    let dir = tempfile::tempdir().unwrap();
6643
    let root = dir.path();
6644
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6645
    write(root, "a.txt", b"a\n");
6646
    let h1 = repo.commit("a", &[]).unwrap();
6647
    write(root, "b.txt", b"b\n");
6648
    repo.commit("b", &[]).unwrap();
6649
    repo.bookmark_create("feature", None).unwrap();
6650
    repo.bookmark_switch("feature", false).unwrap();
6651
    write(root, "c.txt", b"c\n");
6652
    repo.commit("c on feature", &[]).unwrap();
6653
    repo.bookmark_switch("main", false).unwrap();
6654
    // The working copy sits on an older state than main's heads.
6655
    repo.checkout(&[h1], false, "checkout").unwrap();
6656
    assert!(!root.join("b.txt").exists());
6657
    let m = repo.merge("feature").unwrap();
6658
    assert!(m.checked_out, "a clean working copy follows the merge");
6659
    for f in ["a.txt", "b.txt", "c.txt"] {
6660
        assert!(root.join(f).exists(), "{f}");
6661
    }
6662
6663
    // A refusal says which paths are in the way and what to do.
6664
    fs::remove_file(root.join("b.txt")).unwrap();
6665
    write(root, "a.txt", b"a edited\n");
6666
    let err = repo
6667
        .checkout(&[h1], false, "checkout")
6668
        .unwrap_err()
6669
        .to_string();
6670
    assert!(
6671
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
6672
        "{err}"
6673
    );
fe9586d9 Andy McCall ↶ 6674
    // --carry takes them along: h1 has a.txt as the base has it, and the
6675
    // removed b.txt is already as h1 has it (none), so that is no conflict
6676
    // either (oxygen#100).
1c2bd9ab Andy McCall ↶ 6677
    let (_, carried) = repo
6678
        .checkout_carry(&[h1], "the first change", "checkout")
6679
        .unwrap();
6680
    assert_eq!(carried, vec!["a.txt"]);
6681
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
6682
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
6683
}
e7ac6c2e Andy McCall ↶ 6684
6685
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
6686
/// user identity not stored in a new repository yet is fine while its
6687
/// secret key is there; an added subrepo is listed as not committed yet.
6688
#[test]
6689
fn a_new_repository_is_healthy_before_its_first_commit() {
6690
    hermetic();
6691
    let dir = tempfile::tempdir().unwrap();
6692
    let root = dir.path();
6693
    let home = root.join("home");
6694
    let mut first = Repo::init(&root.join("first"))
6695
        .unwrap()
6696
        .with_home(home.clone());
6697
    let (key, _) = first
6698
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6699
        .unwrap();
6700
    let repo = Repo::init(&root.join("second"))
6701
        .unwrap()
6702
        .with_home(home.clone());
6703
    // Only the secret key: no identity object anywhere this repository sees.
6704
    let keys = repo.keys_dir.clone();
6705
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
6706
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
6707
    let r = repo.doctor(true);
6708
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
6709
    assert_eq!(id.health, Health::Ok, "{}", id.message);
6710
    assert!(id.message.contains("first signed change"), "{}", id.message);
6711
6712
    // A subrepo added and not committed yet is listed, pinned where it is.
6713
    let lib = root.join("lib");
6714
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
6715
    write(&lib, "x.txt", b"x\n");
6716
    l.commit("x", &[]).unwrap();
6717
    let second = root.join("second");
6718
    write(&second, "a.txt", b"a\n");
6719
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
6720
        .unwrap();
6721
    let subs = repo.subrepos().unwrap();
6722
    assert_eq!(subs.len(), 1);
6723
    assert_eq!(
6724
        (subs[0].path.as_str(), subs[0].committed),
6725
        ("deps/lib", false)
6726
    );
6727
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
6728
    repo.commit("add lib", &[]).unwrap();
6729
    let subs = repo.subrepos().unwrap();
6730
    assert!(subs[0].committed, "committed now");
6731
}
8ab265dc Andy McCall ↶ 6732
6733
/// Commit, diff, hunks and discard use the partial snapshot: a file
6734
/// unchanged since the manifest is neither read nor rendered, and showing
6735
/// a change renders only what it edits, the same as from a full base.
6736
#[cfg(unix)]
6737
#[test]
6738
fn commits_and_diffs_leave_unchanged_files_alone() {
6739
    use std::os::unix::fs::PermissionsExt;
6740
    hermetic();
6741
    let dir = tempfile::tempdir().unwrap();
6742
    let root = dir.path();
6743
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6744
    write(root, "big.txt", b"lots\nof\nlines\n");
6745
    write(root, "a.txt", b"one\ntwo\n");
6746
    repo.commit("base", &[]).unwrap();
6747
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6748
    for f in ["big.txt", "a.txt"] {
6749
        fs::File::options()
6750
            .write(true)
6751
            .open(root.join(f))
6752
            .unwrap()
6753
            .set_modified(old)
6754
            .unwrap();
6755
    }
6756
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6757
    // big.txt cannot be read at all from here on.
6758
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6759
6760
    write(root, "a.txt", b"one\nTWO\nthree\n");
6761
    let diff = repo.diff_files(None).unwrap();
6762
    assert_eq!(
6763
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
6764
        ["a.txt"]
6765
    );
6766
    let (_, hunks) = repo.hunks().unwrap();
6767
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
6768
    let h = repo.commit("edit a", &[]).unwrap();
6769
6770
    // Showing the change needs only a.txt's graph, and renders as a full base does.
6771
    let c = repo.store().get_change(&h).unwrap();
6772
    let full = repo.load_state(&c.deps).unwrap();
6773
    let want = render_change(&c, &full, &full.materialize());
6774
    assert_eq!(repo.describe_change(&h).unwrap(), want);
6775
    let (base, snap) = repo.change_base(&c).unwrap();
6776
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
6777
6778
    // Discarding works the same way.
6779
    write(root, "a.txt", b"scratch\n");
6780
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
6781
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
6782
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6783
}
f7510b63 Andy McCall ↶ 6784
6785
/// A replace conflict (spec §9.3) is settled by a change that writes one
6786
/// candidate, or new bytes, at the path when the caller names it; a plain
6787
/// snapshot of a checkout never settles it on its own.
6788
#[test]
6789
fn replace_conflicts_are_settled_when_asked() {
6790
    hermetic();
6791
    let dir = tempfile::tempdir().unwrap();
6792
    let root = dir.path();
6793
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6794
    let blob = |n: u8| {
6795
        let mut v = vec![0u8; 64];
6796
        v[1] = n;
6797
        v
6798
    };
6799
    write(root, "img.bin", &blob(1));
6800
    repo.commit("add img", &[]).unwrap();
6801
    repo.bookmark_create("other", None).unwrap();
6802
    write(root, "img.bin", &blob(2));
6803
    repo.commit("img two", &[]).unwrap();
6804
    repo.bookmark_switch("other", false).unwrap();
6805
    write(root, "img.bin", &blob(3));
6806
    repo.commit("img three", &[]).unwrap();
6807
    repo.bookmark_switch("main", false).unwrap();
6808
    repo.merge("other").unwrap();
6809
    let heads = repo.bookmark_heads().unwrap();
6810
    let merged = repo.load_state(&heads).unwrap().materialize();
6811
    assert!(
6812
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
6813
        "a replace conflict"
6814
    );
6815
    // A snapshot of the checkout records nothing.
6816
    assert!(repo
6817
        .snapshot("status")
6818
        .unwrap()
6819
        .statuses
6820
        .iter()
6821
        .all(|s| s.path != "img.bin"));
6822
6823
    // Keeping candidate 3 settles it.
6824
    let author = repo.author();
6825
    let edits = [FileEdit {
6826
        path: "img.bin".into(),
6827
        content: Some(blob(3)),
6828
    }];
6829
    let c = repo
6830
        .build_change(&heads, &edits, "keep three", author)
6831
        .unwrap();
6832
    assert_eq!(c.kind, ChangeKind::Resolution);
6833
    let mut st = repo.load_state(&heads).unwrap();
6834
    for d in &c.deps {
6835
        assert!(st.contains(d));
6836
    }
6837
    assert!(
6838
        heads.iter().all(|h| c.deps.contains(h)),
6839
        "depends on both contributors"
6840
    );
6841
    st.add(c).unwrap();
6842
    let after = st.materialize();
6843
    assert!(!after.is_conflicted());
6844
    assert_eq!(
6845
        after.files["img.bin"].content,
6846
        FileContent::Opaque {
6847
            blobs: vec![Repo::blob_ref(&blob(3))]
6848
        }
6849
    );
6850
6851
    // New bytes settle it too.
6852
    let edits = [FileEdit {
6853
        path: "img.bin".into(),
6854
        content: Some(blob(9)),
6855
    }];
6856
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
6857
    let mut st = repo.load_state(&heads).unwrap();
6858
    st.add(c).unwrap();
6859
    assert_eq!(
6860
        st.materialize().files["img.bin"].content,
6861
        FileContent::Opaque {
6862
            blobs: vec![Repo::blob_ref(&blob(9))]
6863
        }
6864
    );
6865
}
83d61e80 Andy McCall ↶ 6866
6867
/// The history of a range of lines (spec §27): the changes that wrote
6868
/// or deleted its atoms, or deleted atoms from between them; edits outside
6869
/// the range and changes the range's lines survived are not in it.
6870
#[test]
6871
fn line_ranges_have_exact_histories() {
6872
    hermetic();
6873
    let dir = tempfile::tempdir().unwrap();
6874
    let root = dir.path();
6875
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6876
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
6877
    let base = repo.commit("add f", &[]).unwrap();
6878
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
6879
    let outside = repo.commit("change the import", &[]).unwrap();
6880
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
6881
    let inside = repo.commit("edit a line of a", &[]).unwrap();
6882
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
6883
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
6884
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
6885
    let after = repo.commit("add b after a", &[]).unwrap();
6886
    let heads = repo.bookmark_heads().unwrap();
6887
6888
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
6889
    let hist: Vec<ChangeHash> = repo
6890
        .line_history(&heads, "f.rs", 2, 4)
6891
        .unwrap()
6892
        .iter()
6893
        .map(|e| e.hash)
6894
        .collect();
6895
    for (h, what) in [
6896
        (base, "wrote it"),
6897
        (inside, "edited a line"),
6898
        (deleted, "deleted a line from inside"),
6899
    ] {
6900
        assert!(hist.contains(&h), "{what}");
6901
    }
6902
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
6903
        assert!(!hist.contains(&h), "{what}");
6904
    }
6905
    assert_eq!(hist[0], deleted, "newest first");
6906
    // One line: only what touched it.
6907
    let one: Vec<ChangeHash> = repo
6908
        .line_history(&heads, "f.rs", 1, 1)
6909
        .unwrap()
6910
        .iter()
6911
        .map(|e| e.hash)
6912
        .collect();
6913
    assert!(one.contains(&outside) && !one.contains(&inside));
6914
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
6915
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
6916
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
6917
}
fc1a466a Andy McCall ↶ 6918
6919
#[test]
6920
fn receipts_are_kept_with_their_state_and_verified() {
6921
    use crate::receipt::{Receipt, SignedReceipt};
6922
    hermetic();
6923
    let dir = tempfile::tempdir().unwrap();
6924
    let root = dir.path();
6925
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6926
    write(root, "a.txt", b"1\n");
6927
    repo.commit("A", &[]).unwrap();
6928
    let heads = repo.bookmark_heads().unwrap();
6929
    let state = repo
6930
        .store()
6931
        .put_state(&StateObject::new(heads.clone()))
6932
        .unwrap();
6933
    let out = repo.store_blob(b"built\n").unwrap();
6934
    let receipt = Receipt {
6935
        job_name: "build".into(),
6936
        pipeline_hash: ObjectRef([1; 32]),
6937
        scope_tree_hash: ObjectRef([2; 32]),
6938
        inputs: vec![],
6939
        environment: ObjectRef([3; 32]),
6940
        outputs: vec![out],
6941
        exit_code: 0,
6942
        duration_ms: 42,
6943
    };
6944
    let sk = SecretKey::generate();
6945
    let runner = sk.identity("earth-1", "runner@earth", 1);
6946
    let sr = SignedReceipt::sign(
6947
        receipt.clone(),
6948
        repo.id().unwrap(),
6949
        state,
6950
        "demo#1",
6951
        &runner,
6952
        &sk,
6953
    );
6954
6955
    let r = repo.add_receipt(&sr).unwrap();
6956
    let found = repo.receipts(&heads).unwrap();
6957
    assert_eq!(found.len(), 1);
6958
    assert_eq!(found[0].attest, r);
6959
    assert_eq!(found[0].signed, sr);
6960
    assert!(found[0].problem.is_none() && !found[0].revoked);
6961
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
6962
6963
    // Another repository's receipt, or a forged one, is refused.
6964
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
6965
    assert!(repo
6966
        .add_receipt(&elsewhere)
6967
        .unwrap_err()
6968
        .to_string()
6969
        .contains("another repository"));
6970
    let mut forged = sr.clone();
6971
    forged.receipt.exit_code = 1;
6972
    assert!(repo
6973
        .add_receipt(&forged)
6974
        .unwrap_err()
6975
        .to_string()
6976
        .contains("does not verify"));
6977
c63fed2e Andy McCall ↶ 6978
    // A receipt signed by a short-lived key keeps its certificate and the
6979
    // issuer's identity, and reads back with them (oxygenhub#241).
6980
    let hub_sk = SecretKey::generate();
6981
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
6982
    let job_sk = SecretKey::generate();
6983
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
6984
    let mut test_receipt = receipt.clone();
6985
    test_receipt.job_name = "test".into();
6986
    let plain = SignedReceipt::sign(
6987
        test_receipt,
6988
        repo.id().unwrap(),
6989
        state,
6990
        "demo#2",
6991
        &job,
6992
        &job_sk,
6993
    );
6994
    let now = plain.attest.hlc.wall_ms;
6995
    let cert = crate::cert::SignedCertificate::sign(
6996
        crate::cert::Certificate {
6997
            key: job.clone(),
6998
            issuer: hub.hash(),
6999
            subject: "repo:andy/demo:bookmark:main".into(),
7000
            claims: vec![],
7001
            scope: crate::identity::Scope::SEAL,
7002
            not_before: now - 1_000,
7003
            expires: now + 600_000,
a2387d54 Andy McCall ↶ 7004
            grant: None,
c63fed2e Andy McCall ↶ 7005
        },
7006
        &hub,
7007
        &hub_sk,
7008
    );
7009
    let certified = plain.with_certificate(cert, hub.clone());
7010
    repo.add_receipt(&certified).unwrap();
7011
    let found = repo.receipts(&heads).unwrap();
7012
    let got = found
7013
        .iter()
7014
        .find(|i| i.signed.receipt.job_name == "test")
7015
        .unwrap();
7016
    assert_eq!(got.signed, certified);
7017
    assert!(got.problem.is_none(), "{:?}", got.problem);
7018
7019
    // gc keeps the receipts, their runners, the certificate and its issuer,
7020
    // and the output while the state lives.
fc1a466a Andy McCall ↶ 7021
    repo.gc(true).unwrap();
c63fed2e Andy McCall ↶ 7022
    let found = repo.receipts(&heads).unwrap();
7023
    assert_eq!(found.len(), 2);
7024
    let got = found
7025
        .iter()
7026
        .find(|i| i.signed.receipt.job_name == "test")
7027
        .unwrap();
7028
    assert_eq!(got.signed, certified, "the certificate survives gc");
7029
    assert!(got.problem.is_none());
fc1a466a Andy McCall ↶ 7030
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
7031
    assert!(repo.fsck().unwrap().problems.is_empty());
dfb23a3a Andy McCall ↶ 7032
}
7033
7034
#[test]
3a4b3e01 Andy McCall ↶ 7035
fn approvals_are_kept_with_their_state_and_survive_gc() {
7036
    hermetic();
7037
    let dir = tempfile::tempdir().unwrap();
7038
    let root = dir.path();
7039
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7040
    write(root, "a.txt", b"1\n");
7041
    repo.commit("A", &[]).unwrap();
7042
    let heads = repo.bookmark_heads().unwrap();
7043
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
7044
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
7045
    let sk = SecretKey::generate();
7046
    let andy = sk.identity("Andy", "[email protected]", 1);
7047
    let statement = crate::approval::Statement {
7048
        repo: repo.id().unwrap(),
7049
        run: "https://hub.example/andy/infra/flow/8".into(),
7050
        job: "apply".into(),
7051
        job_hash: ObjectRef([1; 32]),
7052
        state,
7053
        inputs: vec![plan],
7054
        environment: "prod".into(),
7055
        approve: true,
7056
    };
7057
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
7058
    let r = repo.add_approval(&sa).unwrap();
7059
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
7060
    // Another repository's approval, or a changed one, is refused.
7061
    let elsewhere = crate::approval::SignedApproval::sign(
7062
        &crate::approval::Statement {
7063
            repo: [0; 16],
7064
            ..statement.clone()
7065
        },
7066
        &andy,
7067
        &sk,
7068
    );
7069
    assert!(repo
7070
        .add_approval(&elsewhere)
7071
        .unwrap_err()
7072
        .to_string()
7073
        .contains("another repository"));
7074
    let mut forged = sa.clone();
7075
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
7076
        *environment = "dev".into();
7077
    }
7078
    assert!(repo
7079
        .add_approval(&forged)
7080
        .unwrap_err()
7081
        .to_string()
7082
        .contains("does not verify"));
7083
    // gc keeps it, its signature and its signer while the state lives.
7084
    repo.gc(true).unwrap();
7085
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
7086
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
7087
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
7088
    assert!(repo.fsck().unwrap().problems.is_empty());
7089
}
7090
7091
#[test]
dfb23a3a Andy McCall ↶ 7092
fn status_leaves_an_unchanged_manifest_alone() {
7093
    hermetic();
7094
    let dir = tempfile::tempdir().unwrap();
7095
    let root = dir.path();
7096
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7097
    write(root, "a.txt", b"1\n");
7098
    write(root, "b.txt", b"2\n");
7099
    repo.commit("A", &[]).unwrap();
7100
    // Files last touched well outside the racy window.
7101
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7102
    for f in ["a.txt", "b.txt"] {
7103
        fs::File::options()
7104
            .write(true)
7105
            .open(root.join(f))
7106
            .unwrap()
7107
            .set_modified(old)
7108
            .unwrap();
7109
    }
7110
    repo.snapshot_status("status").unwrap();
7111
    let path = repo.manifest_path();
7112
    let first = fs::read(&path).unwrap();
7113
    repo.snapshot_status("status").unwrap();
7114
    assert_eq!(
7115
        fs::read(&path).unwrap(),
7116
        first,
7117
        "an unchanged tree does not rewrite the manifest"
7118
    );
7119
    // A change rewrites it.
7120
    write(root, "a.txt", b"1\n2\n");
7121
    repo.snapshot_status("status").unwrap();
7122
    assert_ne!(fs::read(&path).unwrap(), first);
fc1a466a Andy McCall ↶ 7123
}
6f8aeb99 Andy McCall ↶ 7124
7125
#[test]
7126
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
7127
    hermetic();
7128
    let dir = tempfile::tempdir().unwrap();
7129
    let root = dir.path();
7130
    let origin_path = root.join("origin");
7131
    Repo::init(&origin_path).unwrap();
7132
    let origin_url = origin_path.to_string_lossy().to_string();
7133
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
7134
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
7135
    write(&root.join("a"), "big.txt", big.as_bytes());
7136
    write(&root.join("a"), "small.txt", b"small\n");
7137
    let h1 = a.commit("large", &[]).unwrap();
7138
    let (_, body) = a.store().get(&h1).unwrap();
7139
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
7140
    assert!(a.push("origin", false).unwrap()[0].ok);
7141
7142
    // A clone reads the text from the blobs that came with the change.
7143
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
7144
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
7145
    // An edit in the middle of the stored insert is an ordinary change.
7146
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
7147
    write(&root.join("b"), "big.txt", edited.as_bytes());
7148
    let h2 = b.commit("edit", &[]).unwrap();
7149
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
7150
    assert!(b.push("origin", false).unwrap()[0].ok);
7151
    assert!(a.pull("origin").unwrap().checked_out);
7152
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
7153
    assert_eq!(
7154
        a.fsck().unwrap().errors(),
7155
        0,
7156
        "{:?}",
7157
        a.fsck().unwrap().problems
7158
    );
7159
7160
    // With zero retention gc keeps the text blobs of every kept change.
7161
    let mut a = Repo::open(&root.join("a")).unwrap();
7162
    a.config.set("core.op-retention", "0").unwrap();
7163
    a.save_config().unwrap();
7164
    let a = Repo::open(&root.join("a")).unwrap();
7165
    a.gc(true).unwrap();
7166
    let a = Repo::open(&root.join("a")).unwrap();
7167
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
7168
    assert_eq!(
7169
        a.fsck().unwrap().errors(),
7170
        0,
7171
        "{:?}",
7172
        a.fsck().unwrap().problems
7173
    );
7174
    // And a clone of the packed repository reads them from its packs.
7175
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
7176
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
7177
    drop(c);
6caacfff Andy McCall ↶ 7178
}
7179
7180
#[test]
7181
fn operations_that_both_replace_a_working_copy_are_not_merged() {
7182
    hermetic();
7183
    let dir = tempfile::tempdir().unwrap();
7184
    let root = dir.path();
7185
    let repo = Repo::init(root).unwrap();
7186
    write(root, "a.txt", b"a\n");
7187
    let a = repo.commit("a", &[]).unwrap();
7188
    write(root, "b.txt", b"b\n");
7189
    repo.commit("b", &[]).unwrap();
7190
    let (x, op) = repo.head_op().unwrap();
7191
    let ws = *op.view.workspaces.keys().next().unwrap();
7192
    let mut one = op.view.clone();
7193
    one.workspaces.insert(ws, a);
7194
    let mut two = op.view.clone();
7195
    two.workspaces.insert(ws, ObjectRef([7; 32]));
7196
    let first = repo.record_op(&[x], "one", one).unwrap();
7197
    let e = repo.record_op(&[x], "two", two).unwrap_err();
7198
    assert!(
7199
        e.to_string()
7200
            .contains("changed this working copy at the same time"),
7201
        "{e}"
7202
    );
7203
    assert_eq!(
7204
        repo.head_op().unwrap().0,
7205
        first,
7206
        "the second is not recorded"
7207
    );
7208
}
7209
7210
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
7211
/// rewrote the working copy recorded the half-written files as edits, and
7212
/// its view replaced the switch's.
7213
#[test]
7214
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
7215
    hermetic();
7216
    let dir = tempfile::tempdir().unwrap();
7217
    let root = dir.path().to_path_buf();
7218
    let mut repo = Repo::init(&root).unwrap();
7219
    write(&root, "keep.txt", b"keep\n");
7220
    repo.commit("base", &[]).unwrap();
7221
    repo.bookmark_create("small", None).unwrap();
7222
    for i in 0..300 {
7223
        write(
7224
            &root,
7225
            &format!("many/f{i}.txt"),
7226
            format!("file {i}\n").as_bytes(),
7227
        );
7228
    }
7229
    repo.commit("many", &[]).unwrap();
7230
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
7231
    let watcher = {
7232
        let (root, stop) = (root.clone(), stop.clone());
7233
        std::thread::spawn(move || {
7234
            let r = Repo::open(&root).unwrap();
7235
            let mut ran = 0;
7236
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
7237
                if r.snapshot_status("oxy status").is_ok() {
7238
                    ran += 1;
7239
                }
7240
            }
7241
            ran
7242
        })
7243
    };
7244
    for i in 0..20 {
7245
        let to = if i % 2 == 0 { "small" } else { "main" };
7246
        repo.bookmark_switch(to, false).unwrap();
7247
    }
7248
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
7249
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
7250
    // Back on main, clean, with every file where main has it.
7251
    let repo = Repo::open(&root).unwrap();
7252
    let s = repo.snapshot_status("oxy status").unwrap();
7253
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
7254
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
7255
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
7256
    assert!(root.join("many/f299.txt").exists());
1a3b6203 Andy McCall ↶ 7257
}
7258
7259
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
7260
/// put a subrepo that was ahead of its pin back at the pin and moved the
7261
/// subrepo's own bookmark backwards.
7262
#[test]
7263
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
7264
    hermetic();
7265
    let dir = tempfile::tempdir().unwrap();
7266
    let root = dir.path();
7267
    Repo::init(&root.join("lib-origin")).unwrap();
7268
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7269
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
7270
    write(&root.join("lib"), "lib.txt", b"v1\n");
7271
    lib.commit("lib v1", &[]).unwrap();
7272
    assert!(lib.push("origin", false).unwrap()[0].ok);
7273
7274
    let app_dir = root.join("app");
7275
    let mut app = Repo::init(&app_dir).unwrap();
7276
    write(&app_dir, "main.txt", b"app\n");
7277
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7278
    app.commit("app with lib", &[]).unwrap();
7279
    app.bookmark_create("feature", None).unwrap();
7280
7281
    // New work in the subrepo, not yet pinned by the parent.
7282
    let nested_dir = app_dir.join("libs/lib");
7283
    let nested = Repo::open(&nested_dir).unwrap();
7284
    write(&nested_dir, "new.txt", b"new\n");
7285
    let l2 = nested.commit("lib: new file", &[]).unwrap();
7286
    drop(nested);
7287
7288
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
7289
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
7290
    let nested = Repo::open(&nested_dir).unwrap();
7291
    assert!(
7292
        nested.bookmark_heads().unwrap().contains(&l2),
7293
        "its bookmark kept its work"
7294
    );
7295
    assert!(nested_dir.join("new.txt").exists(), "and its files");
7296
    let s = app.snapshot("status").unwrap();
7297
    assert_eq!(
7298
        statuses(&s),
7299
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
7300
    );
6f8aeb99 Andy McCall ↶ 7301
}
7d9dab13 Andy McCall ↶ 7302
7303
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
7304
/// moving `main` to a change this clone had pushed on another bookmark,
7305
/// the first `pull` said "Already up to date" while `main` was behind.
7306
#[test]
7307
fn pull_takes_a_remote_move_to_changes_already_here() {
7308
    hermetic();
7309
    let dir = tempfile::tempdir().unwrap();
7310
    let root = dir.path();
7311
    let origin_path = root.join("origin");
7312
    let origin = Repo::init(&origin_path).unwrap();
7313
    let url = origin_path.to_string_lossy().to_string();
7314
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
7315
    write(&root.join("b"), "base.txt", b"base\n");
7316
    b.commit("base", &[]).unwrap();
7317
    assert!(b.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 7318
    origin.refresh().unwrap();
7d9dab13 Andy McCall ↶ 7319
7320
    // A feature bookmark with one change, pushed.
7321
    b.bookmark_create("feat", None).unwrap();
7322
    b.bookmark_switch("feat", false).unwrap();
7323
    write(&root.join("b"), "x.txt", b"x\n");
7324
    let x = b.commit("x", &[]).unwrap();
7325
    assert!(b.push("origin", false).unwrap()[0].ok);
767ac6cd Andy McCall 7326
    origin.refresh().unwrap();
7d9dab13 Andy McCall ↶ 7327
    b.bookmark_switch("main", false).unwrap();
7328
7329
    // The remote lands it: its main moves to the feature's state.
7330
    let feat = origin
7331
        .store()
7332
        .get_state(&origin.view().unwrap().bookmarks["feat"])
7333
        .unwrap()
7334
        .heads;
7335
    origin.bookmark_set("main", &feat).unwrap();
7336
7337
    let r = b.pull("origin").unwrap();
7338
    assert!(r.changed, "{r:?}");
7339
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
7340
    let main = b
7341
        .bookmarks()
7342
        .unwrap()
7343
        .into_iter()
7344
        .find(|m| m.name == "main")
7345
        .unwrap();
7346
    assert_eq!(main.behind, Some(0), "{main:?}");
7347
}
86e1824f Andy McCall ↶ 7348
14edbaaf Andy McCall ↶ 7349
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
7350
/// to one only the remote has makes a local bookmark from it; a pull moves
7351
/// every local bookmark the remote has too; a clone checks out the remote's
7352
/// default bookmark.
7353
#[test]
7354
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
7355
    hermetic();
7356
    let dir = tempfile::tempdir().unwrap();
7357
    let root = dir.path();
7358
    let origin_path = root.join("origin");
7359
    let mut origin = Repo::init(&origin_path).unwrap();
7360
    let url = origin_path.to_string_lossy().to_string();
7361
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
7362
    write(&root.join("a"), "base.txt", b"base\n");
7363
    a.commit("base", &[]).unwrap();
7364
    assert!(a.push("origin", false).unwrap()[0].ok);
7365
    a.bookmark_create("develop", None).unwrap();
7366
    a.bookmark_switch("develop", false).unwrap();
7367
    write(&root.join("a"), "base.txt", b"base\nd1\n");
7368
    let d1 = a.commit("d1", &[]).unwrap();
7369
    assert!(a.push("origin", false).unwrap()[0].ok);
7370
7371
    // A clone has main only; origin/develop is a name all the same.
7372
    let c_root = root.join("c");
7373
    let mut c = Repo::clone(&url, &c_root).unwrap();
7374
    assert_eq!(c.config.bookmark, "main");
7375
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
7376
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
7377
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
7378
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
7379
7380
    // Switching makes the local bookmark from origin's.
7381
    c.bookmark_switch("develop", false).unwrap();
7382
    assert_eq!(c.config.bookmark, "develop");
7383
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
7384
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
7385
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
7386
    assert!(c.bookmark_switch("nowhere", false).is_err());
7387
7388
    // Both bookmarks move on the remote; one pull takes both.
7389
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
7390
    let d2 = a.commit("d2", &[]).unwrap();
7391
    assert!(a.push("origin", false).unwrap()[0].ok);
7392
    a.bookmark_switch("main", false).unwrap();
7393
    write(&root.join("a"), "m.txt", b"m\n");
7394
    let m = a.commit("m", &[]).unwrap();
7395
    assert!(a.push("origin", false).unwrap()[0].ok);
733ea16a Andy McCall ↶ 7396
    // oxygen#117: a remote's bookmark merges without switching to it.
7397
    let f = Repo::clone(&url, &root.join("f")).unwrap();
7398
    assert!(!f.view().unwrap().bookmarks.contains_key("develop"));
7399
    let merged = f.merge("origin/develop").unwrap();
7400
    assert!(merged.changed, "{merged:?}");
7401
    assert!(
7402
        f.load_state_indexed(&f.bookmark_heads().unwrap())
7403
            .unwrap()
7404
            .contains(&d1),
7405
        "main holds develop's change"
7406
    );
7407
    assert!(f
7408
        .merge("origin/nowhere")
7409
        .unwrap_err()
7410
        .to_string()
7411
        .contains("no bookmark origin/nowhere"));
14edbaaf Andy McCall ↶ 7412
    let r = c.pull("origin").unwrap();
7413
    assert!(r.changed && r.checked_out, "{r:?}");
7414
    assert_eq!(r.heads, vec![d2]);
7415
    assert_eq!(r.others, vec!["main".to_string()]);
7416
    assert!(c.resolve_heads("main").unwrap().contains(&m));
7417
    assert_eq!(
7418
        fs::read(c_root.join("base.txt")).unwrap(),
7419
        b"base\nd1\nd2\n"
7420
    );
7421
    let again = c.pull("origin").unwrap();
7422
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
7423
7424
    // A clone checks out the remote's default bookmark.
7425
    origin.config.set("workspace.bookmark", "develop").unwrap();
7426
    origin.save_config().unwrap();
7427
    let e = Repo::clone(&url, &root.join("e")).unwrap();
7428
    assert_eq!(e.config.bookmark, "develop");
7429
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
7430
    let reopened = Repo::open(&root.join("e")).unwrap();
7431
    assert_eq!(reopened.config.bookmark, "develop");
7432
    // REMOTE/NAME names the remote's bookmark to switch to.
7433
    let mut e = reopened;
7434
    e.bookmark_switch("origin/main", false).unwrap();
7435
    assert_eq!(e.config.bookmark, "main");
7436
    assert!(e.bookmark_heads().unwrap().contains(&m));
7437
}
7438
98a1620a Andy McCall ↶ 7439
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
7440
/// op restore goes back to an operation, files included, and undo takes
7441
/// the restore back whole; op revert undoes one operation alone; each
7442
/// operation's changes are described from the views.
7443
#[test]
7444
fn operations_can_be_read_restored_and_reverted() {
7445
    hermetic();
7446
    let dir = tempfile::tempdir().unwrap();
7447
    let root = dir.path();
7448
    let repo = Repo::init(root).unwrap();
7449
    write(root, "a.txt", b"a\n");
7450
    let first = repo.commit("first", &[]).unwrap();
7451
    write(root, "a.txt", b"a\nb\n");
7452
    let second = repo.commit("second", &[]).unwrap();
7453
    let at_second = repo.head_op().unwrap().0.to_hex();
7454
    repo.bookmark_create("keep", None).unwrap();
7455
    let created = repo.head_op().unwrap().0.to_hex();
7456
    write(root, "n.txt", b"n\n");
7457
    let third = repo.commit("third", &[]).unwrap();
7458
7459
    // What each operation changed.
7460
    let ops = repo.op_log().unwrap();
7461
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
7462
    assert!(
7463
        changes
7464
            .iter()
7465
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
7466
        "{changes:?}"
7467
    );
7468
    assert!(changes
7469
        .iter()
7470
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
7471
7472
    // Reading at an earlier operation.
7473
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
7474
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
7475
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
7476
    write(root, "z.txt", b"z\n");
7477
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
7478
    fs::remove_file(root.join("z.txt")).unwrap();
7479
    assert!(repo.resolve_op("zz").is_err());
7480
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
7481
7482
    // Restore goes back, files and all; undo takes it back whole.
7483
    repo.op_restore(&at_second, false).unwrap();
7484
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
7485
    assert!(!root.join("n.txt").exists());
7486
    repo.undo().unwrap();
7487
    let mut heads = repo.bookmark_heads().unwrap();
7488
    heads.sort();
7489
    let mut want = vec![second, third];
7490
    want.sort();
7491
    assert_eq!(heads, want);
7492
    assert!(
7493
        root.join("n.txt").exists(),
7494
        "the files came back with the undo"
7495
    );
7496
7497
    // Revert the bookmark's creation alone: the commit after it stays.
7498
    let r = repo.op_revert(&created).unwrap();
7499
    assert_eq!(r.reverted, vec!["keep".to_string()]);
7500
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
7501
    assert!(repo
7502
        .load_state(&repo.bookmark_heads().unwrap())
7503
        .unwrap()
7504
        .contains(&third));
7505
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
7506
    let _ = first;
7507
}
7508
36041796 Andy McCall ↶ 7509
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
7510
/// from the status cache while every file is as the snapshot left it, and
7511
/// from a snapshot again as soon as one is not.
7512
#[test]
7513
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
7514
    hermetic();
7515
    let dir = tempfile::tempdir().unwrap();
7516
    let root = dir.path();
7517
    let repo = Repo::init(root).unwrap();
7518
    write(root, "a.txt", b"a\n");
7519
    write(root, "b.txt", b"b\n");
7520
    repo.commit("base", &[]).unwrap();
7521
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
7522
7523
    write(root, "a.txt", b"a\nmore\n");
7524
    assert_eq!(
7525
        repo.status_by_manifest().unwrap(),
7526
        None,
7527
        "no snapshot of the edit yet"
7528
    );
7529
    let snap = repo.snapshot_status("oxy status").unwrap();
7530
    assert_eq!(snap.statuses.len(), 1);
7531
    let cached = repo
7532
        .status_by_manifest()
7533
        .unwrap()
7534
        .expect("answered from the cache");
7535
    assert_eq!(cached.len(), 1);
7536
    assert_eq!(
7537
        (cached[0].path.as_str(), cached[0].status),
7538
        ("a.txt", ChangeStatus::Modified)
7539
    );
7540
7541
    // Any further change sends status back to a snapshot.
7542
    write(root, "a.txt", b"a\nmore\nand more\n");
7543
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
7544
    repo.snapshot_status("oxy status").unwrap();
7545
    assert!(repo.status_by_manifest().unwrap().is_some());
7546
    write(root, "new.txt", b"n\n");
7547
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
7548
    fs::remove_file(root.join("new.txt")).unwrap();
7549
    assert!(
7550
        repo.status_by_manifest().unwrap().is_some(),
7551
        "back as it was"
7552
    );
7553
    fs::remove_file(root.join("b.txt")).unwrap();
7554
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
7555
    write(root, "b.txt", b"b\n");
7556
7557
    // A commit leaves nothing uncommitted: clean again, no cache needed.
7558
    repo.snapshot_status("oxy status").unwrap();
7559
    repo.commit("more", &[]).unwrap();
7560
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7561
}
7562
77445673 Andy McCall ↶ 7563
/// oxygen#41: while the status cache holds, the working copy's diff is
7564
/// rendered from the stored working-copy change, and says exactly what a
7565
/// snapshot's diff says.
7566
#[test]
7567
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
7568
    hermetic();
7569
    let dir = tempfile::tempdir().unwrap();
7570
    let root = dir.path();
7571
    let repo = Repo::init(root).unwrap();
7572
    write(root, "a.txt", b"one\ntwo\nthree\n");
7573
    write(root, "gone.txt", b"bye\n");
7574
    repo.commit("base", &[]).unwrap();
7575
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
7576
    write(root, "new.txt", b"hello\n");
7577
    fs::remove_file(root.join("gone.txt")).unwrap();
7578
    let snap = repo.snapshot_status("oxy status").unwrap();
7579
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
7580
    assert!(
7581
        repo.status_by_manifest().unwrap().is_some(),
7582
        "the cache holds"
7583
    );
7584
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
7585
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
7586
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
74b4a3c6 Andy McCall ↶ 7587
7588
    // Committed, nothing changes: the diff is empty without loading the
7589
    // base (oxygen#94), and the same as rendering it.
7590
    repo.commit("all", &[]).unwrap();
7591
    repo.snapshot_status("oxy status").unwrap();
7592
    assert!(repo.status_by_manifest().unwrap().is_some());
7593
    assert!(repo
7594
        .working_copy_with_base_unless_unchanged()
7595
        .unwrap()
7596
        .is_none());
7597
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
7598
    assert_eq!(render_change(&wc, &base, &snapshot), "");
7599
    assert!(repo.diff_files(None).unwrap().is_empty());
77445673 Andy McCall ↶ 7600
}
7601
1ec3f008 Andy McCall ↶ 7602
/// oxygen#41: a manifest written from a walk keeps every directory's time;
7603
/// while none has moved, the check stats the tracked files without listing
7604
/// the tree, and a file added or removed anywhere moves its directory's
7605
/// time, so the tree is listed again.
7606
#[test]
7607
fn the_manifest_check_skips_listing_while_no_directory_changed() {
7608
    hermetic();
7609
    let dir = tempfile::tempdir().unwrap();
7610
    let root = dir.path();
7611
    let repo = Repo::init(root).unwrap();
7612
    write(root, "a.txt", b"a\n");
7613
    write(root, "sub/deep/b.txt", b"b\n");
7614
    repo.commit("base", &[]).unwrap();
7615
    // Out of the racy window: every file and directory a minute old.
7616
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7617
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
7618
        fs::File::open(root.join(p))
7619
            .unwrap()
7620
            .set_modified(old)
7621
            .unwrap();
7622
    }
7623
    repo.snapshot_status("oxy status").unwrap();
7624
    repo.write_manifest(false, false).unwrap();
7625
    let m = repo.read_manifest().unwrap().unwrap().2;
7626
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
7627
    assert_eq!(
7628
        repo.disk_differs_by_dirs(&m),
7629
        Some(false),
7630
        "no listing needed"
7631
    );
7632
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7633
7634
    // A same-size edit with a new time: found by its stat.
7635
    write(root, "sub/deep/b.txt", b"c\n");
7636
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
7637
    write(root, "sub/deep/b.txt", b"b\n");
7638
    fs::File::open(root.join("sub/deep/b.txt"))
7639
        .unwrap()
7640
        .set_modified(old)
7641
        .unwrap();
7642
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
7643
7644
    // A new file moves its directory's time: the tree must be listed.
7645
    write(root, "sub/deep/new.txt", b"n\n");
7646
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7647
    assert_eq!(repo.status_by_manifest().unwrap(), None);
7648
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
7649
    // A removed one too.
7650
    fs::remove_file(root.join("a.txt")).unwrap();
7651
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7652
}
7653
e226a6cc Andy McCall ↶ 7654
/// oxygen#41: a commit right after a status takes the snapshot the status
7655
/// left (the status cache holds) rather than walking again, and commits
7656
/// exactly what a snapshot would have.
7657
#[test]
7658
fn a_commit_after_a_status_uses_the_cached_snapshot() {
7659
    hermetic();
7660
    let dir = tempfile::tempdir().unwrap();
7661
    let root = dir.path();
7662
    let repo = Repo::init(root).unwrap();
7663
    write(root, "a.txt", b"a\nb\n");
7664
    write(root, ".oxyattributes", b"*.bin binary\n");
7665
    repo.commit("base", &[]).unwrap();
7666
    write(root, "a.txt", b"a\nB\n");
7667
    write(root, "new.txt", b"new\n");
7668
    let snap = repo.snapshot_status("oxy status").unwrap();
7669
    let cached = repo
7670
        .snapshot_from_cache()
7671
        .unwrap()
7672
        .expect("the cache holds");
7673
    assert_eq!(cached.wc_hash, snap.wc_hash);
7674
    assert_eq!(cached.statuses, snap.statuses);
7675
    assert!(
7676
        !cached.attributes.is_empty(),
7677
        "the .oxyattributes file was read"
7678
    );
7679
    let h = repo.commit("edit", &[]).unwrap();
7680
    let c = repo.store().get_change(&h).unwrap();
7681
    assert_eq!(
7682
        c.tree_ops.len() + c.edits.len(),
7683
        snap.wc.tree_ops.len() + snap.wc.edits.len()
7684
    );
7685
    assert_eq!(
7686
        repo.status_by_manifest().unwrap(),
7687
        Some(vec![]),
7688
        "clean after the commit"
7689
    );
7690
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
7691
}
7692
0389c3e8 Andy McCall ↶ 7693
/// oxygen#41: a clean check that verified racy entries restamps the
7694
/// manifest, so later checks can trust them, and a same-size rewrite
7695
/// straight afterwards is still found: entries within two seconds of the
7696
/// new time stay racy.
7697
#[test]
7698
fn a_verified_clean_check_restamps_the_manifest_safely() {
7699
    hermetic();
7700
    let dir = tempfile::tempdir().unwrap();
7701
    let root = dir.path();
7702
    let repo = Repo::init(root).unwrap();
7703
    write(root, "a.txt", b"one\n");
7704
    repo.commit("one", &[]).unwrap();
7705
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
7706
    assert!(repo.clean_by_manifest().unwrap());
7707
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
7708
    assert!(after > before, "restamped");
7709
    write(root, "a.txt", b"two\n");
7710
    assert!(
7711
        !repo.clean_by_manifest().unwrap(),
7712
        "a same-size rewrite is still seen"
7713
    );
7714
}
7715
86e1824f Andy McCall ↶ 7716
/// oxygen#35: a history-only state keeps no inserted text. It reads a
7717
/// stored insert's text blob only when it builds that file's graph, and
7718
/// builds the same graph a full load does.
7719
#[test]
7720
fn history_only_states_read_text_only_for_the_graphs_they_build() {
7721
    hermetic();
7722
    let dir = tempfile::tempdir().unwrap();
7723
    let root = dir.path();
7724
    let repo = Repo::init(root).unwrap();
7725
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
7726
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
7727
    write(root, "big.txt", big.as_bytes());
7728
    write(root, "other.txt", other.as_bytes());
7729
    let h = repo.commit("two large files", &[]).unwrap();
7730
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
7731
    let h2 = repo.commit("append", &[]).unwrap();
7732
7733
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
7734
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
7735
        FileContent::Text { bytes, .. } => bytes.clone(),
7736
        other => panic!("{other:?}"),
7737
    };
7738
    // Built on demand, every graph renders as the full load's.
7739
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7740
    let big_node = full.files["big.txt"].node;
7741
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
7742
    repo.load_all_graphs(&mut hist).unwrap();
7743
    let rendered = hist.materialize();
7744
    for p in ["big.txt", "other.txt"] {
7745
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
7746
    }
7747
7748
    // Without other.txt's text blob, history still loads and big.txt still
7749
    // builds: nothing read the other text.
7750
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7751
    assert_eq!(texts.len(), 2);
7752
    let content = |r: &ObjectRef| -> Vec<u8> {
7753
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
7754
        blob.chunks
7755
            .iter()
7756
            .flat_map(|c| repo.store().get(c).unwrap().1)
7757
            .collect()
7758
    };
7759
    let other_text = texts
7760
        .iter()
a4fad5b0 Andy McCall ↶ 7761
        .filter_map(|t| match t {
0f93f49c Andy McCall ↶ 7762
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
a4fad5b0 Andy McCall ↶ 7763
            _ => None,
7764
        })
86e1824f Andy McCall ↶ 7765
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
7766
        .unwrap();
64818938 Andy McCall ↶ 7767
    repo.store().remove_loose_for_test(&other_text).unwrap();
86e1824f Andy McCall ↶ 7768
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7769
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
7770
    assert!(repo
7771
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
7772
        .is_err());
7773
}
7774
7775
/// oxygen#35: the first status after a commit read and rendered every
7776
/// file (79 s and more than 14 GB on the Linux tree), because the
7777
/// manifest had no graph keys for files the commit added.
7778
#[test]
7779
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
7780
    use std::os::unix::fs::PermissionsExt;
7781
    hermetic();
7782
    let dir = tempfile::tempdir().unwrap();
7783
    let root = dir.path();
7784
    let repo = Repo::init(root).unwrap();
7785
    let files = ["a.txt", "b.txt", "d/c.txt"];
7786
    for p in files {
7787
        write(root, p, format!("{p}\n").as_bytes());
7788
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7789
        fs::File::options()
7790
            .write(true)
7791
            .open(root.join(p))
7792
            .unwrap()
7793
            .set_modified(old)
7794
            .unwrap();
7795
    }
7796
    repo.commit("added", &[]).unwrap();
7797
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
7798
    assert!(
7799
        m.entries.values().all(|e| e.graph.is_some()),
7800
        "keys recorded at commit"
7801
    );
7802
    // Unreadable files prove the next status reads none of them.
7803
    for p in files {
7804
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
7805
    }
7806
    let snap = repo.snapshot_status("status").unwrap();
7807
    for p in files {
7808
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
7809
    }
7810
    assert!(!snap.changed && snap.statuses.is_empty());
7811
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
7812
}
c5ce0367 Andy McCall ↶ 7813
7814
/// oxygen#35: a checkout reads, renders and writes only the files whose
7815
/// graphs differ, and renders the rest a batch at a time.
7816
#[test]
7817
fn checkout_touches_only_what_differs_and_renders_in_batches() {
7818
    use std::os::unix::fs::PermissionsExt;
7819
    hermetic();
7820
    let dir = tempfile::tempdir().unwrap();
7821
    let root = dir.path();
7822
    let origin = root.join("origin");
7823
    let mut repo = Repo::init(&origin).unwrap();
7824
    // More files than one batch holds.
7825
    let n = 2100;
7826
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7827
    for i in 0..n {
7828
        let p = format!("f/{i:04}.txt");
7829
        write(&origin, &p, format!("file {i}\n").as_bytes());
7830
        fs::File::options()
7831
            .write(true)
7832
            .open(origin.join(&p))
7833
            .unwrap()
7834
            .set_modified(old)
7835
            .unwrap();
7836
    }
7837
    repo.commit("many", &[]).unwrap();
7838
    repo.bookmark_create("feature", None).unwrap();
7839
    repo.bookmark_switch("feature", false).unwrap();
7840
    write(&origin, "f/0007.txt", b"changed\n");
7841
    repo.commit("one change", &[]).unwrap();
7842
7843
    // Switching back to main must not read the unchanged files.
7844
    for i in 0..n {
7845
        if i != 7 {
7846
            let p = origin.join(format!("f/{i:04}.txt"));
7847
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
7848
        }
7849
    }
7850
    let r = repo.bookmark_switch("main", false).unwrap();
7851
    for i in 0..n {
7852
        let p = origin.join(format!("f/{i:04}.txt"));
7853
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
7854
    }
7855
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
7856
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
7857
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7858
7859
    // A clone renders every file, across batches.
7860
    let c = root.join("clone");
7861
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
7862
    for i in [0, 2047, 2048, n - 1] {
7863
        assert_eq!(
7864
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
7865
            format!("file {i}\n").as_bytes()
7866
        );
7867
    }
7868
    let cloned = Repo::open(&c).unwrap();
7869
    assert!(cloned
7870
        .snapshot_status("status")
7871
        .unwrap()
7872
        .statuses
7873
        .is_empty());
d3cd7ef9 Andy McCall ↶ 7874
}
7875
7876
/// A file written just before the manifest (inside the racy window) is
7877
/// checked by its hash: trusted when equal, caught when edited in place
7878
/// with the same size and time.
7879
#[test]
7880
fn a_racy_manifest_entry_is_checked_by_hash() {
7881
    hermetic();
7882
    let dir = tempfile::tempdir().unwrap();
7883
    let root = dir.path();
7884
    let repo = Repo::init(root).unwrap();
7885
    write(root, "a.txt", b"one\n");
7886
    repo.commit("fresh", &[]).unwrap();
7887
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
7888
    let t = fs::metadata(root.join("a.txt"))
7889
        .unwrap()
7890
        .modified()
7891
        .unwrap();
7892
    write(root, "a.txt", b"two\n");
7893
    fs::File::options()
7894
        .write(true)
7895
        .open(root.join("a.txt"))
7896
        .unwrap()
7897
        .set_modified(t)
7898
        .unwrap();
7899
    assert!(
7900
        !repo.clean_by_manifest().unwrap(),
7901
        "same size and time, other bytes"
7902
    );
7903
    assert_eq!(
7904
        statuses(&repo.snapshot_status("status").unwrap()),
7905
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
7906
    );
c5ce0367 Andy McCall ↶ 7907
}
2c75672f Andy McCall ↶ 7908
7909
/// A fetch on one machine moves changes as stored, text blobs among the
7910
/// objects; a change whose text blob did not come is refused, not stored.
7911
#[test]
7912
fn a_raw_bundle_without_a_changes_text_is_refused() {
7913
    hermetic();
7914
    let dir = tempfile::tempdir().unwrap();
7915
    let root = dir.path();
7916
    let a = Repo::init(&root.join("a")).unwrap();
7917
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7918
    write(&root.join("a"), "big.txt", big.as_bytes());
7919
    let h = a.commit("big", &[]).unwrap();
7920
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
7921
    assert_eq!(bundle.raw_changes.len(), 1);
7922
    assert!(bundle.changes.is_empty());
7923
    let b = Repo::init(&root.join("b")).unwrap();
7924
    let mut without = bundle.clone();
7925
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
7926
    let e = b.import_bundle(&without, false).unwrap_err();
7927
    assert!(e.to_string().contains("came without its text blob"), "{e}");
7928
    assert!(!b.store().has(&h));
7929
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
7930
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
7931
}
a87c7b9d Andy McCall ↶ 7932
7933
/// oxygen#30 (vscode): a directory deleted in one line of history and made
7934
/// again was a second node for one Git path, so a file moved into it on
7935
/// another line, where the first node still stood, ended up in two places.
7936
/// An import now brings the directory back rather than make a new one.
7937
#[test]
7938
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
7939
    hermetic();
7940
    if std::process::Command::new("git")
7941
        .arg("--version")
7942
        .output()
7943
        .is_err()
7944
    {
7945
        eprintln!("git not installed; skipping");
7946
        return;
7947
    }
7948
    let dir = tempfile::tempdir().unwrap();
7949
    let root = dir.path();
7950
    let g = root.join("src.git");
7951
    fs::create_dir_all(&g).unwrap();
7952
    let git = |args: &[&str]| -> String {
7953
        let out = std::process::Command::new("git")
7954
            .arg("-C")
7955
            .arg(&g)
7956
            .args([
7957
                "-c",
7958
                "user.name=Grace",
7959
                "-c",
7960
                "[email protected]",
7961
                "-c",
7962
                "commit.gpgsign=false",
7963
            ])
7964
            .args(args)
7965
            .output()
7966
            .unwrap();
7967
        assert!(
7968
            out.status.success(),
7969
            "git {args:?}: {}",
7970
            String::from_utf8_lossy(&out.stderr)
7971
        );
7972
        String::from_utf8_lossy(&out.stdout).trim().to_string()
7973
    };
7974
    git(&["init", "-q", "-b", "main"]);
7975
    write(&g, "d/a.txt", b"a\n");
7976
    write(&g, "c/x.txt", b"x\n");
7977
    git(&["add", "."]);
7978
    git(&["commit", "-qm", "base"]);
7979
    // One line: move x into d while d still stands.
7980
    git(&["checkout", "-qb", "side"]);
7981
    git(&["mv", "c/x.txt", "d/x.txt"]);
7982
    git(&["commit", "-qm", "x into d"]);
7983
    // The other: d goes, comes back, and x moves into it too.
7984
    git(&["checkout", "-q", "main"]);
7985
    git(&["rm", "-q", "d/a.txt"]);
7986
    git(&["commit", "-qm", "d goes"]);
7987
    write(&g, "d/b.txt", b"b\n");
7988
    git(&["add", "."]);
7989
    git(&["commit", "-qm", "d comes back"]);
7990
    git(&["mv", "c/x.txt", "d/x.txt"]);
7991
    git(&["commit", "-qm", "x into d again"]);
7992
    git(&["merge", "-q", "--no-edit", "side"]);
7993
7994
    let repo = Repo::init(&root.join("o")).unwrap();
7995
    repo.import_git(&g, "main").unwrap();
7996
    let v = repo.verify_git_import(&g, "main").unwrap();
7997
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
7998
    let st = repo
7999
        .load_state_history(&repo.bookmark_heads().unwrap())
8000
        .unwrap();
8001
    let view = st.tree().view();
8002
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8003
    // The directory is the one the first commit made.
8004
    // Commits made in one second tie on time: find the first by its message.
8005
    let first = repo
8006
        .log()
8007
        .unwrap()
8008
        .into_iter()
8009
        .find(|e| e.change.message.starts_with("base"))
8010
        .unwrap();
8011
    let base = repo
8012
        .load_state_history(&[first.hash])
8013
        .unwrap()
8014
        .tree()
8015
        .view();
8016
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
8017
}
8018
8019
/// oxygen#30, the rest: a placement left under a directory another line
8020
/// removed is out of sight, so no diff reaches it; the merge that settles
8021
/// where the file is retires it.
8022
#[test]
8023
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
8024
    hermetic();
8025
    if std::process::Command::new("git")
8026
        .arg("--version")
8027
        .output()
8028
        .is_err()
8029
    {
8030
        eprintln!("git not installed; skipping");
8031
        return;
8032
    }
8033
    let dir = tempfile::tempdir().unwrap();
8034
    let root = dir.path();
8035
    let g = root.join("src.git");
8036
    fs::create_dir_all(&g).unwrap();
8037
    let run = |args: &[&str]| {
8038
        std::process::Command::new("git")
8039
            .arg("-C")
8040
            .arg(&g)
8041
            .args([
8042
                "-c",
8043
                "user.name=Grace",
8044
                "-c",
8045
                "[email protected]",
8046
                "-c",
8047
                "commit.gpgsign=false",
8048
            ])
8049
            .args(args)
8050
            .output()
8051
            .unwrap()
8052
    };
8053
    let git = |args: &[&str]| {
8054
        let out = run(args);
8055
        assert!(
8056
            out.status.success(),
8057
            "git {args:?}: {}",
8058
            String::from_utf8_lossy(&out.stderr)
8059
        );
8060
    };
8061
    git(&["init", "-q", "-b", "main"]);
8062
    write(&g, "c/x.txt", b"x\n");
8063
    write(&g, "keep.txt", b"k\n");
8064
    git(&["add", "."]);
8065
    git(&["commit", "-qm", "base"]);
8066
    // One line renames the file within c; the other moves it out of c,
8067
    // which goes.
8068
    git(&["checkout", "-qb", "side"]);
8069
    git(&["mv", "c/x.txt", "c/y.txt"]);
8070
    git(&["commit", "-qm", "rename within c"]);
8071
    git(&["checkout", "-q", "main"]);
8072
    fs::create_dir_all(g.join("n")).unwrap();
8073
    git(&["mv", "c/x.txt", "n/x.txt"]);
8074
    git(&["commit", "-qm", "move out of c"]);
8075
    // Git cannot merge the two renames; the merge keeps n/x.txt.
8076
    let _ = run(&["merge", "-q", "side"]);
8077
    let _ = run(&[
8078
        "rm",
8079
        "-q",
8080
        "--cached",
8081
        "--ignore-unmatch",
8082
        "c/y.txt",
8083
        "c/x.txt",
8084
    ]);
8085
    let _ = std::fs::remove_dir_all(g.join("c"));
8086
    write(&g, "n/x.txt", b"x\n");
8087
    git(&["add", "-A"]);
8088
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
8089
8090
    let repo = Repo::init(&root.join("o")).unwrap();
8091
    repo.import_git(&g, "main").unwrap();
8092
    let v = repo.verify_git_import(&g, "main").unwrap();
8093
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8094
    let st = repo
8095
        .load_state_history(&repo.bookmark_heads().unwrap())
8096
        .unwrap();
8097
    let view = st.tree().view();
8098
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8099
    assert!(view.entries.contains_key("n/x.txt"));
8100
}
8101
8102
/// oxygen#30, orphans: a file added on one line into a directory the other
8103
/// line removed is placed where the tree cannot show it; Git's merge keeps
8104
/// the file, and the import's merge leaves exactly one of it.
8105
#[test]
8106
fn git_import_merge_leaves_no_orphan_behind() {
8107
    hermetic();
8108
    if std::process::Command::new("git")
8109
        .arg("--version")
8110
        .output()
8111
        .is_err()
8112
    {
8113
        eprintln!("git not installed; skipping");
8114
        return;
8115
    }
8116
    let dir = tempfile::tempdir().unwrap();
8117
    let root = dir.path();
8118
    let g = root.join("src.git");
8119
    fs::create_dir_all(&g).unwrap();
8120
    let git = |args: &[&str]| {
8121
        let out = std::process::Command::new("git")
8122
            .arg("-C")
8123
            .arg(&g)
8124
            .args([
8125
                "-c",
8126
                "user.name=Grace",
8127
                "-c",
8128
                "[email protected]",
8129
                "-c",
8130
                "commit.gpgsign=false",
8131
            ])
8132
            .args(args)
8133
            .output()
8134
            .unwrap();
8135
        assert!(
8136
            out.status.success(),
8137
            "git {args:?}: {}",
8138
            String::from_utf8_lossy(&out.stderr)
8139
        );
8140
    };
8141
    git(&["init", "-q", "-b", "main"]);
8142
    write(&g, "d/f.txt", b"f\n");
8143
    write(&g, "keep.txt", b"k\n");
8144
    git(&["add", "."]);
8145
    git(&["commit", "-qm", "base"]);
8146
    git(&["checkout", "-qb", "side"]);
8147
    write(&g, "d/new.txt", b"new\n");
8148
    git(&["add", "."]);
8149
    git(&["commit", "-qm", "add into d"]);
8150
    git(&["checkout", "-q", "main"]);
8151
    git(&["rm", "-q", "d/f.txt"]);
8152
    git(&["commit", "-qm", "d goes"]);
8153
    git(&["merge", "-q", "--no-edit", "side"]);
8154
8155
    let repo = Repo::init(&root.join("o")).unwrap();
8156
    repo.import_git(&g, "main").unwrap();
8157
    let v = repo.verify_git_import(&g, "main").unwrap();
8158
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8159
    let st = repo
8160
        .load_state_history(&repo.bookmark_heads().unwrap())
8161
        .unwrap();
8162
    let view = st.tree().view();
8163
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8164
    assert!(view.entries.contains_key("d/new.txt"));
8165
}
d77e1702 Andy McCall ↶ 8166
8167
/// fsck checks a change's text as the blobs it is stored in, without
8168
/// decoding it: a missing text blob is an error named for the change.
8169
#[test]
8170
fn fsck_names_a_missing_text_blob() {
8171
    hermetic();
8172
    let dir = tempfile::tempdir().unwrap();
8173
    let root = dir.path();
8174
    let repo = Repo::init(root).unwrap();
8175
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
8176
    write(root, "big.txt", big.as_bytes());
8177
    let h = repo.commit("big", &[]).unwrap();
8178
    assert_eq!(repo.fsck().unwrap().errors(), 0);
8179
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
8180
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
8181
        panic!("a stored text")
8182
    };
64818938 Andy McCall ↶ 8183
    repo.store().remove_loose_for_test(&b).unwrap();
d77e1702 Andy McCall ↶ 8184
    let rep = repo.fsck().unwrap();
8185
    assert!(rep.errors() > 0);
8186
    assert!(
8187
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
8188
        "{:?}",
8189
        rep.problems
8190
    );
8191
}
a07f60a3 Andy McCall ↶ 8192
8193
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
8194
/// reached with that remote's token and CA (a private subrepo then clones
8195
/// for anyone who can read the parent); another hub gets none of them.
8196
#[test]
8197
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
8198
    hermetic();
8199
    let dir = tempfile::tempdir().unwrap();
8200
    let mut repo = Repo::init(dir.path()).unwrap();
8201
    repo.config
8202
        .set(
8203
            "remote.origin.url",
8204
            "https://Hub.example:7343/doomsdayone/metalgear",
8205
        )
8206
        .unwrap();
8207
    repo.config.set("remote.origin.token", "secret").unwrap();
8208
    repo.config
8209
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
8210
        .unwrap();
8211
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
8212
    assert_eq!(same.token.as_deref(), Some("secret"));
8213
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
8214
    for other in [
8215
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
8216
        "https://hub.example/doomsdayone/rstar-api",
8217
        "http://hub.example:7343/doomsdayone/rstar-api",
8218
    ] {
8219
        let o = repo.credentials_for(other);
8220
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
8221
    }
8222
}
ce14f0d6 Andy McCall ↶ 8223
ff1f62fe Andy McCall ↶ 8224
/// oxygen#47: a remote with no token of its own uses the user's credential
8225
/// store for its hub, and a nested checkout finds its parent's remote
8226
/// token there instead of keeping a copy.
ce14f0d6 Andy McCall ↶ 8227
#[test]
ff1f62fe Andy McCall ↶ 8228
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
8229
    hermetic();
8230
    let home = tempfile::tempdir().unwrap();
8231
    let dir = tempfile::tempdir().unwrap();
8232
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
8233
    parent
8234
        .config
8235
        .set("remote.origin.url", "https://hub.example/o/parent")
8236
        .unwrap();
8237
    parent.save_config().unwrap();
8238
    assert_eq!(parent.remote_options("origin").token, None);
8239
    crate::credentials::Credentials::at(home.path())
8240
        .save("https://hub.example", "stored", Some("andy"), None)
8241
        .unwrap();
8242
    assert_eq!(
8243
        parent.remote_options("origin").token.as_deref(),
8244
        Some("stored")
8245
    );
8246
8247
    let empty_home = tempfile::tempdir().unwrap();
8248
    let nested = dir.path().join("deps").join("child");
8249
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
8250
    child
8251
        .config
8252
        .set("remote.origin.url", "https://hub.example/o/child")
8253
        .unwrap();
8254
    child.save_config().unwrap();
8255
    assert_eq!(child.remote_options("origin").token, None);
8256
    parent
8257
        .config
8258
        .set("remote.origin.token", "checkout")
8259
        .unwrap();
8260
    parent.save_config().unwrap();
8261
    assert_eq!(
8262
        child.remote_options("origin").token.as_deref(),
8263
        Some("checkout")
8264
    );
8265
    // Another hub's checkout token is not borrowed.
8266
    child
8267
        .config
8268
        .set("remote.origin.url", "https://other.example/o/child")
8269
        .unwrap();
8270
    assert_eq!(child.remote_options("origin").token, None);
8271
}
8272
8273
#[test]
ce14f0d6 Andy McCall ↶ 8274
fn the_metadata_cache_survives_a_torn_tail() {
8275
    hermetic();
8276
    let dir = tempfile::tempdir().unwrap();
8277
    let root = dir.path();
8278
    let repo = Repo::init(root).unwrap();
8279
    write(root, "a.txt", b"1\n");
8280
    let h = repo.commit("first", &[]).unwrap();
8281
    let meta = repo.store().get_change_meta(&h).unwrap();
8282
    let cache = repo.store().dir().join("metas");
8283
    let len = fs::metadata(&cache).unwrap().len();
8284
    assert!(len > 0, "a change read is cached");
8285
    // A torn record at the end: the cache reads up to it and cuts it off.
8286
    fs::OpenOptions::new()
8287
        .append(true)
8288
        .open(&cache)
8289
        .unwrap()
8290
        .write_all(&[7; 20])
8291
        .unwrap();
8292
    let again = Repo::open(root).unwrap();
8293
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
8294
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
8295
}
f9466021 Andy McCall ↶ 8296
8297
#[test]
8298
fn a_manifest_that_does_not_check_reads_as_none() {
8299
    hermetic();
8300
    let dir = tempfile::tempdir().unwrap();
8301
    let root = dir.path();
8302
    let repo = Repo::init(root).unwrap();
8303
    write(root, "a.txt", b"1\n");
8304
    repo.commit("first", &[]).unwrap();
8305
    let path = repo.manifest_path();
8306
    let mut bytes = fs::read(&path).unwrap();
8307
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
8308
    let last = bytes.len() - 1;
8309
    bytes[last] ^= 1;
8310
    fs::write(&path, &bytes).unwrap();
8311
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
8312
    // The next status reads the files and writes it again.
8313
    let again = Repo::open(root).unwrap();
8314
    assert!(!again.snapshot("status").unwrap().changed);
8315
    assert!(again.read_manifest().unwrap().is_some());
8316
}
8317
8318
#[test]
8319
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
8320
    hermetic();
8321
    let dir = tempfile::tempdir().unwrap();
8322
    let root = dir.path();
8323
    let repo = Repo::init(root).unwrap();
8324
    write(root, "a.txt", b"1\n");
8325
    write(root, "b.txt", b"2\n");
8326
    // b.txt outside the racy window, so snapshots take it as unchanged.
8327
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
8328
    fs::File::options()
8329
        .write(true)
8330
        .open(root.join("b.txt"))
8331
        .unwrap()
8332
        .set_modified(old)
8333
        .unwrap();
8334
    repo.commit("first", &[]).unwrap();
8335
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
8336
    repo.snapshot_status("status").unwrap();
8337
    write(root, "a.txt", b"1\n2\n");
8338
    repo.commit("second", &[]).unwrap();
8339
    assert!(
8340
        repo.clean_by_manifest().unwrap(),
8341
        "after a commit of one file"
8342
    );
8343
    // Edited, seen by a status, edited again, then committed: the status
8344
    // left the first edit's stat, which the commit must not keep.
8345
    write(root, "a.txt", b"1\n2\n3\n");
8346
    repo.snapshot_status("status").unwrap();
8347
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
8348
    repo.commit("third", &[]).unwrap();
8349
    assert!(
8350
        repo.clean_by_manifest().unwrap(),
8351
        "after an edit a status saw"
8352
    );
8353
}
e266b7d4 Andy McCall ↶ 8354
8355
#[test]
8356
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
8357
    hermetic();
8358
    let dir = tempfile::tempdir().unwrap();
8359
    let root = dir.path();
8360
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8361
    write(root, "a.txt", b"1\n2\n");
8362
    let a = repo.commit("A", &[]).unwrap();
8363
    repo.bookmark_create("develop", Some(&[a])).unwrap();
8364
    write(root, "a.txt", b"1\nX\n");
8365
    let c = repo.commit("C: 2 to X", &[]).unwrap();
8366
    repo.bookmark_switch("develop", false).unwrap();
8367
    write(root, "a.txt", b"1\nY\n");
8368
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
8369
    repo.bookmark_switch("main", false).unwrap();
8370
8371
    let err = repo.rebase(&c, &[d]).unwrap_err();
8372
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
8373
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
8374
    assert!(r.changed && r.checked_out);
8375
    let snap = repo.snapshot_status("status").unwrap();
8376
    assert!(
8377
        snap.base_snapshot.is_conflicted(),
8378
        "the conflict is in the working copy"
8379
    );
8380
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
8381
    assert!(text.contains('X') && text.contains('Y'), "{text}");
8382
8383
    write(root, "a.txt", b"1\nXY\n");
8384
    repo.commit("Resolve", &[]).unwrap();
8385
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
8386
    assert!(st.contains(&c) && st.contains(&d));
8387
    let files = st.materialize().files;
8388
    assert!(!files["a.txt"].is_conflicted());
8389
    assert!(
8390
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
8391
    );
8392
8393
    // A change the current bookmark does not hold is refused.
8394
    repo.bookmark_switch("develop", false).unwrap();
8395
    write(root, "b.txt", b"b\n");
8396
    let e = repo.commit("E", &[]).unwrap();
8397
    repo.bookmark_switch("main", false).unwrap();
8398
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
8399
    assert!(
8400
        err.to_string().contains("not on the current bookmark"),
8401
        "{err}"
8402
    );
8403
}
d4dbab97 Andy McCall ↶ 8404
8405
#[test]
8406
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
8407
    hermetic();
8408
    let dir = tempfile::tempdir().unwrap();
8409
    let root = dir.path();
8410
    let repo = Repo::init(root).unwrap();
8411
    write(root, "a.txt", b"a\n");
8412
    write(root, "kept.log", b"tracked\n");
8413
    repo.commit("first", &[]).unwrap();
8414
    write(root, "build.log", b"made\n");
8415
    let snap = repo.snapshot_status("status").unwrap();
8416
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
8417
    // A rule written afterwards leaves the added file out again, while the
8418
    // committed one stays tracked.
8419
    write(root, ".gitignore", b"*.log\n");
8420
    let snap = repo.snapshot_status("status").unwrap();
8421
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
8422
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
8423
    write(root, "kept.log", b"tracked, edited\n");
8424
    let snap = repo.snapshot_status("status").unwrap();
8425
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
8426
}
fd280228 Andy McCall ↶ 8427
8428
#[test]
8429
fn shed_graphs_come_back_the_same() {
8430
    hermetic();
8431
    let dir = tempfile::tempdir().unwrap();
8432
    let root = dir.path();
8433
    let repo = Repo::init(root).unwrap();
8434
    write(root, "a.txt", b"1\n2\n3\n");
8435
    write(root, "b.txt", b"x\n");
8436
    repo.commit("first", &[]).unwrap();
8437
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
8438
    repo.commit("second", &[]).unwrap();
8439
    let heads = repo.bookmark_heads().unwrap();
8440
    let mut st = repo.load_state_history(&heads).unwrap();
8441
    let view = st.tree().view();
8442
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
8443
        .iter()
8444
        .map(|p| view.entries[*p].node)
8445
        .collect();
8446
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8447
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8448
    assert_eq!(st.built_count(), 2);
8449
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
8450
    assert_eq!((shed, st.built_count()), (2, 0));
8451
    // A later change applies on top of the shed history.
8452
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
8453
    let h3 = repo.commit("third", &[]).unwrap();
8454
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
8455
    st.add_known(h3, skeleton, texts);
8456
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8457
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8458
    assert_eq!(after[1], before[1]);
8459
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
8460
}
360aa74a Andy McCall ↶ 8461
8462
#[test]
8463
fn many_edited_files_diff_in_parallel() {
8464
    // Enough edited files that the builder diffs them in parallel; the
8465
    // commit must hold exactly what is on disk, and a second snapshot
8466
    // must find nothing left to commit.
8467
    hermetic();
8468
    let dir = tempfile::tempdir().unwrap();
8469
    let root = dir.path();
8470
    let repo = Repo::init(root).unwrap();
8471
    let text = |i: usize, round: usize| {
8472
        let mut s = String::new();
8473
        for line in 0..50 {
8474
            if round > 0 && line % 7 == i % 7 {
8475
                s.push_str(&format!("edited {round} {i} {line}\n"));
8476
            } else {
8477
                s.push_str(&format!("file {i} line {line}\n"));
8478
            }
8479
        }
8480
        if round > 0 && i.is_multiple_of(3) {
8481
            s.push_str("appended\n");
8482
        }
8483
        s
8484
    };
8485
    for i in 0..40 {
8486
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
8487
    }
8488
    repo.commit("first", &[]).unwrap();
8489
    for i in 0..40 {
8490
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
8491
    }
8492
    let h = repo.commit("edit every file", &[]).unwrap();
8493
    let snap = repo.load_state(&[h]).unwrap().materialize();
8494
    for i in 0..40 {
8495
        let want = text(i, 1);
8496
        assert!(
8497
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
8498
            "d/f{i}.txt as committed"
8499
        );
8500
    }
8501
    assert!(
8502
        repo.commit("nothing", &[]).is_err(),
8503
        "nothing left to commit"
8504
    );
8505
}
b35df36b Andy McCall ↶ 8506
8507
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
8508
/// is known (fetch printed "up to date" while main was behind), a change
8509
/// only fetched resolves and says where it is, and a checkout whose only
8510
/// remote is not `origin` uses that one.
8511
#[test]
8512
fn a_fetched_change_shows_as_behind_and_resolves() {
8513
    hermetic();
8514
    let dir = tempfile::tempdir().unwrap();
8515
    let root = dir.path();
8516
    let origin = Repo::init(&root.join("origin")).unwrap();
8517
    drop(origin);
8518
    let url = root.join("origin").to_string_lossy().to_string();
8519
    let a = Repo::clone(&url, &root.join("a"))
8520
        .unwrap()
8521
        .with_home(root.join("home-a"));
8522
    write(&root.join("a"), "f.txt", b"one\n");
8523
    a.commit("one", &[]).unwrap();
8524
    a.push("origin", false).unwrap();
8525
    let b = Repo::clone(&url, &root.join("b"))
8526
        .unwrap()
8527
        .with_home(root.join("home-b"));
8528
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8529
8530
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
8531
    let h2 = a.commit("two", &[]).unwrap();
8532
    a.push("origin", false).unwrap();
8533
    b.fetch("origin").unwrap();
8534
    // Fetched, not pulled: one behind, the change found and placed.
8535
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8536
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
8537
    assert_eq!(
8538
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
8539
            .unwrap(),
8540
        h2
8541
    );
8542
    assert_eq!(
8543
        b.remote_only_location(&h2).unwrap().as_deref(),
8544
        Some("origin/main")
8545
    );
8546
    // Fetching again changes nothing: still behind, which is what the
8547
    // CLI now says rather than "up to date".
8548
    b.fetch("origin").unwrap();
8549
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8550
    b.pull("origin").unwrap();
8551
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8552
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
8553
8554
    // One remote, not called origin: it is the default.
8555
    let mut c = Repo::init(&root.join("c")).unwrap();
8556
    assert_eq!(c.default_remote(), "origin");
8557
    c.config.set("remote.earth.url", &url).unwrap();
8558
    assert_eq!(c.default_remote(), "earth");
8559
    c.config.set("remote.origin.url", &url).unwrap();
8560
    assert_eq!(c.default_remote(), "origin");
8561
}
827281ee Andy McCall ↶ 8562
8563
/// oxygen#57: a clone from a relative local path records the remote as an
8564
/// absolute path, so fetch still finds it from inside the clone.
8565
#[test]
8566
fn a_clone_from_a_relative_path_records_it_absolute() {
8567
    hermetic();
8568
    let dir = tempfile::tempdir().unwrap();
8569
    let root = dir.path();
8570
    Repo::init(&root.join("origin")).unwrap();
8571
    let rel = crate::protocol::stored_url("relative/repo");
8572
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
8573
    assert_eq!(
8574
        crate::protocol::stored_url("https://hub.example/o/n"),
8575
        "https://hub.example/o/n"
8576
    );
8577
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8d803563 Andy McCall ↶ 8578
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
8579
    // A bucket is kept as written: it is not a path.
8580
    assert_eq!(
8581
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
8582
        "s3://bucket/prefix?profile=p"
8583
    );
827281ee Andy McCall ↶ 8584
    let url = root.join("origin").to_string_lossy().to_string();
8585
    let b = Repo::clone(&url, &root.join("b")).unwrap();
8586
    assert_eq!(b.config.remotes["origin"], url);
8587
    b.fetch("origin").unwrap();
8588
}
a46f3e4f Andy McCall ↶ 8589
8590
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
8591
/// and gets its subrepos at their pins from this workspace's copies, with
8592
/// their remotes pointing where the subrepos come from.
8593
#[test]
8594
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
8595
    hermetic();
8596
    let dir = tempfile::tempdir().unwrap();
8597
    let root = dir.path();
8598
    Repo::init(&root.join("lib-origin")).unwrap();
8599
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8600
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8601
        .unwrap()
8602
        .with_home(root.join("home"));
8603
    write(&root.join("lib"), "lib.txt", b"v1\n");
8604
    let l1 = lib.commit("lib v1", &[]).unwrap();
8605
    assert!(lib.push("origin", false).unwrap()[0].ok);
8606
8607
    let app_dir = root.join("app");
8608
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8609
    write(&app_dir, "main.txt", b"app\n");
8610
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8611
    app.commit("app with lib", &[]).unwrap();
8612
    // A second bookmark, and the main workspace on another.
8613
    app.bookmark_create("develop", None).unwrap();
8614
    app.bookmark_create("feature", None).unwrap();
8615
    let mut app = app;
8616
    app.bookmark_switch("feature", false).unwrap();
8617
    assert_eq!(app.config.bookmark, "feature");
8618
8619
    // The library's origin goes away: the subrepo must come from here.
8620
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
8621
    let heads = app.resolve_heads("develop").unwrap();
8622
    let ws = app
8623
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
8624
        .unwrap();
8625
    assert_eq!(
8626
        ws.config.bookmark, "develop",
8627
        "the new workspace is on develop"
8628
    );
8629
    assert_eq!(
8630
        app.config.bookmark, "feature",
8631
        "and this one stays on its own"
8632
    );
8633
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
8634
    assert_eq!(
8635
        sub.config.remotes["origin"], lib_url,
8636
        "its origin is the subrepo's URL"
8637
    );
8638
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
8639
    assert_eq!(
8640
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
8641
        b"v1\n"
8642
    );
8643
}
47ce8b8e Andy McCall ↶ 8644
8645
/// Revsets (docs/revset_query_language.md): symbols, relations, set
8646
/// operators and the predicates, over a small graph with two heads and
8647
/// a rename.
8648
#[test]
8649
fn revsets_select_changes_by_relation_author_text_date_and_path() {
8650
    hermetic();
8651
    let dir = tempfile::tempdir().unwrap();
8652
    let root = dir.path();
8653
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8654
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
8655
        .unwrap();
8656
    write(root, "src/a.rs", b"one\n");
8657
    let a = repo.commit("first: add a", &[]).unwrap();
8658
    write(root, "src/a.rs", b"one\ntwo\n");
8659
    let b = repo.commit("second: grow a", &[]).unwrap();
8660
    // A second head, independent of b: a new file on top of a.
8661
    repo.checkout(&[a], false, "checkout a").unwrap();
8662
    write(root, "docs/notes.md", b"notes\n");
8663
    let c = repo.commit("third: notes", &[]).unwrap();
8664
    // Back to both heads, then rename a.rs: the node keeps its identity.
8665
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
8666
        .unwrap();
8667
    fs::remove_file(root.join("src/a.rs")).unwrap();
8668
    write(root, "src/z.rs", b"one\ntwo\n");
8669
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
8670
    let wc = repo.working_copy().unwrap().0;
8671
    // A saved revset is checked when set.
8672
    repo.set_user_config("revset.mine", "author(me) & ::main")
8673
        .unwrap();
8674
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
8675
    let set = |src: &str| -> Vec<ChangeHash> {
8676
        let mut v = repo.revset(src).unwrap().hashes;
8677
        v.sort();
8678
        v
8679
    };
8680
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
8681
        let mut v = hs.to_vec();
8682
        v.sort();
8683
        v
8684
    };
8685
8686
    // Changes commute: a new file depends on nothing and the rename on the
8687
    // file's creation, so the graph is a, b->a, d->a, c, and the working
8688
    // copy on the three heads b, c, d.
8689
    let heads = sorted(&repo.bookmark_heads().unwrap());
8690
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
8691
    assert!(heads.contains(&d) && heads.contains(&c));
8692
    // Symbols and closures.
8693
    assert_eq!(set("main"), heads);
8694
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
8695
    assert_eq!(set("@"), vec![wc]);
8696
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
8697
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
8698
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
8699
    assert_eq!(
8700
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
8701
        sorted(&[a, b])
8702
    );
8703
    // Ranges: what main has beyond b, and `..` forms.
8704
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
8705
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
8706
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
8707
    // Operators and precedence: ~ binds tighter than &, & than |.
8708
    assert_eq!(
8709
        set(&format!("::main ~ #{}", d.short(12))),
8710
        sorted(&[a, b, c])
8711
    );
8712
    assert_eq!(
8713
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
8714
        sorted(&[b, c])
8715
    );
8716
    assert_eq!(set("all() ~ ::main"), vec![wc]);
8717
    // Relations.
8718
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
8719
    head_deps.sort();
8720
    head_deps.dedup();
8721
    assert_eq!(set("deps(main)"), head_deps);
8722
    let on_a: Vec<ChangeHash> = [b, c, d]
8723
        .into_iter()
8724
        .filter(|h| meta(h).deps.contains(&a))
8725
        .collect();
8726
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
8727
    assert_eq!(set("heads(::main)"), heads);
8728
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
8729
    assert_eq!(
8730
        set(&format!(
8731
            "heads(#{} | #{} | #{})",
8732
            a.short(12),
8733
            b.short(12),
8734
            c.short(12)
8735
        )),
8736
        sorted(&[b, c])
8737
    );
8738
    assert_eq!(set("latest(::main, 1)"), vec![d]);
8739
    assert_eq!(set("kind(working-copy)"), vec![wc]);
8740
    assert_eq!(set("none()"), vec![]);
8741
    // Predicates: author by name, email, key prefix and `me`.
8742
    let key = repo.config.author_key.unwrap();
8743
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
8744
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
8745
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
8746
    assert_eq!(set("author(me) & ::main").len(), 4);
8747
    assert_eq!(set("author(nobody)"), vec![]);
8748
    assert_eq!(set("description(notes)"), vec![c]);
8749
    assert_eq!(set("description(\"rename a\")"), vec![d]);
8750
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
8751
    assert_eq!(set("date(..2000-01-01)"), vec![]);
8752
    // touches follows the node through the rename, in the current state.
8753
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
8754
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
8755
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
8756
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
8757
    // Newest first in the result order.
8758
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
8759
    // The saved revset, and errors that say what is wrong.
8760
    assert_eq!(set("mine()").len(), 4);
8761
    let e = repo.revset("nosuch()").unwrap_err().to_string();
8762
    assert!(e.contains("unknown function nosuch()"), "{e}");
8763
    let e = repo.revset("main &").unwrap_err().to_string();
8764
    assert!(e.contains("at character"), "{e}");
8765
    let e = repo.revset("zzzz").unwrap_err().to_string();
8766
    assert!(e.contains("no change matches"), "{e}");
8767
    let e = repo
8768
        .revset_with_budget("::main", std::time::Duration::ZERO)
8769
        .unwrap_err()
8770
        .to_string();
8771
    assert!(e.contains("budget"), "{e}");
8772
    // The log entries carry the bookmark's heads and the working copy.
8773
    let entries = repo.log_revset("::@").unwrap();
8774
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
2c9ddac3 Andy McCall ↶ 8775
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
8776
    // push); then a signed change, a tag, and a revocation.
8777
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
8778
    assert_eq!(set("signed_by(me)"), vec![]);
8779
    repo.sign_change(&d).unwrap();
8780
    assert_eq!(set("signed_by(me)"), vec![d]);
8781
    assert_eq!(set("signed_by([email protected])"), vec![d]);
8782
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
8783
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
8784
    assert_eq!(set("delegated()"), vec![]);
8785
    assert_eq!(set("revoked()"), vec![]);
8786
    assert_eq!(set("attested(tag)"), vec![]);
8787
    repo.tag_create("v1", &[b], "first").unwrap();
8788
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
8789
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
8790
    assert_eq!(set("attested(receipt)"), vec![]);
8791
    assert_eq!(set("built(test)"), vec![]);
8792
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
8793
    assert!(e.contains("tag, receipt or ref"), "{e}");
8794
    repo.revoke_identity(&key, "test").unwrap();
8795
    assert_eq!(set("revoked()"), vec![d]);
8796
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
543bbf64 Andy McCall ↶ 8797
    // independent(X, IN): what could ship without X. c and d neither
8798
    // depend on b nor are depended on by it; a is below, the working copy
8799
    // above.
8800
    assert_eq!(
8801
        set(&format!("independent(#{}, ::@)", b.short(12))),
8802
        sorted(&[c, d])
8803
    );
8804
    assert_eq!(
8805
        set(&format!("independent(#{}, ::main)", a.short(12))),
8806
        vec![c]
8807
    );
8808
    // conflicts(S): nothing conflicts yet; then two edits of one line.
8809
    assert_eq!(set("conflicts()"), vec![]);
8810
    assert_eq!(set("conflicts(main)"), vec![]);
8811
    // (The saved revset above edited the user config under the root:
8812
    // discard it.)
8813
    repo.checkout(&[a], true, "checkout a").unwrap();
8814
    write(root, "src/a.rs", b"one\nTWO\n");
8815
    let e = repo
8816
        .commit("fifth: the other edit of line two", &[])
8817
        .unwrap();
8818
    repo.checkout(&repo.bookmark_heads().unwrap(), true, "checkout main")
8819
        .unwrap();
8820
    let conflicted = repo.revset("conflicts()").unwrap().hashes;
8821
    assert!(
8822
        conflicted.contains(&e) && conflicted.contains(&b),
8823
        "{conflicted:?} should hold b and e"
8824
    );
8825
    assert!(!conflicted.contains(&c));
8826
    assert_eq!(set("conflicts() & author(nobody)"), vec![]);
47ce8b8e Andy McCall ↶ 8827
}
614f55e1 Andy McCall ↶ 8828
8829
#[test]
8830
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
8831
    let dir = tempfile::tempdir().unwrap();
8832
    let root = dir.path();
8833
    let home = root.join("home");
8834
    // Ada's identity lives in the user file; repository `a` pins the same
8835
    // key in its own file, repository `b` names none.
8836
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
8837
    let (key, _) = a
8838
        .create_identity("Ada", "[email protected]", IdentityScope::User)
8839
        .unwrap();
8840
    a.config.set("author.key", &key.to_hex()).unwrap();
8841
    a.save_config().unwrap();
8842
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
8843
    let r = a
8844
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
8845
        .unwrap();
8846
    assert_eq!(
8847
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
8848
        r.new.to_hex(),
8849
        "the user file follows"
8850
    );
8851
    assert_eq!(
8852
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
8853
        r.new.to_hex(),
8854
        "the pinning repository follows"
8855
    );
8856
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
8857
    assert_eq!(
8858
        b.config.author_key,
8859
        Some(r.new),
8860
        "a checkout without a pin follows the user file"
8861
    );
8862
    // A repository-scoped identity leaves the user file alone.
8863
    let other_home = root.join("home2");
8864
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
8865
    let (ck, _) = c
8866
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
8867
        .unwrap();
8868
    assert!(!other_home.join("config.toml").exists());
8869
    let r2 = c.rotate_identity().unwrap();
8870
    assert_ne!(r2.new, ck);
8871
    assert_eq!(
8872
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
8873
        r2.new.to_hex()
8874
    );
8875
    assert!(
8876
        !other_home.join("config.toml").exists(),
8877
        "a repository-scoped identity stays repository-scoped"
8878
    );
8879
    // Several delegates in one rotation; a repeat is refused.
8880
    let (d1, d2) = (
8881
        SecretKey::generate().identity("D1", "d1@x", 1),
8882
        SecretKey::generate().identity("D2", "d2@x", 1),
8883
    );
8884
    let r3 = c
8885
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
8886
        .unwrap();
8887
    assert_eq!(r3.identity.delegates.len(), 2);
8888
    assert!(c
8889
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
8890
        .is_err());
8891
}
33be2409 Andy McCall ↶ 8892
8893
/// Two unrelated histories that both add the same file, joined by two
8894
/// independent merges on two branches, then those branches merged: Git
8895
/// merges identical additions cleanly, and the import must too (#71,
8896
/// found in VS Code's history).
8897
#[test]
8898
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
8899
    // Batches of one: every merge renders apart from the state, where a
8900
    // file whose graph the state had built came out empty (#71).
8901
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8902
    hermetic();
8903
    if std::process::Command::new("git")
8904
        .arg("--version")
8905
        .output()
8906
        .is_err()
8907
    {
8908
        eprintln!("git not installed; skipping");
8909
        return;
8910
    }
8911
    let dir = tempfile::tempdir().unwrap();
8912
    let root = dir.path();
8913
    let g = root.join("src.git");
8914
    fs::create_dir_all(&g).unwrap();
8915
    let git = |args: &[&str]| -> String {
8916
        let out = std::process::Command::new("git")
8917
            .arg("-C")
8918
            .arg(&g)
8919
            .args([
8920
                "-c",
8921
                "user.name=Grace",
8922
                "-c",
8923
                "[email protected]",
8924
                "-c",
8925
                "commit.gpgsign=false",
8926
            ])
8927
            .args(args)
8928
            .output()
8929
            .unwrap();
8930
        assert!(
8931
            out.status.success(),
8932
            "git {args:?}: {}",
8933
            String::from_utf8_lossy(&out.stderr)
8934
        );
8935
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8936
    };
8937
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
8938
    // History A: main.
8939
    git(&["init", "-q", "-b", "main"]);
8940
    write(&g, "gulpfile.js", text);
8941
    write(&g, "a.txt", b"a\n");
8942
    git(&["add", "."]);
8943
    git(&["commit", "-q", "-m", "A root"]);
8944
    // History B: an unrelated root adding the same file, identical.
8945
    git(&["checkout", "-q", "--orphan", "fork"]);
8946
    git(&["rm", "-q", "-r", "--cached", "."]);
8947
    for f in ["gulpfile.js", "a.txt"] {
8948
        let _ = fs::remove_file(g.join(f));
8949
    }
8950
    write(&g, "gulpfile.js", text);
8951
    write(&g, "b.txt", b"b\n");
8952
    git(&["add", "."]);
8953
    git(&["commit", "-q", "-m", "B root"]);
8954
    // Two branches from main, each joining B on its own.
8955
    git(&["checkout", "-q", "-b", "one", "main"]);
8956
    git(&[
8957
        "merge",
8958
        "-q",
8959
        "--no-ff",
8960
        "--allow-unrelated-histories",
8961
        "-m",
8962
        "join on one",
8963
        "fork",
8964
    ]);
8965
    git(&["checkout", "-q", "-b", "two", "main"]);
8966
    write(&g, "a.txt", b"a\ntwo\n");
8967
    git(&["commit", "-q", "-am", "work on two"]);
8968
    git(&[
8969
        "merge",
8970
        "-q",
8971
        "--no-ff",
8972
        "--allow-unrelated-histories",
8973
        "-m",
8974
        "join on two",
8975
        "fork",
8976
    ]);
8977
    // Then the two joins meet, and the file is reformatted after.
8978
    git(&["checkout", "-q", "main"]);
8979
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
8980
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
8981
    write(
8982
        &g,
8983
        "gulpfile.js",
8984
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
8985
    );
8986
    git(&["commit", "-q", "-am", "after"]);
8987
8988
    let dest = root.join("dest");
8989
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
8990
    repo.import_git(&g, "main").unwrap();
8991
    let v = repo.verify_git_import(&g, "main").unwrap();
8992
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8993
    assert_eq!(
8994
        fs::read(dest.join("gulpfile.js")).unwrap(),
8995
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
8996
    );
8997
}
8998
8999
/// As above, but the two joins keep different copies (each branch had a
9000
/// different version when it joined), and later work edits each copy:
9001
/// the shape of VS Code's c67ef57cda90 (#71).
9002
#[test]
9003
fn git_import_joins_where_each_join_kept_a_different_copy() {
9004
    // Batches of one: every merge renders apart from the state, where a
9005
    // file whose graph the state had built came out empty (#71).
9006
    crate::repo::git::set_merge_batch_for_tests(Some(1));
9007
    hermetic();
9008
    if std::process::Command::new("git")
9009
        .arg("--version")
9010
        .output()
9011
        .is_err()
9012
    {
9013
        eprintln!("git not installed; skipping");
9014
        return;
9015
    }
9016
    let dir = tempfile::tempdir().unwrap();
9017
    let root = dir.path();
9018
    let g = root.join("src.git");
9019
    fs::create_dir_all(&g).unwrap();
9020
    let run = |args: &[&str]| {
9021
        std::process::Command::new("git")
9022
            .arg("-C")
9023
            .arg(&g)
9024
            .args([
9025
                "-c",
9026
                "user.name=Grace",
9027
                "-c",
9028
                "[email protected]",
9029
                "-c",
9030
                "commit.gpgsign=false",
9031
            ])
9032
            .args(args)
9033
            .output()
9034
            .unwrap()
9035
    };
9036
    let git = |args: &[&str]| -> String {
9037
        let out = run(args);
9038
        assert!(
9039
            out.status.success(),
9040
            "git {args:?}: {}",
9041
            String::from_utf8_lossy(&out.stderr)
9042
        );
9043
        String::from_utf8_lossy(&out.stdout).trim().to_string()
9044
    };
9045
    git(&["init", "-q", "-b", "main"]);
9046
    write(
9047
        &g,
9048
        "gulpfile.js",
9049
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
9050
    );
9051
    git(&["add", "."]);
9052
    git(&["commit", "-q", "-m", "A root"]);
9053
    write(
9054
        &g,
9055
        "gulpfile.js",
9056
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
9057
    );
9058
    git(&["commit", "-q", "-am", "whitespace"]);
9059
    git(&["checkout", "-q", "--orphan", "fork"]);
9060
    git(&["rm", "-q", "-r", "--cached", "."]);
9061
    let _ = fs::remove_file(g.join("gulpfile.js"));
9062
    write(
9063
        &g,
9064
        "gulpfile.js",
9065
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
9066
    );
9067
    git(&["add", "."]);
9068
    git(&["commit", "-q", "-m", "B root"]);
9069
    // Branch one joins B keeping main's copy; branch two keeps B's.
9070
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
9071
        git(&["checkout", "-q", "-b", branch, "main"]);
9072
        let _ = run(&[
9073
            "merge",
9074
            "-q",
9075
            "--no-ff",
9076
            "--allow-unrelated-histories",
9077
            "-m",
9078
            "join",
9079
            "fork",
9080
        ]);
9081
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
9082
        git(&["add", "gulpfile.js"]);
9083
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
9084
    }
9085
    // Each branch then edits its copy.
9086
    git(&["checkout", "-q", "one"]);
9087
    write(
9088
        &g,
9089
        "gulpfile.js",
9090
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
9091
    );
9092
    git(&["commit", "-q", "-am", "tslint on one"]);
9093
    git(&["checkout", "-q", "two"]);
9094
    write(
9095
        &g,
9096
        "gulpfile.js",
9097
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
9098
    );
9099
    write(&g, "extra.txt", b"x\n");
9100
    write(&g, "more.txt", b"m\n");
9101
    git(&["add", "."]);
9102
    git(&["commit", "-q", "-am", "fmt on two"]);
9103
    // They meet: resolved by hand.
9104
    git(&["checkout", "-q", "one"]);
9105
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
9106
    write(
9107
        &g,
9108
        "gulpfile.js",
9109
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
9110
    );
9111
    git(&["add", "gulpfile.js"]);
9112
    git(&["commit", "-q", "-m", "merge two into one"]);
9113
9114
    let dest = root.join("dest");
9115
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
9116
    repo.import_git(&g, "one").unwrap();
9117
    let v = repo.verify_git_import(&g, "one").unwrap();
9118
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9119
}
dd21fd82 Andy McCall ↶ 9120
9121
/// oxygen#68: on a store that is not this disk's directory, the operation
9122
/// head is the store's reference record, moved by compare-and-swap. Two
9123
/// handles recording from the same head both get through, merged; a swap
9124
/// from a stale version is refused; a second repository cannot start on a
9125
/// store that already holds one.
9126
#[test]
9127
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
9128
    use crate::strata::{MemoryStore, Store as _};
9129
    let backend = std::sync::Arc::new(MemoryStore::new());
9130
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9131
    let dir = tempfile::tempdir().unwrap();
9132
    let a = Repo::init(dir.path()).unwrap();
9133
    assert!(
9134
        !dir.path().join(".oxy/ops/head").exists(),
9135
        "the head is not a file"
9136
    );
9137
    let (h0, op0) = a.head_op().unwrap();
9138
    let record = backend
9139
        .read_ref(HEAD_RECORD)
9140
        .unwrap()
9141
        .expect("the head is the store's record");
9142
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
9143
9144
    let b = Repo::open(dir.path()).unwrap();
9145
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9146
    let mut va = op0.view.clone();
9147
    va.bookmarks.insert("from-a".into(), state);
9148
    let mut vb = op0.view.clone();
9149
    vb.bookmarks.insert("from-b".into(), state);
9150
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
9151
    assert_eq!(b.head_ref().unwrap(), rb);
9152
    // a recorded from h0 too: the head moved, so the two are merged.
9153
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
9154
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
9155
    assert_eq!(head, ra);
9156
    assert!(
9157
        op.command.ends_with("(merged with a concurrent operation)"),
9158
        "{}",
9159
        op.command
9160
    );
9161
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
9162
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
9163
9164
    // A swap from a version that is no longer current moves nothing.
9165
    let (h, v) = a.read_head().unwrap();
9166
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
9167
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
767ac6cd Andy McCall 9168
    a.refresh().unwrap();
dd21fd82 Andy McCall ↶ 9169
    assert_eq!(a.head_ref().unwrap(), rb);
9170
9171
    let other = tempfile::tempdir().unwrap();
9172
    let err = Repo::init(other.path())
9173
        .err()
9174
        .expect("the store already holds a log")
9175
        .to_string();
9176
    assert!(
9177
        err.contains("already holds a repository's operation log"),
9178
        "{err}"
9179
    );
9180
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9181
}
d069701a Andy McCall ↶ 9182
9183
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
9184
/// objects and operation head there, with `.oxy/cache` in front: it works
9185
/// as one on disk does, reopens, and survives losing its cache.
9186
#[test]
9187
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
9188
    hermetic();
9189
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
9190
        return;
9191
    }
9192
    let dir = tempfile::tempdir().unwrap();
9193
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
9194
    let url = format!("dir://{}", bucket.display());
9195
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
9196
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
9197
    write(&root, "a.txt", b"one\n");
9198
    let h1 = repo.commit("First", &[]).unwrap();
9199
    write(&root, "a.txt", b"one\ntwo\n");
9200
    let h2 = repo.commit("Second", &[]).unwrap();
9201
    assert!(
9202
        !root.join(".oxy/ops/head").exists(),
9203
        "the head is in the store"
9204
    );
9205
    assert!(bucket.join("ops/head").is_file());
9206
    assert!(root.join(".oxy/cache").is_dir());
9207
    drop(repo);
9208
9209
    // Reopened, and again with no cache at all: everything comes from the store.
9210
    for drop_cache in [false, true] {
9211
        if drop_cache {
9212
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
9213
        }
9214
        let repo = Repo::open(&root).unwrap();
9215
        let log: Vec<String> = repo
9216
            .op_log()
9217
            .unwrap()
9218
            .into_iter()
9219
            .map(|(_, op)| op.command)
9220
            .collect();
9221
        assert!(log.len() >= 3, "{log:?}");
9222
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
9223
        let heads = repo
9224
            .store()
9225
            .get_state(&repo.view().unwrap().bookmarks["main"])
9226
            .unwrap()
9227
            .heads;
9228
        assert_eq!(heads, vec![h2]);
9229
        assert_eq!(
9230
            repo.load_state(&heads).unwrap().materialize().files.len(),
9231
            1
9232
        );
9233
    }
9234
9235
    // A second repository cannot start on the same store.
9236
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
9237
        .err()
9238
        .unwrap()
9239
        .to_string();
9240
    assert!(
9241
        err.contains("already holds a repository's operation log"),
9242
        "{err}"
9243
    );
9244
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
9245
        .err()
9246
        .unwrap()
9247
        .to_string();
9248
    assert!(err.contains("cannot open that kind of store"), "{err}");
9249
}
80677b7a Andy McCall ↶ 9250
9251
/// oxygen#75: the prompt's quick check agrees with status in a repository
9252
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
9253
/// another state, clean again once that pin is committed. (It compared the
9254
/// subrepo's directory as if it were a file, so it was always dirty.)
9255
#[test]
9256
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
9257
    hermetic();
9258
    let dir = tempfile::tempdir().unwrap();
9259
    let root = dir.path();
9260
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9261
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9262
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9263
        .unwrap()
9264
        .with_home(root.join("home"));
9265
    write(&root.join("lib"), "lib.txt", b"v1\n");
9266
    lib.commit("lib v1", &[]).unwrap();
9267
    assert!(lib.push("origin", false).unwrap()[0].ok);
9268
    let app_dir = root.join("app");
9269
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9270
    write(&app_dir, "main.txt", b"app\n");
9271
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9272
    app.commit("app with lib", &[]).unwrap();
9273
    // Out of the racy window, so the stat-only path decides.
9274
    std::thread::sleep(std::time::Duration::from_millis(2100));
9275
    let reopen = || Repo::open(&app_dir).unwrap();
9276
    assert_eq!(
9277
        reopen().quick_dirty().unwrap(),
9278
        Some(false),
9279
        "clean, as status says"
9280
    );
9281
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
9282
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
9283
    nested.commit("lib v2", &[]).unwrap();
9284
    assert_eq!(
9285
        reopen().quick_dirty().unwrap(),
9286
        Some(true),
9287
        "the subrepo moved"
9288
    );
9289
    reopen().commit("pin lib v2", &[]).unwrap();
9290
    std::thread::sleep(std::time::Duration::from_millis(2100));
9291
    assert_eq!(
9292
        reopen().quick_dirty().unwrap(),
9293
        Some(false),
9294
        "the new pin is committed"
9295
    );
9296
}
7993d465 Andy McCall ↶ 9297
9298
#[test]
9299
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
9300
    // oxygen#72: a .oxymodules section with no subrepo behind it.
9301
    hermetic();
9302
    let dir = tempfile::tempdir().unwrap();
9303
    let root = dir.path();
9304
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9305
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9306
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9307
        .unwrap()
9308
        .with_home(root.join("home"));
9309
    write(&root.join("lib"), "lib.txt", b"v1\n");
9310
    lib.commit("lib v1", &[]).unwrap();
9311
    assert!(lib.push("origin", false).unwrap()[0].ok);
9312
    let app_dir = root.join("app");
9313
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9314
    write(
9315
        &app_dir,
9316
        ".oxymodules",
9317
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
9318
    );
9319
    let unpinned = app.unpinned_modules().unwrap();
9320
    assert_eq!(unpinned.len(), 1);
9321
    assert_eq!(unpinned[0].0, "libs/lib");
9322
    assert_eq!(unpinned[0].1.url, lib_url);
9323
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
9324
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9325
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
9326
}
bf3a6781 Andy McCall ↶ 9327
9328
#[test]
9329
fn the_bookmark_revset_function_names_only_bookmarks() {
9330
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
9331
    hermetic();
9332
    let dir = tempfile::tempdir().unwrap();
9333
    let repo = Repo::init(dir.path()).unwrap();
9334
    write(dir.path(), "a.txt", b"a\n");
9335
    let a = repo.commit("A", &[]).unwrap();
9336
    write(dir.path(), "b.txt", b"b\n");
9337
    let b = repo.commit("B", &[]).unwrap();
9338
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
9339
    heads.sort();
9340
    let mut want = repo.bookmark_heads().unwrap();
9341
    want.sort();
9342
    assert_eq!(heads, want);
9343
    assert!(heads.contains(&b));
9344
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
9345
    // A change prefix is a symbol, not a bookmark.
9346
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
9347
    assert!(repo.revset(&prefix).is_ok());
9348
    let e = repo
9349
        .revset(&format!("bookmark({prefix})"))
9350
        .unwrap_err()
9351
        .to_string();
9352
    assert!(e.contains("no such bookmark"), "{e}");
9353
}
72484195 Andy McCall ↶ 9354
9355
#[test]
9356
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
9357
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
9358
    // pinning the subrepo, and the nested repository on disk at that pin.
9359
    hermetic();
9360
    let dir = tempfile::tempdir().unwrap();
9361
    let root = dir.path();
9362
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9363
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9364
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9365
        .unwrap()
9366
        .with_home(root.join("home"));
9367
    write(&root.join("lib"), "lib.txt", b"v1\n");
9368
    lib.commit("lib v1", &[]).unwrap();
9369
    assert!(lib.push("origin", false).unwrap()[0].ok);
9370
    let app_dir = root.join("app");
9371
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9372
    write(&app_dir, "main.txt", b"app\n");
9373
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9374
    // The stale state: registered in .oxymodules, never pinned.
9375
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
9376
    app.commit("initial", &[]).unwrap();
9377
    let stale = app.bookmark_heads().unwrap();
9378
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
9379
    app.commit("pin lib", &[]).unwrap();
9380
    let newer = app.bookmark_heads().unwrap();
9381
    app.checkout(&stale, false, "test").unwrap();
9382
    write(&app_dir, "notes.txt", b"mine\n");
9383
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
9384
    assert_eq!(carried, vec!["notes.txt".to_string()]);
9385
    assert!(app_dir.join("notes.txt").exists());
9386
}
9387
9388
#[test]
9389
fn a_bookmark_only_behind_its_remote_catches_up() {
9390
    // oxygen#74: switch takes the remote's state rather than a stale one.
9391
    hermetic();
9392
    let dir = tempfile::tempdir().unwrap();
9393
    let root = dir.path();
9394
    let _origin = Repo::init(&root.join("origin")).unwrap();
9395
    let url = root.join("origin").to_string_lossy().to_string();
9396
    let one = Repo::clone(&url, &root.join("one"))
9397
        .unwrap()
9398
        .with_home(root.join("home"));
9399
    write(&root.join("one"), "a.txt", b"a\n");
9400
    one.commit("A", &[]).unwrap();
9401
    assert!(one.push("origin", false).unwrap()[0].ok);
9402
    let two = Repo::clone(&url, &root.join("two"))
9403
        .unwrap()
9404
        .with_home(root.join("home"));
9405
    write(&root.join("two"), "b.txt", b"b\n");
9406
    two.commit("B", &[]).unwrap();
9407
    assert!(two.push("origin", false).unwrap()[0].ok);
9408
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
9409
    one.fetch("origin").unwrap();
9410
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
9411
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
9412
    // Local work the remote lacks: left alone.
9413
    write(&root.join("one"), "c.txt", b"c\n");
9414
    one.commit("C", &[]).unwrap();
9415
    write(&root.join("two"), "d.txt", b"d\n");
9416
    two.commit("D", &[]).unwrap();
9417
    assert!(two.push("origin", false).unwrap()[0].ok);
9418
    one.fetch("origin").unwrap();
9419
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
9420
}
42ccf504 Andy McCall ↶ 9421
9422
#[test]
9423
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
9424
    // oxygen#83: remotes earth and gcs, origin removed.
9425
    hermetic();
9426
    let dir = tempfile::tempdir().unwrap();
9427
    let root = dir.path();
9428
    let _up = Repo::init(&root.join("up")).unwrap();
9429
    let url = root.join("up").to_string_lossy().to_string();
9430
    let other = Repo::clone(&url, &root.join("other"))
9431
        .unwrap()
9432
        .with_home(root.join("home"));
9433
    write(&root.join("other"), "a.txt", b"a\n");
9434
    other.commit("a", &[]).unwrap();
9435
    assert!(other.push("origin", false).unwrap()[0].ok);
9436
    let mut one = Repo::clone(&url, &root.join("one"))
9437
        .unwrap()
9438
        .with_home(root.join("home"));
9439
    one.config.set("remote.earth.url", &url).unwrap();
9440
    one.config.set("remote.gcs.url", &url).unwrap();
9441
    one.config.set("remote.origin.url", "").unwrap();
9442
    one.save_config().unwrap();
9443
    write(&root.join("other"), "b.txt", b"b\n");
9444
    other.commit("b", &[]).unwrap();
9445
    assert!(other.push("origin", false).unwrap()[0].ok);
9446
    one.fetch("earth").unwrap();
9447
    let b = one
9448
        .bookmarks()
9449
        .unwrap()
9450
        .into_iter()
9451
        .find(|b| b.name == "main")
9452
        .unwrap();
9453
    assert_eq!(
9454
        (b.remote.as_deref(), b.behind),
9455
        (Some("earth"), Some(1)),
9456
        "a stale origin copy is not used"
9457
    );
9458
    assert_eq!(
9459
        one.default_remote(),
9460
        "origin",
9461
        "no default chosen among several"
9462
    );
9463
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
9464
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
9465
    one.config.set("core.remote", "earth").unwrap();
9466
    assert_eq!(one.default_remote(), "earth");
9467
}
cbe8499a Andy McCall ↶ 9468
9469
#[test]
9470
fn a_missing_author_identity_says_how_to_fix_it() {
9471
    // oxygen#82: an agent home's author.key naming an identity the
9472
    // repository does not hold.
9473
    hermetic();
9474
    let dir = tempfile::tempdir().unwrap();
9475
    let mut repo = Repo::init(dir.path()).unwrap();
9476
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
9477
    repo.config.set("author.key", &missing.to_hex()).unwrap();
9478
    let e = repo.identity(&missing).unwrap_err().to_string();
9479
    assert!(
9480
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
9481
        "{e}"
9482
    );
9483
    assert!(e.contains("this repository's config"), "{e}");
9484
}
f6dccc45 Andy McCall ↶ 9485
9486
#[test]
9487
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
9488
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
9489
    // the working copy, a pull with nothing new left it there, and status
9490
    // said "clean".
9491
    hermetic();
9492
    let dir = tempfile::tempdir().unwrap();
9493
    let root = dir.path();
9494
    let _up = Repo::init(&root.join("up")).unwrap();
9495
    let url = root.join("up").to_string_lossy().to_string();
9496
    let other = Repo::clone(&url, &root.join("other"))
9497
        .unwrap()
9498
        .with_home(root.join("home"));
9499
    write(&root.join("other"), "a.txt", b"a\n");
9500
    other.commit("a", &[]).unwrap();
9501
    assert!(other.push("origin", false).unwrap()[0].ok);
9502
    let one = Repo::clone(&url, &root.join("one"))
9503
        .unwrap()
9504
        .with_home(root.join("home"));
9505
    write(&root.join("other"), "b.txt", b"b\n");
9506
    other.commit("b", &[]).unwrap();
9507
    assert!(other.push("origin", false).unwrap()[0].ok);
9508
    one.fetch("origin").unwrap();
9509
    // The bookmark moves; the working copy does not.
9510
    let theirs = one.resolve_heads("origin/main").unwrap();
9511
    one.bookmark_set("main", &theirs).unwrap();
9512
    assert!(!root.join("one/b.txt").exists());
9513
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
9514
    let r = one.pull("origin").unwrap();
9515
    assert!(
9516
        !r.changed && r.checked_out,
9517
        "nothing new, but the working copy caught up"
9518
    );
9519
    assert!(root.join("one/b.txt").exists());
9520
    assert_eq!(one.working_copy_behind().unwrap(), None);
9521
}
170bb436 Andy McCall ↶ 9522
9523
#[test]
9524
fn touched_nodes_cache_answers_as_the_changes_do() {
9525
    hermetic();
9526
    let dir = tempfile::tempdir().unwrap();
9527
    let repo = Repo::init(dir.path()).unwrap();
9528
    write(dir.path(), "a.txt", b"one\n");
9529
    write(dir.path(), "b.txt", b"x\n");
9530
    repo.snapshot("t").unwrap();
9531
    let c1 = repo.commit("first", &[]).unwrap();
9532
    write(dir.path(), "b.txt", b"y\n");
9533
    repo.snapshot("t").unwrap();
9534
    repo.commit("b only", &[]).unwrap();
9535
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
9536
    write(dir.path(), "c.txt", b"one\ntwo\n");
9537
    repo.snapshot("t").unwrap();
9538
    let c3 = repo.commit("rename and edit", &[]).unwrap();
9539
    // Uncommitted work, so the working copy touches a file too.
9540
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
9541
    repo.snapshot("t").unwrap();
9542
9543
    let path = dir.path().join(".oxy/index/touched");
9544
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
9545
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
9546
    assert!(path.exists(), "the first query writes the cache");
9547
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
9548
    assert_eq!(cold, warm, "the cache answers as the changes do");
9549
    let (wc, _) = repo.working_copy().unwrap();
9550
    assert_eq!(
9551
        cold,
9552
        vec![wc, c3, c1],
9553
        "renames followed, the working copy included"
9554
    );
9555
9556
    // Working-copy changes are not kept: they are replaced by every snapshot.
9557
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
9558
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
9559
    assert!(cached.contains(&c1) && cached.contains(&c3));
9560
9561
    // A damaged cache is ignored, not trusted.
9562
    let mut bytes = fs::read(&path).unwrap();
9563
    let last = bytes.len() - 40;
9564
    bytes[last] ^= 1;
9565
    fs::write(&path, &bytes).unwrap();
9566
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
9567
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
9568
    assert_eq!(hashes(touches), vec![c3, c1]);
9569
}
e8e6e0ca Andy McCall ↶ 9570
9571
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
9572
/// file back where it was leave two placements at one place, which the
9573
/// tree shows as one file. Removing it, and then its directory, retires
9574
/// both, so no copy is left under a directory that is gone.
9575
#[test]
9576
fn git_import_removes_every_copy_of_a_file_at_one_place() {
9577
    hermetic();
9578
    if std::process::Command::new("git")
9579
        .arg("--version")
9580
        .output()
9581
        .is_err()
9582
    {
9583
        eprintln!("git not installed; skipping");
9584
        return;
9585
    }
9586
    let dir = tempfile::tempdir().unwrap();
9587
    let root = dir.path();
9588
    let g = root.join("src.git");
9589
    fs::create_dir_all(&g).unwrap();
9590
    let git = |args: &[&str]| {
9591
        let out = std::process::Command::new("git")
9592
            .arg("-C")
9593
            .arg(&g)
9594
            .args([
9595
                "-c",
9596
                "user.name=Grace",
9597
                "-c",
9598
                "[email protected]",
9599
                "-c",
9600
                "commit.gpgsign=false",
9601
            ])
9602
            .args(args)
9603
            .output()
9604
            .unwrap();
9605
        assert!(
9606
            out.status.success(),
9607
            "git {args:?}: {}",
9608
            String::from_utf8_lossy(&out.stderr)
9609
        );
9610
    };
9611
    git(&["init", "-q", "-b", "main"]);
9612
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
9613
    write(&g, "keep.txt", b"k\n");
9614
    git(&["add", "."]);
9615
    git(&["commit", "-qm", "base"]);
9616
    fs::create_dir_all(g.join("d/sub")).unwrap();
9617
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
9618
    git(&["commit", "-qm", "into sub"]);
9619
    git(&["checkout", "-qb", "side"]);
9620
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9621
    git(&["commit", "-qm", "back, on side"]);
9622
    git(&["checkout", "-q", "main"]);
9623
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9624
    git(&["commit", "-qm", "back, on main"]);
9625
    git(&["merge", "-q", "--no-edit", "side"]);
9626
    git(&["rm", "-rq", "d"]);
9627
    git(&["commit", "-qm", "d goes"]);
9628
9629
    let repo = Repo::init(&root.join("o")).unwrap();
9630
    repo.import_git(&g, "main").unwrap();
9631
    let v = repo.verify_git_import(&g, "main").unwrap();
9632
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9633
    let st = repo
9634
        .load_state_history(&repo.bookmark_heads().unwrap())
9635
        .unwrap();
9636
    let view = st.tree().view();
9637
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
9638
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
9639
}
5552e69c Andy McCall ↶ 9640
9641
/// oxygen#94: a state index's file histories are read, and checked by
9642
/// their own hashes, only when a file is built. One found damaged is an
9643
/// error that says so, the index is removed, and the next read rebuilds it.
9644
#[test]
9645
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
9646
    hermetic();
9647
    let dir = tempfile::tempdir().unwrap();
9648
    let repo = Repo::init(dir.path()).unwrap();
9649
    for i in 0..6 {
9650
        write(
9651
            dir.path(),
9652
            &format!("f{i}.txt"),
9653
            format!("one {i}\n").as_bytes(),
9654
        );
9655
    }
9656
    repo.snapshot("t").unwrap();
9657
    repo.commit("first", &[]).unwrap();
9658
    for i in 0..6 {
9659
        write(
9660
            dir.path(),
9661
            &format!("f{i}.txt"),
9662
            format!("one {i}\ntwo\n").as_bytes(),
9663
        );
9664
    }
9665
    repo.snapshot("t").unwrap();
9666
    repo.commit("second", &[]).unwrap();
9667
    let want: Vec<Vec<u8>> = (0..6)
9668
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
9669
        .collect();
9670
    // The index of the working copy's base, holding every file's history
9671
    // (a few changes behind, an index is replayed onto, not rewritten).
9672
    let (_, wc) = repo.working_copy().unwrap();
9673
    let base = repo.load_state_history(&wc.deps).unwrap();
9674
    repo.write_state_index(&wc.deps, &base);
9675
    for (i, w) in want.iter().enumerate() {
9676
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9677
    }
9678
    let index = repo.state_indexes();
9679
    assert!(!index.is_empty(), "a state index was written");
9680
    // The histories are last in the file: damage the last of them.
9681
    let mut bytes = fs::read(&index[0]).unwrap();
9682
    let last = bytes.len() - 1;
9683
    bytes[last] ^= 0x40;
9684
    fs::write(&index[0], &bytes).unwrap();
9685
9686
    let reads: Vec<_> = (0..6)
9687
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
9688
        .collect();
9689
    let damaged: Vec<String> = reads
9690
        .iter()
9691
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
9692
        .collect();
9693
    assert_eq!(damaged.len(), 1, "{damaged:?}");
9694
    assert!(
9695
        damaged[0].contains("state index was damaged")
9696
            && damaged[0].contains("run the command again"),
9697
        "{}",
9698
        damaged[0]
9699
    );
9700
    // Every file reads right again, from an index rebuilt from history.
9701
    for (i, w) in want.iter().enumerate() {
9702
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9703
    }
9704
}
cb8b8082 Andy McCall ↶ 9705
9706
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
9707
/// objects alone and in dependency order, and the last moves the bookmark.
9708
/// The remote ends with every change and the same state, and says how each
9709
/// part went.
9710
#[test]
9711
fn a_long_push_goes_in_parts() {
9712
    hermetic();
9713
    let dir = tempfile::tempdir().unwrap();
9714
    let root = dir.path();
9715
    let origin = root.join("origin");
9716
    Repo::init_bare_unbound(&origin).unwrap();
9717
    let main = root.join("main");
9718
    let mut repo = Repo::init(&main).unwrap();
9719
    repo.config
9720
        .set("remote.origin.url", &origin.to_string_lossy())
9721
        .unwrap();
9722
    // One byte: every change is a part of its own.
9723
    repo.config.set("push.batch-bytes", "1").unwrap();
9724
    repo.save_config().unwrap();
9725
    for i in 0..6 {
9726
        write(
9727
            &main,
9728
            &format!("f{i}.txt"),
9729
            format!("file {i}\n").as_bytes(),
9730
        );
9731
        repo.commit(&format!("c{i}"), &[]).unwrap();
9732
    }
9733
    let mut parts = Vec::new();
9734
    let results = repo
9735
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9736
        .unwrap();
9737
    assert!(
9738
        results.iter().any(|r| r.ok && r.name == "main"),
9739
        "{results:?}"
9740
    );
9741
    assert_eq!(parts.len(), 6, "{parts:?}");
9742
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
9743
9744
    let remote = Repo::open(&origin).unwrap();
9745
    let heads = repo.bookmark_heads().unwrap();
9746
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
9747
    assert_eq!(
9748
        remote.log_state(&heads).unwrap().len(),
9749
        repo.log_state(&heads).unwrap().len()
9750
    );
9751
    // A push of objects alone reports how it went, as `objects`.
9752
    let got = remote
9753
        .receive_push(Bundle::default(), vec![], None, vec![])
9754
        .unwrap();
9755
    assert_eq!(got.len(), 1);
9756
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
9757
}
d6e0d5b8 Andy McCall ↶ 9758
9759
/// oxygen#97: with `git.claim`, an import authors the importing identity's
9760
/// own commits (Git author email = its email, any case) with its key, and
9761
/// leaves anyone else's with the zero key; the history verifies as before.
9762
#[test]
9763
fn git_import_claims_your_own_commits() {
9764
    hermetic();
9765
    if std::process::Command::new("git")
9766
        .arg("--version")
9767
        .output()
9768
        .is_err()
9769
    {
9770
        eprintln!("git not installed; skipping");
9771
        return;
9772
    }
9773
    let dir = tempfile::tempdir().unwrap();
9774
    let root = dir.path();
9775
    let g = root.join("src.git");
9776
    fs::create_dir_all(&g).unwrap();
9777
    let git = |who: &str, args: &[&str]| {
9778
        let (name, email) = who.split_once(' ').unwrap();
9779
        let out = std::process::Command::new("git")
9780
            .arg("-C")
9781
            .arg(&g)
9782
            .args([
9783
                "-c",
9784
                &format!("user.name={name}"),
9785
                "-c",
9786
                &format!("user.email={email}"),
9787
                "-c",
9788
                "commit.gpgsign=false",
9789
            ])
9790
            .args(args)
9791
            .output()
9792
            .unwrap();
9793
        assert!(
9794
            out.status.success(),
9795
            "git {args:?}: {}",
9796
            String::from_utf8_lossy(&out.stderr)
9797
        );
9798
    };
9799
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
9800
    write(&g, "a.txt", b"a\n");
9801
    git("Grace [email protected]", &["add", "."]);
9802
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
9803
    write(&g, "b.txt", b"b\n");
9804
    git("Ada [email protected]", &["add", "."]);
9805
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
9806
9807
    let mut repo = Repo::init(&root.join("o")).unwrap();
9808
    let (key, _) = repo
9809
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
9810
        .unwrap();
9811
    repo.config.set("git.claim", "true").unwrap();
9812
    repo.save_config().unwrap();
9813
    let repo = Repo::open(&root.join("o")).unwrap();
9814
    repo.import_git(&g, "main").unwrap();
9815
    let v = repo.verify_git_import(&g, "main").unwrap();
9816
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9817
    let heads = repo.bookmark_heads().unwrap();
9818
    let by_message: std::collections::HashMap<String, KeyId> = repo
9819
        .log_state(&heads)
9820
        .unwrap()
9821
        .into_iter()
9822
        .map(|e| {
9823
            (
9824
                e.change.message.lines().next().unwrap_or("").to_string(),
9825
                e.change.author,
9826
            )
9827
        })
9828
        .collect();
9829
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
9830
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
9831
}
34fad4a9 Andy McCall ↶ 9832
9833
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
9834
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
9835
#[test]
9836
fn removing_a_remote_leaves_nothing_of_it() {
9837
    hermetic();
9838
    let dir = tempfile::tempdir().unwrap();
9839
    let origin = dir.path().join("origin");
9840
    Repo::init_bare_unbound(&origin).unwrap();
9841
    let main = dir.path().join("main");
9842
    let mut repo = Repo::init(&main).unwrap();
9843
    repo.config
9844
        .set("remote.origin.url", &origin.to_string_lossy())
9845
        .unwrap();
9846
    repo.config
9847
        .set("remote.origin.token", "secret-ish")
9848
        .unwrap();
9849
    repo.config
9850
        .set("remote.keep.url", &origin.to_string_lossy())
9851
        .unwrap();
9852
    repo.save_config().unwrap();
9853
    write(&main, "a.txt", b"a\n");
9854
    repo.commit("a", &[]).unwrap();
9855
    assert!(repo.push("origin", false).unwrap()[0].ok);
9856
    assert!(
9857
        repo.view().unwrap().remotes.contains_key("origin"),
9858
        "a tracking bookmark"
9859
    );
9860
9861
    repo.remove_remote("origin").unwrap();
9862
    let again = Repo::open(&main).unwrap();
9863
    assert!(
9864
        !again
9865
            .config
9866
            .repo_layer()
9867
            .keys()
9868
            .any(|k| k.starts_with("remote.origin.")),
9869
        "{:?}",
9870
        again.config.repo_layer()
9871
    );
9872
    assert!(!again.config.remotes.contains_key("origin"));
9873
    assert!(
9874
        !again.view().unwrap().remotes.contains_key("origin"),
9875
        "its tracking bookmarks go"
9876
    );
9877
    assert!(
9878
        again.config.remotes.contains_key("keep"),
9879
        "another remote stays"
9880
    );
9881
    let mut again = again;
9882
    assert!(
9883
        again.remove_remote("origin").is_err(),
9884
        "a second removal is refused"
9885
    );
9886
}
9d580f21 Andy McCall ↶ 9887
9888
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
9889
/// unreachable from history, so gc prunes it, unless the host names it:
9890
/// then it and its chunks stay, and it reads back whole.
9891
#[test]
9892
fn gc_keeps_the_blobs_a_host_names() {
9893
    hermetic();
9894
    let dir = tempfile::tempdir().unwrap();
9895
    let repo = Repo::init(dir.path()).unwrap();
9896
    write(dir.path(), "a.txt", b"a\n");
9897
    repo.commit("a", &[]).unwrap();
9898
    // Large enough to be several chunks.
9899
    let body: Vec<u8> = (0..400_000u32)
9900
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
9901
        .collect();
9902
    let kept = repo.store_blob(&body).unwrap();
9903
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
9904
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
9905
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
9906
    assert!(!repo.store().has(&lost), "not named: pruned");
9907
    repo.gc(true).unwrap();
9908
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
9909
}
530a0fc6 Andy McCall ↶ 9910
9911
/// oxygen#99: undo in one workspace undoes that workspace's last command,
9912
/// never another workspace's, says what it undid, and goes further back
9913
/// when run again.
9914
#[test]
9915
fn undo_is_scoped_to_its_workspace() {
9916
    hermetic();
9917
    let dir = tempfile::tempdir().unwrap();
9918
    let root = dir.path().join("main");
9919
    let a = Repo::init(&root).unwrap();
9920
    write(&root, "base.txt", b"base\n");
9921
    let base = a.commit("base", &[]).unwrap();
9922
    a.bookmark_create("feature", None).unwrap();
9923
    let ws_dir = dir.path().join("ws");
9924
    let heads = a.resolve_heads("feature").unwrap();
9925
    let b = a
9926
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
9927
        .unwrap();
9928
9929
    // A commits on main, then B commits on feature: B's is the newest.
9930
    write(&root, "a.txt", b"a\n");
9931
    let ca = a.commit("from a", &[]).unwrap();
9932
    write(&ws_dir, "b.txt", b"b\n");
9933
    let cb = b.commit("from b", &[]).unwrap();
9934
9935
    // A's undo undoes A's commit and leaves B's.
9936
    let u = a.undo().unwrap();
9937
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9938
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
9939
    assert!(!u.changes.is_empty());
9940
    let view = a.view().unwrap();
9941
    // (Independent changes commute, so a bookmark's heads may hold base too.)
9942
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
9943
    assert!(
9944
        a.heads_of(&view, "feature").unwrap().contains(&cb),
9945
        "B's commit stands"
9946
    );
9947
    assert!(
9948
        a.store().get_change(&ca).is_ok(),
9949
        "the change itself is still in the store"
9950
    );
9951
    // A's working copy was clean, so its files followed; B's are untouched.
9952
    assert!(!root.join("a.txt").exists());
9953
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
9954
    assert!(ws_dir.join("b.txt").exists());
9955
9956
    // B's undo still finds B's own commit, under A's undo.
9957
    let u = b.undo().unwrap();
9958
    assert_eq!(u.command, "oxy commit -m \"from b\"");
9959
    assert!(!b
9960
        .heads_of(&b.view().unwrap(), "feature")
9961
        .unwrap()
9962
        .contains(&cb));
9963
    assert_eq!(
9964
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
9965
        vec![base],
9966
        "A's undo stands"
9967
    );
9968
9969
    // A's next undo goes past the commit it already undid, to adding B's
9970
    // workspace: refused, since B has worked there since.
9971
    let e = a.undo().unwrap_err().to_string();
9972
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
9973
}
9974
9975
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
9976
/// own commit's head, and the other workspace's head stays.
9977
#[test]
9978
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
9979
    hermetic();
9980
    let dir = tempfile::tempdir().unwrap();
9981
    let root = dir.path().join("main");
9982
    let a = Repo::init(&root).unwrap();
9983
    write(&root, "base.txt", b"base\n");
9984
    a.commit("base", &[]).unwrap();
9985
    let ws_dir = dir.path().join("ws");
9986
    let b = a.workspace_add(&ws_dir, None).unwrap();
9987
    write(&root, "a.txt", b"a\n");
9988
    let ca = a.commit("from a", &[]).unwrap();
9989
    write(&ws_dir, "b.txt", b"b\n");
9990
    let cb = b.commit("from b", &[]).unwrap();
9991
    let u = a.undo().unwrap();
9992
    assert_eq!(u.command, "oxy commit -m \"from a\"");
9993
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
9994
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
9995
}
9996
9997
/// oxygen#99: an undo that would also take back what another workspace
9998
/// did since to the same bookmark is refused, naming it.
9999
#[test]
10000
fn undo_refuses_to_take_back_another_workspaces_work() {
10001
    hermetic();
10002
    let dir = tempfile::tempdir().unwrap();
10003
    let root = dir.path().join("main");
10004
    let a = Repo::init(&root).unwrap();
10005
    write(&root, "base.txt", b"base\n");
10006
    a.commit("base", &[]).unwrap();
10007
    let ws_dir = dir.path().join("ws");
10008
    let b = a.workspace_add(&ws_dir, None).unwrap();
10009
    // Both on main: A commits, then B builds on it, editing A's file.
10010
    write(&root, "a.txt", b"a\n");
10011
    a.commit("from a", &[]).unwrap();
767ac6cd Andy McCall 10012
    b.refresh().unwrap();
530a0fc6 Andy McCall ↶ 10013
    let heads = b.resolve_heads("main").unwrap();
10014
    b.checkout(&heads, false, "oxy checkout").unwrap();
10015
    write(&ws_dir, "a.txt", b"a, then b\n");
10016
    b.commit("from b", &[]).unwrap();
10017
    let e = a.undo().unwrap_err().to_string();
10018
    assert!(
10019
        e.contains("bookmark main") && e.contains("builds on"),
10020
        "{e}"
10021
    );
10022
    assert!(e.contains("oxy op restore"), "{e}");
10023
}
10024
10025
/// oxygen#99: undoing a commit that was already pushed says so: the remote
10026
/// still has it.
10027
#[test]
10028
fn undo_says_when_the_commit_was_pushed() {
10029
    hermetic();
10030
    let dir = tempfile::tempdir().unwrap();
10031
    let root = dir.path();
10032
    Repo::init(&root.join("origin")).unwrap();
10033
    let url = root.join("origin").to_string_lossy().to_string();
10034
    let repo = Repo::clone(&url, &root.join("work"))
10035
        .unwrap()
10036
        .with_home(root.join("home"));
10037
    write(&root.join("work"), "a.txt", b"a\n");
10038
    repo.commit("a", &[]).unwrap();
10039
    assert!(repo.push("origin", false).unwrap()[0].ok);
10040
    // The push itself is passed over: the remote keeps what it was sent.
10041
    let u = repo.undo().unwrap();
10042
    assert_eq!(u.command, "oxy commit -m \"a\"");
10043
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
10044
}
b689779e Andy McCall ↶ 10045
10046
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
10047
/// out of the snapshot and named; tracked files and files already in the
10048
/// working copy are not.
10049
#[test]
10050
fn large_new_files_are_left_out_of_snapshots() {
10051
    hermetic();
10052
    let dir = tempfile::tempdir().unwrap();
10053
    let root = dir.path();
10054
    let mut repo = Repo::init(root).unwrap();
10055
    repo.config.max_new_file = 1024;
10056
    write(root, "small.txt", b"small\n");
10057
    write(root, "big.bin", &vec![0u8; 4096]);
10058
    let s = repo.snapshot("oxy status").unwrap();
10059
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
10060
    assert_eq!(paths, ["small.txt"]);
10061
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
10062
    repo.commit("small", &[]).unwrap();
10063
10064
    // A tracked file may grow past the limit.
10065
    write(root, "small.txt", &vec![b'x'; 4096]);
10066
    let s = repo.snapshot("oxy status").unwrap();
10067
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
10068
    // With no limit the big file is taken in, and stays once it is.
10069
    repo.config.max_new_file = 0;
10070
    let s = repo.snapshot("oxy status").unwrap();
10071
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
10072
    repo.config.max_new_file = 1024;
10073
    let s = repo.snapshot("oxy status").unwrap();
10074
    assert!(
10075
        s.statuses.iter().any(|p| p.path == "big.bin"),
10076
        "already in the working copy"
10077
    );
10078
    assert!(repo.skipped_large().is_empty());
10079
}
10080
10081
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
10082
/// snapshots expire, and kept while they have not.
10083
#[test]
10084
fn gc_prunes_what_only_expired_snapshots_held() {
10085
    hermetic();
10086
    let dir = tempfile::tempdir().unwrap();
10087
    let root = dir.path();
10088
    let mut repo = Repo::init(root).unwrap();
10089
    repo.config.gc_grace_days = 0;
10090
    write(root, "a.txt", b"a\n");
10091
    repo.commit("a", &[]).unwrap();
10092
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
10093
    write(root, "image.tar", &image);
10094
    repo.snapshot("oxy status").unwrap();
10095
    std::fs::remove_file(root.join("image.tar")).unwrap();
10096
    repo.snapshot("oxy status").unwrap();
10097
    let blob = Repo::blob_ref(&image);
10098
    assert!(repo.store().has(&blob));
10099
    repo.gc(true).unwrap();
10100
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
10101
    repo.config.snapshot_retention_days = 0;
10102
    repo.gc(true).unwrap();
10103
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
10104
    assert_eq!(
10105
        repo.file_at("a.txt", None).unwrap(),
10106
        b"a\n",
10107
        "committed files stay"
10108
    );
fe9586d9 Andy McCall ↶ 10109
}
10110
10111
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
10112
/// already has is no conflict: the switch goes through, nothing is lost,
10113
/// and other carried work still comes along.
10114
#[test]
10115
fn carrying_work_the_target_already_has_is_no_conflict() {
10116
    hermetic();
10117
    let dir = tempfile::tempdir().unwrap();
10118
    let root = dir.path();
10119
    let mut repo = Repo::init(root).unwrap();
10120
    write(root, "a.txt", b"one\n");
10121
    write(root, "b.txt", b"b\n");
10122
    repo.commit("one", &[]).unwrap();
10123
    repo.bookmark_create("landed", None).unwrap();
10124
    // On landed, a.txt becomes "two" (as a proposal landing would).
10125
    repo.bookmark_switch("landed", false).unwrap();
10126
    write(root, "a.txt", b"two\n");
10127
    repo.commit("two", &[]).unwrap();
10128
    repo.bookmark_switch("main", false).unwrap();
10129
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
10130
    // The same edit, uncommitted, on main; and another edit besides.
10131
    write(root, "a.txt", b"two\n");
10132
    write(root, "b.txt", b"b, edited\n");
10133
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
10134
    assert_eq!(
10135
        carried,
10136
        vec!["b.txt".to_string()],
10137
        "only the work landed lacks is carried"
10138
    );
10139
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
10140
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
10141
    let s = repo.snapshot("oxy status").unwrap();
10142
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
10143
    assert_eq!(paths, ["b.txt"]);
10144
10145
    // A real difference is still refused.
10146
    repo.bookmark_switch("main", true).unwrap();
10147
    write(root, "a.txt", b"three\n");
10148
    let e = repo
10149
        .bookmark_switch_carry("landed")
10150
        .unwrap_err()
10151
        .to_string();
10152
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
b689779e Andy McCall ↶ 10153
}
aa4939e0 Andy McCall ↶ 10154
10155
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
10156
/// resolves, so JSON output feeds back into commands.
10157
#[test]
10158
fn a_full_hash_resolves_without_its_hash_sign() {
10159
    hermetic();
10160
    let dir = tempfile::tempdir().unwrap();
10161
    let root = dir.path();
10162
    let repo = Repo::init(root).unwrap();
10163
    write(root, "a.txt", b"a\n");
10164
    let h = repo.commit("a", &[]).unwrap();
10165
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
10166
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
10167
    assert!(repo
10168
        .resolve_change(&"0".repeat(64))
10169
        .unwrap_err()
10170
        .to_string()
10171
        .contains("no change matches"));
10172
}
f2f91ceb Andy McCall ↶ 10173
10174
#[test]
10175
fn a_pin_change_moves_only_the_pin() {
10176
    hermetic();
10177
    let dir = tempfile::tempdir().unwrap();
10178
    let root = dir.path();
10179
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
10180
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
10181
    let lib = Repo::clone(&lib_url, &root.join("lib"))
10182
        .unwrap()
10183
        .with_home(root.join("home"));
10184
    write(&root.join("lib"), "lib.txt", b"v1\n");
10185
    lib.commit("lib v1", &[]).unwrap();
10186
    assert!(lib.push("origin", false).unwrap()[0].ok);
10187
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
10188
    let app_dir = root.join("app");
10189
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
10190
        .unwrap()
10191
        .with_home(root.join("home"));
10192
    write(&app_dir, "main.txt", b"app\n");
10193
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
10194
    let a1 = app.commit("app with lib", &[]).unwrap();
10195
    // The library moves on.
10196
    write(&root.join("lib"), "more.txt", b"v2\n");
10197
    let l2 = lib.commit("lib v2", &[]).unwrap();
10198
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
10199
        panic!("an Oxygen pin")
10200
    };
10201
    let pin2 = crate::subrepo::Pin::Oxy {
10202
        repo,
10203
        heads: vec![l2],
10204
        bookmark,
10205
    };
10206
    let author = app.store().get_change(&a1).unwrap().author;
10207
    let change = app
10208
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
10209
        .unwrap();
10210
    let mut state = app.load_state(&[a1]).unwrap();
10211
    state.add(change).unwrap();
10212
    let files = state.materialize().files;
10213
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
10214
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
10215
        panic!("a pin is opaque")
10216
    };
10217
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
10218
    assert_eq!(read, pin2, "the new pin");
10219
    assert!(
10220
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
10221
        "nothing else changes"
10222
    );
10223
    // Only a subrepo's pin can be moved this way.
10224
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
10225
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
10226
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
10227
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
10228
}
767ac6cd Andy McCall 10229
10230
/// oxygenhub#249: a handle reads the operation head once and keeps it,
10231
/// so one command or request never mixes two heads; another handle's
10232
/// operation shows only after `refresh`. Its own operations move it, and
10233
/// one recorded from the head it kept merges with what landed since, as
10234
/// any concurrent operation does.
10235
#[test]
10236
fn one_handle_keeps_one_head_until_it_refreshes() {
10237
    hermetic();
10238
    let dir = tempfile::tempdir().unwrap();
10239
    let root = dir.path();
10240
    let writer = Repo::init(root).unwrap();
10241
    write(root, "a.txt", b"one\n");
10242
    let h1 = writer.commit("one", &[]).unwrap();
10243
    let reader = Repo::open(root).unwrap();
10244
    let before = reader.view().unwrap();
10245
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
10246
    write(root, "a.txt", b"two\n");
10247
    let h2 = writer.commit("two", &[]).unwrap();
10248
    assert_eq!(
10249
        writer.bookmark_heads().unwrap(),
10250
        vec![h2],
10251
        "its own operation"
10252
    );
10253
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
10254
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
10255
    reader.refresh().unwrap();
10256
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
10257
10258
    // A handle recording from an older head merges with the newer one.
10259
    let stale = Repo::open(root).unwrap();
10260
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
10261
    write(root, "a.txt", b"three\n");
10262
    let h3 = writer.commit("three", &[]).unwrap();
10263
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
10264
    let view = stale.view().unwrap();
10265
    assert!(view.bookmarks.contains_key("feature"));
10266
    assert_eq!(
10267
        stale.bookmark_heads().unwrap(),
10268
        vec![h3],
10269
        "merged, not lost"
10270
    );
10271
    let fresh = Repo::open(root).unwrap();
10272
    assert_eq!(fresh.view().unwrap(), view);
10273
}
10274
10275
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
10276
#[test]
10277
fn over_a_store_one_handle_keeps_one_head() {
10278
    hermetic();
10279
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
10280
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
10281
    let dir = tempfile::tempdir().unwrap();
10282
    let a = Repo::init(dir.path()).unwrap();
10283
    let (h0, _) = a.head_op().unwrap();
10284
    let b = Repo::open(dir.path()).unwrap();
10285
    assert_eq!(b.head_op().unwrap().0, h0);
10286
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
10287
    let mut view = a.view().unwrap();
10288
    view.bookmarks.insert("x".into(), state);
10289
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
10290
    assert_eq!(a.head_op().unwrap().0, r);
10291
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
10292
    b.refresh().unwrap();
10293
    assert_eq!(b.head_op().unwrap().0, r);
10294
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
10295
}
10296
10297
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
10298
/// reader opened before reads on, then and after the next gc deletes the
10299
/// retired files once their hour is up. Younger ones are kept.
10300
#[test]
10301
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
10302
    hermetic();
10303
    let dir = tempfile::tempdir().unwrap();
10304
    let root = dir.path();
10305
    let repo = Repo::init(root).unwrap();
10306
    let mut heads = Vec::new();
10307
    for i in 0..4 {
10308
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
10309
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
10310
    }
10311
    let reader = Repo::open(root).unwrap();
10312
    assert_eq!(reader.log().unwrap().len(), 5);
10313
    let r = repo.gc(true).unwrap();
10314
    assert_eq!(r.retired, crate::store::RetiredReport::default());
10315
    assert_eq!(repo.store().loose_count().unwrap(), 0);
10316
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
10317
    // Nothing is an hour old yet: a gc keeps it all.
10318
    let r = repo.gc(true).unwrap();
10319
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
10320
    assert!(r.retired.kept > 0, "{r:?}");
10321
    write(root, "f9.txt", b"9\n");
10322
    heads.push(repo.commit("c9", &[]).unwrap());
10323
    crate::store::reader_tests::age_retired(
10324
        repo.store(),
10325
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
10326
    );
10327
    let r = repo.gc(true).unwrap();
10328
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
10329
    assert_eq!(r.retired.kept, 0, "{r:?}");
10330
    let r = repo.gc(true).unwrap();
10331
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
10332
    assert!(r.retired.kept > 0, "what the last gc retired is young");
10333
    // The reader opened before all of it still reads everything, from
10334
    // the packs it finds when what it loaded is gone.
10335
    assert_eq!(reader.log().unwrap().len(), 5);
10336
    for h in &heads[..4] {
10337
        reader.store().get_change(h).unwrap();
10338
    }
10339
    reader.refresh().unwrap();
10340
    assert_eq!(reader.log().unwrap().len(), 6);
10341
    let fresh = Repo::open(root).unwrap();
10342
    assert_eq!(
10343
        fresh.store().pack_count(),
10344
        1,
10345
        "retired packs are not loaded"
10346
    );
10347
}
10348
10349
/// oxygenhub#249: a repository opens when its store's pack listing names
10350
/// an index that is not there (deleted between the listing and the read).
10351
#[test]
10352
fn a_repository_opens_when_a_listed_index_is_gone() {
10353
    hermetic();
10354
    let backend = crate::store::reader_tests::racing(true);
10355
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
10356
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
10357
    let dir = tempfile::tempdir().unwrap();
10358
    let repo = Repo::init(dir.path()).unwrap();
10359
    write(dir.path(), "a.txt", b"a\n");
10360
    let h = repo.commit("a", &[]).unwrap();
10361
    repo.gc(true).unwrap();
10362
    let again = Repo::open(dir.path()).unwrap();
10363
    assert_eq!(again.store().pack_count(), 1);
10364
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
10365
    // And when one is deleted between the listing and the read: a copy of
10366
    // the live pack, whose index goes as the store opens.
10367
    use crate::strata::Store as _;
10368
    let idx = backend
10369
        .list("pack-")
10370
        .unwrap()
10371
        .into_iter()
10372
        .map(|e| e.key)
10373
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
10374
        .unwrap();
10375
    let stem = idx.trim_end_matches(".idx");
10376
    for ext in ["pack", "idx"] {
10377
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
10378
        backend
10379
            .put_new(&format!("pack-copy.{ext}"), &bytes)
10380
            .unwrap();
10381
    }
10382
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
10383
    let again = Repo::open(dir.path()).unwrap();
10384
    assert_eq!(again.store().pack_count(), 1);
10385
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
10386
    assert!(!backend.has("pack-copy.idx").unwrap());
10387
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
10388
}