OXYGENHUB
# cea2e2f860c5 oxygen / crates / oxy-core / src / repo / tests.rs
401.2 KiB · Rust · last changed A subrepo put back after its removal is pinned in the change that registers it; oxy identity create needs no repository (closes #152, closes #144) 7 days ago source blame history raw
1
//! Tests for the repository layer.
2
3
use super::*;
4
use crate::protocol::SignedPolicy;
5
use crate::repo::{BisectStep, Selection};
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)> {
26
    s.statuses
27
        .iter()
28
        .map(|p| (p.path.clone(), p.status))
29
        .collect()
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.
80
    write(
81
        root,
82
        "src/main.rs",
83
        b"fn main() {\n    println!(\"hi\");\n}\n",
84
    );
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();
103
    assert_eq!(
104
        c2.deps,
105
        vec![h1],
106
        "everything it touches was introduced by h1"
107
    );
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());
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
    );
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}");
137
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
138
    assert!(d.contains("-fn main() {}"), "{d}");
139
140
    // Resolution by prefix.
141
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
142
    assert_eq!(
143
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
144
        h1
145
    );
146
    assert!(repo.resolve_change("zzzz").is_err());
147
148
    // Undo the commit: bookmark and working copy go back.
149
    repo.undo().unwrap();
150
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
151
    let s = repo.snapshot("oxy status").unwrap();
152
    assert!(
153
        !s.changed,
154
        "files on disk still match the pre-commit working copy"
155
    );
156
    assert_eq!(s.statuses.len(), 3);
157
}
158
159
/// Make `main` conflicted: two commits on the same base that edit the same line.
160
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
161
    let dir = tempfile::tempdir().unwrap();
162
    let root = dir.path();
163
    let repo = Repo::init(root).unwrap();
164
    write(root, "f.txt", b"a\nb\nc\n");
165
    let h1 = repo.commit("base", &[]).unwrap();
166
    write(root, "f.txt", b"a\nB\nc\n");
167
    let h2 = repo.commit("upper", &[]).unwrap();
168
    repo.checkout(&[h1], false, "checkout").unwrap();
169
    write(root, "f.txt", b"a\nX\nc\n");
170
    let h3 = repo.commit("ex", &[]).unwrap();
171
    (dir, repo, h1, h2, h3)
172
}
173
174
/// oxygen#126: a file whose text includes an example of oxy's markers (as
175
/// the spec's §9.5 does) can still have its conflict resolved; a real
176
/// marker left behind is still caught.
177
#[test]
178
fn marker_like_text_does_not_block_a_resolution() {
179
    hermetic();
180
    let dir = tempfile::tempdir().unwrap();
181
    let root = dir.path();
182
    let repo = Repo::init(root).unwrap();
183
    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";
184
    write(
185
        root,
186
        "doc.md",
187
        format!("intro\n{example}b\nend\n").as_bytes(),
188
    );
189
    let h1 = repo.commit("base", &[]).unwrap();
190
    write(
191
        root,
192
        "doc.md",
193
        format!("intro\n{example}B\nend\n").as_bytes(),
194
    );
195
    repo.commit("upper", &[]).unwrap();
196
    repo.checkout(&[h1], false, "checkout").unwrap();
197
    write(
198
        root,
199
        "doc.md",
200
        format!("intro\n{example}X\nend\n").as_bytes(),
201
    );
202
    repo.commit("ex", &[]).unwrap();
203
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
204
        .unwrap();
205
    let marked = fs::read_to_string(root.join("doc.md")).unwrap();
206
    assert!(marked.contains("oxy conflict 1 of 1"), "{marked}");
207
    // A real marker left: still caught.
208
    write(root, "doc.md", marked.replace("B\n", "BB\n").as_bytes());
209
    let s = repo.snapshot("status").unwrap();
210
    assert_eq!(
211
        statuses(&s),
212
        vec![("doc.md".into(), ChangeStatus::ConflictEdited)]
213
    );
214
    // Resolved, the example kept: a resolution.
215
    write(
216
        root,
217
        "doc.md",
218
        format!("intro\n{example}X\nend\n").as_bytes(),
219
    );
220
    let s = repo.snapshot("status").unwrap();
221
    assert_eq!(
222
        statuses(&s),
223
        vec![("doc.md".into(), ChangeStatus::Resolved)]
224
    );
225
    let h = repo.commit("resolve", &[]).unwrap();
226
    assert_eq!(
227
        repo.store().get_change(&h).unwrap().kind,
228
        ChangeKind::Resolution
229
    );
230
    assert!(!repo.load_state(&[h]).unwrap().materialize().is_conflicted());
231
}
232
233
/// oxygen#121: two changes each adding a line after the same line conflict;
234
/// the markers list the earlier change first, and `oxy resolve --both`
235
/// keeps both lines in that order (or the other with `--reverse`).
236
#[test]
237
fn adjacent_insertions_are_settled_by_keeping_both() {
238
    hermetic();
239
    for reverse in [false, true] {
240
        let dir = tempfile::tempdir().unwrap();
241
        let root = dir.path();
242
        let repo = Repo::init(root).unwrap();
243
        write(root, "f.txt", b"a\nb\n");
244
        let h1 = repo.commit("base", &[]).unwrap();
245
        write(root, "f.txt", b"a\nfirst\nb\n");
246
        repo.commit("first", &[]).unwrap();
247
        repo.checkout(&[h1], false, "checkout").unwrap();
248
        write(root, "f.txt", b"a\nsecond\nb\n");
249
        repo.commit("second", &[]).unwrap();
250
        repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
251
            .unwrap();
252
        let marked = fs::read_to_string(root.join("f.txt")).unwrap();
253
        let (f, s) = (
254
            marked.find("first\n").unwrap(),
255
            marked.find("second\n").unwrap(),
256
        );
257
        assert!(f < s, "the earlier change's side comes first: {marked}");
258
259
        let snap = repo.snapshot("status").unwrap();
260
        let node = snap.base_snapshot.files["f.txt"].node;
261
        assert_eq!(snap.base.both_sides(&node).iter().flatten().count(), 1);
262
        let kept = repo.keep_both(&snap, &[], reverse).unwrap();
263
        assert_eq!(
264
            kept,
265
            vec![KeptBoth {
266
                path: "f.txt".into(),
267
                settled: vec![1],
268
                identical: vec![],
269
                left: vec![]
270
            }]
271
        );
272
        let want: &[u8] = if reverse {
273
            b"a\nsecond\nfirst\nb\n"
274
        } else {
275
            b"a\nfirst\nsecond\nb\n"
276
        };
277
        assert_eq!(fs::read(root.join("f.txt")).unwrap(), want);
278
        let s = repo.snapshot("status").unwrap();
279
        assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
280
        let h = repo.commit("both", &[]).unwrap();
281
        assert_eq!(
282
            repo.store().get_change(&h).unwrap().kind,
283
            ChangeKind::Resolution
284
        );
285
        assert!(!repo.load_state(&[h]).unwrap().materialize().is_conflicted());
286
    }
287
}
288
289
/// oxygen#145: a file marked `merge=union` has its adjacent insertions
290
/// settled by the checkout itself, both kept, earliest first; the next
291
/// commit records the resolution. Other files keep their markers.
292
#[test]
293
fn union_files_keep_both_sides_on_checkout() {
294
    hermetic();
295
    let dir = tempfile::tempdir().unwrap();
296
    let root = dir.path();
297
    let repo = Repo::init(root).unwrap();
298
    write(root, ".oxyattributes", b"CHANGELOG.md merge=union\n");
299
    write(
300
        root,
301
        "CHANGELOG.md",
302
        b"# Changelog\n## Unreleased\n## 1.0\n",
303
    );
304
    write(root, "f.txt", b"a\nb\n");
305
    let h1 = repo.commit("base", &[]).unwrap();
306
    write(
307
        root,
308
        "CHANGELOG.md",
309
        b"# Changelog\n## Unreleased\n- one\n## 1.0\n",
310
    );
311
    write(root, "f.txt", b"a\none\nb\n");
312
    repo.commit("one", &[]).unwrap();
313
    repo.checkout(&[h1], false, "checkout").unwrap();
314
    write(
315
        root,
316
        "CHANGELOG.md",
317
        b"# Changelog\n## Unreleased\n- two\n## 1.0\n",
318
    );
319
    write(root, "f.txt", b"a\ntwo\nb\n");
320
    repo.commit("two", &[]).unwrap();
321
    let r = repo
322
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
323
        .unwrap();
324
    assert!(r.conflicted);
325
    assert_eq!(r.kept_both.len(), 1, "{:?}", r.kept_both);
326
    assert_eq!(r.kept_both[0].path, "CHANGELOG.md");
327
    assert_eq!(
328
        fs::read_to_string(root.join("CHANGELOG.md")).unwrap(),
329
        "# Changelog\n## Unreleased\n- one\n- two\n## 1.0\n"
330
    );
331
    assert!(has_conflict_markers(&fs::read(root.join("f.txt")).unwrap()));
332
    let s = repo.snapshot("status").unwrap();
333
    assert_eq!(
334
        statuses(&s),
335
        vec![("CHANGELOG.md".into(), ChangeStatus::Resolved)]
336
    );
337
}
338
339
/// oxygen#146: two bookmarks that resolved the same conflict to the same
340
/// text agree. Merged, their resolutions are a conflict whose sides are
341
/// identical: a checkout keeps one, in any file, and a host settles it so
342
/// too; the next commit records it.
343
#[test]
344
fn identical_resolutions_on_two_bookmarks_settle_by_themselves() {
345
    hermetic();
346
    let dir = tempfile::tempdir().unwrap();
347
    let root = dir.path();
348
    let repo = Repo::init(root).unwrap();
349
    write(root, "f.txt", b"a\nx\nb\n");
350
    let base = repo.commit("base", &[]).unwrap();
351
    write(root, "f.txt", b"a\nX1\nb\n");
352
    let c1 = repo.commit("X1", &[]).unwrap();
353
    repo.checkout(&[base], false, "checkout").unwrap();
354
    write(root, "f.txt", b"a\nX2\nb\n");
355
    let c2 = repo.commit("X2", &[]).unwrap();
356
    // Each bookmark merges both and resolves the conflict the same way.
357
    repo.checkout(&[c1, c2], false, "checkout").unwrap();
358
    assert!(has_conflict_markers(&fs::read(root.join("f.txt")).unwrap()));
359
    write(root, "f.txt", b"a\nX\nb\n");
360
    let r1 = repo.commit("resolve on one", &[]).unwrap();
361
    repo.checkout(&[c1, c2], false, "checkout").unwrap();
362
    write(root, "f.txt", b"a\nX\nb\n");
363
    let r2 = repo.commit("resolve on two", &[]).unwrap();
364
    assert_ne!(r1, r2);
365
366
    let st = repo.load_state(&[r1, r2]).unwrap();
367
    assert!(
368
        st.materialize().is_conflicted(),
369
        "two resolutions, one place"
370
    );
371
    assert_eq!(
372
        Repo::union_resolution(&st, &st.materialize()),
373
        Some(vec![("f.txt".into(), b"a\nX\nb\n".to_vec())]),
374
        "a host settles it"
375
    );
376
    let r = repo.checkout(&[r1, r2], false, "checkout").unwrap();
377
    assert!(r.conflicted);
378
    assert_eq!(r.kept_both.len(), 1, "{:?}", r.kept_both);
379
    assert_eq!(
380
        (r.kept_both[0].path.as_str(), &r.kept_both[0].identical),
381
        ("f.txt", &vec![1])
382
    );
383
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), "a\nX\nb\n");
384
    let s = repo.snapshot("status").unwrap();
385
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
386
    let merged = repo.commit("merge", &[]).unwrap();
387
    let st = repo.load_state(&[merged]).unwrap();
388
    assert!(!st.materialize().is_conflicted());
389
}
390
391
/// oxygen#145: a host (OxygenHub landing a proposal) settles a state whose
392
/// only conflicts are adjacent insertions in union files; any other
393
/// conflict needs a person.
394
#[test]
395
fn a_host_settles_a_state_whose_conflicts_are_all_union() {
396
    hermetic();
397
    let dir = tempfile::tempdir().unwrap();
398
    let root = dir.path();
399
    let repo = Repo::init(root).unwrap();
400
    write(root, ".oxyattributes", b"*.md merge=union\n");
401
    write(root, "A.md", b"a\nb\n");
402
    write(root, "B.md", b"x\ny\n");
403
    let h1 = repo.commit("base", &[]).unwrap();
404
    write(root, "A.md", b"a\none\nb\n");
405
    write(root, "B.md", b"x\nY1\n");
406
    let h2 = repo.commit("one", &[]).unwrap();
407
    repo.checkout(&[h1], false, "checkout").unwrap();
408
    write(root, "A.md", b"a\ntwo\nb\n");
409
    let h3 = repo.commit("two", &[]).unwrap();
410
    let st = repo.load_state(&[h2, h3]).unwrap();
411
    assert_eq!(
412
        Repo::union_resolution(&st, &st.materialize()),
413
        Some(vec![("A.md".into(), b"a\none\ntwo\nb\n".to_vec())])
414
    );
415
    // B.md's line replaced two ways: a person decides.
416
    repo.checkout(&[h3], false, "checkout").unwrap();
417
    write(root, "B.md", b"x\nY2\n");
418
    let h4 = repo.commit("Y2", &[]).unwrap();
419
    let st = repo.load_state(&[h2, h4]).unwrap();
420
    assert!(st.materialize().is_conflicted());
421
    assert_eq!(Repo::union_resolution(&st, &st.materialize()), None);
422
}
423
424
/// oxygen#121: two changes that each replaced the same line are not an
425
/// adjacent insertion: keeping both would keep two versions of the line,
426
/// so `--both` leaves the markers, as it does for markers already edited.
427
#[test]
428
fn keeping_both_refuses_replaced_or_edited_lines() {
429
    hermetic();
430
    let (dir, repo, _, _, _) = conflicted_repo();
431
    let root = dir.path();
432
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
433
        .unwrap();
434
    let marked = fs::read(root.join("f.txt")).unwrap();
435
    let snap = repo.snapshot("status").unwrap();
436
    let node = snap.base_snapshot.files["f.txt"].node;
437
    assert_eq!(snap.base.both_sides(&node), vec![None]);
438
    let kept = repo.keep_both(&snap, &["f.txt".into()], false).unwrap();
439
    assert!(kept[0].settled.is_empty());
440
    assert_eq!(kept[0].left[0].0, 1);
441
    assert!(kept[0].left[0].1.contains("both sides changed"), "{kept:?}");
442
    assert_eq!(fs::read(root.join("f.txt")).unwrap(), marked);
443
444
    // An adjacent insertion whose lines were edited between the markers.
445
    let sides = vec![Some(vec![b"x\n".to_vec(), b"y\n".to_vec()])];
446
    let text = b"a\n<<<<<<< oxy conflict 1 of 1, side 1 of 2: change k \"x\"\nx!\n======= oxy conflict 1 of 1, side 2 of 2: change q \"y\"\ny\n>>>>>>> oxy conflict 1 of 1 end\nb\n";
447
    let (out, settled, left) = super::snapshot::keep_both_text(text, &sides, false);
448
    assert_eq!(out, text.to_vec());
449
    assert!(settled.is_empty());
450
    assert!(left[0].1.contains("edited"), "{left:?}");
451
    // Unedited, in either order on disk: kept in the graph's order.
452
    let text = b"a\n<<<<<<< oxy conflict 1 of 1, side 1 of 2: change q \"y\"\ny\n======= oxy conflict 1 of 1, side 2 of 2: change k \"x\"\nx\n>>>>>>> oxy conflict 1 of 1 end\nb\n";
453
    let (out, settled, _) = super::snapshot::keep_both_text(text, &sides, false);
454
    assert_eq!(out, b"a\nx\ny\nb\n".to_vec());
455
    assert_eq!(settled, vec![1]);
456
}
457
458
#[test]
459
fn concurrent_edits_conflict_and_can_be_resolved() {
460
    hermetic();
461
    let (dir, repo, h1, h2, h3) = conflicted_repo();
462
    let root = dir.path();
463
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
464
    assert_eq!(heads, [h2, h3].into_iter().collect());
465
    let st = repo.load_state(&[h2, h3]).unwrap();
466
    assert!(st.materialize().is_conflicted());
467
468
    // Checking out main writes markers.
469
    let r = repo
470
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
471
        .unwrap();
472
    assert!(r.conflicted);
473
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
474
    assert!(
475
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
476
        "{marked}"
477
    );
478
    assert!(
479
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
480
        "{marked}"
481
    );
482
    assert!(has_conflict_markers(marked.as_bytes()));
483
    // Untouched markers: clean working copy; commit has nothing to do.
484
    let s = repo.snapshot("status").unwrap();
485
    assert!(s.statuses.is_empty());
486
    assert!(!s.resolves);
487
488
    // Partially edited file that still has markers cannot be committed.
489
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
490
    let s = repo.snapshot("status").unwrap();
491
    assert_eq!(
492
        statuses(&s),
493
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
494
    );
495
    assert!(repo.commit("no", &[]).is_err());
496
497
    // Resolve by keeping one side and adding a line elsewhere.
498
    write(root, "f.txt", b"a\nX\nc\nd\n");
499
    let s = repo.snapshot("status").unwrap();
500
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
501
    assert!(s.resolves);
502
    let h4 = repo.commit("resolve", &[]).unwrap();
503
    let c4 = repo.store().get_change(&h4).unwrap();
504
    assert_eq!(c4.kind, ChangeKind::Resolution);
505
    let mut want = vec![h1, h2, h3];
506
    want.sort();
507
    assert_eq!(
508
        c4.deps, want,
509
        "a resolution depends on exactly the contributors and what it references"
510
    );
511
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
512
    let snap = repo.load_state(&[h4]).unwrap().materialize();
513
    assert!(!snap.is_conflicted());
514
    assert!(
515
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
516
    );
517
    assert!(!repo.snapshot("status").unwrap().changed);
518
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
519
    // whatever order the changes arrive in.
520
    let mut st = State::new();
521
    for h in [h4, h3, h1, h2] {
522
        st.add_unchecked(repo.store().get_change(&h).unwrap());
523
    }
524
    st.validate().unwrap();
525
    assert!(
526
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
527
    );
528
}
529
530
/// oxygen#118 (Metal Gear): a resolution commits by paths, leaving other
531
/// work uncommitted, so long as it takes every file it resolves; and
532
/// `amend PATHS` folds only those paths into the head.
533
#[test]
534
fn resolutions_and_amends_take_paths() {
535
    hermetic();
536
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
537
    let root = dir.path();
538
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
539
        .unwrap();
540
    // The conflict resolved, and other work beside it.
541
    write(root, "f.txt", b"a\nX\nc\n");
542
    write(root, "notes.txt", b"pending\n");
543
    let s = repo.snapshot("status").unwrap();
544
    assert!(s.resolves);
545
    let err = repo
546
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["notes.txt".into()]))
547
        .unwrap_err()
548
        .to_string();
549
    assert!(
550
        err.contains("takes every file it resolves") && err.contains("f.txt"),
551
        "{err}"
552
    );
553
    let (h4, partial) = repo
554
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["f.txt".into()]))
555
        .unwrap();
556
    assert!(partial);
557
    assert_eq!(
558
        repo.store().get_change(&h4).unwrap().kind,
559
        ChangeKind::Resolution
560
    );
561
    assert!(!repo
562
        .load_state(&[h4])
563
        .unwrap()
564
        .materialize()
565
        .is_conflicted());
566
    let s = repo.snapshot("status").unwrap();
567
    assert_eq!(
568
        statuses(&s),
569
        vec![("notes.txt".into(), ChangeStatus::Added)],
570
        "the other work waits"
571
    );
572
573
    // amend PATHS: only those paths join the head; it keeps its ChangeId.
574
    // On the resolution, so the bookmark has one head to amend.
575
    let h5 = repo.commit("notes", &[h4]).unwrap();
576
    let id5 = repo.store().get_change(&h5).unwrap().change_id;
577
    write(root, "notes.txt", b"pending\nmore\n");
578
    write(root, "other.txt", b"later\n");
579
    let h6 = repo
580
        .amend_paths(Some("notes, amended"), &["notes.txt".into()])
581
        .unwrap();
582
    let c6 = repo.store().get_change(&h6).unwrap();
583
    assert_eq!((c6.change_id, c6.message.as_str()), (id5, "notes, amended"));
584
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h6]);
585
    let snap6 = repo.load_state(&[h6]).unwrap().materialize();
586
    assert!(
587
        matches!(&snap6.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"pending\nmore\n")
588
    );
589
    assert!(
590
        !snap6.files.contains_key("other.txt"),
591
        "other.txt stays out"
592
    );
593
    let s = repo.snapshot("status").unwrap();
594
    assert_eq!(
595
        statuses(&s),
596
        vec![("other.txt".into(), ChangeStatus::Added)]
597
    );
598
}
599
600
#[test]
601
fn resolution_may_keep_both_sides_or_neither() {
602
    hermetic();
603
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
604
    let root = dir.path();
605
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
606
        .unwrap();
607
    // Keep both sides in a chosen order.
608
    write(root, "f.txt", b"a\nX\nB\nc\n");
609
    let h = repo.commit("both", &[]).unwrap();
610
    let snap = repo.load_state(&[h]).unwrap().materialize();
611
    assert!(!snap.is_conflicted());
612
    assert!(
613
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
614
    );
615
    // Undo and instead drop the whole region.
616
    repo.undo().unwrap();
617
    write(root, "f.txt", b"a\nc\n");
618
    let h = repo.commit("neither", &[]).unwrap();
619
    let snap = repo.load_state(&[h]).unwrap().materialize();
620
    assert!(!snap.is_conflicted());
621
    assert!(
622
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
623
    );
624
}
625
626
#[test]
627
fn name_conflict_resolved_by_removing_a_candidate() {
628
    hermetic();
629
    let dir = tempfile::tempdir().unwrap();
630
    let root = dir.path();
631
    let repo = Repo::init(root).unwrap();
632
    write(root, "keep.txt", b"k\n");
633
    let h1 = repo.commit("base", &[]).unwrap();
634
    write(root, "new.txt", b"one\n");
635
    repo.commit("one", &[]).unwrap();
636
    repo.checkout(&[h1], false, "checkout").unwrap();
637
    write(root, "new.txt", b"two\n");
638
    repo.commit("two", &[]).unwrap();
639
    let r = repo
640
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
641
        .unwrap();
642
    assert!(r.conflicted);
643
    assert!(
644
        root.join("new.txt.oxy-conflict-1").exists()
645
            && root.join("new.txt.oxy-conflict-2").exists()
646
    );
647
    assert!(!root.join("new.txt").exists());
648
    // Candidate numbering follows change-hash order, so pick by content:
649
    // keep the "two" candidate under the real name and drop the other.
650
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
651
        (1, 2)
652
    } else {
653
        (2, 1)
654
    };
655
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
656
    fs::rename(
657
        root.join(format!("new.txt.oxy-conflict-{keep}")),
658
        root.join("new.txt"),
659
    )
660
    .unwrap();
661
    let h = repo.commit("pick two", &[]).unwrap();
662
    assert_eq!(
663
        repo.store().get_change(&h).unwrap().kind,
664
        ChangeKind::Resolution
665
    );
666
    // The resolution does not touch keep.txt, so it does not depend on h1;
667
    // the bookmark keeps both as heads and their union is the state.
668
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
669
    assert_eq!(heads, [h1, h].into_iter().collect());
670
    let snap = repo
671
        .load_state(&repo.bookmark_heads().unwrap())
672
        .unwrap()
673
        .materialize();
674
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
675
    assert_eq!(
676
        snap.files.keys().cloned().collect::<Vec<_>>(),
677
        ["keep.txt", "new.txt"]
678
    );
679
    assert!(
680
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
681
    );
682
}
683
684
#[test]
685
fn identities_and_signed_commits() {
686
    hermetic();
687
    let dir = tempfile::tempdir().unwrap();
688
    let root = dir.path();
689
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
690
    write(root, "a.txt", b"a\n");
691
    let h0 = repo.commit("unsigned", &[]).unwrap();
692
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
693
    assert_eq!(
694
        repo.store().get_change(&h0).unwrap().author,
695
        ObjectRef::ZERO
696
    );
697
698
    let (key, id) = repo
699
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
700
        .unwrap();
701
    assert_eq!(id.hash(), key);
702
    assert_eq!(repo.config.author_key, Some(key));
703
    // Config survives reopen; the secret key is found again.
704
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
705
    assert_eq!(reopened.config.author_key, Some(key));
706
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
707
708
    // Default core.sign = seal: commits carry the author but no signature.
709
    write(root, "a.txt", b"a\nb\n");
710
    let h1 = repo.commit("authored", &[]).unwrap();
711
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
712
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
713
    // Signing later works too.
714
    repo.sign_change(&h1).unwrap();
715
    assert!(
716
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
717
    );
718
719
    repo.config.set("core.sign", "change").unwrap();
720
    repo.save_config().unwrap();
721
    write(root, "a.txt", b"a\nb\nc\n");
722
    let h2 = repo.commit("signed", &[]).unwrap();
723
    assert_eq!(
724
        repo.verify_change(&h2).unwrap(),
725
        SignatureStatus::Valid {
726
            key,
727
            name: "Ada".into(),
728
            email: "[email protected]".into(),
729
            sealed: false,
730
            revoked: false
731
        }
732
    );
733
734
    // A signature by a key that is not the author or a delegate is rejected
735
    // when the change names an author; an anonymous change (made before any
736
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
737
    let other = SecretKey::generate();
738
    let other_id = other.identity("Mallory", "[email protected]", 0);
739
    let other_key = repo.store().put_identity(&other_id).unwrap();
740
    write(root, "a.txt", b"a\nb\nc\nd\n");
741
    repo.config.set("core.sign", "seal").unwrap();
742
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
743
    let forged = other.sign(Domain::Change, &other_key, &h3);
744
    repo.store().put_signature(&h3, &forged).unwrap();
745
    assert!(
746
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
747
    );
748
    let adopted = other.sign(Domain::Change, &other_key, &h0);
749
    repo.store().put_signature(&h0, &adopted).unwrap();
750
    assert!(
751
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
752
    );
753
754
    // Tampering with the stored signature invalidates it.
755
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
756
    sig.ed[0] ^= 1;
757
    repo.store().put_signature(&h2, &sig).unwrap();
758
    assert!(matches!(
759
        repo.verify_change(&h2).unwrap(),
760
        SignatureStatus::Invalid(_)
761
    ));
762
763
    // Without the secret key, signing at commit fails cleanly.
764
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
765
    write(root, "a.txt", b"z\n");
766
    assert!(no_keys.commit("cannot sign", &[]).is_err());
767
}
768
769
#[test]
770
fn checkout_moves_the_working_copy() {
771
    hermetic();
772
    let dir = tempfile::tempdir().unwrap();
773
    let root = dir.path();
774
    let repo = Repo::init(root).unwrap();
775
    write(root, "a.txt", b"one\n");
776
    write(root, "sub/deep/b.txt", b"b\n");
777
    let h1 = repo.commit("first", &[]).unwrap();
778
    write(root, "a.txt", b"two\n");
779
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
780
    write(root, "bin.dat", &[0, 1, 2, 3]);
781
    let h2 = repo.commit("second", &[]).unwrap();
782
783
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
784
    assert_eq!(
785
        r,
786
        CheckoutReport {
787
            written: 2,
788
            removed: 1,
789
            removed_paths: vec!["bin.dat".into()],
790
            conflicted: false,
791
            notes: vec![],
792
            lacks: 1,
793
            kept_both: vec![],
794
        }
795
    );
796
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
797
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
798
    assert!(!root.join("bin.dat").exists());
799
    let (_, wc) = repo.working_copy().unwrap();
800
    assert_eq!(wc.deps, vec![h1]);
801
    assert!(
802
        !repo.snapshot("status").unwrap().changed,
803
        "checkout leaves a clean working copy"
804
    );
805
    // The bookmark still points at h2.
806
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
807
808
    // Dirty working copy refuses without --discard.
809
    write(root, "a.txt", b"dirty\n");
810
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
811
    let r = repo
812
        .checkout(&[h2], true, "oxy checkout --discard")
813
        .unwrap();
814
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
815
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
816
    assert!(!root.join("sub").exists(), "empty directories are pruned");
817
    assert_eq!(r.removed, 1);
818
    assert!(!repo.snapshot("status").unwrap().changed);
819
820
    // Refuses to write through a symlinked directory.
821
    #[cfg(unix)]
822
    {
823
        fs::remove_dir_all(root.join("sub")).ok();
824
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
825
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
826
    }
827
}
828
829
#[test]
830
fn large_files_are_chunked_and_read_back() {
831
    hermetic();
832
    let dir = tempfile::tempdir().unwrap();
833
    let repo = Repo::init(dir.path()).unwrap();
834
    let mut big = vec![0u8; 700 * 1024];
835
    for (i, b) in big.iter_mut().enumerate() {
836
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
837
    }
838
    let r = repo.store_blob(&big).unwrap();
839
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
840
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
841
    assert_eq!(repo.read_blob(&r).unwrap(), big);
842
    assert_eq!(Repo::blob_ref(&big), r);
843
}
844
845
#[test]
846
fn clone_push_pull_with_seals_and_attestations() {
847
    hermetic();
848
    let dir = tempfile::tempdir().unwrap();
849
    let root = dir.path();
850
    let origin_path = root.join("origin");
851
    let origin = Repo::init(&origin_path).unwrap();
852
    let origin_url = origin_path.to_string_lossy().to_string();
853
854
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
855
    let mut a = Repo::clone(&origin_url, &root.join("a"))
856
        .unwrap()
857
        .with_home(root.join("home-a"));
858
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
859
    let (key_a, _) = a
860
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
861
        .unwrap();
862
    write(&root.join("a"), "f.txt", b"a\n");
863
    let h1 = a.commit("first", &[]).unwrap();
864
    let results = a.push("origin", false).unwrap();
865
    origin.refresh().unwrap();
866
    assert!(results[0].ok, "{}", results[0].reason);
867
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
868
    // The change was sealed at push and the reference attested.
869
    assert!(
870
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
871
    );
872
    assert_eq!(
873
        origin.verify_change(&h1).unwrap(),
874
        SignatureStatus::Unsigned
875
    );
876
    let serial_of = |att: &SignedAttest| match att.attest.body {
877
        AttestBody::Ref { serial, .. } => serial,
878
        _ => unreachable!(),
879
    };
880
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
881
    // A bookmark new to the remote starts at the clock (past any deleted
882
    // namesake's serial); later updates count up from there.
883
    let first = serial_of(&att);
884
    assert!(first > 1_000_000_000_000, "{first}");
885
    let again = a.push("origin", false).unwrap();
886
    origin.refresh().unwrap();
887
    assert!(again[0].ok && again[0].reason.contains("up to date"));
888
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
889
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
890
891
    // B clones and sees the file and the seal.
892
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
893
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
894
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
895
    assert!(matches!(
896
        b.authenticate_change(&h1).unwrap(),
897
        SignatureStatus::Valid { sealed: true, .. }
898
    ));
899
900
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
901
    write(&root.join("b"), "f.txt", b"a\nb\n");
902
    let h2 = b.commit("second", &[]).unwrap();
903
    assert!(b.push("origin", false).unwrap()[0].ok);
904
    origin.refresh().unwrap();
905
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
906
907
    // A commits an independent change; push is refused until A pulls.
908
    write(&root.join("a"), "g.txt", b"g\n");
909
    let h3 = a.commit("third", &[]).unwrap();
910
    assert!(a.push("origin", false).is_err());
911
    let pr = a.pull("origin").unwrap();
912
    assert!(pr.changed && pr.checked_out);
913
    let mut want = vec![h2, h3];
914
    want.sort();
915
    assert_eq!(pr.heads, want);
916
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
917
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
918
    let results = a.push("origin", false).unwrap();
919
    origin.refresh().unwrap();
920
    assert!(results[0].ok, "{}", results[0].reason);
921
    let mut origin_heads = origin.bookmark_heads().unwrap();
922
    origin_heads.sort();
923
    assert_eq!(origin_heads, want);
924
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
925
    assert_eq!(serial_of(&att), first + 1);
926
927
    // B pulls and ends up identical.
928
    let pr = b.pull("origin").unwrap();
929
    assert_eq!(pr.heads, want);
930
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
931
    assert!(!b.snapshot("status").unwrap().changed);
932
933
    // Concurrent edits of the same line: the union is a reified conflict.
934
    write(&root.join("a"), "f.txt", b"a\nA\n");
935
    a.commit("a-edit", &[]).unwrap();
936
    a.push("origin", false).unwrap();
937
    origin.refresh().unwrap();
938
    write(&root.join("b"), "f.txt", b"a\nB\n");
939
    b.commit("b-edit", &[]).unwrap();
940
    let pr = b.pull("origin").unwrap();
941
    assert!(pr.changed && pr.checked_out);
942
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
943
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
944
    write(&root.join("b"), "f.txt", b"a\nAB\n");
945
    let hr = b.commit("resolve", &[]).unwrap();
946
    assert_eq!(
947
        b.store().get_change(&hr).unwrap().kind,
948
        ChangeKind::Resolution
949
    );
950
    assert!(b.push("origin", false).unwrap()[0].ok);
951
    origin.refresh().unwrap();
952
    a.pull("origin").unwrap();
953
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
954
    // The resolution depends on the conflicting edits, but nothing depends
955
    // on "third" (it only added g.txt), so it stays a head beside it.
956
    let mut want = vec![hr, h3];
957
    want.sort();
958
    assert_eq!(a.bookmark_heads().unwrap(), want);
959
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
960
}
961
962
#[test]
963
fn receive_push_rejects_bad_updates() {
964
    hermetic();
965
    let dir = tempfile::tempdir().unwrap();
966
    let root = dir.path();
967
    let origin = Repo::init(&root.join("origin")).unwrap();
968
    let url = root.join("origin").to_string_lossy().to_string();
969
    let mut a = Repo::clone(&url, &root.join("a"))
970
        .unwrap()
971
        .with_home(root.join("home"));
972
    let (key, _) = a
973
        .create_identity("Ada", "a@b", IdentityScope::Repo)
974
        .unwrap();
975
    write(&root.join("a"), "f.txt", b"x\n");
976
    let h1 = a.commit("one", &[]).unwrap();
977
    assert!(a.push("origin", false).unwrap()[0].ok);
978
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
979
    let s1 = origin
980
        .store()
981
        .put_state(&StateObject::new(vec![h1]))
982
        .unwrap();
983
984
    // Missing head.
985
    let ghost = origin
986
        .store()
987
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
988
        .unwrap();
989
    let r = origin
990
        .receive_push(
991
            Bundle::default(),
992
            vec![RefUpdate {
993
                name: "main".into(),
994
                old_state: s1,
995
                new_state: ghost,
996
                force: false,
997
                attestation: None,
998
            }],
999
            None,
1000
            vec![],
1001
        )
1002
        .unwrap();
1003
    assert!(
1004
        !r[0].ok && r[0].reason.contains("missing"),
1005
        "{}",
1006
        r[0].reason
1007
    );
1008
1009
    // Stale old_state.
1010
    let r = origin
1011
        .receive_push(
1012
            Bundle::default(),
1013
            vec![RefUpdate {
1014
                name: "main".into(),
1015
                old_state: empty,
1016
                new_state: s1,
1017
                force: false,
1018
                attestation: None,
1019
            }],
1020
            None,
1021
            vec![],
1022
        )
1023
        .unwrap();
1024
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
1025
1026
    // Non-fast-forward without force is refused; with force it passes.
1027
    let r = origin
1028
        .receive_push(
1029
            Bundle::default(),
1030
            vec![RefUpdate {
1031
                name: "main".into(),
1032
                old_state: s1,
1033
                new_state: empty,
1034
                force: false,
1035
                attestation: None,
1036
            }],
1037
            None,
1038
            vec![],
1039
        )
1040
        .unwrap();
1041
    assert!(
1042
        !r[0].ok && r[0].reason.contains("fast-forward"),
1043
        "{}",
1044
        r[0].reason
1045
    );
1046
    let r = origin
1047
        .receive_push(
1048
            Bundle::default(),
1049
            vec![RefUpdate {
1050
                name: "main".into(),
1051
                old_state: s1,
1052
                new_state: empty,
1053
                force: true,
1054
                attestation: None,
1055
            }],
1056
            None,
1057
            vec![],
1058
        )
1059
        .unwrap();
1060
    assert!(r[0].ok);
1061
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
1062
1063
    // Attestation with a stale serial is a rollback and is refused.
1064
    let sa = a
1065
        .sign_attest(&Attest {
1066
            repo: a.id().unwrap(),
1067
            hlc: Hlc::now(),
1068
            body: AttestBody::Ref {
1069
                name: "main".into(),
1070
                old_state: empty,
1071
                new_state: s1,
1072
                serial: 1,
1073
            },
1074
        })
1075
        .unwrap();
1076
    let r = origin
1077
        .receive_push(
1078
            Bundle::default(),
1079
            vec![RefUpdate {
1080
                name: "main".into(),
1081
                old_state: empty,
1082
                new_state: s1,
1083
                force: false,
1084
                attestation: Some(sa.clone()),
1085
            }],
1086
            None,
1087
            vec![],
1088
        )
1089
        .unwrap();
1090
    assert!(
1091
        !r[0].ok && r[0].reason.contains("serial"),
1092
        "{}",
1093
        r[0].reason
1094
    );
1095
    // An attestation for a different update is refused too.
1096
    let sa2 = a
1097
        .sign_attest(&Attest {
1098
            repo: a.id().unwrap(),
1099
            hlc: Hlc::now(),
1100
            body: AttestBody::Ref {
1101
                name: "main".into(),
1102
                old_state: s1,
1103
                new_state: empty,
1104
                serial: 5,
1105
            },
1106
        })
1107
        .unwrap();
1108
    let r = origin
1109
        .receive_push(
1110
            Bundle::default(),
1111
            vec![RefUpdate {
1112
                name: "main".into(),
1113
                old_state: empty,
1114
                new_state: s1,
1115
                force: false,
1116
                attestation: Some(sa2),
1117
            }],
1118
            None,
1119
            vec![],
1120
        )
1121
        .unwrap();
1122
    assert!(
1123
        !r[0].ok && r[0].reason.contains("describe"),
1124
        "{}",
1125
        r[0].reason
1126
    );
1127
    let _ = key;
1128
}
1129
1130
#[test]
1131
fn user_config_supplies_defaults_and_clones_sign() {
1132
    hermetic();
1133
    let dir = tempfile::tempdir().unwrap();
1134
    let root = dir.path();
1135
    let home = root.join("home");
1136
    let origin = Repo::init(&root.join("origin")).unwrap();
1137
    let url = root.join("origin").to_string_lossy().to_string();
1138
1139
    // Identity at user scope: the repository file stays free of author keys.
1140
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
1141
    let (key, _) = a
1142
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1143
        .unwrap();
1144
    assert!(!a.config.repo_layer().contains_key("author.key"));
1145
    assert_eq!(a.config.author_key, Some(key));
1146
    assert!(home.join("config.toml").exists());
1147
    a.set_user_config("core.sign", "change").unwrap();
1148
    assert!(a.config.sign_changes);
1149
1150
    // Repository settings override user settings and are the only ones saved.
1151
    a.config.set("core.sign", "seal").unwrap();
1152
    a.save_config().unwrap();
1153
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
1154
    assert!(!again.config.sign_changes);
1155
    assert_eq!(again.config.author_key, Some(key));
1156
    assert_eq!(
1157
        read_config_file(&root.join("a/.oxy/config"))
1158
            .unwrap()
1159
            .get("core.sign")
1160
            .map(String::as_str),
1161
        Some("seal")
1162
    );
1163
1164
    // A fresh clone made by this user signs with the user-level identity,
1165
    // even though the clone's store has never seen the identity object.
1166
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
1167
    assert!(b.config.sign_changes);
1168
    write(&root.join("b"), "f.txt", b"f\n");
1169
    let h = b.commit("signed from a clone", &[]).unwrap();
1170
    assert!(
1171
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
1172
    );
1173
    assert!(b.push("origin", false).unwrap()[0].ok);
1174
    assert!(matches!(
1175
        origin.verify_change(&h).unwrap(),
1176
        SignatureStatus::Valid { .. }
1177
    ));
1178
}
1179
1180
#[test]
1181
fn format1_repositories_are_migrated_on_open() {
1182
    hermetic();
1183
    use crate::oplog::{Format1Op, Format1View};
1184
    let dir = tempfile::tempdir().unwrap();
1185
    let root = dir.path();
1186
    let repo = Repo::init(root).unwrap();
1187
    write(root, "a.txt", b"a\n");
1188
    let h1 = repo.commit("one", &[]).unwrap();
1189
    let (wc_hash, _) = repo.working_copy().unwrap();
1190
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
1191
    let mut v1 = Format1View::default();
1192
    v1.bookmarks.insert("main".into(), vec![]);
1193
    v1.workspaces.insert(repo.workspace(), wc_hash);
1194
    let init = Format1Op {
1195
        parents: vec![],
1196
        hlc: Hlc::default(),
1197
        command: "oxy init".into(),
1198
        view: v1.clone(),
1199
    };
1200
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
1201
    v1.bookmarks.insert("main".into(), vec![h1]);
1202
    let commit = Format1Op {
1203
        parents: vec![init_ref],
1204
        hlc: Hlc::default(),
1205
        command: "oxy commit".into(),
1206
        view: v1,
1207
    };
1208
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
1209
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
1210
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
1211
    drop(repo);
1212
1213
    let repo = Repo::open(root).unwrap();
1214
    assert_eq!(
1215
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
1216
        FORMAT_LINE
1217
    );
1218
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
1219
    let ops = repo.op_log().unwrap();
1220
    assert_eq!(
1221
        ops.iter()
1222
            .map(|(_, o)| o.command.as_str())
1223
            .collect::<Vec<_>>(),
1224
        ["oxy commit", "oxy init"]
1225
    );
1226
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
1227
    assert!(!repo.snapshot("status").unwrap().changed);
1228
    // Reopening again is a no-op.
1229
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
1230
}
1231
1232
#[test]
1233
fn undo_skips_snapshot_operations() {
1234
    hermetic();
1235
    let dir = tempfile::tempdir().unwrap();
1236
    let root = dir.path();
1237
    let repo = Repo::init(root).unwrap();
1238
    write(root, "a.txt", b"a\n");
1239
    let h1 = repo.commit("a", &[]).unwrap();
1240
    // A later command snapshots new edits on top of the commit.
1241
    write(root, "b.txt", b"b\n");
1242
    let s = repo.snapshot("oxy status").unwrap();
1243
    assert!(s.changed);
1244
    assert!(repo.head_op().unwrap().1.is_snapshot());
1245
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
1246
    // Undo must undo the commit, not the snapshot.
1247
    repo.undo().unwrap();
1248
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
1249
    let s = repo.snapshot("oxy status").unwrap();
1250
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
1251
    assert_eq!(
1252
        paths,
1253
        ["a.txt", "b.txt"],
1254
        "both files are back in the working copy"
1255
    );
1256
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
1257
    // Only snapshots remain above `init`, so there is nothing left to undo.
1258
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
1259
    assert!(repo.undo().is_err());
1260
}
1261
1262
#[test]
1263
fn independent_changes_commute_and_make_multiple_heads() {
1264
    hermetic();
1265
    let dir = tempfile::tempdir().unwrap();
1266
    let root = dir.path();
1267
    let repo = Repo::init(root).unwrap();
1268
    write(root, "a.txt", b"a\n");
1269
    let h1 = repo.commit("a", &[]).unwrap();
1270
    write(root, "b.txt", b"b\n");
1271
    let h2 = repo.commit("b", &[]).unwrap();
1272
    let c2 = repo.store().get_change(&h2).unwrap();
1273
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
1274
    let mut heads = repo.bookmark_heads().unwrap();
1275
    heads.sort();
1276
    let mut want = vec![h1, h2];
1277
    want.sort();
1278
    assert_eq!(heads, want);
1279
    // Editing a.txt depends on h1 only.
1280
    write(root, "a.txt", b"a\na2\n");
1281
    let h3 = repo.commit("a2", &[]).unwrap();
1282
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
1283
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1284
    assert_eq!(heads, [h2, h3].into_iter().collect());
1285
    // Explicit dependency.
1286
    write(root, "c.txt", b"c\n");
1287
    let h4 = repo.commit("c", &[h2]).unwrap();
1288
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
1289
}
1290
1291
#[test]
1292
fn mode_change_and_text_binary_switch() {
1293
    hermetic();
1294
    let dir = tempfile::tempdir().unwrap();
1295
    let root = dir.path();
1296
    let repo = Repo::init(root).unwrap();
1297
    write(root, "run.sh", b"#!/bin/sh\n");
1298
    repo.commit("add script", &[]).unwrap();
1299
    #[cfg(unix)]
1300
    {
1301
        use std::os::unix::fs::PermissionsExt;
1302
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1303
        let s = repo.snapshot("status").unwrap();
1304
        assert_eq!(
1305
            statuses(&s),
1306
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
1307
        );
1308
        let h = repo.commit("exec", &[]).unwrap();
1309
        let snap = repo.load_state(&[h]).unwrap().materialize();
1310
        assert!(snap.files["run.sh"].mode.exec);
1311
    }
1312
    // Text → binary → text.
1313
    write(root, "run.sh", b"\0binary");
1314
    let h = repo.commit("binary", &[]).unwrap();
1315
    let snap = repo.load_state(&[h]).unwrap().materialize();
1316
    assert!(snap.files["run.sh"].mode.opaque);
1317
    write(root, "run.sh", b"text again\n");
1318
    let h = repo.commit("text", &[]).unwrap();
1319
    let snap = repo.load_state(&[h]).unwrap().materialize();
1320
    assert!(!snap.files["run.sh"].mode.opaque);
1321
    assert!(
1322
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
1323
    );
1324
    assert!(!snap.is_conflicted());
1325
}
1326
1327
/// oxygen#87: a binary file given new contents and the executable bit in
1328
/// one commit kept the contents and lost the bit.
1329
#[cfg(unix)]
1330
#[test]
1331
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
1332
    use std::os::unix::fs::PermissionsExt;
1333
    hermetic();
1334
    let dir = tempfile::tempdir().unwrap();
1335
    let root = dir.path();
1336
    let repo = Repo::init(root).unwrap();
1337
    write(root, "tool.exe", b"MZ\0one");
1338
    repo.commit("add", &[]).unwrap();
1339
    write(root, "tool.exe", b"MZ\0two");
1340
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
1341
    let h = repo.commit("update and +x", &[]).unwrap();
1342
    let snap = repo.load_state(&[h]).unwrap().materialize();
1343
    let f = &snap.files["tool.exe"];
1344
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
1345
    assert!(
1346
        repo.snapshot("status").unwrap().statuses.is_empty(),
1347
        "nothing left to commit"
1348
    );
1349
}
1350
1351
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
1352
/// key whose certificate an issuer gave pushes when the policy grants its
1353
/// subject, and a fetch accepts what it attested; an expired certificate,
1354
/// or a subject the policy does not grant, may not move the bookmark.
1355
#[test]
1356
fn a_certified_key_pushes_under_a_subject_grant() {
1357
    use crate::cert::{Certificate, SignedCertificate};
1358
    use crate::identity::Scope;
1359
    hermetic();
1360
    let dir = tempfile::tempdir().unwrap();
1361
    let root = dir.path();
1362
    let _origin = Repo::init(&root.join("origin")).unwrap();
1363
    let url = root.join("origin").to_string_lossy().to_string();
1364
    let mut a = Repo::clone(&url, &root.join("a"))
1365
        .unwrap()
1366
        .with_home(root.join("home-a"));
1367
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1368
        .unwrap();
1369
    write(&root.join("a"), "a.txt", b"a\n");
1370
    a.commit("a", &[]).unwrap();
1371
    a.policy_init().unwrap();
1372
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1373
    let hub_sk = SecretKey::generate();
1374
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1375
    a.policy_grant_subject(
1376
        "agent:claude@ada",
1377
        hub.clone(),
1378
        Scope::CHANGES | Scope::REFS,
1379
        None,
1380
    )
1381
    .unwrap();
1382
    assert!(a
1383
        .push("origin", false)
1384
        .unwrap()
1385
        .iter()
1386
        .any(|r| r.name == "policy" && r.ok));
1387
1388
    let now = Hlc::now().wall_ms;
1389
    // An agent repository whose key the hub certified for `subject`, from
1390
    // `from` to `to`.
1391
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1392
        let mut r = Repo::clone(&url, &root.join(name))
1393
            .unwrap()
1394
            .with_home(root.join(format!("home-{name}")));
1395
        let (_, id) = r
1396
            .create_identity(name, "[email protected]", IdentityScope::User)
1397
            .unwrap();
1398
        let cert = SignedCertificate::sign(
1399
            Certificate {
1400
                key: id,
1401
                issuer: hub.hash(),
1402
                subject: subject.into(),
1403
                claims: vec![],
1404
                scope: Scope::CHANGES | Scope::REFS,
1405
                not_before: from,
1406
                expires: to,
1407
                grant: None,
1408
            },
1409
            &hub,
1410
            &hub_sk,
1411
        );
1412
        r.store().put_identity(&hub).unwrap();
1413
        r.store().put_certificate(&cert).unwrap();
1414
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1415
        r.commit("work", &[]).unwrap();
1416
        r
1417
    };
1418
1419
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1420
    let r = claude.push("origin", false).unwrap();
1421
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1422
    // Ada's fetch accepts the bookmark the certified key attested.
1423
    a.pull("origin").unwrap();
1424
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1425
        .store()
1426
        .get_change(h)
1427
        .map(|c| c.message == "work")
1428
        .unwrap_or(false)));
1429
1430
    // Step 4c: a host with an acceptor key records when it accepted the
1431
    // certified update and serves it; a fetch checks the certificate at
1432
    // that time only when the certificate's issuer signed it for exactly
1433
    // this attestation, else at the attestation's own time.
1434
    let host = Repo::open(&root.join("origin"))
1435
        .unwrap()
1436
        .with_acceptor(hub.clone(), hub_sk.clone());
1437
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1438
    host.record_acceptance(&attest_ref).unwrap();
1439
    let served = host.remote_refs().unwrap();
1440
    let acc = served
1441
        .refs
1442
        .iter()
1443
        .find(|r| r.name == "main")
1444
        .unwrap()
1445
        .accepted
1446
        .clone()
1447
        .expect("served with the refs");
1448
    let signer = sa.sigs[0].key;
1449
    assert_eq!(
1450
        a.certified_time(&signer, &sa, Some(&acc)),
1451
        acc.attest.hlc.wall_ms
1452
    );
1453
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1454
    let stranger_sk = SecretKey::generate();
1455
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1456
    let mut forged = acc.clone();
1457
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1458
    assert_eq!(
1459
        a.certified_time(&signer, &sa, Some(&forged)),
1460
        sa.attest.hlc.wall_ms,
1461
        "not the issuer's"
1462
    );
1463
    let mut elsewhere = acc.clone();
1464
    elsewhere.attest.body = AttestBody::Accepted {
1465
        attest: ObjectRef([7; 32]),
1466
    };
1467
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1468
    assert_eq!(
1469
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1470
        sa.attest.hlc.wall_ms,
1471
        "another attestation's"
1472
    );
1473
    a.pull("origin").unwrap();
1474
    // gc keeps the acceptance with the attestation.
1475
    host.gc(true).unwrap();
1476
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1477
1478
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1479
    let r = late.push("origin", false).unwrap();
1480
    assert!(
1481
        !r[0].ok && r[0].reason.contains("may not update"),
1482
        "an expired certificate: {r:?}"
1483
    );
1484
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1485
    let r = other.push("origin", false).unwrap();
1486
    assert!(
1487
        !r[0].ok && r[0].reason.contains("may not update"),
1488
        "a subject not granted: {r:?}"
1489
    );
1490
}
1491
1492
/// A tag made under one short-lived key and pushed under another: its
1493
/// signer travels with the push (identity and certificate), so a receiver
1494
/// that has never seen that key accepts it. A tag-only push by a keyless
1495
/// agent was refused "unknown key" (found releasing OxygenFlow 0.2.0).
1496
#[test]
1497
fn a_tag_signed_by_an_earlier_short_lived_key_is_pushed() {
1498
    use crate::cert::{Certificate, SignedCertificate};
1499
    use crate::identity::Scope;
1500
    hermetic();
1501
    let dir = tempfile::tempdir().unwrap();
1502
    let root = dir.path();
1503
    let _origin = Repo::init(&root.join("origin")).unwrap();
1504
    let url = root.join("origin").to_string_lossy().to_string();
1505
    let mut a = Repo::clone(&url, &root.join("a"))
1506
        .unwrap()
1507
        .with_home(root.join("home-a"));
1508
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1509
        .unwrap();
1510
    write(&root.join("a"), "a.txt", b"a\n");
1511
    a.commit("a", &[]).unwrap();
1512
    a.policy_init().unwrap();
1513
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1514
    let hub_sk = SecretKey::generate();
1515
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1516
    a.policy_grant_subject(
1517
        "agent:claude@ada",
1518
        hub.clone(),
1519
        Scope::CHANGES | Scope::REFS,
1520
        Some("*"),
1521
    )
1522
    .unwrap();
1523
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1524
1525
    let now = Hlc::now().wall_ms;
1526
    let mut agent = Repo::clone(&url, &root.join("agent"))
1527
        .unwrap()
1528
        .with_home(root.join("home-agent"));
1529
    agent.store().put_identity(&hub).unwrap();
1530
    let certify = |agent: &Repo, id| {
1531
        let cert = SignedCertificate::sign(
1532
            Certificate {
1533
                key: id,
1534
                issuer: hub.hash(),
1535
                subject: "agent:claude@ada".into(),
1536
                claims: vec![],
1537
                scope: Scope::CHANGES | Scope::REFS,
1538
                not_before: now - 60_000,
1539
                expires: now + 600_000,
1540
                grant: None,
1541
            },
1542
            &hub,
1543
            &hub_sk,
1544
        );
1545
        agent.store().put_certificate(&cert).unwrap();
1546
    };
1547
    // The tag, under the first short-lived key.
1548
    let (first, first_id) = agent
1549
        .create_identity("claude", "[email protected]", IdentityScope::User)
1550
        .unwrap();
1551
    certify(&agent, first_id);
1552
    let heads = agent.bookmark_heads().unwrap();
1553
    agent.tag_create("v1", &heads, "first").unwrap();
1554
    // The push, under a second one (a later process's ten-minute key).
1555
    let (second, second_id) = agent
1556
        .create_identity("claude", "[email protected]", IdentityScope::User)
1557
        .unwrap();
1558
    assert_ne!(first, second);
1559
    certify(&agent, second_id);
1560
    agent
1561
        .set_user_config("author.signer", &second.to_hex())
1562
        .unwrap();
1563
    let host = Repo::open(&root.join("origin")).unwrap();
1564
    assert!(
1565
        host.store().get_identity(&first).is_err(),
1566
        "the host has never seen the tag's key"
1567
    );
1568
    let r = agent.push("origin", false).unwrap();
1569
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1570
    let host = Repo::open(&root.join("origin")).unwrap();
1571
    assert!(
1572
        host.tag_refs().unwrap().iter().any(|t| t.name == "v1"),
1573
        "the tag arrived"
1574
    );
1575
}
1576
1577
/// oxygen#129: a short-lived key's tag is checked on a fetch at a time its
1578
/// signer did not choose, its issuer's acceptance, never at the time it
1579
/// claims nor at the fetch's (when the ten-minute certificate has long
1580
/// expired). Without an acceptance it is left out and said so; with one
1581
/// inside the certificate's window it is fetched however much later, and
1582
/// a host it is pushed on to keeps and serves the acceptance.
1583
#[test]
1584
fn a_short_lived_key_s_tag_is_fetched_at_its_issuer_s_acceptance() {
1585
    use crate::cert::{Certificate, SignedCertificate};
1586
    use crate::identity::Scope;
1587
    hermetic();
1588
    let dir = tempfile::tempdir().unwrap();
1589
    let root = dir.path();
1590
    let _origin = Repo::init(&root.join("origin")).unwrap();
1591
    let url = root.join("origin").to_string_lossy().to_string();
1592
    let mut a = Repo::clone(&url, &root.join("a"))
1593
        .unwrap()
1594
        .with_home(root.join("home-a"));
1595
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1596
        .unwrap();
1597
    write(&root.join("a"), "a.txt", b"a\n");
1598
    a.commit("a", &[]).unwrap();
1599
    a.policy_init().unwrap();
1600
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1601
    let hub_sk = SecretKey::generate();
1602
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1603
    a.policy_grant_subject(
1604
        "agent:claude@ada",
1605
        hub.clone(),
1606
        Scope::CHANGES | Scope::REFS,
1607
        Some("*"),
1608
    )
1609
    .unwrap();
1610
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1611
1612
    let now = Hlc::now().wall_ms;
1613
    // An agent whose key the hub certified from `from` to `to`.
1614
    let agent = |name: &str, from: u64, to: u64| {
1615
        let mut r = Repo::clone(&url, &root.join(name))
1616
            .unwrap()
1617
            .with_home(root.join(format!("home-{name}")));
1618
        r.store().put_identity(&hub).unwrap();
1619
        let (_, id) = r
1620
            .create_identity(name, "[email protected]", IdentityScope::User)
1621
            .unwrap();
1622
        let cert = SignedCertificate::sign(
1623
            Certificate {
1624
                key: id,
1625
                issuer: hub.hash(),
1626
                subject: "agent:claude@ada".into(),
1627
                claims: vec![],
1628
                scope: Scope::CHANGES | Scope::REFS,
1629
                not_before: from,
1630
                expires: to,
1631
                grant: None,
1632
            },
1633
            &hub,
1634
            &hub_sk,
1635
        );
1636
        r.store().put_certificate(&cert).unwrap();
1637
        r
1638
    };
1639
1640
    // A tag by a key certified now, pushed to a host that records no
1641
    // acceptance (a path on disk): it lands, but a fetch has no time to
1642
    // check its certificate at, so it is left out and the fetch goes on.
1643
    let claude = agent("claude", now - 60_000, now + 600_000);
1644
    let heads = claude.bookmark_heads().unwrap();
1645
    claude.tag_create("v1", &heads, "one").unwrap();
1646
    let r = claude.push("origin", false).unwrap();
1647
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1648
    let b = Repo::clone(&url, &root.join("b"))
1649
        .unwrap()
1650
        .with_home(root.join("home-b"));
1651
    let rep = b.fetch("origin").unwrap();
1652
    assert!(
1653
        rep.skipped
1654
            .iter()
1655
            .any(|(n, why)| n == "tags/v1" && why.contains("no time to check its certificate at")),
1656
        "{rep:?}"
1657
    );
1658
    assert_eq!(b.tag_heads("v1").unwrap(), None);
1659
1660
    // The host's acceptance, signed by the certificate's issuer, served
1661
    // with the tag: fetched.
1662
    let host = Repo::open(&root.join("origin"))
1663
        .unwrap()
1664
        .with_acceptor(hub.clone(), hub_sk.clone());
1665
    let (v1, _) = host.tag_attest("v1").unwrap().unwrap();
1666
    host.record_acceptance(&v1).unwrap();
1667
    let served = host.tag_refs().unwrap();
1668
    assert!(served
1669
        .iter()
1670
        .any(|t| t.name == "v1" && t.accepted.is_some()));
1671
    let rep = b.fetch("origin").unwrap();
1672
    assert!(rep.skipped.is_empty(), "{rep:?}");
1673
    assert_eq!(b.tag_heads("v1").unwrap(), Some(heads.clone()));
1674
    // gc keeps the acceptance with the tag.
1675
    host.gc(true).unwrap();
1676
    assert!(host.acceptance_of(&v1).unwrap().is_some());
1677
1678
    // Long after: a key whose certificate expired an hour ago may not
1679
    // create a tag now.
1680
    let late = agent("late", now - 7_200_000, now - 3_600_000);
1681
    late.tag_create("v2", &heads, "two").unwrap();
1682
    let r = late.push("origin", false).unwrap();
1683
    assert!(
1684
        r.iter()
1685
            .any(|x| x.name == "tags/v2" && !x.ok && x.reason.contains("may not create")),
1686
        "{r:?}"
1687
    );
1688
    // With its issuer's acceptance from inside the window (as a hub gave
1689
    // it then, passed on to another host), it is taken at that time: by
1690
    // the host it is pushed to, which keeps it, and by a fresh clone.
1691
    let (v2, _) = late.tag_attest("v2").unwrap().unwrap();
1692
    let acc = Attest {
1693
        repo: late.id().unwrap(),
1694
        hlc: Hlc {
1695
            wall_ms: now - 5_400_000,
1696
            logical: 0,
1697
        },
1698
        body: AttestBody::Accepted { attest: v2 },
1699
    };
1700
    let sig = hub_sk.sign(Domain::Attest, &hub.hash(), &acc.hash());
1701
    // One by any other key gives no time.
1702
    let stranger_sk = SecretKey::generate();
1703
    let stranger = stranger_sk.identity("stranger", "[email protected]", 1);
1704
    let forged = stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.hash());
1705
    late.keep_acceptance(
1706
        &v2,
1707
        &SignedAttest {
1708
            attest: acc.clone(),
1709
            sigs: vec![forged],
1710
        },
1711
    )
1712
    .unwrap();
1713
    let r = late.push("origin", false).unwrap();
1714
    assert!(
1715
        r.iter().any(|x| x.name == "tags/v2" && !x.ok),
1716
        "not the issuer's: {r:?}"
1717
    );
1718
    let theirs = SignedAttest {
1719
        attest: acc,
1720
        sigs: vec![sig],
1721
    };
1722
    // Kept beside the stranger's: the issuer's is the one sent.
1723
    late.keep_acceptance(&v2, &theirs).unwrap();
1724
    let r = late.push("origin", false).unwrap();
1725
    // (Its re-attestation of main is refused: an expired key moves no
1726
    // bookmark.)
1727
    assert!(r.iter().any(|x| x.name == "tags/v2" && x.ok), "{r:?}");
1728
    let host = Repo::open(&root.join("origin")).unwrap();
1729
    let (hv2, _) = host.tag_attest("v2").unwrap().unwrap();
1730
    assert_eq!(hv2, v2);
1731
    assert!(host
1732
        .store()
1733
        .index_get_pub("accepted", &v2)
1734
        .unwrap()
1735
        .contains(&theirs.attest.hash()));
1736
    let c = Repo::clone(&url, &root.join("c"))
1737
        .unwrap()
1738
        .with_home(root.join("home-c"));
1739
    assert_eq!(c.tag_heads("v2").unwrap(), Some(heads.clone()));
1740
    assert_eq!(c.tag_heads("v1").unwrap(), Some(heads));
1741
}
1742
1743
/// oxygenhub#266: a short-lived key its issuer certified moves a bookmark
1744
/// and signs no change (a keyless agent naming a bookmark). A third
1745
/// party's clone gets the key's identity, its certificate and the
1746
/// issuer's identity with the fetch, so the policy's subject grant
1747
/// authorizes the move and the signature verifies.
1748
#[test]
1749
fn a_bookmark_moved_by_a_certified_key_alone_is_fetched() {
1750
    use crate::cert::{Certificate, SignedCertificate};
1751
    use crate::identity::Scope;
1752
    hermetic();
1753
    let dir = tempfile::tempdir().unwrap();
1754
    let root = dir.path();
1755
    let _origin = Repo::init(&root.join("origin")).unwrap();
1756
    let url = root.join("origin").to_string_lossy().to_string();
1757
    let mut a = Repo::clone(&url, &root.join("a"))
1758
        .unwrap()
1759
        .with_home(root.join("home-a"));
1760
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1761
        .unwrap();
1762
    write(&root.join("a"), "a.txt", b"a\n");
1763
    a.commit("a", &[]).unwrap();
1764
    a.policy_init().unwrap();
1765
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1766
    let hub_sk = SecretKey::generate();
1767
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1768
    a.policy_grant_subject(
1769
        "agent:claude@ada",
1770
        hub.clone(),
1771
        Scope::CHANGES | Scope::REFS,
1772
        None,
1773
    )
1774
    .unwrap();
1775
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1776
1777
    let now = Hlc::now().wall_ms;
1778
    let mut agent = Repo::clone(&url, &root.join("agent"))
1779
        .unwrap()
1780
        .with_home(root.join("home-agent"));
1781
    let (key, id) = agent
1782
        .create_identity("claude", "[email protected]", IdentityScope::User)
1783
        .unwrap();
1784
    let cert = SignedCertificate::sign(
1785
        Certificate {
1786
            key: id,
1787
            issuer: hub.hash(),
1788
            subject: "agent:claude@ada".into(),
1789
            claims: vec![],
1790
            scope: Scope::CHANGES | Scope::REFS,
1791
            not_before: now - 60_000,
1792
            expires: now + 600_000,
1793
            grant: None,
1794
        },
1795
        &hub,
1796
        &hub_sk,
1797
    );
1798
    agent.store().put_identity(&hub).unwrap();
1799
    agent.store().put_certificate(&cert).unwrap();
1800
    let heads = agent.bookmark_heads().unwrap();
1801
    agent.bookmark_create("agent-work", Some(&heads)).unwrap();
1802
    let r = agent.push_bookmark("origin", "agent-work", false).unwrap();
1803
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1804
    let host = Repo::open(&root.join("origin")).unwrap();
1805
    let (_, sa) = host.latest_ref_attest("agent-work").unwrap().unwrap();
1806
    assert_eq!(sa.sigs[0].key, key, "the certified key alone moved it");
1807
1808
    // A fetch naming no change brings the certificate and both identities.
1809
    let bundle = host.bundle_raw_for(&[], None).unwrap();
1810
    assert!(bundle.changes.is_empty() && bundle.raw_changes.is_empty());
1811
    assert_eq!(bundle.certificates.len(), 1);
1812
    for k in [key, hub.hash()] {
1813
        assert!(bundle
1814
            .objects
1815
            .iter()
1816
            .any(|(t, b)| *t == ObjectType::Identity && hash_object(*t, b) == k));
1817
    }
1818
1819
    let c = Repo::clone(&url, &root.join("c")).unwrap();
1820
    let tracked = c.view().unwrap().remotes["origin"].clone();
1821
    assert_eq!(
1822
        tracked.get("agent-work"),
1823
        host.view().unwrap().bookmarks.get("agent-work")
1824
    );
1825
    assert!(c.store().certificate_of(&key).unwrap().is_some());
1826
}
1827
1828
/// Trusted time (oxygenhub#240, spec §14.8): a fetched attestation by a
1829
/// short-lived key is judged at its integrated time, the earliest time a
1830
/// pinned witness cosigned a checkpoint holding it. A certificate valid
1831
/// then but expired now passes; a witness this user does not trust gives
1832
/// no time (the earlier rule, said so); a backdated attestation is noted;
1833
/// an answer without the new fields is judged as before.
1834
#[test]
1835
fn a_fetched_attestation_is_judged_at_its_integrated_time() {
1836
    use super::transparency::LogCheck;
1837
    use crate::cert::{Certificate, SignedCertificate};
1838
    use crate::identity::Scope;
1839
    use crate::protocol::{Integration, Logged, RefsResponse, RemoteRef};
1840
    use crate::tlog::{self, Checkpoint, Entry, Hash, Integrated, Note};
1841
    hermetic();
1842
    let dir = tempfile::tempdir().unwrap();
1843
    let root = dir.path();
1844
    let mut a = Repo::init(&root.join("a"))
1845
        .unwrap()
1846
        .with_home(root.join("home-a"));
1847
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1848
        .unwrap();
1849
    write(&root.join("a"), "a.txt", b"a\n");
1850
    a.commit("a", &[]).unwrap();
1851
    a.policy_init().unwrap();
1852
    let issuer_sk = SecretKey::generate();
1853
    let issuer = issuer_sk.identity("hub", "[email protected]", 1);
1854
    a.policy_grant_subject(
1855
        "agent:claude@ada",
1856
        issuer.clone(),
1857
        Scope::CHANGES | Scope::REFS,
1858
        None,
1859
    )
1860
    .unwrap();
1861
    let p = a.current_policy().unwrap().unwrap().1.policy;
1862
1863
    // An agent key the issuer certified for ten minutes two hours ago.
1864
    let now = Hlc::now().wall_ms;
1865
    let t0 = now - 2 * 3_600_000;
1866
    let agent_sk = SecretKey::generate();
1867
    let agent = agent_sk.identity("claude", "[email protected]", t0);
1868
    let cert = SignedCertificate::sign(
1869
        Certificate {
1870
            key: agent.clone(),
1871
            issuer: issuer.hash(),
1872
            subject: "agent:claude@ada".into(),
1873
            claims: vec![],
1874
            scope: Scope::CHANGES | Scope::REFS,
1875
            not_before: t0,
1876
            expires: t0 + 600_000,
1877
            grant: None,
1878
        },
1879
        &issuer,
1880
        &issuer_sk,
1881
    );
1882
    a.store().put_identity(&agent).unwrap();
1883
    a.store().put_certificate(&cert).unwrap();
1884
    let signer = agent.hash();
1885
    let attested = |claimed: u64| {
1886
        let attest = Attest {
1887
            repo: a.id().unwrap(),
1888
            hlc: Hlc {
1889
                wall_ms: claimed,
1890
                logical: 0,
1891
            },
1892
            body: AttestBody::Ref {
1893
                name: "main".into(),
1894
                old_state: ObjectRef([1; 32]),
1895
                new_state: ObjectRef([2; 32]),
1896
                serial: 1,
1897
            },
1898
        };
1899
        let sig = agent_sk.sign(Domain::Attest, &signer, &attest.hash());
1900
        SignedAttest {
1901
            attest,
1902
            sigs: vec![sig],
1903
        }
1904
    };
1905
1906
    // The hub's log: eight entries, the attestation's at 3, the latest
1907
    // checkpoint of 8, and one of 4 that witnesses cosigned.
1908
    let log_sk = SecretKey::generate();
1909
    let log_key = log_sk.identity("hub.example", "[email protected]", 1);
1910
    let origin = "hub.example/log";
1911
    let hub = "https://hub.example";
1912
    let url = "https://hub.example/ada/a";
1913
    let w_sk = SecretKey::generate();
1914
    let w = w_sk.identity("w", "[email protected]", 1);
1915
    let stranger_sk = SecretKey::generate();
1916
    let stranger = stranger_sk.identity("s", "[email protected]", 1);
1917
    let sa = attested(t0 + 300_000);
1918
    let entry_of = |i: u64| {
1919
        let (kind, object) = if i == 3 {
1920
            ("ref", sa.attest.hash())
1921
        } else {
1922
            ("seal", ObjectRef([i as u8; 32]))
1923
        };
1924
        Entry {
1925
            kind: kind.into(),
1926
            repo: sa.attest.repo,
1927
            object,
1928
            signers: vec![signer],
1929
            received: t0 + 300_000,
1930
        }
1931
        .encode()
1932
    };
1933
    let mut stored: Vec<Hash> = Vec::new();
1934
    for i in 0..8 {
1935
        let add = tlog::stored_hashes_for_leaf(i, tlog::leaf_hash(&entry_of(i)), &stored).unwrap();
1936
        stored.extend(add);
1937
    }
1938
    let note_of = |n: u64, cosigners: &[(&str, &Identity, &SecretKey, u64)]| {
1939
        let mut note = Checkpoint {
1940
            origin: origin.into(),
1941
            size: n,
1942
            root: tlog::tree_hash(n, &stored).unwrap(),
1943
            extensions: vec![],
1944
        }
1945
        .sign(&log_key, &log_sk)
1946
        .unwrap();
1947
        for (name, id, sk, t) in cosigners {
1948
            note.sigs
1949
                .extend(tlog::cosign(&note.text, name, id, sk, *t).unwrap());
1950
        }
1951
        note.encode()
1952
    };
1953
    let latest = note_of(8, &[]);
1954
    let witnessed_at = (t0 + 360_000) / 1000;
1955
    let cosigned = note_of(
1956
        4,
1957
        &[
1958
            ("w.example", &w, &w_sk, witnessed_at),
1959
            ("s.example", &stranger, &stranger_sk, 1),
1960
        ],
1961
    );
1962
    let answer = |integration: Vec<Integration>, witnesses: Vec<(String, Vec<u8>)>| RefsResponse {
1963
        refs: vec![RemoteRef {
1964
            name: "main".into(),
1965
            state: ObjectRef([2; 32]),
1966
            heads: vec![],
1967
            attestation: Some(sa.clone()),
1968
            last_serial: None,
1969
            accepted: None,
1970
            logged: Some(Logged {
1971
                index: 3,
1972
                entry: entry_of(3),
1973
                proof: tlog::prove_inclusion(8, 3, &stored).unwrap(),
1974
            }),
1975
            integration,
1976
        }],
1977
        log: Some(latest.clone()),
1978
        witnesses,
1979
        ..RefsResponse::default()
1980
    };
1981
    let proof4 = tlog::prove_inclusion(4, 3, &stored).unwrap();
1982
    let served = vec![Integration {
1983
        note: cosigned.clone(),
1984
        proof: proof4.clone(),
1985
    }];
1986
    let listed = vec![("w.example".to_string(), w.encode())];
1987
    // This user saw the hub's log before (pinned, so nothing is fetched).
1988
    a.remember_log(hub, &log_key, &Note::parse(&latest).unwrap())
1989
        .unwrap();
1990
1991
    // The witness is pinned on first sight, silently; the stranger's
1992
    // earlier cosignature counts for nothing.
1993
    let resp = answer(served.clone(), listed.clone());
1994
    let lc = a.check_log(url, None, &resp).unwrap();
1995
    assert!(lc.notes.is_empty(), "{:?}", lc.notes);
1996
    let t = lc.time_of("main").unwrap();
1997
    assert_eq!((t.time, t.witness.as_str()), (witnessed_at, "w.example"));
1998
    // The certificate expired an hour and fifty minutes ago, but covered
1999
    // the integrated time: accepted, and nothing to say.
2000
    assert!(cert.cert.expires < now);
2001
    let mut notes = Vec::new();
2002
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
2003
        .unwrap();
2004
    assert!(notes.is_empty(), "{notes:?}");
2005
2006
    // Only the stranger cosigned: no witnessed time, so the earlier rule
2007
    // (the attestation's own time, inside the window), said so.
2008
    let lonely = vec![Integration {
2009
        note: note_of(4, &[("s.example", &stranger, &stranger_sk, 1)]),
2010
        proof: proof4.clone(),
2011
    }];
2012
    let resp = answer(lonely, vec![]);
2013
    let lc = a.check_log(url, None, &resp).unwrap();
2014
    assert!(lc
2015
        .time_of("main")
2016
        .unwrap_err()
2017
        .contains("no witness this user trusts"));
2018
    let mut notes = Vec::new();
2019
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
2020
        .unwrap();
2021
    assert!(
2022
        notes.len() == 1 && notes[0].contains("not at a witnessed time"),
2023
        "{notes:?}"
2024
    );
2025
2026
    // A witness listed later under the pinned name with another key is
2027
    // pinned with a note, as a new log key is.
2028
    let resp = answer(
2029
        served.clone(),
2030
        vec![("w.example".into(), stranger.encode())],
2031
    );
2032
    let lc = a.check_log(url, None, &resp).unwrap();
2033
    assert!(
2034
        lc.notes.iter().any(|n| n.contains("another key")),
2035
        "{:?}",
2036
        lc.notes
2037
    );
2038
    assert!(
2039
        lc.time_of("main").is_err(),
2040
        "w's cosignature is by its old key"
2041
    );
2042
    a.check_log(url, None, &answer(served.clone(), listed.clone()))
2043
        .unwrap();
2044
2045
    // An old peer's answer: no log, no witnesses, no integration. Judged
2046
    // as before, silently.
2047
    let mut old = answer(vec![], vec![]);
2048
    old.log = None;
2049
    old.refs[0].logged = None;
2050
    let lc = a.check_log(url, None, &old).unwrap();
2051
    assert!(!lc.kept && lc.notes.is_empty());
2052
    let mut notes = Vec::new();
2053
    a.authorize_in_time(&p, "origin", &old.refs[0], &sa, &signer, &lc, &mut notes)
2054
        .unwrap();
2055
    assert!(notes.is_empty(), "{notes:?}");
2056
2057
    // Judged at given integrated times.
2058
    let at = |secs_after_t0: u64| {
2059
        let mut times = std::collections::HashMap::new();
2060
        times.insert(
2061
            "main".to_string(),
2062
            Ok(Integrated {
2063
                time: (t0 + secs_after_t0 * 1000) / 1000,
2064
                witness: "w.example".into(),
2065
                size: 4,
2066
            }),
2067
        );
2068
        LogCheck {
2069
            kept: true,
2070
            times,
2071
            ..LogCheck::default()
2072
        }
2073
    };
2074
    let judged = |sa: &SignedAttest, lc: &LogCheck| {
2075
        let mut notes = Vec::new();
2076
        a.authorize_in_time(&p, "origin", &old.refs[0], sa, &signer, lc, &mut notes)
2077
            .map(|_| notes)
2078
    };
2079
    // Claimed inside the window, first witnessed an hour later, after
2080
    // the certificate expired: backdated, or held back. Accepted by the
2081
    // earlier rule while logs are new, with both said.
2082
    let notes = judged(&sa, &at(3600)).unwrap();
2083
    assert!(
2084
        notes
2085
            .iter()
2086
            .any(|n| n.contains("had lapsed when witness w.example"))
2087
            && notes
2088
                .iter()
2089
                .any(|n| n.contains("55 minutes before witness")),
2090
        "{notes:?}"
2091
    );
2092
    // Claimed after the certificate expired, but witnessed inside its
2093
    // window: the clock the signer did not choose decides. The gap is
2094
    // still noted.
2095
    let fast = attested(now);
2096
    let notes = judged(&fast, &at(400)).unwrap();
2097
    assert!(
2098
        notes.len() == 1 && notes[0].contains("after witness w.example saw it"),
2099
        "{notes:?}"
2100
    );
2101
    // Claimed and witnessed after it expired: refused, as before.
2102
    assert!(judged(&fast, &at(3600)).is_err());
2103
    // A gap within ten minutes is nothing to note.
2104
    assert!(judged(&sa, &at(500)).unwrap().is_empty());
2105
}
2106
2107
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
2108
/// subject the author granted, seals changes in the author's name; with
2109
/// no grant, a stranger's, or one that had ended, it is neither the
2110
/// author nor a delegate.
2111
/// oxygen#135: an owner renews or rotates with every delegation, and a
2112
/// repository may name the newest key as the author; the agent's grant by
2113
/// the earlier key still counts, but not one that key made after.
2114
#[test]
2115
fn a_grant_outlives_its_owner_s_rotation() {
2116
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
2117
    use crate::identity::Scope;
2118
    hermetic();
2119
    let dir = tempfile::tempdir().unwrap();
2120
    let root = dir.path();
2121
    let mut a = Repo::init(&root.join("a"))
2122
        .unwrap()
2123
        .with_home(root.join("home-a"));
2124
    let (old, _) = a
2125
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2126
        .unwrap();
2127
    let (_, old_sk) = a.secret_key().unwrap().unwrap();
2128
    let old_id = a.identity(&old).unwrap();
2129
    let hub_sk = SecretKey::generate();
2130
    let hub = hub_sk.identity("hub", "[email protected]", 1);
2131
    let now = Hlc::now().wall_ms;
2132
    let grant = |from: u64| {
2133
        SignedGrant::sign(
2134
            Grant {
2135
                grantor: old,
2136
                subject: "agent:claude@ada".into(),
2137
                issuer: hub.hash(),
2138
                scope: Scope::CHANGES | Scope::SEAL,
2139
                not_before: from,
2140
                expires: now + 86_400_000,
2141
            },
2142
            &old_id,
2143
            &old_sk,
2144
        )
2145
    };
2146
    let before = grant(now - 60_000);
2147
    let after = grant(now + 60_000);
2148
    let rot = a.renew_identity(None).unwrap();
2149
    assert_ne!(rot.new, old);
2150
    let agent = |name: &str, g: SignedGrant| {
2151
        let mut r = Repo::init(&root.join(name))
2152
            .unwrap()
2153
            .with_home(root.join(format!("home-{name}")));
2154
        let (key, id) = r
2155
            .create_identity(name, "[email protected]", IdentityScope::User)
2156
            .unwrap();
2157
        for i in [&old_id, &rot.identity, &hub] {
2158
            r.store().put_identity(i).unwrap();
2159
        }
2160
        r.set_user_config("author.key", &rot.new.to_hex()).unwrap();
2161
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
2162
        let cert = SignedCertificate::sign(
2163
            Certificate {
2164
                key: id,
2165
                issuer: hub.hash(),
2166
                subject: "agent:claude@ada".into(),
2167
                claims: vec![],
2168
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
2169
                not_before: now - 60_000,
2170
                expires: now + 600_000,
2171
                grant: Some(g),
2172
            },
2173
            &hub,
2174
            &hub_sk,
2175
        );
2176
        r.store().put_certificate(&cert).unwrap();
2177
        write(&root.join(name), "work.txt", b"agent work\n");
2178
        let h = r.commit("work", &[]).unwrap();
2179
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, rot.new);
2180
        r.seal(&[h]).unwrap();
2181
        (r, h)
2182
    };
2183
    let (r, h) = agent("kept", before);
2184
    assert!(
2185
        matches!(
2186
            r.authenticate_change(&h).unwrap(),
2187
            SignatureStatus::Valid { .. }
2188
        ),
2189
        "{:?}",
2190
        r.authenticate_change(&h).unwrap()
2191
    );
2192
    let (r, h) = agent("late", after);
2193
    assert!(
2194
        matches!(r.authenticate_change(&h).unwrap(), SignatureStatus::Invalid(e) if e.contains("neither")),
2195
        "a grant the old key made after the rotation: {:?}",
2196
        r.authenticate_change(&h).unwrap()
2197
    );
2198
}
2199
2200
#[test]
2201
fn a_certified_key_acts_for_its_author_under_a_grant() {
2202
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
2203
    use crate::identity::{Identity, Scope};
2204
    hermetic();
2205
    let dir = tempfile::tempdir().unwrap();
2206
    let root = dir.path();
2207
    let _origin = Repo::init(&root.join("origin")).unwrap();
2208
    let url = root.join("origin").to_string_lossy().to_string();
2209
    let mut a = Repo::clone(&url, &root.join("a"))
2210
        .unwrap()
2211
        .with_home(root.join("home-a"));
2212
    let (ada, _) = a
2213
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2214
        .unwrap();
2215
    write(&root.join("a"), "a.txt", b"a\n");
2216
    a.commit("a", &[]).unwrap();
2217
    a.policy_init().unwrap();
2218
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2219
    let hub_sk = SecretKey::generate();
2220
    let hub = hub_sk.identity("hub", "[email protected]", 1);
2221
    a.policy_grant_subject(
2222
        "agent:claude@ada",
2223
        hub.clone(),
2224
        Scope::CHANGES | Scope::REFS,
2225
        None,
2226
    )
2227
    .unwrap();
2228
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2229
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
2230
    let ada_id = a.identity(&ada).unwrap();
2231
2232
    let now = Hlc::now().wall_ms;
2233
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
2234
        SignedGrant::sign(
2235
            Grant {
2236
                grantor: by.hash(),
2237
                subject: "agent:claude@ada".into(),
2238
                issuer: hub.hash(),
2239
                scope: Scope::CHANGES | Scope::SEAL,
2240
                not_before: from,
2241
                expires: to,
2242
            },
2243
            by,
2244
            sk,
2245
        )
2246
    };
2247
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
2248
    // certified (with `g` inside) the signer.
2249
    let agent = |name: &str, g: Option<SignedGrant>| {
2250
        let mut r = Repo::clone(&url, &root.join(name))
2251
            .unwrap()
2252
            .with_home(root.join(format!("home-{name}")));
2253
        let (key, id) = r
2254
            .create_identity(name, "[email protected]", IdentityScope::User)
2255
            .unwrap();
2256
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
2257
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
2258
        let cert = SignedCertificate::sign(
2259
            Certificate {
2260
                key: id,
2261
                issuer: hub.hash(),
2262
                subject: "agent:claude@ada".into(),
2263
                claims: vec![],
2264
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
2265
                not_before: now - 60_000,
2266
                expires: now + 600_000,
2267
                grant: g,
2268
            },
2269
            &hub,
2270
            &hub_sk,
2271
        );
2272
        r.store().put_identity(&hub).unwrap();
2273
        r.store().put_certificate(&cert).unwrap();
2274
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
2275
        let h = r.commit("work", &[]).unwrap();
2276
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
2277
        (r, key, h)
2278
    };
2279
2280
    let (claude, key, h) = agent(
2281
        "claude",
2282
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
2283
    );
2284
    let r = claude.push("origin", false).unwrap();
2285
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2286
    let host = Repo::open(&root.join("origin")).unwrap();
2287
    assert!(
2288
        matches!(
2289
            host.authenticate_change(&h).unwrap(),
2290
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
2291
        ),
2292
        "named by its certificate's subject"
2293
    );
2294
    a.pull("origin").unwrap();
2295
    assert!(matches!(
2296
        a.authenticate_change(&h).unwrap(),
2297
        SignatureStatus::Valid { key: k, .. } if k == key
2298
    ));
2299
2300
    let (none, _, _) = agent("none", None);
2301
    let r = none.push("origin", false).unwrap();
2302
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
2303
    let mallory_sk = SecretKey::generate();
2304
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
2305
    let (stranger, _, _) = agent(
2306
        "stranger",
2307
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
2308
    );
2309
    let r = stranger.push("origin", false).unwrap();
2310
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
2311
    let (ended, _, eh) = agent(
2312
        "ended",
2313
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
2314
    );
2315
    let r = ended.push("origin", false).unwrap();
2316
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
2317
    assert!(matches!(
2318
        ended.authenticate_change(&eh).unwrap(),
2319
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
2320
    ));
2321
}
2322
2323
#[test]
2324
fn trust_policy_governs_pushes_and_fetches() {
2325
    hermetic();
2326
    let dir = tempfile::tempdir().unwrap();
2327
    let root = dir.path();
2328
    let origin = Repo::init(&root.join("origin")).unwrap();
2329
    let url = root.join("origin").to_string_lossy().to_string();
2330
2331
    // A is the root. Before the policy, an unsigned push from B is fine.
2332
    let mut a = Repo::clone(&url, &root.join("a"))
2333
        .unwrap()
2334
        .with_home(root.join("home-a"));
2335
    let (key_a, _) = a
2336
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2337
        .unwrap();
2338
    let mut b = Repo::clone(&url, &root.join("b"))
2339
        .unwrap()
2340
        .with_home(root.join("home-b"));
2341
    write(&root.join("b"), "b.txt", b"b\n");
2342
    b.commit("unsigned before policy", &[]).unwrap();
2343
    assert!(b.push("origin", false).unwrap()[0].ok);
2344
    origin.refresh().unwrap();
2345
2346
    // A creates the policy and pushes it; origin now enforces it.
2347
    write(&root.join("a"), "a.txt", b"a\n");
2348
    a.commit("a", &[]).unwrap();
2349
    let sp = a.policy_init().unwrap();
2350
    assert_eq!(sp.policy.serial, 1);
2351
    a.pull("origin").unwrap();
2352
    let results = a.push("origin", false).unwrap();
2353
    origin.refresh().unwrap();
2354
    assert!(results.iter().all(|r| r.ok), "{results:?}");
2355
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
2356
2357
    // B pulls the policy. Without an identity B cannot push at all.
2358
    b.pull("origin").unwrap();
2359
    assert!(
2360
        b.current_policy().unwrap().is_some(),
2361
        "the policy arrived with the fetch"
2362
    );
2363
    assert!(b.push("origin", false).is_err());
2364
    // With an identity the policy does not list, the push is rejected by origin.
2365
    let (key_b, id_b) = b
2366
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2367
        .unwrap();
2368
    write(&root.join("b"), "b.txt", b"b2\n");
2369
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
2370
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
2371
    let r = b.push("origin", false).unwrap();
2372
    origin.refresh().unwrap();
2373
    assert!(
2374
        !r[0].ok && r[0].reason.contains("may not update"),
2375
        "{:?}",
2376
        r
2377
    );
2378
2379
    // A grants B (identity handed over as a file) and publishes the policy.
2380
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
2381
    assert_eq!(sp.policy.serial, 2);
2382
    let r = a.push("origin", false).unwrap();
2383
    origin.refresh().unwrap();
2384
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2385
    // B must fetch the new policy before pushing.
2386
    assert!(b
2387
        .push("origin", false)
2388
        .unwrap_or_else(|e| vec![RefResult {
2389
            name: "main".into(),
2390
            ok: false,
2391
            reason: e.to_string()
2392
        }])
2393
        .iter()
2394
        .all(|x| !x.ok));
2395
    b.pull("origin").unwrap();
2396
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
2397
    let r = b.push("origin", false).unwrap();
2398
    origin.refresh().unwrap();
2399
    assert!(r[0].ok, "{:?}", r);
2400
    // Origin verified B's change under the policy.
2401
    let heads = origin.bookmark_heads().unwrap();
2402
    for h in &heads {
2403
        let c = origin.store().get_change(h).unwrap();
2404
        if c.author == key_b {
2405
            origin
2406
                .change_allowed(
2407
                    h,
2408
                    &origin.current_policy().unwrap().unwrap().1.policy,
2409
                    "main",
2410
                )
2411
                .unwrap();
2412
        }
2413
    }
2414
2415
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
2416
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
2417
    forged.serial = 3;
2418
    forged.roots = vec![key_b];
2419
    let fh = forged.hash();
2420
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2421
    let forged = SignedPolicy {
2422
        policy: forged,
2423
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
2424
    };
2425
    let r = origin
2426
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
2427
        .unwrap();
2428
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
2429
    let stale = a.current_policy().unwrap().unwrap().1;
2430
    let mut old = stale.clone();
2431
    old.policy.serial = 1;
2432
    let r = origin
2433
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
2434
        .unwrap();
2435
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
2436
2437
    // A revokes B; after B pulls the policy, B's pushes are refused again.
2438
    a.pull("origin").unwrap();
2439
    a.policy_revoke(&key_b).unwrap();
2440
    let r = a.push("origin", false).unwrap();
2441
    origin.refresh().unwrap();
2442
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2443
    b.pull("origin").unwrap();
2444
    write(&root.join("b"), "b.txt", b"b3\n");
2445
    b.commit("b3", &[]).unwrap();
2446
    let r = b.push("origin", false).unwrap();
2447
    origin.refresh().unwrap();
2448
    assert!(!r[0].ok, "{:?}", r);
2449
2450
    // A clone by a third party receives and verifies everything.
2451
    let c = Repo::clone(&url, &root.join("c"))
2452
        .unwrap()
2453
        .with_home(root.join("home-c"));
2454
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
2455
    assert!(c
2456
        .current_policy()
2457
        .unwrap()
2458
        .unwrap()
2459
        .1
2460
        .policy
2461
        .roots
2462
        .contains(&key_a));
2463
    assert!(!c.snapshot("status").unwrap().changed);
2464
}
2465
2466
/// oxygen#66: a gc says what it is doing, phase by phase.
2467
#[test]
2468
fn gc_reports_its_phases() {
2469
    hermetic();
2470
    let dir = tempfile::tempdir().unwrap();
2471
    let repo = Repo::init(dir.path()).unwrap();
2472
    for i in 0..3 {
2473
        write(
2474
            dir.path(),
2475
            &format!("f{i}.txt"),
2476
            format!("{i}\n").as_bytes(),
2477
        );
2478
        repo.commit(&format!("c{i}"), &[]).unwrap();
2479
    }
2480
    let mut phases = Vec::new();
2481
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
2482
        .unwrap();
2483
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
2484
    assert!(
2485
        phases.iter().any(|p| p.starts_with("pruning")),
2486
        "{phases:?}"
2487
    );
2488
    assert!(
2489
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
2490
        "{phases:?}"
2491
    );
2492
    assert!(
2493
        phases
2494
            .iter()
2495
            .any(|p| p.starts_with("writing the index of ")),
2496
        "{phases:?}"
2497
    );
2498
}
2499
2500
#[test]
2501
fn gc_packs_objects_and_history_still_works() {
2502
    hermetic();
2503
    let dir = tempfile::tempdir().unwrap();
2504
    let root = dir.path();
2505
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2506
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2507
        .unwrap();
2508
    repo.set_user_config("core.sign", "change").unwrap();
2509
    write(root, "a.txt", b"one\n");
2510
    let h1 = repo.commit("one", &[]).unwrap();
2511
    write(root, "a.txt", b"two\n");
2512
    write(root, "big.bin", &vec![0u8; 100_000]);
2513
    let h2 = repo.commit("two", &[]).unwrap();
2514
    // Several snapshots leave superseded working-copy versions behind.
2515
    for i in 0..5 {
2516
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
2517
        repo.snapshot("status").unwrap();
2518
    }
2519
    write(root, "a.txt", b"two\n");
2520
    repo.snapshot("status").unwrap();
2521
    let before = repo.store().list().unwrap();
2522
    assert!(repo.store().loose_count().unwrap() > 0);
2523
2524
    // With the default retention every operation's view is a root: nothing prunes.
2525
    let r = repo.gc(true).unwrap();
2526
    assert_eq!(r.packed.objects, before.len());
2527
    assert_eq!(r.pruned.objects, 0);
2528
    assert_eq!(repo.store().loose_count().unwrap(), 0);
2529
    assert_eq!(repo.store().list().unwrap(), before);
2530
2531
    // With zero retention only the current view is a root: superseded
2532
    // working copies go, everything reachable stays.
2533
    repo.config.set("core.op-retention", "0").unwrap();
2534
    repo.save_config().unwrap();
2535
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
2536
    let r = repo.gc(true).unwrap();
2537
    assert!(r.pruned.objects >= 5, "{r:?}");
2538
    let after = repo.store().list().unwrap();
2539
    assert!(after.len() < before.len());
2540
    assert!(after.contains(&h1) && after.contains(&h2));
2541
    for (_, op) in repo.op_log().unwrap() {
2542
        assert!(!op.command.is_empty(), "operation objects are all kept");
2543
    }
2544
    // Everything still works from the pruned, packed store.
2545
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
2546
    assert!(matches!(
2547
        repo.verify_change(&h2).unwrap(),
2548
        SignatureStatus::Valid { .. }
2549
    ));
2550
    assert_eq!(repo.log().unwrap().len(), 3);
2551
    repo.checkout(&[h1], false, "checkout").unwrap();
2552
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
2553
    repo.checkout(&[h2], false, "checkout").unwrap();
2554
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
2555
    assert!(!repo.snapshot("status").unwrap().changed);
2556
    // Grace period defers pruning of young garbage.
2557
    write(root, "a.txt", b"three\n");
2558
    repo.commit("three", &[]).unwrap();
2559
    let r = repo.gc(false).unwrap();
2560
    assert_eq!(r.pruned.objects, 0);
2561
    assert!(r.pruned.deferred > 0);
2562
    let r = repo.gc(true).unwrap();
2563
    assert!(r.pruned.objects > 0);
2564
    assert_eq!(repo.log().unwrap().len(), 4);
2565
    // Restoring the default retention makes the old views roots again; the
2566
    // working copies they name were pruned, which gc tolerates.
2567
    repo.config.set("core.op-retention", "90").unwrap();
2568
    repo.save_config().unwrap();
2569
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2570
    let r = repo.gc(false).unwrap();
2571
    assert_eq!(r.pruned.objects, 0);
2572
    assert_eq!(repo.log().unwrap().len(), 4);
2573
}
2574
2575
#[test]
2576
fn describe_amend_abandon_heads() {
2577
    hermetic();
2578
    let dir = tempfile::tempdir().unwrap();
2579
    let root = dir.path();
2580
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2581
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2582
        .unwrap();
2583
    repo.set_user_config("core.sign", "change").unwrap();
2584
    write(root, "a.txt", b"one\n");
2585
    let h1 = repo.commit("first", &[]).unwrap();
2586
    write(root, "a.txt", b"one\ntwo\n");
2587
    let h2 = repo.commit("secnod", &[]).unwrap();
2588
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
2589
2590
    // describe: same ChangeId, new hash, bookmark and working copy follow.
2591
    let h2b = repo.describe(&h2, "second").unwrap();
2592
    assert_ne!(h2b, h2);
2593
    let c = repo.store().get_change(&h2b).unwrap();
2594
    assert_eq!(
2595
        (c.change_id, c.message.as_str(), c.deps.clone()),
2596
        (id2, "second", vec![h1])
2597
    );
2598
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
2599
    assert!(matches!(
2600
        repo.verify_change(&h2b).unwrap(),
2601
        SignatureStatus::Valid { .. }
2602
    ));
2603
    let s = repo.snapshot("status").unwrap();
2604
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
2605
    assert_eq!(
2606
        repo.resolve_change(&id2.short(8)).unwrap(),
2607
        h2b,
2608
        "the old object is no longer reachable from the log"
2609
    );
2610
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
2611
    let h1b = repo.describe(&h1, "first, described").unwrap();
2612
    assert_ne!(h1b, h1);
2613
    let heads = repo.bookmark_heads().unwrap();
2614
    assert_eq!(heads.len(), 1);
2615
    let top = repo.store().get_change(&heads[0]).unwrap();
2616
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
2617
    assert!(
2618
        matches!(
2619
            repo.verify_change(&heads[0]).unwrap(),
2620
            SignatureStatus::Valid { .. }
2621
        ),
2622
        "rewritten own change is re-signed"
2623
    );
2624
    let (_, wc) = repo.working_copy().unwrap();
2625
    assert_eq!(
2626
        wc.deps,
2627
        vec![heads[0]],
2628
        "the working copy follows the rewrite"
2629
    );
2630
    assert!(!repo.snapshot("status").unwrap().changed);
2631
    let snap = repo.load_state(&heads).unwrap().materialize();
2632
    assert!(
2633
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
2634
    );
2635
2636
    // amend: fold an edit into the head; the result is one change from h1.
2637
    write(root, "a.txt", b"one\ntwo\nthree\n");
2638
    write(root, "b.txt", b"b\n");
2639
    let h2c = repo.amend(None).unwrap();
2640
    let c = repo.store().get_change(&h2c).unwrap();
2641
    assert_eq!(c.change_id, id2);
2642
    assert_eq!(c.message, "second");
2643
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
2644
    assert_eq!(
2645
        repo.log().unwrap().len(),
2646
        3,
2647
        "working copy, amended head, first"
2648
    );
2649
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
2650
    assert!(
2651
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
2652
    );
2653
    assert!(snap.files.contains_key("b.txt"));
2654
    assert!(!repo.snapshot("status").unwrap().changed);
2655
    assert!(
2656
        repo.amend(None).is_err(),
2657
        "clean working copy and no message"
2658
    );
2659
    let h2d = repo.amend(Some("second, amended")).unwrap();
2660
    assert_eq!(
2661
        repo.store().get_change(&h2d).unwrap().message,
2662
        "second, amended"
2663
    );
2664
2665
    // abandon: the head goes, its content stays as uncommitted work.
2666
    repo.abandon(&h2d).unwrap();
2667
    assert_eq!(
2668
        repo.bookmark_heads().unwrap(),
2669
        vec![h1b],
2670
        "the described first change is the head again"
2671
    );
2672
    let s = repo.snapshot("status").unwrap();
2673
    let paths: Vec<_> = s
2674
        .statuses
2675
        .iter()
2676
        .map(|p| (p.path.as_str(), p.status))
2677
        .collect();
2678
    assert_eq!(
2679
        paths,
2680
        vec![
2681
            ("a.txt", ChangeStatus::Modified),
2682
            ("b.txt", ChangeStatus::Added)
2683
        ]
2684
    );
2685
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
2686
    let h3 = repo.commit("recommitted", &[]).unwrap();
2687
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
2688
    // undo brings the abandoned head back.
2689
    repo.undo().unwrap();
2690
    repo.undo().unwrap();
2691
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
2692
2693
    // Abandoning a non-head whose dependent references its atoms reifies
2694
    // the references (here: a.txt vanishes with it, so the dependent's edit
2695
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
2696
    let base = repo.bookmark_heads().unwrap()[0];
2697
    let base_change = repo.store().get_change(&base).unwrap();
2698
    let h1_now = base_change.deps[0];
2699
    let notes = repo.abandon(&h1_now).unwrap();
2700
    assert!(
2701
        !notes.is_empty(),
2702
        "the dependent's edit of a.txt was reified"
2703
    );
2704
    let heads = repo.bookmark_heads().unwrap();
2705
    let after = repo.load_state(&heads).unwrap().materialize();
2706
    assert!(
2707
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
2708
        "{:?}",
2709
        after.files.keys()
2710
    );
2711
    repo.undo().unwrap();
2712
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
2713
    write(root, "c.txt", b"c\n");
2714
    let hc = repo.commit("c", &[]).unwrap();
2715
    write(root, "d.txt", b"d\n");
2716
    let hd = repo.commit("d", &[hc]).unwrap();
2717
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
2718
    repo.abandon(&hc).unwrap();
2719
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2720
    assert!(!heads.contains(&hc));
2721
    let d_now = heads
2722
        .iter()
2723
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
2724
        .copied()
2725
        .unwrap();
2726
    assert!(
2727
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
2728
        "d inherited c's (empty) dependencies"
2729
    );
2730
    let s = repo.snapshot("status").unwrap();
2731
    assert_eq!(
2732
        s.statuses
2733
            .iter()
2734
            .map(|p| p.path.as_str())
2735
            .collect::<Vec<_>>(),
2736
        vec!["c.txt"],
2737
        "c's content is now uncommitted work"
2738
    );
2739
}
2740
2741
#[test]
2742
fn git_export_mirrors_history() {
2743
    hermetic();
2744
    if std::process::Command::new("git")
2745
        .arg("--version")
2746
        .output()
2747
        .is_err()
2748
    {
2749
        eprintln!("git not installed; skipping");
2750
        return;
2751
    }
2752
    let dir = tempfile::tempdir().unwrap();
2753
    let root = dir.path();
2754
    let mut repo = Repo::init(&root.join("r"))
2755
        .unwrap()
2756
        .with_home(root.join("home"));
2757
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
2758
        .unwrap();
2759
    let r = root.join("r");
2760
    write(&r, "README.md", b"hello\n");
2761
    write(&r, "src/main.rs", b"fn main() {}\n");
2762
    let h1 = repo.commit("first", &[]).unwrap();
2763
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
2764
    write(&r, "logo.png", b"\x89PNG\0\0");
2765
    let h2 = repo.commit("second", &[]).unwrap();
2766
2767
    let git_dir = root.join("mirror.git");
2768
    let rep = repo.git_export(&git_dir).unwrap();
2769
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
2770
    let git = |args: &[&str]| -> String {
2771
        let out = std::process::Command::new("git")
2772
            .arg("-C")
2773
            .arg(&git_dir)
2774
            .args(args)
2775
            .output()
2776
            .unwrap();
2777
        assert!(
2778
            out.status.success(),
2779
            "{}",
2780
            String::from_utf8_lossy(&out.stderr)
2781
        );
2782
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2783
    };
2784
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
2785
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2786
    assert_eq!(git(&["show", "main:README.md"]), "hello");
2787
    let body = git(&["log", "-1", "--format=%B", "main"]);
2788
    assert!(
2789
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
2790
        "{body}"
2791
    );
2792
    assert!(body.contains("Change-Id: "), "{body}");
2793
    assert_eq!(
2794
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
2795
        "Ada Lovelace <[email protected]>"
2796
    );
2797
    assert_eq!(
2798
        git(&["ls-tree", "--name-only", "main"]),
2799
        "README.md\nlogo.png\nsrc"
2800
    );
2801
2802
    // Re-export is incremental.
2803
    let rep = repo.git_export(&git_dir).unwrap();
2804
    assert_eq!((rep.exported, rep.skipped), (0, 2));
2805
2806
    // An independent change makes two heads; the next state is one more
2807
    // commit on the linear branch whose tree is the union.
2808
    repo.checkout(&[h1], false, "checkout").unwrap();
2809
    write(&r, "other.txt", b"o\n");
2810
    let h3 = repo.commit("third", &[]).unwrap();
2811
    let rep = repo.git_export(&git_dir).unwrap();
2812
    assert_eq!((rep.exported, rep.heads), (1, 2));
2813
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
2814
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
2815
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
2816
    assert_eq!(git(&["show", "main:other.txt"]), "o");
2817
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
2818
    assert_eq!(
2819
        git(&["ls-tree", "--name-only", "main"]),
2820
        "README.md\nlogo.png\nother.txt\nsrc"
2821
    );
2822
    let body = git(&["log", "-1", "--format=%B", "main"]);
2823
    assert!(
2824
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
2825
        "{body}"
2826
    );
2827
    // A rewrite is a new state whose one new change is the rewritten one.
2828
    repo.describe(&h3, "third, described").unwrap();
2829
    let rep = repo.git_export(&git_dir).unwrap();
2830
    assert_eq!(rep.exported, 1);
2831
    assert_eq!(
2832
        git(&["log", "-1", "--format=%s", "main"]),
2833
        "third, described"
2834
    );
2835
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
2836
    let _ = h2;
2837
}
2838
2839
#[test]
2840
fn git_import_reproduces_trees() {
2841
    git_import_reproduces_trees_with(None);
2842
}
2843
2844
/// The same import with every merge rendered in batches of one file
2845
/// (oxygen#25): what a merge onto a base of thousands of files takes.
2846
#[test]
2847
fn git_import_reproduces_trees_in_batches() {
2848
    git_import_reproduces_trees_with(Some(1));
2849
}
2850
2851
fn git_import_reproduces_trees_with(batch: Option<usize>) {
2852
    crate::repo::git::set_merge_batch_for_tests(batch);
2853
    hermetic();
2854
    if std::process::Command::new("git")
2855
        .arg("--version")
2856
        .output()
2857
        .is_err()
2858
    {
2859
        eprintln!("git not installed; skipping");
2860
        return;
2861
    }
2862
    let dir = tempfile::tempdir().unwrap();
2863
    let root = dir.path();
2864
    let g = root.join("src.git");
2865
    fs::create_dir_all(&g).unwrap();
2866
    let git = |args: &[&str]| -> String {
2867
        let out = std::process::Command::new("git")
2868
            .arg("-C")
2869
            .arg(&g)
2870
            .args([
2871
                "-c",
2872
                "user.name=Grace",
2873
                "-c",
2874
                "[email protected]",
2875
                "-c",
2876
                "commit.gpgsign=false",
2877
            ])
2878
            .args(args)
2879
            .output()
2880
            .unwrap();
2881
        assert!(
2882
            out.status.success(),
2883
            "git {args:?}: {}",
2884
            String::from_utf8_lossy(&out.stderr)
2885
        );
2886
        String::from_utf8_lossy(&out.stdout).trim().to_string()
2887
    };
2888
    git(&["init", "-q", "-b", "main"]);
2889
    write(&g, "README.md", b"# Hi\n");
2890
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
2891
    git(&["add", "."]);
2892
    git(&["commit", "-q", "-m", "initial"]);
2893
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
2894
    write(&g, "run.sh", b"#!/bin/sh\n");
2895
    #[cfg(unix)]
2896
    {
2897
        use std::os::unix::fs::PermissionsExt;
2898
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
2899
    }
2900
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
2901
    git(&["add", "."]);
2902
    git(&[
2903
        "commit",
2904
        "-q",
2905
        "-m",
2906
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
2907
    ]);
2908
    // A branch that edits README, merged back with a conflict-free merge.
2909
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
2910
    write(&g, "README.md", b"# Hi\n\nMore.\n");
2911
    git(&["commit", "-q", "-am", "readme"]);
2912
    git(&["checkout", "-q", "main"]);
2913
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
2914
    // A branch from the initial commit inserting at the same place as
2915
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
2916
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
2917
    git(&["checkout", "-q", "-b", "clash", &initial]);
2918
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
2919
    git(&["commit", "-q", "-am", "clash"]);
2920
    git(&["checkout", "-q", "main"]);
2921
    let _ = std::process::Command::new("git")
2922
        .arg("-C")
2923
        .arg(&g)
2924
        .args(["merge", "-q", "clash"])
2925
        .output();
2926
    write(
2927
        &g,
2928
        "src/lib.rs",
2929
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
2930
    );
2931
    git(&["add", "."]);
2932
    git(&["commit", "-q", "-m", "resolve clash"]);
2933
    git(&["rm", "-q", "logo.png"]);
2934
    git(&["commit", "-q", "-m", "drop logo"]);
2935
    // A rename with a small edit is imported as a move of the same node.
2936
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
2937
    write(
2938
        &g,
2939
        "src/lib2.rs",
2940
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
2941
    );
2942
    git(&["add", "."]);
2943
    git(&["commit", "-q", "-m", "rename lib"]);
2944
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
2945
    // run.sh is the same as in the first parent's tree, but the merged
2946
    // change touched it, so the importer must compare it, not skip it.
2947
    git(&["checkout", "-q", "-b", "discarded"]);
2948
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
2949
    git(&["commit", "-q", "-am", "discarded edit"]);
2950
    git(&["checkout", "-q", "main"]);
2951
    git(&[
2952
        "merge",
2953
        "-q",
2954
        "-s",
2955
        "ours",
2956
        "-m",
2957
        "merge discarded, keeping ours",
2958
        "discarded",
2959
    ]);
2960
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
2961
2962
    let dest = root.join("oxy");
2963
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
2964
    let rep = repo.import_git(&g, "main").unwrap();
2965
    assert_eq!(rep.commits, expected_count);
2966
    assert_eq!(rep.merges, 3);
2967
    assert_eq!(
2968
        fs::read(dest.join("run.sh")).unwrap(),
2969
        b"#!/bin/sh\n",
2970
        "the ours merge kept main's run.sh"
2971
    );
2972
    let v = repo.verify_git_import(&g, "main").unwrap();
2973
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
2974
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
2975
    // The working copy equals the Git tree at main.
2976
    assert_eq!(
2977
        fs::read(dest.join("src/lib2.rs")).unwrap(),
2978
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
2979
    );
2980
    assert!(!dest.join("src/lib.rs").exists());
2981
    assert_eq!(
2982
        fs::read(dest.join("README.md")).unwrap(),
2983
        b"# Hi\n\nMore.\n"
2984
    );
2985
    assert!(!dest.join("logo.png").exists());
2986
    #[cfg(unix)]
2987
    {
2988
        use std::os::unix::fs::PermissionsExt;
2989
        assert!(
2990
            fs::metadata(dest.join("run.sh"))
2991
                .unwrap()
2992
                .permissions()
2993
                .mode()
2994
                & 0o111
2995
                != 0
2996
        );
2997
    }
2998
    assert!(
2999
        !repo.snapshot("status").unwrap().changed,
3000
        "clean after import"
3001
    );
3002
    let heads = repo.bookmark_heads().unwrap();
3003
    let st = repo.load_state(&heads).unwrap();
3004
    assert!(!st.materialize().is_conflicted());
3005
    assert_eq!(st.len(), expected_count);
3006
    let tip = repo
3007
        .log()
3008
        .unwrap()
3009
        .into_iter()
3010
        .find(|e| e.change.message.starts_with("rename lib"))
3011
        .unwrap();
3012
    let c = repo.store().get_change(&tip.hash).unwrap();
3013
    assert!(
3014
        c.tree_ops
3015
            .iter()
3016
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
3017
        "{:?}",
3018
        c.tree_ops
3019
    );
3020
    assert!(!c
3021
        .tree_ops
3022
        .iter()
3023
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
3024
    // Messages carry Git trailers; the Change-Id trailer was honoured.
3025
    let log = repo.log().unwrap();
3026
    let second = log
3027
        .iter()
3028
        .find(|e| e.change.message.starts_with("second"))
3029
        .unwrap();
3030
    assert_eq!(
3031
        second.change.change_id,
3032
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
3033
    );
3034
    assert!(second
3035
        .change
3036
        .message
3037
        .contains("Git-Author: Grace <[email protected]>"));
3038
    let resolve = log
3039
        .iter()
3040
        .find(|e| e.change.message.starts_with("resolve clash"))
3041
        .unwrap();
3042
    assert_eq!(
3043
        resolve.change.kind,
3044
        ChangeKind::Resolution,
3045
        "a conflicting Git merge becomes a resolution"
3046
    );
3047
    // Re-importing into another fresh repository gives the same ChangeIds.
3048
    let repo2 = Repo::init(&root.join("oxy2"))
3049
        .unwrap()
3050
        .with_home(root.join("home"));
3051
    repo2.import_git(&g, "main").unwrap();
3052
    // New nodes' identifiers derive from the commit (spec §23), so the
3053
    // re-import is not just the same ChangeIds but the same changes.
3054
    assert_eq!(
3055
        repo2.bookmark_heads().unwrap(),
3056
        repo.bookmark_heads().unwrap()
3057
    );
3058
    let ids: BTreeSet<ChangeId> = repo
3059
        .log()
3060
        .unwrap()
3061
        .iter()
3062
        .filter(|e| !e.is_working_copy)
3063
        .map(|e| e.change.change_id)
3064
        .collect();
3065
    let ids2: BTreeSet<ChangeId> = repo2
3066
        .log()
3067
        .unwrap()
3068
        .iter()
3069
        .filter(|e| !e.is_working_copy)
3070
        .map(|e| e.change.change_id)
3071
        .collect();
3072
    assert_eq!(ids, ids2);
3073
    // Round trip back out to Git reproduces the tip tree.
3074
    let mirror = root.join("mirror.git");
3075
    repo.git_export(&mirror).unwrap();
3076
    let out = std::process::Command::new("git")
3077
        .arg("-C")
3078
        .arg(&mirror)
3079
        .args(["show", "main:src/lib2.rs"])
3080
        .output()
3081
        .unwrap();
3082
    assert_eq!(
3083
        String::from_utf8_lossy(&out.stdout),
3084
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
3085
    );
3086
    let out = std::process::Command::new("git")
3087
        .arg("-C")
3088
        .arg(&mirror)
3089
        .args(["show", "main:src/lib.rs"])
3090
        .output()
3091
        .unwrap();
3092
    assert!(
3093
        !out.status.success(),
3094
        "the old path is gone from the export"
3095
    );
3096
}
3097
3098
#[test]
3099
fn checkpoints_accelerate_loading_and_stay_correct() {
3100
    hermetic();
3101
    let dir = tempfile::tempdir().unwrap();
3102
    let root = dir.path();
3103
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3104
    repo.config.set("core.checkpoint-interval", "5").unwrap();
3105
    repo.save_config().unwrap();
3106
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
3107
    let mut hashes = Vec::new();
3108
    for i in 0..12 {
3109
        write(
3110
            root,
3111
            "a.txt",
3112
            format!(
3113
                "{}\n",
3114
                (0..=i)
3115
                    .map(|k| k.to_string())
3116
                    .collect::<Vec<_>>()
3117
                    .join("\n")
3118
            )
3119
            .as_bytes(),
3120
        );
3121
        write(root, &format!("f{i}.txt"), b"x\n");
3122
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
3123
    }
3124
    let (_, cp) = repo
3125
        .latest_checkpoint("main")
3126
        .unwrap()
3127
        .expect("automatic checkpoint");
3128
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
3129
    // Loading through the checkpoint equals loading everything.
3130
    let heads = repo.bookmark_heads().unwrap();
3131
    let fast = repo.load_state(&heads).unwrap();
3132
    let full = repo.load_state_full(&heads).unwrap();
3133
    assert_eq!(fast.len(), full.len());
3134
    assert_eq!(fast.heads(), full.heads());
3135
    let (a, b) = (fast.materialize(), full.materialize());
3136
    assert_eq!(
3137
        a.files.keys().collect::<Vec<_>>(),
3138
        b.files.keys().collect::<Vec<_>>()
3139
    );
3140
    for (p, f) in &a.files {
3141
        assert_eq!(f.content, b.files[p].content, "{p}");
3142
    }
3143
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
3144
    // A head set that does not contain the checkpoint's heads falls back.
3145
    assert!(repo
3146
        .load_state_checkpointed(&[hashes[0]])
3147
        .unwrap()
3148
        .is_none());
3149
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
3150
    // Everything else keeps working on top of the checkpoint.
3151
    assert!(!repo.snapshot("status").unwrap().changed);
3152
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
3153
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
3154
    let (r, n, bytes) = repo.checkpoint().unwrap();
3155
    assert!(n >= 12 && bytes > 0);
3156
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
3157
    write(root, "a.txt", b"after\n");
3158
    let h_after = repo.commit("after", &[]).unwrap();
3159
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3160
    assert!(st.contains(&h_after));
3161
    assert!(
3162
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
3163
    );
3164
    assert_eq!(repo.log().unwrap().len(), 14);
3165
    // Checkpoints survive gc.
3166
    repo.gc(true).unwrap();
3167
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
3168
    assert!(repo
3169
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
3170
        .unwrap()
3171
        .is_some());
3172
}
3173
3174
#[test]
3175
fn quick_status_for_prompts() {
3176
    hermetic();
3177
    let dir = tempfile::tempdir().unwrap();
3178
    let root = dir.path();
3179
    let origin = Repo::init(&root.join("origin")).unwrap();
3180
    let url = root.join("origin").to_string_lossy().to_string();
3181
    let a = Repo::clone(&url, &root.join("a"))
3182
        .unwrap()
3183
        .with_home(root.join("home"));
3184
    let ops_before = a.op_log().unwrap().len();
3185
    let info = a.quick_status().unwrap();
3186
    assert_eq!(
3187
        (
3188
            info.bookmark.as_str(),
3189
            info.heads,
3190
            info.dirty,
3191
            info.conflicted,
3192
            info.ahead,
3193
            info.behind
3194
        ),
3195
        ("main", 0, false, false, Some(0), Some(0))
3196
    );
3197
    write(&root.join("a"), "f.txt", b"f\n");
3198
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
3199
    assert_eq!(
3200
        a.op_log().unwrap().len(),
3201
        ops_before,
3202
        "quick_status records nothing"
3203
    );
3204
    // A snapshotted but uncommitted change is still dirty.
3205
    a.snapshot("status").unwrap();
3206
    assert!(a.quick_status().unwrap().dirty);
3207
    a.commit("f", &[]).unwrap();
3208
    let info = a.quick_status().unwrap();
3209
    assert!(!info.dirty, "clean right after a commit");
3210
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
3211
    assert_eq!(
3212
        info.format("%b %c%d%x%A%D"),
3213
        format!("main {}+1", info.change_id)
3214
    );
3215
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
3216
    // Touching a file without changing it is not dirty; changing content of
3217
    // the same size is.
3218
    let p = root.join("a/f.txt");
3219
    let content = fs::read(&p).unwrap();
3220
    fs::write(&p, &content).unwrap();
3221
    assert!(!a.quick_status().unwrap().dirty);
3222
    fs::write(&p, b"g\n").unwrap();
3223
    assert!(a.quick_status().unwrap().dirty);
3224
    fs::write(&p, b"f\n").unwrap();
3225
    // Push, then a second clone commits and pushes: we are behind.
3226
    assert!(a.push("origin", false).unwrap()[0].ok);
3227
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
3228
    let b = Repo::clone(&url, &root.join("b"))
3229
        .unwrap()
3230
        .with_home(root.join("home-b"));
3231
    write(&root.join("b"), "g.txt", b"g\n");
3232
    b.commit("g", &[]).unwrap();
3233
    b.push("origin", false).unwrap();
3234
    a.fetch("origin").unwrap();
3235
    let info = a.quick_status().unwrap();
3236
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
3237
    assert_eq!(info.format("%A%D"), "-1");
3238
    let _ = origin;
3239
}
3240
3241
#[test]
3242
fn lazy_blobs_are_fetched_on_first_read() {
3243
    hermetic();
3244
    let dir = tempfile::tempdir().unwrap();
3245
    let root = dir.path();
3246
    let origin_dir = root.join("origin");
3247
    let origin = Repo::init(&origin_dir)
3248
        .unwrap()
3249
        .with_home(root.join("home"));
3250
    let url = origin_dir.to_string_lossy().to_string();
3251
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
3252
    write(&origin_dir, "big.bin", &big);
3253
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
3254
    write(&origin_dir, "t.txt", b"t\n");
3255
    let h = origin.commit("blobs", &[]).unwrap();
3256
    let big_ref = Repo::blob_ref(&big);
3257
3258
    // Fetch only (no checkout) with a filter: the big blob stays absent.
3259
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
3260
        .unwrap()
3261
        .with_home(root.join("home"));
3262
    let a = {
3263
        let mut a = a;
3264
        a.config.set("remote.origin.url", &url).unwrap();
3265
        a.config.set("filter.max-blob", "100K").unwrap();
3266
        a.save_config().unwrap();
3267
        a
3268
    };
3269
    assert_eq!(a.config.max_blob, Some(100 * 1024));
3270
    a.fetch("origin").unwrap();
3271
    assert!(a.store().has(&h));
3272
    assert!(!a.store().has(&big_ref), "withheld");
3273
    assert!(
3274
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
3275
        "small blob came along"
3276
    );
3277
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
3278
3279
    // status and commit do not need it: adopt the state, edit a text file, commit.
3280
    let (op_ref, op) = a.head_op().unwrap();
3281
    let mut view = op.view.clone();
3282
    view.bookmarks.insert(
3283
        "main".into(),
3284
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
3285
    );
3286
    a.record_op(&[op_ref], "adopt", view).unwrap();
3287
    // Checkout reads the blob lazily, which fetches it.
3288
    a.checkout(&[h], true, "checkout").unwrap();
3289
    assert!(a.store().has(&big_ref), "fetched on first read");
3290
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
3291
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
3292
    write(&root.join("a"), "t.txt", b"t2\n");
3293
    a.commit("text edit", &[]).unwrap();
3294
3295
    // clone --max-blob records the filter; the checkout fetches lazily.
3296
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
3297
    assert_eq!(b.config.max_blob, Some(1024));
3298
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
3299
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
3300
    assert!(parse_size("lots").is_err());
3301
}
3302
3303
#[test]
3304
fn sparse_checkout_materializes_only_chosen_paths() {
3305
    hermetic();
3306
    let dir = tempfile::tempdir().unwrap();
3307
    let root = dir.path();
3308
    let origin_dir = root.join("origin");
3309
    let origin = Repo::init(&origin_dir)
3310
        .unwrap()
3311
        .with_home(root.join("home"));
3312
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
3313
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
3314
    write(&origin_dir, "docs/guide.md", b"# guide\n");
3315
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
3316
    write(&origin_dir, "docs/logo.png", &logo);
3317
    write(&origin_dir, "README.md", b"# top\n");
3318
    let h1 = origin.commit("tree", &[]).unwrap();
3319
    let url = origin_dir.to_string_lossy().to_string();
3320
3321
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
3322
        .unwrap()
3323
        .with_home(root.join("home"));
3324
    assert_eq!(a.config.sparse_paths, vec!["src"]);
3325
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
3326
    assert!(root.join("a/src/main.rs").exists());
3327
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
3328
    assert!(
3329
        !a.store().has(&Repo::blob_ref(&logo)),
3330
        "out-of-scope blob never fetched"
3331
    );
3332
    assert!(
3333
        !a.snapshot("status").unwrap().changed,
3334
        "out-of-scope files are not removals"
3335
    );
3336
    assert!(!a.quick_status().unwrap().dirty);
3337
3338
    // Edits in scope commit normally and keep the rest of the tree intact.
3339
    write(
3340
        &root.join("a"),
3341
        "src/lib.rs",
3342
        b"pub fn a() {}\npub fn b() {}\n",
3343
    );
3344
    let h2 = a.commit("edit lib", &[]).unwrap();
3345
    let st = a.load_state(&[h2]).unwrap().materialize();
3346
    assert!(
3347
        st.files.contains_key("docs/guide.md"),
3348
        "the state still has everything"
3349
    );
3350
    assert!(a.push("origin", false).unwrap()[0].ok);
3351
    origin.refresh().unwrap();
3352
    // Files created outside the scope are ignored by status.
3353
    write(&root.join("a"), "docs/new.md", b"ignored\n");
3354
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
3355
3356
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
3357
    let mut a = a;
3358
    a.config.set("filter.paths", "src,docs").unwrap();
3359
    a.save_config().unwrap();
3360
    let r = a
3361
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
3362
        .unwrap();
3363
    assert!(r.written >= 2);
3364
    assert_eq!(
3365
        fs::read(root.join("a/docs/logo.png")).unwrap(),
3366
        logo,
3367
        "now fetched lazily"
3368
    );
3369
    assert!(!root.join("a/README.md").exists());
3370
    // Origin sees the change made under a sparse checkout with the full tree intact.
3371
    origin.pull("origin").err();
3372
    let full = origin
3373
        .load_state(&origin.bookmark_heads().unwrap())
3374
        .unwrap()
3375
        .materialize();
3376
    assert!(
3377
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
3378
    );
3379
    assert!(full.files.contains_key("README.md"));
3380
    let _ = h1;
3381
}
3382
3383
/// #137: a depth-0 clone takes no change, so the blobs of the state's
3384
/// binary files came with nothing and the checkout failed ("object … not
3385
/// found"); they are fetched with the checkpoint, or left lazy under
3386
/// `--max-blob`.
3387
#[test]
3388
fn a_depth_0_clone_brings_its_binary_files() {
3389
    hermetic();
3390
    let dir = tempfile::tempdir().unwrap();
3391
    let root = dir.path();
3392
    let origin_dir = root.join("origin");
3393
    let origin = Repo::init(&origin_dir)
3394
        .unwrap()
3395
        .with_home(root.join("home"));
3396
    let png: Vec<u8> = (0..4000u32)
3397
        .map(|i| (i * 7 % 251) as u8)
3398
        .chain([0, 0xff])
3399
        .collect();
3400
    // The logo comes with a.txt's first line, and the head edits that line,
3401
    // so the change that set the logo is below the head, not a head itself.
3402
    write(&origin_dir, "logo.png", &png);
3403
    write(&origin_dir, "a.txt", b"first\n");
3404
    origin.commit("logo", &[]).unwrap();
3405
    write(&origin_dir, "a.txt", b"later\n");
3406
    origin.commit("later", &[]).unwrap();
3407
    assert_eq!(origin.bookmark_heads().unwrap().len(), 1);
3408
    let url = origin_dir.to_string_lossy().to_string();
3409
    Repo::clone_shallow(&url, &root.join("a"), 0, None, &[]).unwrap();
3410
    assert_eq!(fs::read(root.join("a/logo.png")).unwrap(), png);
3411
    let lazy = Repo::clone_shallow(&url, &root.join("b"), 0, Some(0), &[]).unwrap();
3412
    assert_eq!(fs::read(root.join("b/a.txt")).unwrap(), b"later\n");
3413
    let blob = {
3414
        let heads = lazy.bookmark_heads().unwrap();
3415
        let st = lazy.load_state_history(&heads).unwrap();
3416
        st.opaque_nodes()
3417
            .iter()
3418
            .flat_map(|n| st.live_blobs(n))
3419
            .next()
3420
            .unwrap()
3421
    };
3422
    assert_eq!(lazy.read_blob(&blob).unwrap(), png, "fetched on read");
3423
    // Depth 0 takes no change: the head is the boundary; the log comes from
3424
    // the checkpoint; a change on top commits and pushes.
3425
    let mut a = Repo::open(&root.join("a"))
3426
        .unwrap()
3427
        .with_home(root.join("home"));
3428
    let head = origin.bookmark_heads().unwrap()[0];
3429
    assert!(!a.store().has(&head), "no change fetched");
3430
    assert!(a.boundary().contains(&head));
3431
    assert_eq!(
3432
        a.log()
3433
            .unwrap()
3434
            .iter()
3435
            .filter(|e| !e.is_working_copy)
3436
            .count(),
3437
        2,
3438
        "the log from the checkpoint"
3439
    );
3440
    write(&root.join("a"), "a.txt", b"later\nmine\n");
3441
    a.config.set("remote.origin.url", &url).unwrap();
3442
    a.save_config().unwrap();
3443
    let mine = a.commit("mine", &[]).unwrap();
3444
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3445
    origin.refresh().unwrap();
3446
    assert!(origin.store().has(&mine));
3447
    assert_eq!(origin.bookmark_heads().unwrap(), vec![mine]);
3448
    // And pulls what comes after.
3449
    origin
3450
        .checkout(&origin.bookmark_heads().unwrap(), false, "co")
3451
        .unwrap();
3452
    write(&origin_dir, "a.txt", b"later\nmine\ntheirs\n");
3453
    origin.snapshot("t").unwrap();
3454
    origin.commit("theirs", &[]).unwrap();
3455
    a.pull("origin").unwrap();
3456
    assert_eq!(
3457
        fs::read(root.join("a/a.txt")).unwrap(),
3458
        b"later\nmine\ntheirs\n"
3459
    );
3460
}
3461
3462
#[test]
3463
fn shallow_clone_and_deepen() {
3464
    hermetic();
3465
    let dir = tempfile::tempdir().unwrap();
3466
    let root = dir.path();
3467
    let origin_dir = root.join("origin");
3468
    let origin = Repo::init(&origin_dir)
3469
        .unwrap()
3470
        .with_home(root.join("home"));
3471
    let mut hashes = Vec::new();
3472
    for i in 0..8 {
3473
        write(
3474
            &origin_dir,
3475
            "a.txt",
3476
            format!(
3477
                "{}\n",
3478
                (0..=i)
3479
                    .map(|k| k.to_string())
3480
                    .collect::<Vec<_>>()
3481
                    .join("\n")
3482
            )
3483
            .as_bytes(),
3484
        );
3485
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
3486
    }
3487
    let url = origin_dir.to_string_lossy().to_string();
3488
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
3489
        .unwrap()
3490
        .with_home(root.join("home"));
3491
    assert!(a.is_shallow());
3492
    assert_eq!(
3493
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
3494
        "0\n1\n2\n3\n4\n5\n6\n7\n"
3495
    );
3496
    assert!(
3497
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
3498
        "three levels present"
3499
    );
3500
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
3501
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
3502
    assert_eq!(
3503
        a.log().unwrap().len(),
3504
        9,
3505
        "the log shows every change from the checkpoint's metadata"
3506
    );
3507
    assert!(!a.snapshot("status").unwrap().changed);
3508
    assert_eq!(a.quick_status().unwrap().heads, 1);
3509
3510
    // Work continues on top of the shallow history and pushes back.
3511
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
3512
    let h_new = a.commit("c8", &[]).unwrap();
3513
    assert!(a.push("origin", false).unwrap()[0].ok);
3514
    origin.refresh().unwrap();
3515
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
3516
    // Fetching new work from origin into the shallow clone works too.
3517
    write(&origin_dir, "b.txt", b"b\n");
3518
    origin.pull("origin").err();
3519
    let (_, wc) = origin.working_copy().unwrap();
3520
    let _ = wc;
3521
    origin
3522
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
3523
        .unwrap();
3524
    write(&origin_dir, "b.txt", b"b\n");
3525
    let h_b = origin.commit("b", &[]).unwrap();
3526
    let pr = a.pull("origin").unwrap();
3527
    assert!(pr.changed);
3528
    assert!(a.store().has(&h_b));
3529
    assert!(root.join("a/b.txt").exists());
3530
3531
    // Deepening fetches older history until the boundary is gone.
3532
    // Every commit also depends on the change that created the file, so two
3533
    // levels below the boundary hold h4, h3, and the root.
3534
    assert!(a.deepen("origin", 2).unwrap() >= 2);
3535
    assert!(a.store().has(&hashes[3]));
3536
    assert!(a.is_shallow());
3537
    a.deepen("origin", 100).unwrap();
3538
    assert!(!a.is_shallow(), "boundary reached the root");
3539
    assert!(a.store().has(&hashes[0]));
3540
    assert_eq!(
3541
        a.load_state_full(&a.bookmark_heads().unwrap())
3542
            .unwrap()
3543
            .len(),
3544
        10
3545
    );
3546
}
3547
3548
#[test]
3549
fn tags_are_immutable_named_states_and_travel() {
3550
    hermetic();
3551
    let dir = tempfile::tempdir().unwrap();
3552
    let root = dir.path();
3553
    let origin = Repo::init(&root.join("origin")).unwrap();
3554
    let url = root.join("origin").to_string_lossy().to_string();
3555
    let mut a = Repo::clone(&url, &root.join("a"))
3556
        .unwrap()
3557
        .with_home(root.join("home-a"));
3558
    let (key_a, _) = a
3559
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3560
        .unwrap();
3561
    write(&root.join("a"), "f.txt", b"1\n");
3562
    let h1 = a.commit("one", &[]).unwrap();
3563
    write(&root.join("a"), "f.txt", b"1\n2\n");
3564
    let h2 = a.commit("two", &[]).unwrap();
3565
3566
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
3567
    assert_eq!(
3568
        (t.heads.clone(), t.signer.as_deref()),
3569
        (vec![h1], Some("Ada"))
3570
    );
3571
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
3572
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
3573
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
3574
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
3575
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
3576
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
3577
    assert_eq!(sa.sigs[0].key, key_a);
3578
    // Without a policy every client is sent every tag, whatever features
3579
    // it declares (oxygen#131).
3580
    let mut refs = a.remote_refs().unwrap();
3581
    a.refs_for_client(&mut refs, None);
3582
    assert_eq!(refs.tags.len(), 1);
3583
    // Checkout by tag.
3584
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
3585
        .unwrap();
3586
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
3587
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
3588
        .unwrap();
3589
3590
    // Push carries the tag; a second attestation for the name is refused.
3591
    let r = a.push("origin", false).unwrap();
3592
    origin.refresh().unwrap();
3593
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
3594
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3595
    let mut forged = a
3596
        .tag_refs()
3597
        .unwrap()
3598
        .into_iter()
3599
        .find(|t| t.name == "v1")
3600
        .unwrap();
3601
    forged.state = origin
3602
        .store()
3603
        .put_state(&StateObject::new(vec![h2]))
3604
        .unwrap();
3605
    forged.heads = vec![h2];
3606
    forged.attestation = None;
3607
    let r = origin
3608
        .receive_push(Bundle::default(), vec![], None, vec![forged])
3609
        .unwrap();
3610
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
3611
3612
    // A clone gets the tag; a later tag arrives on fetch.
3613
    let b = Repo::clone(&url, &root.join("b"))
3614
        .unwrap()
3615
        .with_home(root.join("home-b"));
3616
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3617
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
3618
    a.tag_create("v2", &[h2], "second").unwrap();
3619
    a.push("origin", false).unwrap();
3620
    origin.refresh().unwrap();
3621
    let rep = b.fetch("origin").unwrap();
3622
    assert_eq!(rep.new_tags, 1);
3623
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
3624
3625
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
3626
    a.policy_init().unwrap();
3627
    a.push("origin", false).unwrap();
3628
    origin.refresh().unwrap();
3629
    let unattested = crate::protocol::TagRef::new(
3630
        "v3".into(),
3631
        origin
3632
            .store()
3633
            .put_state(&StateObject::new(vec![h2]))
3634
            .unwrap(),
3635
        vec![h2],
3636
        None,
3637
    );
3638
    let r = origin
3639
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
3640
        .unwrap();
3641
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
3642
    a.tag_create("v3", &[h2], "").unwrap();
3643
    let r = a.push("origin", false).unwrap();
3644
    origin.refresh().unwrap();
3645
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
3646
    assert!(a.gc(true).is_ok());
3647
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
3648
3649
    // After a rotation the policy names only the new key, yet a fresh clone
3650
    // still takes the tags the old key made before it; the old key makes
3651
    // nothing new.
3652
    let rot = a.rotate_identity().unwrap();
3653
    let r = a.push("origin", false).unwrap();
3654
    origin.refresh().unwrap();
3655
    assert!(r.iter().all(|x| x.ok), "{r:?}");
3656
    let c = Repo::clone(&url, &root.join("c"))
3657
        .unwrap()
3658
        .with_home(root.join("home-c"));
3659
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
3660
    let (_, sp) = c.current_policy().unwrap().unwrap();
3661
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
3662
    let made = c.identity(&rot.new).unwrap().created;
3663
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
3664
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
3665
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
3666
}
3667
3668
#[test]
3669
fn multiple_workspaces_share_a_repository() {
3670
    hermetic();
3671
    let dir = tempfile::tempdir().unwrap();
3672
    let root = dir.path();
3673
    let main_dir = root.join("main");
3674
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
3675
    write(&main_dir, "a.txt", b"a\n");
3676
    let h1 = repo.commit("a", &[]).unwrap();
3677
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3678
3679
    // A second workspace elsewhere, checked out on the bookmark.
3680
    let ws_dir = root.join("ws2");
3681
    let ops = repo.op_log().unwrap().len();
3682
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
3683
    assert_eq!(
3684
        ws.op_log().unwrap().len(),
3685
        ops + 2,
3686
        "the add and its checkout, and no snapshot finding the tree deleted (oxygen#137)"
3687
    );
3688
    assert!(ws_dir.join(".oxy").is_file());
3689
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
3690
    assert_ne!(ws.workspace(), repo.workspace());
3691
    let list = repo.workspaces().unwrap();
3692
    assert_eq!(list.len(), 2);
3693
    assert!(list
3694
        .iter()
3695
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
3696
    assert!(!ws.snapshot("status").unwrap().changed);
3697
3698
    // Work in the second workspace: its own working copy, shared bookmark.
3699
    write(&ws_dir, "b.txt", b"b\n");
3700
    let s = ws.snapshot("status").unwrap();
3701
    assert_eq!(s.statuses.len(), 1);
3702
    assert!(
3703
        !repo.snapshot("status").unwrap().changed,
3704
        "the first workspace is untouched"
3705
    );
3706
    let h2 = ws.commit("b from ws2", &[]).unwrap();
3707
    repo.refresh().unwrap();
3708
    let mut heads = repo.bookmark_heads().unwrap();
3709
    heads.sort();
3710
    let mut want = vec![h1, h2];
3711
    want.sort();
3712
    assert_eq!(heads, want, "both workspaces see the bookmark move");
3713
    assert!(!main_dir.join("b.txt").exists());
3714
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
3715
        .unwrap();
3716
    assert!(main_dir.join("b.txt").exists());
3717
3718
    // Reopening from inside the second workspace finds the shared repository.
3719
    let reopened = Repo::open(&ws_dir).unwrap();
3720
    assert_eq!(reopened.workspace(), ws.workspace());
3721
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
3722
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
3723
3724
    // Workspaces cannot nest; forget drops one from the view but keeps files.
3725
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
3726
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
3727
    repo.workspace_forget(&ws.workspace()).unwrap();
3728
    assert_eq!(repo.workspaces().unwrap().len(), 1);
3729
    assert!(ws_dir.join("b.txt").exists());
3730
    assert!(
3731
        ws.snapshot("status").is_err(),
3732
        "a forgotten workspace is no longer in the view"
3733
    );
3734
3735
    // The working-copy lock: re-entrant in a thread; a lock whose process
3736
    // is gone is taken over, and a live process's is not, however old.
3737
    let lock = repo.lock_snapshot().unwrap();
3738
    let again = repo.lock_working_copy().unwrap();
3739
    drop(again);
3740
    drop(lock);
3741
    let lock_path = main_dir
3742
        .join(".oxy/workspaces")
3743
        .join(repo.workspace().to_hex())
3744
        .join("lock");
3745
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
3746
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
3747
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
3748
    age(&lock_path);
3749
    assert!(
3750
        !super::workspace::lock_is_stale(&lock_path),
3751
        "a live process keeps its lock"
3752
    );
3753
    fs::write(&lock_path, "4294967295").unwrap();
3754
    age(&lock_path);
3755
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
3756
}
3757
3758
#[test]
3759
fn attributes_binary_eol_nocompress_lockable() {
3760
    hermetic();
3761
    let dir = tempfile::tempdir().unwrap();
3762
    let root = dir.path();
3763
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
3764
    write(
3765
        root,
3766
        ".oxyattributes",
3767
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
3768
    );
3769
    write(root, "plain.dat", b"no nul bytes here\n");
3770
    write(root, "notes.txt", b"one\r\ntwo\r\n");
3771
    write(root, "assets/model.bin", b"\0model");
3772
    let h = repo.commit("attrs", &[]).unwrap();
3773
    let snap = repo.load_state(&[h]).unwrap().materialize();
3774
    assert!(
3775
        snap.files["plain.dat"].mode.opaque,
3776
        "binary attribute forces opaque without NUL bytes"
3777
    );
3778
    assert!(
3779
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
3780
        "stored with LF"
3781
    );
3782
    assert!(
3783
        !repo.snapshot("status").unwrap().changed,
3784
        "CRLF on disk equals LF in the state"
3785
    );
3786
    // nocompress chunks pack raw.
3787
    let r = repo.gc(true).unwrap();
3788
    assert!(r.packed.objects > 0);
3789
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
3790
    fs::remove_file(root.join("notes.txt")).unwrap();
3791
    repo.checkout(&[h], true, "co").unwrap();
3792
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
3793
    assert!(fs::metadata(root.join("assets/model.bin"))
3794
        .unwrap()
3795
        .permissions()
3796
        .readonly());
3797
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
3798
    repo.lock_path("assets/model.bin").unwrap();
3799
    assert!(!fs::metadata(root.join("assets/model.bin"))
3800
        .unwrap()
3801
        .permissions()
3802
        .readonly());
3803
    assert!(repo.is_locked("assets/model.bin"));
3804
    write(root, "assets/model.bin", b"\0model2");
3805
    repo.commit("edit model", &[]).unwrap();
3806
    repo.unlock_path("assets/model.bin").unwrap();
3807
    assert!(fs::metadata(root.join("assets/model.bin"))
3808
        .unwrap()
3809
        .permissions()
3810
        .readonly());
3811
    // A later checkout can still overwrite a read-only lockable file.
3812
    repo.checkout(&[h], true, "co").unwrap();
3813
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
3814
}
3815
3816
#[cfg(unix)]
3817
#[test]
3818
fn hooks_can_veto_observe_and_add_dependencies() {
3819
    use std::os::unix::fs::PermissionsExt;
3820
    hermetic();
3821
    let dir = tempfile::tempdir().unwrap();
3822
    let root = dir.path();
3823
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3824
    let hooks = root.join(".oxy/hooks");
3825
    fs::create_dir_all(&hooks).unwrap();
3826
    let hook = |name: &str, body: &str| {
3827
        let p = hooks.join(name);
3828
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
3829
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
3830
    };
3831
    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");
3832
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
3833
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
3834
    hook("pre-push", "echo pushing blocked >&2; exit 3");
3835
    write(root, ".oxyignore", b".last-*\n");
3836
    write(root, "a.txt", b"a\n");
3837
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
3838
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
3839
    let h1 = repo.commit("first", &[]).unwrap();
3840
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
3841
    assert!(
3842
        pre.contains("\"event\":\"pre-commit\"")
3843
            && pre.contains("\"path\":\"a.txt\"")
3844
            && pre.contains("\"message\":\"first\""),
3845
        "{pre}"
3846
    );
3847
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
3848
    assert!(post.contains(&h1.to_hex()), "{post}");
3849
    repo.checkout(&[h1], false, "co").unwrap();
3850
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
3851
        .unwrap()
3852
        .contains("post-checkout"));
3853
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
3854
    repo.save_config().unwrap();
3855
    let err = repo.push("origin", false).unwrap_err().to_string();
3856
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
3857
3858
    // semantic-deps: only when enabled; adds an explicit dependency.
3859
    write(root, "b.txt", b"b\n");
3860
    hook(
3861
        "semantic-deps",
3862
        &format!(
3863
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
3864
            h1.to_hex()
3865
        ),
3866
    );
3867
    let h2 = repo.commit("b without hook", &[]).unwrap();
3868
    assert!(
3869
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
3870
        "hook disabled by default"
3871
    );
3872
    repo.config.set("hooks.semantic-deps", "true").unwrap();
3873
    repo.save_config().unwrap();
3874
    write(root, "c.txt", b"c\n");
3875
    let h3 = repo.commit("c with hook", &[]).unwrap();
3876
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
3877
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
3878
    assert!(
3879
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
3880
        "{sem}"
3881
    );
3882
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
3883
}
3884
3885
#[test]
3886
fn amend_into_older_change_and_split() {
3887
    hermetic();
3888
    let dir = tempfile::tempdir().unwrap();
3889
    let root = dir.path();
3890
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3891
    repo.create_identity("Ada", "a@b", IdentityScope::User)
3892
        .unwrap();
3893
    repo.set_user_config("core.sign", "change").unwrap();
3894
    write(root, "a.txt", b"one\ntwo\n");
3895
    let h0 = repo.commit("base", &[]).unwrap();
3896
    write(root, "a.txt", b"one\nTWO\n");
3897
    let h1 = repo.commit("edit two", &[]).unwrap();
3898
    write(root, "a.txt", b"one\nTWO\nthree\n");
3899
    let h2 = repo.commit("add three", &[]).unwrap();
3900
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
3901
3902
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
3903
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3904
    let h1b = repo.amend_into(&h1, None).unwrap();
3905
    assert_ne!(h1b, h1);
3906
    let c1b = repo.store().get_change(&h1b).unwrap();
3907
    assert_eq!(c1b.change_id, id1);
3908
    assert_eq!(c1b.deps, vec![h0]);
3909
    assert!(matches!(
3910
        repo.verify_change(&h1b).unwrap(),
3911
        SignatureStatus::Valid { .. }
3912
    ));
3913
    let heads = repo.bookmark_heads().unwrap();
3914
    assert_eq!(heads.len(), 1);
3915
    let top = repo.store().get_change(&heads[0]).unwrap();
3916
    assert_eq!(top.message, "add three");
3917
    assert_eq!(
3918
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
3919
        [h0, h1b].into_iter().collect(),
3920
        "depends on the file's creator and the rewritten line"
3921
    );
3922
    let snap = repo.load_state(&heads).unwrap().materialize();
3923
    assert!(
3924
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
3925
    );
3926
    assert!(
3927
        !repo.snapshot("status").unwrap().changed,
3928
        "the working copy is clean after folding"
3929
    );
3930
    // Only h1b's own state shows the fix without "three".
3931
    let only = repo.load_state(&[h1b]).unwrap().materialize();
3932
    assert!(
3933
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
3934
    );
3935
    assert_eq!(repo.log().unwrap().len(), 4);
3936
3937
    // An edit to a line introduced by h2 cannot fold into h1.
3938
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
3939
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
3940
    assert!(err.contains("introduced after"), "{err}");
3941
    assert!(
3942
        repo.snapshot("status").unwrap().statuses.len() == 1,
3943
        "nothing was changed by the refusal"
3944
    );
3945
    write(root, "a.txt", b"one\nTWO!\nthree\n");
3946
3947
    // Split the head that touches two files.
3948
    write(root, "b.txt", b"b\n");
3949
    write(root, "c.txt", b"c\n");
3950
    let h3 = repo.commit("b and c", &[]).unwrap();
3951
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
3952
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
3953
    let c_1 = repo.store().get_change(&p1).unwrap();
3954
    let c_2 = repo.store().get_change(&p2).unwrap();
3955
    assert!(c_1.message.contains("part 1: b.txt"));
3956
    assert_eq!(c_2.change_id, id3);
3957
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
3958
    assert!(
3959
        heads.contains(&p1) && heads.contains(&p2),
3960
        "independent parts are both heads"
3961
    );
3962
    let snap = repo
3963
        .load_state(&repo.bookmark_heads().unwrap())
3964
        .unwrap()
3965
        .materialize();
3966
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
3967
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
3968
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
3969
    assert!(!repo.snapshot("status").unwrap().changed);
3970
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
3971
    let _ = h2;
3972
}
3973
3974
#[test]
3975
fn identity_lifecycle() {
3976
    hermetic();
3977
    let dir = tempfile::tempdir().unwrap();
3978
    let root = dir.path();
3979
    let origin = Repo::init(&root.join("origin")).unwrap();
3980
    let url = root.join("origin").to_string_lossy().to_string();
3981
    let mut a = Repo::clone(&url, &root.join("a"))
3982
        .unwrap()
3983
        .with_home(root.join("home-a"));
3984
    a.set_user_config("core.sign", "change").unwrap();
3985
    let (key_a, _) = a
3986
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3987
        .unwrap();
3988
    write(&root.join("a"), "a.txt", b"a\n");
3989
    let h1 = a.commit("one", &[]).unwrap();
3990
    assert!(a.policy_init().unwrap().applied);
3991
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3992
    origin.refresh().unwrap();
3993
3994
    // Expiry: an identity that had expired when the change was made does not authenticate it.
3995
    let mut e = Repo::init(&root.join("e"))
3996
        .unwrap()
3997
        .with_home(root.join("home-e"));
3998
    e.set_user_config("core.sign", "change").unwrap();
3999
    e.create_identity_with(
4000
        "Eve",
4001
        "[email protected]",
4002
        IdentityScope::User,
4003
        Some(Hlc::now().wall_ms - 1),
4004
    )
4005
    .unwrap();
4006
    write(&root.join("e"), "e.txt", b"e\n");
4007
    let he = e.commit("late", &[]).unwrap();
4008
    assert!(
4009
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
4010
    );
4011
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
4012
    let r = e
4013
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
4014
        .unwrap();
4015
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
4016
    write(&root.join("e"), "e.txt", b"e2\n");
4017
    let he2 = e.commit("in time", &[]).unwrap();
4018
    assert!(
4019
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
4020
    );
4021
4022
    // Rotation: a fresh key; the old change still verifies; the policy follows.
4023
    let r = a.rotate_identity().unwrap();
4024
    assert_eq!(r.old, key_a);
4025
    assert_eq!(a.config.author_key, Some(r.new));
4026
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
4027
    assert!(r.policy.as_ref().unwrap().applied);
4028
    let (_, sp) = a.current_policy().unwrap().unwrap();
4029
    assert_eq!(
4030
        (sp.policy.serial, sp.policy.roots.clone()),
4031
        (2, vec![r.new])
4032
    );
4033
    assert!(
4034
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
4035
        "superseded, not revoked"
4036
    );
4037
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
4038
    assert!(
4039
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
4040
    );
4041
    write(&root.join("a"), "a.txt", b"a2\n");
4042
    let h2 = a.commit("two", &[]).unwrap();
4043
    assert!(
4044
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
4045
    );
4046
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
4047
    let res = a.push("origin", false).unwrap();
4048
    origin.refresh().unwrap();
4049
    assert!(res.iter().all(|x| x.ok), "{res:?}");
4050
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
4051
    let key_a = r.new;
4052
4053
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
4054
    // identity object, so Ada's KeyId changes while her keys stay the same.
4055
    let mut b = Repo::clone(&url, &root.join("b"))
4056
        .unwrap()
4057
        .with_home(root.join("home-b"));
4058
    let (key_b, id_b) = b
4059
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4060
        .unwrap();
4061
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
4062
    assert_eq!(r.old, key_a);
4063
    let key_a2 = r.new;
4064
    assert_eq!(
4065
        a.identity(&key_a2).unwrap().delegates,
4066
        vec![Delegate::full(key_b)]
4067
    );
4068
    assert_eq!(
4069
        a.identity(&key_a2).unwrap().ed25519_pk,
4070
        a.identity(&key_a).unwrap().ed25519_pk
4071
    );
4072
    assert!(
4073
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
4074
        "already a delegate"
4075
    );
4076
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
4077
    origin.refresh().unwrap();
4078
    write(&root.join("a"), "a.txt", b"a3\n");
4079
    let h3 = a.commit("three", &[]).unwrap();
4080
    assert!(
4081
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
4082
        "the same secret signs under the new KeyId"
4083
    );
4084
    // A change authored by Ada but signed only by Bob verifies through the delegation.
4085
    a.set_user_config("core.sign", "seal").unwrap();
4086
    write(&root.join("a"), "a.txt", b"a4\n");
4087
    let h4 = a.commit("four", &[]).unwrap();
4088
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
4089
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
4090
    a.store()
4091
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
4092
        .unwrap();
4093
    assert!(
4094
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
4095
    );
4096
    a.set_user_config("core.sign", "change").unwrap();
4097
    // Withdrawing the delegation re-issues the identity again.
4098
    let r = a.delegate_remove(&key_b).unwrap();
4099
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
4100
    assert!(a.delegate_remove(&key_b).is_err());
4101
    let key_a3 = r.new;
4102
    let res = a.push("origin", false).unwrap();
4103
    origin.refresh().unwrap();
4104
    assert!(res.iter().all(|x| x.ok), "{res:?}");
4105
4106
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
4107
    // both applied under the old threshold of 1. A grant then needs Bob too.
4108
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
4109
    assert!(a.policy_root_add(id_b.clone()).is_err());
4110
    assert!(a.policy_set_threshold(3).is_err());
4111
    assert!(a.policy_set_threshold(2).unwrap().applied);
4112
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
4113
    origin.refresh().unwrap();
4114
    b.pull("origin").unwrap();
4115
    assert_eq!(
4116
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
4117
        2
4118
    );
4119
    let mut c = Repo::init(&root.join("c"))
4120
        .unwrap()
4121
        .with_home(root.join("home-c"));
4122
    let (key_c, id_c) = c
4123
        .create_identity("Cy", "[email protected]", IdentityScope::User)
4124
        .unwrap();
4125
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
4126
    let proposal = a.policy_grant(id_c, None).unwrap();
4127
    assert!(!proposal.applied && proposal.sigs.len() == 1);
4128
    assert_eq!(proposal.policy.serial, serial_before + 1);
4129
    assert_eq!(
4130
        a.current_policy().unwrap().unwrap().1.policy.serial,
4131
        serial_before,
4132
        "a proposal changes nothing yet"
4133
    );
4134
    // Bob signs the proposal, handed over as a file, and it applies for him.
4135
    let bytes = proposal.signed().encode();
4136
    let signed = b
4137
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
4138
        .unwrap();
4139
    assert!(signed.applied && signed.sigs.len() == 2);
4140
    assert!(b
4141
        .current_policy()
4142
        .unwrap()
4143
        .unwrap()
4144
        .1
4145
        .policy
4146
        .authorizes(&key_c, "main"));
4147
    assert!(
4148
        b.policy_sign(signed.signed()).is_err(),
4149
        "a stale proposal is refused"
4150
    );
4151
    // Bob publishes it and Ada picks it up.
4152
    assert!(b
4153
        .push("origin", false)
4154
        .unwrap()
4155
        .iter()
4156
        .any(|x| x.name == "policy" && x.ok));
4157
    origin.refresh().unwrap();
4158
    a.pull("origin").unwrap();
4159
    assert_eq!(
4160
        a.current_policy().unwrap().unwrap().1.policy.serial,
4161
        serial_before + 1
4162
    );
4163
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
4164
    assert!(a.policy_revoke(&key_a3).is_err());
4165
    let u = a
4166
        .revoke_identity(&key_c, "left the project")
4167
        .unwrap()
4168
        .unwrap();
4169
    assert!(!u.applied);
4170
    assert!(a.is_revoked(&key_c).unwrap());
4171
    assert!(!b.is_revoked(&key_c).unwrap());
4172
    let u = b.policy_sign(u.signed()).unwrap();
4173
    assert!(u.applied && u.policy.is_revoked(&key_c));
4174
    assert!(b.is_revoked(&key_c).unwrap());
4175
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
4176
    assert!(
4177
        b.policy_revoke(&key_a3).is_err(),
4178
        "would leave one root for a threshold of 2"
4179
    );
4180
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
4181
    let key_c_own = c.config.author_key.unwrap();
4182
    assert!(c
4183
        .revoke_identity(&key_c_own, "lost laptop")
4184
        .unwrap()
4185
        .is_none());
4186
    assert!(c.is_revoked(&key_c_own).unwrap());
4187
    assert_eq!(key_c_own, key_c);
4188
}
4189
4190
#[test]
4191
fn renames_are_detected_and_tracked_as_moves() {
4192
    hermetic();
4193
    let dir = tempfile::tempdir().unwrap();
4194
    let root = dir.path();
4195
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4196
    write(
4197
        root,
4198
        "src/old.rs",
4199
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
4200
    );
4201
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
4202
    write(root, "tiny.txt", b"x\n");
4203
    let h1 = repo.commit("base", &[]).unwrap();
4204
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
4205
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
4206
4207
    // Rename with a small edit, a binary moved unchanged, and a rewrite
4208
    // that shares nothing with the removed file.
4209
    fs::remove_file(root.join("src/old.rs")).unwrap();
4210
    write(
4211
        root,
4212
        "lib/new.rs",
4213
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
4214
    );
4215
    fs::remove_file(root.join("img.bin")).unwrap();
4216
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
4217
    fs::remove_file(root.join("tiny.txt")).unwrap();
4218
    write(root, "other.txt", b"completely different\n");
4219
    let snap = repo.snapshot("status").unwrap();
4220
    let statuses: Vec<(&str, ChangeStatus)> = snap
4221
        .statuses
4222
        .iter()
4223
        .map(|s| (s.path.as_str(), s.status))
4224
        .collect();
4225
    assert_eq!(
4226
        statuses,
4227
        vec![
4228
            ("assets/img.bin", ChangeStatus::Renamed),
4229
            ("lib/new.rs", ChangeStatus::Renamed),
4230
            ("other.txt", ChangeStatus::Added),
4231
            ("src", ChangeStatus::Removed),
4232
            ("tiny.txt", ChangeStatus::Removed)
4233
        ]
4234
    );
4235
    let h2 = repo.commit("move things", &[]).unwrap();
4236
    let c = repo.store().get_change(&h2).unwrap();
4237
    let moves: Vec<_> = c
4238
        .tree_ops
4239
        .iter()
4240
        .filter(|op| matches!(op, TreeOp::Move { .. }))
4241
        .collect();
4242
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
4243
    assert!(c.tree_ops.iter().any(
4244
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
4245
    ));
4246
    assert!(c.tree_ops.iter().any(
4247
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
4248
    ));
4249
    let snap = repo.load_state(&[h2]).unwrap().materialize();
4250
    assert_eq!(
4251
        snap.files["lib/new.rs"].node, node_old,
4252
        "the node survives the rename"
4253
    );
4254
    assert!(
4255
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
4256
    );
4257
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
4258
    assert!(render_change(
4259
        &c,
4260
        &repo.load_state(&[h1]).unwrap(),
4261
        &repo.load_state(&[h1]).unwrap().materialize()
4262
    )
4263
    .contains("R "));
4264
    // A fresh checkout reproduces the tree.
4265
    let other = tempfile::tempdir().unwrap();
4266
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
4267
    assert_eq!(
4268
        fs::read(other.path().join("lib/new.rs")).unwrap(),
4269
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
4270
    );
4271
    assert!(!other.path().join("src").exists());
4272
    assert!(!clone.snapshot("status").unwrap().changed);
4273
    // Similarity is line based, byte weighted.
4274
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
4275
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
4276
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
4277
    assert_eq!(similarity(b"", b"x\n"), 0);
4278
}
4279
4280
#[test]
4281
fn git_fetch_and_push_round_trip() {
4282
    hermetic();
4283
    if std::process::Command::new("git")
4284
        .arg("--version")
4285
        .output()
4286
        .is_err()
4287
    {
4288
        eprintln!("git not installed; skipping");
4289
        return;
4290
    }
4291
    let dir = tempfile::tempdir().unwrap();
4292
    let root = dir.path();
4293
    let git_in = |d: &Path, args: &[&str]| -> String {
4294
        let out = std::process::Command::new("git")
4295
            .arg("-C")
4296
            .arg(d)
4297
            .args([
4298
                "-c",
4299
                "user.name=Grace",
4300
                "-c",
4301
                "[email protected]",
4302
                "-c",
4303
                "commit.gpgsign=false",
4304
            ])
4305
            .args(args)
4306
            .output()
4307
            .unwrap();
4308
        assert!(
4309
            out.status.success(),
4310
            "git {args:?}: {}",
4311
            String::from_utf8_lossy(&out.stderr)
4312
        );
4313
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4314
    };
4315
    // A bare "remote" and a work tree that pushes to it.
4316
    let remote = root.join("remote.git");
4317
    fs::create_dir_all(&remote).unwrap();
4318
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
4319
    let work = root.join("work");
4320
    git_in(
4321
        root,
4322
        &[
4323
            "clone",
4324
            "-q",
4325
            remote.to_str().unwrap(),
4326
            work.to_str().unwrap(),
4327
        ],
4328
    );
4329
    git_in(&work, &["checkout", "-q", "-b", "main"]);
4330
    write(&work, "README.md", b"# Project\n");
4331
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
4332
    git_in(&work, &["add", "."]);
4333
    git_in(&work, &["commit", "-q", "-m", "initial"]);
4334
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
4335
    git_in(&work, &["commit", "-q", "-am", "second"]);
4336
    git_in(&work, &["push", "-q", "origin", "main"]);
4337
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
4338
4339
    // Fetch into a fresh oxy repository.
4340
    let o = root.join("oxy");
4341
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
4342
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4343
        .unwrap();
4344
    let url = remote.to_string_lossy().to_string();
4345
    let r = repo.git_fetch(&url, "main").unwrap();
4346
    assert_eq!((r.commits, r.heads), (2, 1));
4347
    assert_eq!(
4348
        fs::read(o.join("src/lib.rs")).unwrap(),
4349
        b"pub fn a() {}\npub fn b() {}\n"
4350
    );
4351
    assert!(!repo.snapshot("status").unwrap().changed);
4352
    assert_eq!(
4353
        repo.git_fetch(&url, "main").unwrap().commits,
4354
        0,
4355
        "nothing new"
4356
    );
4357
4358
    // An oxy change, pushed back: one commit on top of the Git tip.
4359
    write(
4360
        &o,
4361
        "src/lib.rs",
4362
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
4363
    );
4364
    write(&o, "NOTES.md", b"from oxy\n");
4365
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
4366
    let r = repo.git_push(&url, "main").unwrap();
4367
    assert_eq!(r.exported, 1, "{r:?}");
4368
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
4369
    assert_eq!(
4370
        git_in(&work, &["log", "--format=%s", "main"]),
4371
        "add c and notes\nsecond\ninitial"
4372
    );
4373
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
4374
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
4375
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
4376
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
4377
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
4378
    assert_eq!(
4379
        repo.git_push(&url, "main").unwrap().exported,
4380
        0,
4381
        "already pushed"
4382
    );
4383
4384
    // Git moves on; pushing without fetching is refused, fetching brings
4385
    // the commit in and the working copy follows.
4386
    write(&work, "README.md", b"# Project\n\nMore.\n");
4387
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
4388
    git_in(&work, &["push", "-q", "origin", "main"]);
4389
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
4390
    assert!(repo
4391
        .git_push(&url, "main")
4392
        .unwrap_err()
4393
        .to_string()
4394
        .contains("fetch"));
4395
    let r = repo.git_fetch(&url, "main").unwrap();
4396
    assert_eq!(
4397
        (r.commits, r.heads),
4398
        (1, 2),
4399
        "the Git change and the oxy change commute"
4400
    );
4401
    assert_eq!(
4402
        fs::read(o.join("README.md")).unwrap(),
4403
        b"# Project\n\nMore.\n"
4404
    );
4405
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
4406
    assert!(!repo.snapshot("status").unwrap().changed);
4407
    // Another oxy change pushes on top of Git's newest commit.
4408
    write(&o, "NOTES.md", b"from oxy\nagain\n");
4409
    repo.commit("notes again", &[]).unwrap();
4410
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
4411
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
4412
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
4413
    assert_eq!(
4414
        fs::read(work.join("NOTES.md")).unwrap(),
4415
        b"from oxy\nagain\n"
4416
    );
4417
    assert_eq!(
4418
        git_in(&work, &["log", "--format=%s", "main"])
4419
            .lines()
4420
            .count(),
4421
        5
4422
    );
4423
}
4424
4425
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
4426
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
4427
#[test]
4428
#[ignore]
4429
fn bench_one_gibibyte_file() {
4430
    hermetic();
4431
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
4432
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
4433
        Some(d) => tempfile::tempdir_in(d).unwrap(),
4434
        None => tempfile::tempdir().unwrap(),
4435
    };
4436
    let root = dir.path();
4437
    let repo = Repo::init(&root.join("r"))
4438
        .unwrap()
4439
        .with_home(root.join("home"));
4440
    let size = 1usize << 30;
4441
    let mut data = vec![0u8; size];
4442
    let mut x = 0x9e3779b97f4a7c15u64;
4443
    for chunk in data.chunks_mut(8) {
4444
        x ^= x << 13;
4445
        x ^= x >> 7;
4446
        x ^= x << 17;
4447
        let b = x.to_le_bytes();
4448
        chunk.copy_from_slice(&b[..chunk.len()]);
4449
    }
4450
    let t = std::time::Instant::now();
4451
    write(&root.join("r"), "big.bin", &data);
4452
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
4453
    let t = std::time::Instant::now();
4454
    let h = repo.commit("big", &[]).unwrap();
4455
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
4456
    let t = std::time::Instant::now();
4457
    assert!(!repo.snapshot("status").unwrap().changed);
4458
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
4459
    let t = std::time::Instant::now();
4460
    let objects = repo.store().list().unwrap().len();
4461
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
4462
    let t = std::time::Instant::now();
4463
    let g = repo.gc(true).unwrap();
4464
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
4465
    let t = std::time::Instant::now();
4466
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
4467
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
4468
    let t = std::time::Instant::now();
4469
    let back = fs::read(root.join("c/big.bin")).unwrap();
4470
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
4471
    eprintln!("read back and verify: {:.2?}", t.elapsed());
4472
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
4473
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
4474
    eprintln!(
4475
        "store size: {:.1} MiB for 1 GiB of data",
4476
        store_bytes as f64 / (1024.0 * 1024.0)
4477
    );
4478
}
4479
4480
fn walkdir_size(p: &Path) -> u64 {
4481
    let mut total = 0;
4482
    if let Ok(rd) = fs::read_dir(p) {
4483
        for e in rd.flatten() {
4484
            let path = e.path();
4485
            if path.is_dir() {
4486
                total += walkdir_size(&path);
4487
            } else if let Ok(m) = fs::metadata(&path) {
4488
                total += m.len();
4489
            }
4490
        }
4491
    }
4492
    total
4493
}
4494
4495
/// An opaque file whose size and mtime match the manifest is not read on
4496
/// the next snapshot: its blob comes from the manifest's stat cache.
4497
#[cfg(unix)]
4498
#[test]
4499
fn stat_cache_skips_reading_unchanged_opaque_files() {
4500
    use std::os::unix::fs::PermissionsExt;
4501
    hermetic();
4502
    let dir = tempfile::tempdir().unwrap();
4503
    let root = dir.path();
4504
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4505
    let mut big = vec![0u8; 300 * 1024];
4506
    for (i, b) in big.iter_mut().enumerate() {
4507
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
4508
    }
4509
    big[0] = 0;
4510
    write(root, "big.bin", &big);
4511
    write(root, "a.txt", b"text\n");
4512
    let h1 = repo.commit("base", &[]).unwrap();
4513
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4514
    assert!(
4515
        m.entries["big.bin"].blob.is_some(),
4516
        "opaque files record their blob"
4517
    );
4518
    assert!(m.entries["a.txt"].blob.is_none());
4519
    let blob = m.entries["big.bin"].blob.unwrap();
4520
    assert!(repo.store().has(&blob));
4521
4522
    // Files modified within two seconds of the manifest are racy and still
4523
    // read; age the file so the cache applies, then snapshot to record it.
4524
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4525
    fs::File::options()
4526
        .write(true)
4527
        .open(root.join("big.bin"))
4528
        .unwrap()
4529
        .set_modified(old)
4530
        .unwrap();
4531
    assert!(!repo.snapshot("status").unwrap().changed);
4532
    // Now the file cannot be read at all; the snapshot succeeds without it.
4533
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
4534
    let snap = repo.snapshot("status").unwrap();
4535
    assert!(
4536
        !snap.changed && snap.statuses.is_empty(),
4537
        "{:?}",
4538
        snap.statuses
4539
    );
4540
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
4541
    // A real change (new mtime, new content) is seen and committed correctly.
4542
    let mut big2 = big.clone();
4543
    big2[10] ^= 0xff;
4544
    write(root, "big.bin", &big2);
4545
    let snap = repo.snapshot("status").unwrap();
4546
    assert_eq!(
4547
        snap.statuses
4548
            .iter()
4549
            .map(|s| (s.path.as_str(), s.status))
4550
            .collect::<Vec<_>>(),
4551
        vec![("big.bin", ChangeStatus::Modified)]
4552
    );
4553
    let h2 = repo.commit("edit", &[]).unwrap();
4554
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4555
    assert_eq!(
4556
        files["big.bin"].content,
4557
        FileContent::Opaque {
4558
            blobs: vec![Repo::blob_ref(&big2)]
4559
        }
4560
    );
4561
    // Checkout writes a manifest with blobs too, so the next status is cached.
4562
    repo.checkout(&[h1], false, "checkout").unwrap();
4563
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4564
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
4565
    assert!(!repo.snapshot("status").unwrap().changed);
4566
}
4567
4568
#[test]
4569
fn status_json_lists_conflicts_with_contributors() {
4570
    hermetic();
4571
    let dir = tempfile::tempdir().unwrap();
4572
    let root = dir.path();
4573
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4574
    write(root, "a.txt", b"one\n");
4575
    let h1 = repo.commit("base", &[]).unwrap();
4576
    write(root, "a.txt", b"one\nleft\n");
4577
    let ha = repo.commit("left", &[]).unwrap();
4578
    repo.checkout(&[h1], true, "checkout").unwrap();
4579
    write(root, "a.txt", b"one\nright\n");
4580
    let hb = repo.commit("right", &[]).unwrap();
4581
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
4582
    let snap = repo.snapshot("status").unwrap();
4583
    assert!(snap.base_snapshot.is_conflicted());
4584
    let json = repo.status_json(&snap).unwrap();
4585
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
4586
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
4587
    assert!(json.contains("\"conflicted\":true"), "{json}");
4588
    assert!(
4589
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
4590
        "{json}"
4591
    );
4592
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
4593
    assert!(json.contains("\"resolved\":false"), "{json}");
4594
    assert!(json.starts_with('{') && json.ends_with('}'));
4595
    // Resolve and the report says so; a clean copy has no conflicts.
4596
    write(root, "a.txt", b"one\nleft\nright\n");
4597
    let snap = repo.snapshot("status").unwrap();
4598
    let json = repo.status_json(&snap).unwrap();
4599
    assert!(json.contains("\"resolved\":true"), "{json}");
4600
    repo.commit("resolve", &[]).unwrap();
4601
    let snap = repo.snapshot("status").unwrap();
4602
    let json = repo.status_json(&snap).unwrap();
4603
    assert!(
4604
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
4605
        "{json}"
4606
    );
4607
}
4608
4609
#[test]
4610
fn ignore_rules_do_not_untrack_files() {
4611
    hermetic();
4612
    let dir = tempfile::tempdir().unwrap();
4613
    let root = dir.path();
4614
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4615
    write(root, "src.c", b"int x;\n");
4616
    write(root, "build/out.o", b"\0obj");
4617
    write(root, "sub/keep.log", b"keep\n");
4618
    write(root, "sub/junk.log", b"junk\n");
4619
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
4620
    let snap = repo.snapshot("status").unwrap();
4621
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4622
    assert_eq!(
4623
        added,
4624
        vec![".oxyignore", "src.c", "sub/keep.log"],
4625
        "anchored, glob, and negated rules"
4626
    );
4627
    let h1 = repo.commit("base", &[]).unwrap();
4628
    // Ignoring a tracked file changes nothing about it.
4629
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
4630
    let snap = repo.snapshot("status").unwrap();
4631
    assert_eq!(
4632
        snap.statuses
4633
            .iter()
4634
            .map(|s| s.path.as_str())
4635
            .collect::<Vec<_>>(),
4636
        vec![".oxyignore"]
4637
    );
4638
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
4639
    assert!(repo
4640
        .load_state(&[h2])
4641
        .unwrap()
4642
        .materialize()
4643
        .files
4644
        .contains_key("src.c"));
4645
    // Its edits are still seen, by status and by the prompt.
4646
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
4647
    write(root, "src.c", b"int x, y;\n");
4648
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
4649
    let snap = repo.snapshot("status").unwrap();
4650
    assert_eq!(
4651
        snap.statuses
4652
            .iter()
4653
            .map(|s| (s.path.as_str(), s.status))
4654
            .collect::<Vec<_>>(),
4655
        vec![("src.c", ChangeStatus::Modified)]
4656
    );
4657
    let h3 = repo.commit("edit src.c", &[]).unwrap();
4658
    assert!(
4659
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
4660
    );
4661
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
4662
    fs::remove_file(root.join("src.c")).unwrap();
4663
    let snap = repo.snapshot("status").unwrap();
4664
    assert_eq!(
4665
        snap.statuses
4666
            .iter()
4667
            .map(|s| (s.path.as_str(), s.status))
4668
            .collect::<Vec<_>>(),
4669
        vec![("src.c", ChangeStatus::Removed)]
4670
    );
4671
    repo.checkout(&[h3], true, "checkout").unwrap();
4672
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
4673
    assert!(!repo.snapshot("status").unwrap().changed);
4674
    let _ = h1;
4675
}
4676
4677
#[test]
4678
fn split_works_on_non_heads_by_node() {
4679
    hermetic();
4680
    let dir = tempfile::tempdir().unwrap();
4681
    let root = dir.path();
4682
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4683
    write(root, "a.txt", b"one\n");
4684
    write(root, "junk/x.lock", b"lock\n");
4685
    let h1 = repo.commit("work plus junk", &[]).unwrap();
4686
    write(root, "a.txt", b"one\ntwo\n");
4687
    let h2 = repo.commit("more work", &[]).unwrap();
4688
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
4689
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
4690
    // h1 is not a head: split it by node.
4691
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
4692
    assert_ne!(h1b, h1);
4693
    assert_eq!(
4694
        repo.store().get_change(&h1b).unwrap().change_id,
4695
        id1,
4696
        "the rest keeps the ChangeId"
4697
    );
4698
    let junk = repo.store().get_change(&hj).unwrap();
4699
    assert!(junk.tree_ops.iter().all(
4700
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
4701
    ));
4702
    let heads = repo.bookmark_heads().unwrap();
4703
    assert!(
4704
        heads.contains(&hj),
4705
        "the split-off part is a head of its own"
4706
    );
4707
    let snap = repo.load_state(&heads).unwrap().materialize();
4708
    assert!(
4709
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
4710
        "the dependent was rewritten onto the new hash"
4711
    );
4712
    assert!(snap.files.contains_key("junk/x.lock"));
4713
    let h2b = heads
4714
        .iter()
4715
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
4716
        .copied()
4717
        .unwrap();
4718
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
4719
    assert!(!repo.snapshot("status").unwrap().changed);
4720
    // Abandoning the split-off head removes the junk from history.
4721
    repo.abandon(&hj).unwrap();
4722
    let heads = repo.bookmark_heads().unwrap();
4723
    let snap = repo.load_state(&heads).unwrap().materialize();
4724
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
4725
    assert!(snap.files.contains_key("a.txt"));
4726
    // A dependent that touches the split-off paths blocks the split.
4727
    write(root, "junk/y.lock", b"y\n");
4728
    let hb = repo.commit("junk base", &[]).unwrap();
4729
    write(root, "junk/y.lock", b"yy\n");
4730
    write(root, "b.txt", b"b\n");
4731
    repo.commit("touches junk", &[]).unwrap();
4732
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
4733
    assert!(err.contains("depends on the split-off paths"), "{err}");
4734
}
4735
4736
#[test]
4737
fn bookmarks_switch_merge_and_push() {
4738
    hermetic();
4739
    let dir = tempfile::tempdir().unwrap();
4740
    let root = dir.path();
4741
    let origin = Repo::init(&root.join("origin")).unwrap();
4742
    let url = root.join("origin").to_string_lossy().to_string();
4743
    let mut repo = Repo::clone(&url, &root.join("r"))
4744
        .unwrap()
4745
        .with_home(root.join("home"));
4746
    let r = root.join("r");
4747
    write(&r, "a.txt", b"a\n");
4748
    let h_a = repo.commit("a", &[]).unwrap();
4749
    assert!(repo.push("origin", false).unwrap()[0].ok);
4750
    origin.refresh().unwrap();
4751
4752
    // A bookmark at the working copy's base, then work on it.
4753
    assert!(repo.bookmark_create("bad name..", None).is_err());
4754
    assert!(repo.bookmark_create("-x", None).is_err());
4755
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
4756
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
4757
    repo.bookmark_switch("feature", false).unwrap();
4758
    assert_eq!(repo.config.bookmark, "feature");
4759
    write(&r, "a.txt", b"a\nb\n");
4760
    write(&r, "b.txt", b"b\n");
4761
    let h_b = repo.commit("b on feature", &[]).unwrap();
4762
    assert_eq!(
4763
        repo.bookmark_heads().unwrap(),
4764
        vec![h_b],
4765
        "b edits a.txt, so it depends on a"
4766
    );
4767
    assert_eq!(
4768
        repo.resolve_heads("main").unwrap(),
4769
        vec![h_a],
4770
        "main is untouched"
4771
    );
4772
    assert_eq!(
4773
        repo.resolve_change("feature").unwrap(),
4774
        h_b,
4775
        "a one-head bookmark names its change"
4776
    );
4777
    // Reopening keeps the workspace's bookmark.
4778
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
4779
    assert_eq!(reopened.config.bookmark, "feature");
4780
    // Back to main: b.txt goes away; work there.
4781
    repo.bookmark_switch("main", false).unwrap();
4782
    assert!(!r.join("b.txt").exists());
4783
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
4784
    write(&r, "c.txt", b"c\n");
4785
    let h_c = repo.commit("c on main", &[]).unwrap();
4786
    let list = repo.bookmarks().unwrap();
4787
    assert_eq!(
4788
        list.iter()
4789
            .map(|b| (b.name.as_str(), b.current))
4790
            .collect::<Vec<_>>(),
4791
        vec![("feature", false), ("main", true)]
4792
    );
4793
    assert_eq!(
4794
        list.iter().find(|b| b.name == "main").unwrap().ahead,
4795
        Some(1),
4796
        "c is not on origin yet"
4797
    );
4798
    // Merge feature into main: the union, both heads, no merge change.
4799
    let m = repo.merge("feature").unwrap();
4800
    assert!(m.changed && m.checked_out);
4801
    let mut want = vec![h_b, h_c];
4802
    want.sort();
4803
    assert_eq!(m.heads, want);
4804
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
4805
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
4806
    assert!(repo.merge("main").is_err());
4807
    // The other bookmark can be pushed by name and appears at origin.
4808
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
4809
    origin.refresh().unwrap();
4810
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
4811
    assert!(repo.push("origin", false).unwrap()[0].ok);
4812
    origin.refresh().unwrap();
4813
    assert_eq!(
4814
        repo.bookmarks()
4815
            .unwrap()
4816
            .iter()
4817
            .find(|b| b.name == "main")
4818
            .unwrap()
4819
            .ahead,
4820
        Some(0)
4821
    );
4822
    // A second workspace inherits the current bookmark and can switch independently.
4823
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
4824
    assert_eq!(ws.config.bookmark, "main");
4825
    let mut ws = ws;
4826
    ws.bookmark_switch("feature", false).unwrap();
4827
    assert_eq!(
4828
        Repo::open(&r).unwrap().config.bookmark,
4829
        "main",
4830
        "the first workspace is unaffected"
4831
    );
4832
    assert!(
4833
        repo.bookmark_delete("feature").is_err(),
4834
        "current bookmark of another workspace"
4835
    );
4836
    ws.bookmark_switch("main", false).unwrap();
4837
    // Set and delete.
4838
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
4839
    assert!(repo.bookmark_delete("main").is_err(), "current here");
4840
    repo.bookmark_delete("feature").unwrap();
4841
    assert!(repo.resolve_heads("feature").is_err());
4842
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
4843
    assert!(
4844
        repo.checkout(&[h_a], false, "checkout").is_ok(),
4845
        "changes of a deleted bookmark remain"
4846
    );
4847
}
4848
4849
#[test]
4850
fn oxygen_subrepos_pin_follow_and_update() {
4851
    hermetic();
4852
    let dir = tempfile::tempdir().unwrap();
4853
    let root = dir.path();
4854
    // A library repository with two commits, and a bare-ish origin for it.
4855
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
4856
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
4857
    let lib = Repo::clone(&lib_url, &root.join("lib"))
4858
        .unwrap()
4859
        .with_home(root.join("home"));
4860
    write(&root.join("lib"), "lib.txt", b"v1\n");
4861
    let l1 = lib.commit("lib v1", &[]).unwrap();
4862
    assert!(lib.push("origin", false).unwrap()[0].ok);
4863
    let _ = lib_origin;
4864
4865
    // The application (a clone of its own origin) adds it as a subrepo.
4866
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
4867
    let app_url = root.join("app-origin").to_string_lossy().to_string();
4868
    let _ = app_origin;
4869
    let app_dir = root.join("app");
4870
    let app = Repo::clone(&app_url, &app_dir)
4871
        .unwrap()
4872
        .with_home(root.join("home"));
4873
    write(&app_dir, "main.txt", b"app\n");
4874
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
4875
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
4876
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
4877
    let snap = app.snapshot("status").unwrap();
4878
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4879
    assert_eq!(
4880
        paths,
4881
        vec![".oxymodules", "libs/lib", "main.txt"],
4882
        "the nested files are not walked"
4883
    );
4884
    let a1 = app.commit("app with lib", &[]).unwrap();
4885
    let files = app.load_state(&[a1]).unwrap().materialize().files;
4886
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
4887
    assert!(!files.contains_key("libs/lib/lib.txt"));
4888
    assert!(!app.snapshot("status").unwrap().changed);
4889
    let subs = app.subrepos().unwrap();
4890
    assert_eq!(subs.len(), 1);
4891
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
4892
4893
    // Advance the nested repository: the parent sees a modified pin.
4894
    let nested = Repo::open(&app_dir.join("libs/lib"))
4895
        .unwrap()
4896
        .with_home(root.join("home"));
4897
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
4898
    let l2 = nested.commit("lib v2", &[]).unwrap();
4899
    assert!(nested.push("origin", false).unwrap()[0].ok);
4900
    let snap = app.snapshot("status").unwrap();
4901
    assert_eq!(
4902
        snap.statuses
4903
            .iter()
4904
            .map(|s| (s.path.as_str(), s.status))
4905
            .collect::<Vec<_>>(),
4906
        vec![("libs/lib", ChangeStatus::Modified)]
4907
    );
4908
    let a2 = app.commit("bump lib", &[]).unwrap();
4909
    // Checking out the older app state brings the nested working copy back
4910
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
4911
    let r = app.checkout(&[a1], false, "checkout").unwrap();
4912
    assert!(
4913
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
4914
        "{:?}",
4915
        r.notes
4916
    );
4917
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4918
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
4919
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
4920
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
4921
    assert!(!app.snapshot("status").unwrap().changed);
4922
    // A dirty nested repository is left alone and reported.
4923
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
4924
    let r = app.checkout(&[a2], false, "checkout").unwrap();
4925
    assert!(
4926
        r.notes.iter().any(|n| n.contains("uncommitted")),
4927
        "{:?}",
4928
        r.notes
4929
    );
4930
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
4931
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
4932
    let r = app.submodule_update(false, &[]).unwrap();
4933
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
4934
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
4935
    let _ = l2;
4936
4937
    // A fresh clone of the app has the pin but no nested repository until update --init.
4938
    assert!(app.push("origin", false).unwrap()[0].ok);
4939
    let clone_dir = root.join("app-clone");
4940
    let clone = Repo::clone(&app_url, &clone_dir)
4941
        .unwrap()
4942
        .with_home(root.join("home"));
4943
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
4944
    assert_eq!(
4945
        clone.submodule_update(false, &[]).unwrap(),
4946
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
4947
    );
4948
    assert_eq!(
4949
        clone.submodule_update(true, &[]).unwrap(),
4950
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
4951
    );
4952
    assert_eq!(
4953
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
4954
        b"v2\n"
4955
    );
4956
    assert!(!clone.snapshot("status").unwrap().changed);
4957
    // Removing the subrepo leaves the directory and drops the node.
4958
    clone.submodule_remove("libs/lib").unwrap();
4959
    let snap = clone.snapshot("status").unwrap();
4960
    assert!(
4961
        snap.statuses
4962
            .iter()
4963
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
4964
        "{:?}",
4965
        snap.statuses
4966
    );
4967
    let c = clone.commit("drop lib", &[]).unwrap();
4968
    assert!(!clone
4969
        .load_state(&[c])
4970
        .unwrap()
4971
        .materialize()
4972
        .files
4973
        .contains_key("libs/lib"));
4974
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
4975
    assert!(
4976
        !clone.snapshot("status").unwrap().changed,
4977
        "an unregistered nested repository is ignored"
4978
    );
4979
4980
    // Registered again, it is pinned again; removed and committed, then
4981
    // registered again with no snapshot between, the change that adds it
4982
    // back pins it too: the removal's marker is spent (oxygen#152).
4983
    let modules = format!("[libs/lib]\nurl = {lib_url}\n");
4984
    let pinned = |c: ChangeHash| {
4985
        clone
4986
            .load_state(&[c])
4987
            .unwrap()
4988
            .materialize()
4989
            .files
4990
            .get("libs/lib")
4991
            .map(|n| n.kind)
4992
    };
4993
    write(&clone_dir, ".oxymodules", modules.as_bytes());
4994
    let c = clone.commit("lib again", &[]).unwrap();
4995
    assert_eq!(pinned(c), Some(NodeKind::Subrepo));
4996
    clone.submodule_remove("libs/lib").unwrap();
4997
    let c = clone.commit("drop lib again", &[]).unwrap();
4998
    assert_eq!(pinned(c), None);
4999
    write(&clone_dir, ".oxymodules", modules.as_bytes());
5000
    let c = clone.commit("lib back", &[]).unwrap();
5001
    assert_eq!(
5002
        pinned(c),
5003
        Some(NodeKind::Subrepo),
5004
        "pinned in the change that registers it"
5005
    );
5006
    assert!(!clone.snapshot("status").unwrap().changed);
5007
}
5008
5009
#[test]
5010
fn git_submodules_import_and_export_as_gitlinks() {
5011
    hermetic();
5012
    if std::process::Command::new("git")
5013
        .arg("--version")
5014
        .output()
5015
        .is_err()
5016
    {
5017
        eprintln!("git not installed; skipping");
5018
        return;
5019
    }
5020
    let dir = tempfile::tempdir().unwrap();
5021
    let root = dir.path();
5022
    let git_in = |d: &Path, args: &[&str]| -> String {
5023
        let out = std::process::Command::new("git")
5024
            .arg("-C")
5025
            .arg(d)
5026
            .args([
5027
                "-c",
5028
                "user.name=Grace",
5029
                "-c",
5030
                "[email protected]",
5031
                "-c",
5032
                "commit.gpgsign=false",
5033
                "-c",
5034
                "protocol.file.allow=always",
5035
            ])
5036
            .args(args)
5037
            .output()
5038
            .unwrap();
5039
        assert!(
5040
            out.status.success(),
5041
            "git {args:?}: {}",
5042
            String::from_utf8_lossy(&out.stderr)
5043
        );
5044
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5045
    };
5046
    let sub = root.join("sub");
5047
    fs::create_dir_all(&sub).unwrap();
5048
    git_in(&sub, &["init", "-q", "-b", "main"]);
5049
    write(&sub, "s.txt", b"sub\n");
5050
    git_in(&sub, &["add", "."]);
5051
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
5052
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
5053
    let g = root.join("main.git");
5054
    fs::create_dir_all(&g).unwrap();
5055
    git_in(&g, &["init", "-q", "-b", "main"]);
5056
    write(&g, "README.md", b"# app\n");
5057
    git_in(&g, &["add", "."]);
5058
    git_in(&g, &["commit", "-q", "-m", "initial"]);
5059
    git_in(
5060
        &g,
5061
        &[
5062
            "submodule",
5063
            "add",
5064
            "-q",
5065
            sub.to_str().unwrap(),
5066
            "vendor/sub",
5067
        ],
5068
    );
5069
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
5070
5071
    let dest = root.join("oxy");
5072
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
5073
    let rep = repo.import_git(&g, "main").unwrap();
5074
    assert_eq!((rep.commits, rep.submodules), (2, 1));
5075
    let files = repo
5076
        .load_state(&repo.bookmark_heads().unwrap())
5077
        .unwrap()
5078
        .materialize()
5079
        .files;
5080
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
5081
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
5082
        panic!()
5083
    };
5084
    assert_eq!(
5085
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
5086
        crate::subrepo::Pin::Git {
5087
            sha: sub_sha.clone(),
5088
            branch: "HEAD".into()
5089
        }
5090
    );
5091
    let modules =
5092
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
5093
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
5094
    assert!(modules.entries["vendor/sub"].git);
5095
    assert!(
5096
        files.contains_key(".gitmodules"),
5097
        "the Git file is kept for round trips"
5098
    );
5099
    assert!(
5100
        !dest.join("vendor/sub/.git").exists(),
5101
        "not cloned until update --init"
5102
    );
5103
    assert!(!repo.snapshot("status").unwrap().changed);
5104
    // update --init clones it at the pinned commit; status is unchanged.
5105
    assert_eq!(
5106
        repo.submodule_update(true, &[]).unwrap(),
5107
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
5108
    );
5109
    assert_eq!(
5110
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
5111
        sub_sha
5112
    );
5113
    assert!(!repo.snapshot("status").unwrap().changed);
5114
    // Export writes the gitlink and .gitmodules back.
5115
    let mirror = root.join("mirror.git");
5116
    let rep = repo.git_export(&mirror).unwrap();
5117
    assert_eq!(rep.skipped_subrepos, 0);
5118
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
5119
    assert!(
5120
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
5121
        "{ls}"
5122
    );
5123
    assert_eq!(
5124
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
5125
        ".gitmodules\nREADME.md\nvendor"
5126
    );
5127
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
5128
    assert_eq!(
5129
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
5130
        orig_tree,
5131
        "tree round trip"
5132
    );
5133
}
5134
5135
#[test]
5136
fn partial_commits_by_path_and_by_hunk() {
5137
    hermetic();
5138
    let dir = tempfile::tempdir().unwrap();
5139
    let root = dir.path();
5140
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5141
    write(root, "a.txt", b"1\n2\n3\n");
5142
    write(root, "b.txt", b"b\n");
5143
    let h0 = repo.commit("base", &[]).unwrap();
5144
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
5145
    write(root, "b.txt", b"b\nbb\n");
5146
    write(root, "c.txt", b"c\n");
5147
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
5148
    let h1 = repo
5149
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
5150
        .unwrap();
5151
    let c1 = repo.store().get_change(&h1).unwrap();
5152
    assert!(
5153
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
5154
        "{:?}",
5155
        c1.tree_ops
5156
    );
5157
    assert_eq!(c1.deps, vec![h0]);
5158
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
5159
    assert!(
5160
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
5161
    );
5162
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
5163
    assert!(!files.contains_key("c.txt"));
5164
    let snap = repo.snapshot("status").unwrap();
5165
    assert_eq!(
5166
        snap.statuses
5167
            .iter()
5168
            .map(|s| (s.path.as_str(), s.status))
5169
            .collect::<Vec<_>>(),
5170
        vec![
5171
            ("b.txt", ChangeStatus::Modified),
5172
            ("c.txt", ChangeStatus::Added)
5173
        ]
5174
    );
5175
    assert_eq!(
5176
        fs::read(root.join("b.txt")).unwrap(),
5177
        b"b\nbb\n",
5178
        "disk untouched"
5179
    );
5180
    // By hunk: pick the b.txt insert; c.txt's addition is left.
5181
    let (_, hunks) = repo.hunks().unwrap();
5182
    let b_hunk = hunks
5183
        .iter()
5184
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
5185
        .unwrap()
5186
        .index;
5187
    let h2 = repo
5188
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
5189
        .unwrap();
5190
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
5191
    assert!(
5192
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
5193
    );
5194
    assert!(!files.contains_key("c.txt"));
5195
    let snap = repo.snapshot("status").unwrap();
5196
    assert_eq!(
5197
        snap.statuses
5198
            .iter()
5199
            .map(|s| s.path.as_str())
5200
            .collect::<Vec<_>>(),
5201
        vec!["c.txt"]
5202
    );
5203
    // Choosing only the content hunk of a file in a new directory pulls in
5204
    // the directory and file additions it needs.
5205
    write(root, "d/e.txt", b"e\n");
5206
    let (_, hunks) = repo.hunks().unwrap();
5207
    let e_insert = hunks
5208
        .iter()
5209
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
5210
        .unwrap()
5211
        .index;
5212
    let h3 = repo
5213
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
5214
        .unwrap();
5215
    let c3 = repo.store().get_change(&h3).unwrap();
5216
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
5217
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
5218
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
5219
    // Choosing a new file's addition hunk brings its content along.
5220
    write(root, "f/g.txt", b"g\n");
5221
    let (_, hunks) = repo.hunks().unwrap();
5222
    let g_add = hunks
5223
        .iter()
5224
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
5225
        .unwrap()
5226
        .index;
5227
    let h4 = repo
5228
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
5229
        .unwrap();
5230
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
5231
    assert!(
5232
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
5233
    );
5234
    assert!(!repo
5235
        .snapshot("status")
5236
        .unwrap()
5237
        .statuses
5238
        .iter()
5239
        .any(|s| s.path == "f/g.txt"));
5240
    // Everything left commits normally; the working copy is then clean.
5241
    repo.commit("the rest", &[]).unwrap();
5242
    assert!(!repo.snapshot("status").unwrap().changed);
5243
    let files = repo
5244
        .load_state(&repo.bookmark_heads().unwrap())
5245
        .unwrap()
5246
        .materialize()
5247
        .files;
5248
    assert!(files.contains_key("c.txt"));
5249
}
5250
5251
#[test]
5252
fn blame_attributes_lines_to_introducing_changes_across_renames() {
5253
    hermetic();
5254
    let dir = tempfile::tempdir().unwrap();
5255
    let root = dir.path();
5256
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5257
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
5258
        .unwrap();
5259
    write(root, "a.txt", b"one\n");
5260
    let h1 = repo.commit("first", &[]).unwrap();
5261
    write(root, "a.txt", b"one\ntwo\n");
5262
    let h2 = repo.commit("second", &[]).unwrap();
5263
    let b = repo.blame("a.txt").unwrap();
5264
    assert_eq!(
5265
        b.iter()
5266
            .map(|l| (l.line, l.hash, l.text.as_slice()))
5267
            .collect::<Vec<_>>(),
5268
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
5269
    );
5270
    assert!(b.iter().all(|l| l.author == "Ada"));
5271
    assert_eq!(
5272
        b[0].change_id,
5273
        repo.store().get_change(&h1).unwrap().change_id
5274
    );
5275
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
5276
    repo.commit("rename", &[]).unwrap();
5277
    let b = repo.blame("b.txt").unwrap();
5278
    assert_eq!(
5279
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
5280
        vec![h1, h2],
5281
        "the node survives the rename"
5282
    );
5283
    assert!(repo.blame("a.txt").is_err());
5284
}
5285
5286
#[test]
5287
fn bisect_finds_the_first_bad_change() {
5288
    hermetic();
5289
    let dir = tempfile::tempdir().unwrap();
5290
    let root = dir.path();
5291
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5292
    let mut content = String::new();
5293
    let mut hashes = Vec::new();
5294
    for i in 1..=8 {
5295
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
5296
        write(root, "f.txt", content.as_bytes());
5297
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
5298
    }
5299
    // Each step appends after the previous line, so the chain is linear.
5300
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
5301
    repo.bisect_start().unwrap();
5302
    assert!(matches!(
5303
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
5304
        BisectStep::NeedMarks { good: 1, bad: 0 }
5305
    ));
5306
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5307
    assert!(
5308
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
5309
        "{step:?}"
5310
    );
5311
    // Automated: bad when the bug line is present.
5312
    let step = repo
5313
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
5314
        .unwrap();
5315
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
5316
    assert_eq!(
5317
        repo.bisect_status().unwrap(),
5318
        Some(BisectStep::Found { culprit: hashes[4] })
5319
    );
5320
    repo.bisect_reset().unwrap();
5321
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
5322
    assert!(repo.bisect_status().unwrap().is_none());
5323
    assert!(!repo.snapshot("status").unwrap().changed);
5324
    // Manual marks and a skip.
5325
    repo.bisect_start().unwrap();
5326
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
5327
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5328
    let mut skipped_once = false;
5329
    let mut guard = 0;
5330
    while let BisectStep::Testing { .. } = step {
5331
        guard += 1;
5332
        assert!(guard < 20);
5333
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
5334
        if !skipped_once && text.contains("line 6") {
5335
            // An untestable state away from the boundary: the search routes around it.
5336
            skipped_once = true;
5337
            step = repo.bisect_mark(None, &[]).unwrap();
5338
            continue;
5339
        }
5340
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
5341
    }
5342
    assert!(skipped_once);
5343
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
5344
    repo.bisect_reset().unwrap();
5345
    // Skipping the culprit itself leaves it among the candidates reported.
5346
    repo.bisect_start().unwrap();
5347
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
5348
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5349
    let mut guard = 0;
5350
    while let BisectStep::Testing { heads, .. } = &step {
5351
        guard += 1;
5352
        assert!(guard < 20);
5353
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
5354
        let is_culprit_state =
5355
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
5356
        step = if is_culprit_state {
5357
            repo.bisect_mark(None, &[]).unwrap()
5358
        } else {
5359
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
5360
        };
5361
    }
5362
    match step {
5363
        BisectStep::Inconclusive { candidates } => assert!(
5364
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
5365
            "{candidates:?}"
5366
        ),
5367
        other => panic!("{other:?}"),
5368
    }
5369
    repo.bisect_reset().unwrap();
5370
}
5371
5372
#[test]
5373
fn squash_folds_a_change_into_its_dependency() {
5374
    hermetic();
5375
    let dir = tempfile::tempdir().unwrap();
5376
    let root = dir.path();
5377
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5378
    write(root, "a.txt", b"1\n");
5379
    let a = repo.commit("A", &[]).unwrap();
5380
    write(root, "a.txt", b"1\n2\n");
5381
    let c = repo.commit("C", &[]).unwrap();
5382
    write(root, "a.txt", b"1\n2\n3\n");
5383
    let e = repo.commit("E", &[]).unwrap();
5384
    write(root, "b.txt", b"b\n");
5385
    let b = repo.commit("B", &[]).unwrap();
5386
    let id_a = repo.store().get_change(&a).unwrap().change_id;
5387
    let id_e = repo.store().get_change(&e).unwrap().change_id;
5388
    // E depends on C which A lacks: refused, naming it.
5389
    let err = repo.squash(&e, &a).unwrap_err().to_string();
5390
    assert!(err.contains(&c.short(12)), "{err}");
5391
    // C into A: A' has both, C is gone, E follows and still reads the same.
5392
    let a2 = repo.squash(&c, &a).unwrap();
5393
    let a2c = repo.store().get_change(&a2).unwrap();
5394
    assert_eq!(a2c.change_id, id_a);
5395
    assert!(a2c.deps.is_empty());
5396
    let heads = repo.bookmark_heads().unwrap();
5397
    let st = repo.load_state(&heads).unwrap();
5398
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
5399
    let e2 = st
5400
        .changes()
5401
        .find(|(_, m)| m.change_id == id_e)
5402
        .map(|(h, _)| *h)
5403
        .unwrap();
5404
    assert_eq!(
5405
        repo.store().get_change(&e2).unwrap().deps,
5406
        vec![a2],
5407
        "E now depends on A' alone"
5408
    );
5409
    let files = st.materialize().files;
5410
    assert!(
5411
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
5412
    );
5413
    assert!(files.contains_key("b.txt"));
5414
    assert!(st.contains(&b));
5415
    assert!(!repo.snapshot("status").unwrap().changed);
5416
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
5417
    // Undo restores the three original changes.
5418
    repo.undo().unwrap();
5419
    repo.undo().unwrap();
5420
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
5421
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
5422
}
5423
5424
#[test]
5425
fn rebase_re_expresses_a_change_against_another_base() {
5426
    hermetic();
5427
    let dir = tempfile::tempdir().unwrap();
5428
    let root = dir.path();
5429
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5430
    write(root, "a.txt", b"1\n2\n");
5431
    let a = repo.commit("A", &[]).unwrap();
5432
    write(root, "a.txt", b"1\n2\n3\n");
5433
    let c = repo.commit("C: append 3", &[]).unwrap();
5434
    write(root, "a.txt", b"1\n2\n3\n4\n");
5435
    let e = repo.commit("E: append 4", &[]).unwrap();
5436
    // A different base: A plus a change that prepends a line.
5437
    repo.checkout(&[a], true, "checkout").unwrap();
5438
    write(root, "a.txt", b"0\n1\n2\n");
5439
    let d = repo.commit("D: prepend 0", &[]).unwrap();
5440
    let id_c = repo.store().get_change(&c).unwrap().change_id;
5441
    let id_e = repo.store().get_change(&e).unwrap().change_id;
5442
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
5443
    let c2 = repo.rebase(&c, &[d]).unwrap();
5444
    let c2c = repo.store().get_change(&c2).unwrap();
5445
    assert_eq!(c2c.change_id, id_c);
5446
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
5447
    let heads = repo.bookmark_heads().unwrap();
5448
    let st = repo.load_state(&heads).unwrap();
5449
    assert!(!st.contains(&c) && st.contains(&d));
5450
    let e2 = st
5451
        .changes()
5452
        .find(|(_, m)| m.change_id == id_e)
5453
        .map(|(h, _)| *h)
5454
        .unwrap();
5455
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
5456
    assert!(
5457
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
5458
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
5459
    );
5460
    let files = st.materialize().files;
5461
    assert!(
5462
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
5463
        "{:?}",
5464
        files["a.txt"].content
5465
    );
5466
    assert!(!files["a.txt"].is_conflicted());
5467
    // Rebasing onto a state that already contains the change is refused.
5468
    assert!(repo.rebase(&c2, &[c2]).is_err());
5469
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
5470
    assert!(
5471
        err.contains("lacks dependencies"),
5472
        "E needs C, which D's state does not have: {err}"
5473
    );
5474
}
5475
5476
#[test]
5477
fn unsigned_tags_keep_their_message() {
5478
    hermetic();
5479
    let dir = tempfile::tempdir().unwrap();
5480
    let root = dir.path();
5481
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5482
    write(root, "a.txt", b"a\n");
5483
    repo.commit("a", &[]).unwrap();
5484
    assert!(repo.secret_key().unwrap().is_none());
5485
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
5486
        .unwrap();
5487
    let tags = repo.tags().unwrap();
5488
    assert_eq!(
5489
        (
5490
            tags[0].name.as_str(),
5491
            tags[0].message.as_str(),
5492
            tags[0].signer.as_deref()
5493
        ),
5494
        ("v1", "first release", None)
5495
    );
5496
    assert!(
5497
        repo.tag_refs().unwrap()[0].attestation.is_none(),
5498
        "an unsigned attestation is not advertised"
5499
    );
5500
}
5501
5502
#[test]
5503
fn fsck_passes_a_sound_repository_and_names_each_fault() {
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
    }
5509
    hermetic();
5510
    let dir = tempfile::tempdir().unwrap();
5511
    let root = dir.path();
5512
    let origin_path = root.join("origin");
5513
    let origin = Repo::init(&origin_path).unwrap();
5514
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
5515
        .unwrap()
5516
        .with_home(root.join("home-a"));
5517
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5518
        .unwrap();
5519
    write(&root.join("a"), "f.txt", b"one\n");
5520
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
5521
    let h1 = a.commit("first", &[]).unwrap();
5522
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
5523
    let h2 = a.commit("second", &[]).unwrap();
5524
    a.tag_create("v1", &[h2], "first release").unwrap();
5525
    a.checkpoint().unwrap();
5526
    assert!(a.push("origin", false).unwrap()[0].ok);
5527
    origin.refresh().unwrap();
5528
5529
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
5530
    for repo in [&a, &origin] {
5531
        let rep = repo.fsck().unwrap();
5532
        assert_eq!(rep.problems, vec![], "{rep:?}");
5533
        // The two commits, plus the working copy's change in `a`.
5534
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
5535
        assert!(rep.ops > 1 && rep.objects > 5);
5536
    }
5537
    assert!(origin.fsck().unwrap().attestations >= 1);
5538
5539
    // A flipped byte in a stored object is corruption, named by hash.
5540
    let c1 = a.store().path_for(&h1);
5541
    let pristine = fs::read(&c1).unwrap();
5542
    let mut bytes = pristine.clone();
5543
    *bytes.last_mut().unwrap() ^= 1;
5544
    fs::write(&c1, &bytes).unwrap();
5545
    let rep = a.fsck().unwrap();
5546
    assert!(rep.errors() >= 1);
5547
    assert!(
5548
        rep.problems
5549
            .iter()
5550
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
5551
        "{rep:?}"
5552
    );
5553
    fs::write(&c1, &pristine).unwrap();
5554
    assert_eq!(a.fsck().unwrap().errors(), 0);
5555
5556
    // A missing change is named with what needed it.
5557
    fs::remove_file(&c1).unwrap();
5558
    let rep = a.fsck().unwrap();
5559
    assert!(
5560
        rep.problems.iter().any(|p| p.severity == Severity::Error
5561
            && p.object == Some(h1)
5562
            && p.what.contains("change missing, needed by change")),
5563
        "{rep:?}"
5564
    );
5565
    fs::write(&c1, &pristine).unwrap();
5566
5567
    // A missing blob is an error in a full clone.
5568
    let c2 = a.store().get_change(&h1).unwrap();
5569
    let blob = c2
5570
        .edits
5571
        .iter()
5572
        .find_map(|e| match e {
5573
            Edit::Replace { new: Some(b), .. } => Some(*b),
5574
            _ => None,
5575
        })
5576
        .expect("the binary file is a blob");
5577
    let bp = a.store().path_for(&blob);
5578
    let blob_bytes = fs::read(&bp).unwrap();
5579
    fs::remove_file(&bp).unwrap();
5580
    let rep = a.fsck().unwrap();
5581
    assert!(
5582
        rep.problems
5583
            .iter()
5584
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
5585
        "{rep:?}"
5586
    );
5587
    fs::write(&bp, &blob_bytes).unwrap();
5588
5589
    // A broken op log head is reported, not a crash.
5590
    let head = root.join("a/.oxy/ops/head");
5591
    let saved = fs::read(&head).unwrap();
5592
    fs::write(&head, b"not a hash").unwrap();
5593
    let rep = a.fsck().unwrap();
5594
    assert!(
5595
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
5596
        "{rep:?}"
5597
    );
5598
    fs::write(&head, saved).unwrap();
5599
    assert_eq!(a.fsck().unwrap().problems, vec![]);
5600
}
5601
5602
/// Copy a directory tree (for restoring a pristine repository).
5603
fn copy_tree(from: &Path, to: &Path) {
5604
    fs::create_dir_all(to).unwrap();
5605
    for e in fs::read_dir(from).unwrap() {
5606
        let e = e.unwrap();
5607
        let target = to.join(e.file_name());
5608
        if e.file_type().unwrap().is_dir() {
5609
            copy_tree(&e.path(), &target);
5610
        } else {
5611
            fs::copy(e.path(), &target).unwrap();
5612
        }
5613
    }
5614
}
5615
5616
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
5617
/// would, and check that both repositories still open, pass `fsck`, and
5618
/// accept the same operation again.
5619
#[test]
5620
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
5621
    // Files on disk are what this tests: tampering with them, and the
5622
    // directory store's crash points.
5623
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5624
        return;
5625
    }
5626
    use crate::durable::failpoint;
5627
    hermetic();
5628
    let dir = tempfile::tempdir().unwrap();
5629
    let pristine = dir.path().join("pristine");
5630
    let origin_path = pristine.join("origin");
5631
    Repo::init(&origin_path).unwrap();
5632
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
5633
        .unwrap()
5634
        .with_home(dir.path().join("home"));
5635
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5636
        .unwrap();
5637
    write(&pristine.join("a"), "f.txt", b"one\n");
5638
    a.commit("first", &[]).unwrap();
5639
    assert!(a.push("origin", false).unwrap()[0].ok);
5640
    drop(a);
5641
5642
    type Op = fn(&Repo) -> Result<()>;
5643
    let edit_and_commit: Op = |r| {
5644
        write(r.root(), "f.txt", b"one\ntwo\n");
5645
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
5646
        r.commit("second", &[]).map(|_| ())
5647
    };
5648
    let push: Op = |r| {
5649
        let res = r.push("origin", false)?;
5650
        if res.iter().all(|x| x.ok) {
5651
            Ok(())
5652
        } else {
5653
            Err(RepoError::Msg(format!("{res:?}")))
5654
        }
5655
    };
5656
5657
    for (name, prepare, op) in [
5658
        ("commit", None, edit_and_commit),
5659
        ("push", Some(edit_and_commit), push),
5660
    ] {
5661
        let mut steps = 0;
5662
        for n in 1.. {
5663
            let run = dir.path().join(format!("{name}-{n}"));
5664
            copy_tree(&pristine, &run);
5665
            // Clones record their remote by path; point it at this copy.
5666
            let open = |p: &Path| {
5667
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
5668
                r.config
5669
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
5670
                    .unwrap();
5671
                r.save_config().unwrap();
5672
                r
5673
            };
5674
            let a = open(&run.join("a"));
5675
            if let Some(prep) = prepare {
5676
                prep(&a).unwrap();
5677
            }
5678
            failpoint::crash_after(n);
5679
            let outcome = op(&a);
5680
            let crashed = failpoint::disarm();
5681
            drop(a);
5682
            if !crashed {
5683
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
5684
                steps = n - 1;
5685
                break;
5686
            }
5687
            assert!(
5688
                outcome.is_err(),
5689
                "{name}: a crash at step {n} was swallowed"
5690
            );
5691
            for repo in ["a", "origin"] {
5692
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
5693
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
5694
                });
5695
                let rep = r.fsck().unwrap();
5696
                assert_eq!(
5697
                    rep.errors(),
5698
                    0,
5699
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
5700
                    rep.problems
5701
                );
5702
            }
5703
            // The interrupted operation can simply be run again.
5704
            let a = open(&run.join("a"));
5705
            // A crash after the commit point leaves the commit done.
5706
            let landed = a
5707
                .bookmark_heads()
5708
                .unwrap()
5709
                .iter()
5710
                .any(|h| a.store().get_change(h).unwrap().message == "second");
5711
            let again = match (name, landed) {
5712
                ("commit", true) => Ok(()),
5713
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
5714
                _ => op(&a),
5715
            };
5716
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
5717
            assert_eq!(a.fsck().unwrap().errors(), 0);
5718
            fs::remove_dir_all(&run).unwrap();
5719
        }
5720
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
5721
    }
5722
}
5723
5724
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
5725
/// running at the same time lose nothing: every commit ends up on the
5726
/// bookmark, locally and on the remote, and the repository passes fsck.
5727
#[test]
5728
fn concurrent_commits_in_two_workspaces_lose_nothing() {
5729
    hermetic();
5730
    let dir = tempfile::tempdir().unwrap();
5731
    let root = dir.path();
5732
    let origin = root.join("origin");
5733
    Repo::init_bare_unbound(&origin).unwrap();
5734
    let main = root.join("main");
5735
    let mut repo = Repo::init(&main).unwrap();
5736
    repo.config
5737
        .set("remote.origin.url", &origin.to_string_lossy())
5738
        .unwrap();
5739
    repo.save_config().unwrap();
5740
    write(&main, "seed.txt", b"seed\n");
5741
    repo.commit("seed", &[]).unwrap();
5742
    let second = root.join("second");
5743
    repo.workspace_add(&second, None).unwrap();
5744
    drop(repo);
5745
5746
    const EACH: usize = 15;
5747
    std::thread::scope(|s| {
5748
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
5749
            s.spawn(move || {
5750
                let r = Repo::open(&dir).unwrap();
5751
                for i in 0..EACH {
5752
                    write(
5753
                        &dir,
5754
                        &format!("{tag}-{i}.txt"),
5755
                        format!("{tag} {i}\n").as_bytes(),
5756
                    );
5757
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
5758
                    if push && i % 5 == 4 {
5759
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
5760
                        let _ = r.push("origin", false);
5761
                    }
5762
                }
5763
            });
5764
        }
5765
    });
5766
5767
    let repo = Repo::open(&main).unwrap();
5768
    let heads = repo.bookmark_heads().unwrap();
5769
    let state = repo.load_state(&heads).unwrap();
5770
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
5771
    for tag in ["a", "b"] {
5772
        for i in 0..EACH {
5773
            assert!(
5774
                messages.contains(&format!("{tag} {i}")),
5775
                "lost commit {tag} {i}; have {messages:?}"
5776
            );
5777
        }
5778
    }
5779
    let rep = repo.fsck().unwrap();
5780
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
5781
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
5782
    let hosted = Repo::open(&origin).unwrap();
5783
    let hosted_heads = hosted.bookmark_heads().unwrap();
5784
    assert_eq!(
5785
        hosted.load_state(&hosted_heads).unwrap().len(),
5786
        state.len(),
5787
        "the remote has every commit"
5788
    );
5789
}
5790
5791
/// Two operations recorded from the same parent (what two processes do
5792
/// when they race) are merged: both bookmarks' heads survive, and a
5793
/// change made on one side only is kept.
5794
#[test]
5795
fn operations_from_the_same_parent_are_merged() {
5796
    hermetic();
5797
    let dir = tempfile::tempdir().unwrap();
5798
    let root = dir.path();
5799
    let repo = Repo::init(root).unwrap();
5800
    write(root, "a.txt", b"a\n");
5801
    let a = repo.commit("a", &[]).unwrap();
5802
    write(root, "b.txt", b"b\n");
5803
    let b = repo.commit("b", &[]).unwrap();
5804
    let (x, op) = repo.head_op().unwrap();
5805
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
5806
5807
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
5808
    let mut one = op.view.clone();
5809
    one.bookmarks.insert("main".into(), state(vec![a]));
5810
    one.bookmarks.insert("topic".into(), state(vec![a]));
5811
    let mut two = op.view.clone();
5812
    two.bookmarks.insert("main".into(), state(vec![b]));
5813
    repo.record_op(&[x], "one", one).unwrap();
5814
    let merged = repo.record_op(&[x], "two", two).unwrap();
5815
5816
    let (head, op) = repo.head_op().unwrap();
5817
    assert_eq!(head, merged);
5818
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
5819
    assert!(op.command.contains("merged with a concurrent operation"));
5820
    let mut main = repo
5821
        .store()
5822
        .get_state(&op.view.bookmarks["main"])
5823
        .unwrap()
5824
        .heads;
5825
    main.sort();
5826
    let mut want = vec![a, b];
5827
    want.sort();
5828
    assert_eq!(main, want, "both sides' heads are kept");
5829
    assert!(
5830
        op.view.bookmarks.contains_key("topic"),
5831
        "a one-sided change survives"
5832
    );
5833
    assert_eq!(repo.fsck().unwrap().errors(), 0);
5834
}
5835
5836
#[test]
5837
fn failed_requests_come_with_a_next_step() {
5838
    use crate::protocol::hint_for;
5839
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
5840
        .unwrap()
5841
        .contains("token"));
5842
    assert!(hint_for("…: HTTP 403: forbidden")
5843
        .unwrap()
5844
        .contains("repo:write"));
5845
    assert!(hint_for("…: HTTP 404: no such repository")
5846
        .unwrap()
5847
        .contains("owner and repository name"));
5848
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
5849
        .unwrap()
5850
        .contains("oxyhub-ca.pem"));
5851
    assert!(hint_for("Connect error: Connection refused (os error 111)")
5852
        .unwrap()
5853
        .contains("running"));
5854
    assert!(hint_for("Dns Failed: failed to lookup address information")
5855
        .unwrap()
5856
        .contains("resolve"));
5857
    assert_eq!(hint_for("something else entirely"), None);
5858
}
5859
5860
#[test]
5861
fn doctor_names_problems_and_what_to_do() {
5862
    hermetic();
5863
    let dir = tempfile::tempdir().unwrap();
5864
    let root = dir.path();
5865
    let origin = root.join("origin");
5866
    Repo::init_bare_unbound(&origin).unwrap();
5867
    let mut repo = Repo::init(&root.join("r"))
5868
        .unwrap()
5869
        .with_home(root.join("home"));
5870
    let find = |r: &DoctorReport, area: &str, h: Health| {
5871
        r.checks
5872
            .iter()
5873
            .find(|c| c.area == area && c.health == h)
5874
            .cloned()
5875
    };
5876
5877
    let r = repo.doctor(true);
5878
    assert!(find(&r, "identity", Health::Warn)
5879
        .unwrap()
5880
        .hint
5881
        .unwrap()
5882
        .contains("oxy identity create"));
5883
    assert!(find(&r, "repository", Health::Ok).is_some());
5884
5885
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5886
        .unwrap();
5887
    repo.config.set("author.name", "Ada").unwrap();
5888
    repo.config.set("author.email", "[email protected]").unwrap();
5889
    repo.config
5890
        .set("remote.origin.url", &origin.to_string_lossy())
5891
        .unwrap();
5892
    repo.config
5893
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
5894
        .unwrap();
5895
    repo.config.set("remote.down.token", "t").unwrap();
5896
    repo.config
5897
        .set("remote.badca.url", "https://example.invalid/a/b")
5898
        .unwrap();
5899
    repo.config
5900
        .set(
5901
            "remote.badca.ca",
5902
            &root.join("missing.pem").to_string_lossy(),
5903
        )
5904
        .unwrap();
5905
    repo.save_config().unwrap();
5906
5907
    let r = repo.doctor(true);
5908
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
5909
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
5910
    assert!(find(&r, "remote origin", Health::Ok)
5911
        .unwrap()
5912
        .message
5913
        .contains("first push binds it"));
5914
    let down = find(&r, "remote down", Health::Fail).unwrap();
5915
    assert!(
5916
        down.hint.as_deref().unwrap_or("").contains("running"),
5917
        "{down:?}"
5918
    );
5919
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
5920
    assert!(
5921
        badca.hint.unwrap().contains("remote.badca.ca"),
5922
        "the remote's own name is in the hint"
5923
    );
5924
    assert_eq!(r.worst(), Health::Fail);
5925
5926
    // Offline, nothing is contacted.
5927
    let r = repo.doctor(false);
5928
    assert!(find(&r, "remote down", Health::Fail).is_none());
5929
    assert!(find(&r, "remote down", Health::Ok)
5930
        .unwrap()
5931
        .message
5932
        .contains("not contacted"));
5933
}
5934
5935
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
5936
/// after it. Inserting after `b` and then deleting `b`, one commit after
5937
/// the other, must not leave a delete/insert conflict.
5938
#[test]
5939
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
5940
    hermetic();
5941
    let dir = tempfile::tempdir().unwrap();
5942
    let root = dir.path();
5943
    let repo = Repo::init(root).unwrap();
5944
    write(root, "f", b"a\nb\nc\n");
5945
    repo.commit("base", &[]).unwrap();
5946
    write(root, "f", b"a\nb\nx\nc\n");
5947
    let insert = repo.commit("insert x after b", &[]).unwrap();
5948
    write(root, "f", b"a\nx\nc\n");
5949
    let delete = repo.commit("delete b", &[]).unwrap();
5950
    assert!(
5951
        repo.store()
5952
            .get_change(&delete)
5953
            .unwrap()
5954
            .deps
5955
            .contains(&insert),
5956
        "the deletion depends on the insertion below the deleted line"
5957
    );
5958
    let heads = repo.bookmark_heads().unwrap();
5959
    assert_eq!(heads, vec![delete]);
5960
    let snap = repo.load_state(&heads).unwrap().materialize();
5961
    assert!(!snap.is_conflicted());
5962
    assert!(
5963
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
5964
    );
5965
}
5966
5967
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
5968
/// replacement depends on the change that set the blob it replaces.
5969
#[test]
5970
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
5971
    hermetic();
5972
    let dir = tempfile::tempdir().unwrap();
5973
    let root = dir.path();
5974
    let repo = Repo::init(root).unwrap();
5975
    write(root, "bin", b"\0A");
5976
    let v1 = repo.commit("v1", &[]).unwrap();
5977
    write(root, "bin", b"\0B");
5978
    let v2 = repo.commit("v2", &[]).unwrap();
5979
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
5980
    write(root, "bin", b"\0A");
5981
    let v3 = repo.commit("back to A", &[]).unwrap();
5982
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
5983
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
5984
    let state = repo.load_state(&[v3]).unwrap();
5985
    let snap = state.materialize();
5986
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
5987
        panic!("opaque")
5988
    };
5989
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
5990
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
5991
}
5992
5993
/// Spec §23: a binary file changed on two branches and merged in Git to
5994
/// one side's version comes back as that version at the merge, and the
5995
/// import verifies commit by commit.
5996
#[test]
5997
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
5998
    hermetic();
5999
    if std::process::Command::new("git")
6000
        .arg("--version")
6001
        .output()
6002
        .is_err()
6003
    {
6004
        eprintln!("git not installed; skipping");
6005
        return;
6006
    }
6007
    let dir = tempfile::tempdir().unwrap();
6008
    let root = dir.path();
6009
    let g = root.join("src.git");
6010
    fs::create_dir_all(&g).unwrap();
6011
    let git = |args: &[&str]| -> String {
6012
        let out = std::process::Command::new("git")
6013
            .arg("-C")
6014
            .arg(&g)
6015
            .args([
6016
                "-c",
6017
                "user.name=Grace",
6018
                "-c",
6019
                "[email protected]",
6020
                "-c",
6021
                "commit.gpgsign=false",
6022
            ])
6023
            .args(args)
6024
            .output()
6025
            .unwrap();
6026
        assert!(
6027
            out.status.success(),
6028
            "git {args:?}: {}",
6029
            String::from_utf8_lossy(&out.stderr)
6030
        );
6031
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6032
    };
6033
    git(&["init", "-q", "-b", "main"]);
6034
    write(&g, "logo.bin", b"\0base");
6035
    write(&g, "notes.txt", b"a\nb\nc\n");
6036
    git(&["add", "."]);
6037
    git(&["commit", "-qm", "base"]);
6038
    git(&["checkout", "-qb", "side"]);
6039
    write(&g, "logo.bin", b"\0side");
6040
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
6041
    git(&["commit", "-qam", "side"]);
6042
    git(&["checkout", "-q", "main"]);
6043
    write(&g, "logo.bin", b"\0main");
6044
    git(&["commit", "-qam", "main"]);
6045
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
6046
    let _ = std::process::Command::new("git")
6047
        .arg("-C")
6048
        .arg(&g)
6049
        .args([
6050
            "-c",
6051
            "user.name=G",
6052
            "-c",
6053
            "user.email=g@e",
6054
            "merge",
6055
            "-q",
6056
            "side",
6057
        ])
6058
        .output();
6059
    write(&g, "logo.bin", b"\0main");
6060
    git(&["add", "."]);
6061
    git(&["commit", "-qm", "merge side"]);
6062
    // Then a revert of the binary to its first version.
6063
    write(&g, "logo.bin", b"\0base");
6064
    git(&["commit", "-qam", "back to base"]);
6065
6066
    let repo = Repo::init(&root.join("o")).unwrap();
6067
    let rep = repo.import_git(&g, "main").unwrap();
6068
    assert_eq!(rep.merges, 1);
6069
    let v = repo.verify_git_import(&g, "main").unwrap();
6070
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6071
    assert_eq!(v.commits, 5);
6072
    let snap = repo
6073
        .load_state(&repo.bookmark_heads().unwrap())
6074
        .unwrap()
6075
        .materialize();
6076
    assert!(!snap.is_conflicted());
6077
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
6078
        panic!("opaque")
6079
    };
6080
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
6081
}
6082
6083
/// Spec §7.7 on a file system without executable bits or symlinks: the
6084
/// recorded bit is kept, and a symlink checked out as a plain file holding
6085
/// its target is still that symlink.
6086
#[cfg(unix)]
6087
#[test]
6088
fn windows_file_systems_keep_exec_bits_and_symlinks() {
6089
    use crate::portable::Platform;
6090
    use std::os::unix::fs::PermissionsExt;
6091
    hermetic();
6092
    let dir = tempfile::tempdir().unwrap();
6093
    let root = dir.path();
6094
    let repo = Repo::init(root).unwrap();
6095
    write(root, "run.sh", b"#!/bin/sh\n");
6096
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
6097
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
6098
    repo.commit("script and link", &[]).unwrap();
6099
    drop(repo);
6100
6101
    // What checking out on Windows leaves: no exec bit, the link as a file.
6102
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
6103
    fs::remove_file(root.join("link")).unwrap();
6104
    write(root, "link", b"run.sh");
6105
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
6106
    let s = win.snapshot("oxy status").unwrap();
6107
    assert!(
6108
        s.statuses.is_empty(),
6109
        "nothing changed on Windows: {:?}",
6110
        statuses(&s)
6111
    );
6112
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
6113
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
6114
    write(root, "link", b"other");
6115
    let h = win.commit("edit on Windows", &[]).unwrap();
6116
    let snap = win.load_state(&[h]).unwrap().materialize();
6117
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
6118
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
6119
    // The same working copy read as Linux sees the lost bit and the plain file.
6120
    let linux = Repo::open(root).unwrap();
6121
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
6122
}
6123
6124
/// Paths that collide on case-insensitive or Windows file systems are
6125
/// named at checkout there, and by doctor everywhere.
6126
#[test]
6127
fn paths_other_platforms_cannot_hold_are_reported() {
6128
    use crate::portable::Platform;
6129
    hermetic();
6130
    let dir = tempfile::tempdir().unwrap();
6131
    let root = dir.path();
6132
    let repo = Repo::init(root).unwrap();
6133
    write(root, "README.md", b"a\n");
6134
    write(root, "readme.md", b"b\n");
6135
    write(root, "src/aux.c", b"int x;\n");
6136
    let h = repo.commit("unportable", &[]).unwrap();
6137
    let r = repo.doctor(false);
6138
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
6139
    assert_eq!(port.health, Health::Warn);
6140
    assert!(
6141
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
6142
        "{}",
6143
        port.message
6144
    );
6145
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
6146
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
6147
    assert!(
6148
        rep.notes
6149
            .iter()
6150
            .any(|n| n.contains("README.md and readme.md")),
6151
        "{:?}",
6152
        rep.notes
6153
    );
6154
    assert!(
6155
        !rep.notes.iter().any(|n| n.contains("aux.c")),
6156
        "macOS allows aux.c"
6157
    );
6158
}
6159
6160
#[test]
6161
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
6162
    hermetic();
6163
    let dir = tempfile::tempdir().unwrap();
6164
    let repo = Repo::init(dir.path()).unwrap();
6165
    write(dir.path(), "a.txt", b"one\n");
6166
    write(dir.path(), "other.txt", b"x\n");
6167
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
6168
    repo.snapshot("t").unwrap();
6169
    let c1 = repo.commit("first", &[]).unwrap();
6170
    write(dir.path(), "other.txt", b"y\n");
6171
    repo.snapshot("t").unwrap();
6172
    repo.commit("other only", &[]).unwrap();
6173
    write(dir.path(), "a.txt", b"one\ntwo\n");
6174
    repo.snapshot("t").unwrap();
6175
    let c3 = repo.commit("second line", &[]).unwrap();
6176
    write(dir.path(), "other.txt", b"z\n");
6177
    repo.snapshot("t").unwrap();
6178
    repo.commit("other again", &[]).unwrap();
6179
6180
    let heads = repo.bookmark_heads().unwrap();
6181
    let state = repo.load_state(&heads).unwrap();
6182
    let full: Vec<ChangeHash> = repo
6183
        .log_for_path_in("a.txt", &heads)
6184
        .unwrap()
6185
        .iter()
6186
        .map(|e| e.hash)
6187
        .collect();
6188
    assert_eq!(
6189
        full,
6190
        vec![c3, c1],
6191
        "newest first, only changes touching the path"
6192
    );
6193
    let newest: Vec<ChangeHash> = repo
6194
        .log_for_path_of(&state, "a.txt", Some(1))
6195
        .unwrap()
6196
        .iter()
6197
        .map(|e| e.hash)
6198
        .collect();
6199
    assert_eq!(newest, vec![c3], "stops at the first");
6200
    assert_eq!(
6201
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
6202
        2
6203
    );
6204
    assert!(repo
6205
        .log_for_path_of(&state, "missing.txt", Some(1))
6206
        .is_err());
6207
    assert_eq!(
6208
        repo.log_state(&heads).unwrap().len(),
6209
        repo.log_of(&state).len()
6210
    );
6211
6212
    let tree = state.tree().view();
6213
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
6214
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
6215
    assert_eq!(
6216
        via_state
6217
            .iter()
6218
            .map(|l| (l.hash, l.text.clone()))
6219
            .collect::<Vec<_>>(),
6220
        via_heads
6221
            .iter()
6222
            .map(|l| (l.hash, l.text.clone()))
6223
            .collect::<Vec<_>>()
6224
    );
6225
    assert_eq!(
6226
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
6227
        vec![c1, c3]
6228
    );
6229
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
6230
}
6231
6232
/// A text file whose stat matches the manifest and whose recorded hash is
6233
/// the base's content is taken from the base without reading it; anything
6234
/// else is read, so no edit is missed (spec §12.3).
6235
#[cfg(unix)]
6236
#[test]
6237
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
6238
    use std::os::unix::fs::PermissionsExt;
6239
    hermetic();
6240
    let dir = tempfile::tempdir().unwrap();
6241
    let root = dir.path();
6242
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6243
    write(root, "a.txt", b"one\ntwo\n");
6244
    write(root, "b.txt", b"bee\n");
6245
    repo.commit("base", &[]).unwrap();
6246
    let age = |p: &str| {
6247
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6248
        fs::File::options()
6249
            .write(true)
6250
            .open(root.join(p))
6251
            .unwrap()
6252
            .set_modified(old)
6253
            .unwrap();
6254
    };
6255
    age("a.txt");
6256
    age("b.txt");
6257
    assert!(
6258
        !repo.snapshot("status").unwrap().changed,
6259
        "records the aged stat"
6260
    );
6261
6262
    // Clean and equal to the base: not read at all.
6263
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6264
    let snap = repo.snapshot("status").unwrap();
6265
    assert!(
6266
        !snap.changed && snap.statuses.is_empty(),
6267
        "{:?}",
6268
        snap.statuses
6269
    );
6270
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6271
6272
    // An uncommitted edit that is older than the manifest: stat-clean, but
6273
    // its hash is not the base's, so it is read and stays visible.
6274
    write(root, "b.txt", b"bee edited\n");
6275
    age("b.txt");
6276
    let first = repo.snapshot("status").unwrap();
6277
    assert_eq!(
6278
        statuses(&first),
6279
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
6280
    );
6281
    let again = repo.snapshot("status").unwrap();
6282
    assert_eq!(
6283
        statuses(&again),
6284
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
6285
        "still seen once stat-clean"
6286
    );
6287
    assert!(!again.changed, "and the working copy hashes the same");
6288
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6289
    assert!(
6290
        repo.snapshot("status").is_err(),
6291
        "an edited file must be read, never taken from the base"
6292
    );
6293
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6294
6295
    // A same-size edit made just now is racy and read.
6296
    write(root, "a.txt", b"one\nTWO\n");
6297
    assert_eq!(
6298
        statuses(&repo.snapshot("status").unwrap()),
6299
        vec![
6300
            ("a.txt".to_string(), ChangeStatus::Modified),
6301
            ("b.txt".to_string(), ChangeStatus::Modified)
6302
        ]
6303
    );
6304
    // Committing makes the edits the base: both are clean and served from it again.
6305
    repo.commit("edits", &[]).unwrap();
6306
    age("a.txt");
6307
    age("b.txt");
6308
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6309
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6310
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6311
    let snap = repo.snapshot("status").unwrap();
6312
    assert!(!snap.changed && snap.statuses.is_empty());
6313
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6314
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6315
}
6316
6317
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
6318
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
6319
/// file is unchanged, and loading through the checkpoint equals a full load.
6320
#[test]
6321
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
6322
    hermetic();
6323
    let dir = tempfile::tempdir().unwrap();
6324
    let root = dir.path();
6325
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6326
    let long: String = (0..300)
6327
        .map(|i| format!("line {i} of a long file\n"))
6328
        .collect();
6329
    write(root, "long.txt", long.as_bytes());
6330
    write(root, "short.txt", b"short\n");
6331
    repo.commit("base", &[]).unwrap();
6332
    let (r1, _, _) = repo.checkpoint().unwrap();
6333
    let cp1 = crate::objects::Checkpoint::decode(
6334
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
6335
    )
6336
    .unwrap();
6337
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
6338
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
6339
6340
    // gc keeps the graph blob; fsck finds the checkpoint sound.
6341
    repo.gc(true).unwrap();
6342
    assert!(repo.store().has(&graphs1[0]));
6343
    let report = repo.fsck().unwrap();
6344
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
6345
6346
    // Loading through the checkpoint equals a full load.
6347
    write(root, "short.txt", b"short, edited\n");
6348
    repo.commit("edit the short file", &[]).unwrap();
6349
    let heads = repo.bookmark_heads().unwrap();
6350
    let fast = repo.load_state(&heads).unwrap();
6351
    let full = repo.load_state_full(&heads).unwrap();
6352
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
6353
6354
    // The next checkpoint shares the unchanged long file's graph.
6355
    let (r2, _, _) = repo.checkpoint().unwrap();
6356
    let cp2 = crate::objects::Checkpoint::decode(
6357
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
6358
    )
6359
    .unwrap();
6360
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
6361
6362
    // A shallow clone's bundle carries the graph blob with the checkpoint.
6363
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
6364
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
6365
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
6366
6367
    // A version 1 checkpoint written by an older oxy still loads.
6368
    let state = repo.load_state_full(&heads).unwrap();
6369
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
6370
    let cp_old = crate::objects::Checkpoint {
6371
        heads: cp2.heads.clone(),
6372
        count: cp2.count,
6373
        payload: old,
6374
    };
6375
    let r_old = repo
6376
        .store()
6377
        .put(ObjectType::Checkpoint, &cp_old.encode())
6378
        .unwrap();
6379
    repo.install_checkpoint("main", &r_old).unwrap();
6380
    assert_eq!(
6381
        repo.load_state(&heads).unwrap().checkpoint_payload(),
6382
        full.checkpoint_payload()
6383
    );
6384
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6385
6386
    // A lost graph blob fails the load loudly rather than dropping the
6387
    // file, and fsck reports it (a fresh repository, objects still loose).
6388
    let dir2 = tempfile::tempdir().unwrap();
6389
    let root2 = dir2.path();
6390
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
6391
    write(root2, "long.txt", long.as_bytes());
6392
    repo2.commit("base", &[]).unwrap();
6393
    let (r, _, _) = repo2.checkpoint().unwrap();
6394
    let cp = crate::objects::Checkpoint::decode(
6395
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
6396
    )
6397
    .unwrap();
6398
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
6399
    repo2.store().remove_loose_for_test(&graph).unwrap();
6400
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
6401
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
6402
}
6403
6404
/// A new repository has not stored the user's identity yet (that happens
6405
/// at the first signed change); looking it up falls back to the key
6406
/// directory, and a file there that does not hash to the key is refused.
6407
#[test]
6408
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
6409
    hermetic();
6410
    let dir = tempfile::tempdir().unwrap();
6411
    let home = dir.path().join("home");
6412
    let mut first = Repo::init(&dir.path().join("a"))
6413
        .unwrap()
6414
        .with_home(home.clone());
6415
    let (key, _) = first
6416
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6417
        .unwrap();
6418
    let fresh = Repo::init(&dir.path().join("b"))
6419
        .unwrap()
6420
        .with_home(home.clone());
6421
    assert!(!fresh.store().has(&key), "nothing stored yet");
6422
    let id = fresh.identity(&key).unwrap();
6423
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
6424
    // A key file that is not this identity is an error, not a wrong answer.
6425
    let keys = fresh.keys_dir.clone();
6426
    let (other, _) = first
6427
        .create_identity("Bob", "[email protected]", IdentityScope::User)
6428
        .unwrap();
6429
    fs::copy(
6430
        keys.join(format!("{}.identity", other.to_hex())),
6431
        keys.join(format!("{}.identity", key.to_hex())),
6432
    )
6433
    .unwrap();
6434
    assert!(fresh
6435
        .identity(&key)
6436
        .unwrap_err()
6437
        .to_string()
6438
        .contains("does not hold identity"));
6439
}
6440
6441
/// Status snapshots (spec §12.3): a text file whose stat matches the
6442
/// manifest, and whose base graph key is the one the manifest recorded it
6443
/// equal to, is neither read nor rendered; any edit, and any change to the
6444
/// file's graph in the base, brings it back.
6445
#[cfg(unix)]
6446
#[test]
6447
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
6448
    use std::os::unix::fs::PermissionsExt;
6449
    hermetic();
6450
    let dir = tempfile::tempdir().unwrap();
6451
    let root = dir.path();
6452
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6453
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
6454
        write(root, p, c.as_bytes());
6455
    }
6456
    repo.commit("base", &[]).unwrap();
6457
    let age = |p: &str| {
6458
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6459
        fs::File::options()
6460
            .write(true)
6461
            .open(root.join(p))
6462
            .unwrap()
6463
            .set_modified(old)
6464
            .unwrap();
6465
    };
6466
    let lock = |p: &str, mode: u32| {
6467
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
6468
    };
6469
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6470
        age(p);
6471
    }
6472
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6473
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6474
    assert!(
6475
        m.entries.values().all(|e| e.graph.is_some()),
6476
        "keys recorded"
6477
    );
6478
6479
    // Unreadable files prove they are not read; the status snapshot does
6480
    // not render them either, and its base lacks their graphs.
6481
    lock("a.txt", 0o000);
6482
    lock("b.txt", 0o000);
6483
    let snap = repo.snapshot_status("status").unwrap();
6484
    assert!(!snap.changed && snap.statuses.is_empty());
6485
    assert_eq!(
6486
        snap.base_snapshot
6487
            .unrendered
6488
            .iter()
6489
            .cloned()
6490
            .collect::<Vec<_>>(),
6491
        vec!["a.txt", "b.txt", "d/c.txt"]
6492
    );
6493
    assert!(!snap.base.is_full());
6494
    assert!(!snap.base_snapshot.is_conflicted());
6495
    // A full snapshot does not read them either, but renders everything.
6496
    let full = repo.snapshot("status").unwrap();
6497
    assert!(full.statuses.is_empty() && full.base.is_full());
6498
    assert!(full.base_snapshot.unrendered.is_empty());
6499
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
6500
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
6501
6502
    // An edit is seen; the file is rendered, the others still are not.
6503
    write(root, "d/c.txt", b"sea edited\n");
6504
    let snap = repo.snapshot_status("status").unwrap();
6505
    assert_eq!(
6506
        statuses(&snap),
6507
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
6508
    );
6509
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
6510
    // So is a mode change of an unread file.
6511
    lock("b.txt", 0o100);
6512
    assert_eq!(
6513
        statuses(&repo.snapshot_status("status").unwrap()),
6514
        vec![
6515
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
6516
            ("d/c.txt".to_string(), ChangeStatus::Modified)
6517
        ]
6518
    );
6519
    lock("b.txt", 0o000);
6520
6521
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
6522
    // stays unread, c.txt is read once and then skipped too.
6523
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
6524
        .unwrap();
6525
    age("d/c.txt");
6526
    let snap = repo.snapshot_status("status").unwrap();
6527
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
6528
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
6529
    lock("d/c.txt", 0o000);
6530
    let snap = repo.snapshot_status("status").unwrap();
6531
    assert!(snap.statuses.is_empty());
6532
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
6533
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6534
        lock(p, 0o644);
6535
    }
6536
}
6537
6538
/// Attributes decide how a file compares with the base, so a changed
6539
/// `.oxyattributes` makes every text file be compared again.
6540
#[cfg(unix)]
6541
#[test]
6542
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
6543
    hermetic();
6544
    let dir = tempfile::tempdir().unwrap();
6545
    let root = dir.path();
6546
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6547
    write(root, "a.txt", b"crlf\r\n");
6548
    repo.commit("base", &[]).unwrap();
6549
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6550
    fs::File::options()
6551
        .write(true)
6552
        .open(root.join("a.txt"))
6553
        .unwrap()
6554
        .set_modified(old)
6555
        .unwrap();
6556
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6557
    assert!(repo
6558
        .snapshot_status("status")
6559
        .unwrap()
6560
        .base_snapshot
6561
        .unrendered
6562
        .contains("a.txt"));
6563
    // With eol=lf, a.txt as stored no longer equals the base.
6564
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
6565
    let snap = repo.snapshot_status("status").unwrap();
6566
    assert_eq!(
6567
        statuses(&snap),
6568
        vec![
6569
            (".oxyattributes".to_string(), ChangeStatus::Added),
6570
            ("a.txt".to_string(), ChangeStatus::Modified)
6571
        ]
6572
    );
6573
}
6574
6575
/// Bookmarks with `/` in their names: pushing records their
6576
/// attestations, and checkpoints are kept for them, beside `feature`
6577
/// itself.
6578
#[test]
6579
fn bookmarks_with_slashes_push_and_checkpoint() {
6580
    hermetic();
6581
    let dir = tempfile::tempdir().unwrap();
6582
    let root = dir.path();
6583
    let origin = Repo::init(&root.join("origin")).unwrap();
6584
    let url = root.join("origin").to_string_lossy().to_string();
6585
    let mut repo = Repo::clone(&url, &root.join("r"))
6586
        .unwrap()
6587
        .with_home(root.join("home"));
6588
    // With an identity, pushes carry reference attestations: the case
6589
    // that failed, since the attestation is a file named after the bookmark.
6590
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6591
        .unwrap();
6592
    let r = root.join("r");
6593
    write(&r, "a.txt", b"a\n");
6594
    let h_a = repo.commit("a", &[]).unwrap();
6595
    assert!(repo.push("origin", false).unwrap()[0].ok);
6596
    origin.refresh().unwrap();
6597
    repo.bookmark_create("feature", None).unwrap();
6598
    repo.bookmark_create("feature/x", None).unwrap();
6599
    repo.bookmark_switch("feature/x", false).unwrap();
6600
    write(&r, "b.txt", b"b\n");
6601
    let h_b = repo.commit("b", &[]).unwrap();
6602
    for name in ["feature", "feature/x"] {
6603
        let res = repo.push_bookmark("origin", name, false).unwrap();
6604
        origin.refresh().unwrap();
6605
        assert!(res[0].ok, "{name}: {res:?}");
6606
    }
6607
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
6608
    assert_eq!(
6609
        origin.resolve_heads("feature/x").unwrap(),
6610
        repo.resolve_heads("feature/x").unwrap()
6611
    );
6612
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
6613
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
6614
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
6615
6616
    // A checkpoint of feature/x is found again when loading its state.
6617
    let (cp, _, _) = repo.checkpoint().unwrap();
6618
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
6619
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
6620
    let heads = repo.resolve_heads("feature/x").unwrap();
6621
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
6622
}
6623
6624
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
6625
/// never the remote's own bookmark, and a bookmark created again later is
6626
/// accepted although the deletion's attestation stays the latest.
6627
#[test]
6628
fn bookmarks_are_deleted_on_a_remote() {
6629
    hermetic();
6630
    let dir = tempfile::tempdir().unwrap();
6631
    let root = dir.path();
6632
    let origin = Repo::init(&root.join("origin")).unwrap();
6633
    let url = root.join("origin").to_string_lossy().to_string();
6634
    let mut repo = Repo::clone(&url, &root.join("r"))
6635
        .unwrap()
6636
        .with_home(root.join("home"));
6637
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6638
        .unwrap();
6639
    let r = root.join("r");
6640
    write(&r, "a.txt", b"a\n");
6641
    repo.commit("a", &[]).unwrap();
6642
    assert!(repo.push("origin", false).unwrap()[0].ok);
6643
    origin.refresh().unwrap();
6644
    repo.bookmark_create("feature/x", None).unwrap();
6645
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
6646
    origin.refresh().unwrap();
6647
    assert!(origin.resolve_heads("feature/x").is_ok());
6648
6649
    let res = repo.push_delete("origin", "feature/x").unwrap();
6650
    origin.refresh().unwrap();
6651
    assert!(res[0].ok, "{res:?}");
6652
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
6653
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
6654
    assert!(
6655
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
6656
        "the deletion is attested"
6657
    );
6658
    assert!(
6659
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
6660
        "the local bookmark stays"
6661
    );
6662
    assert!(!repo
6663
        .view()
6664
        .unwrap()
6665
        .remotes
6666
        .get("origin")
6667
        .is_some_and(|m| m.contains_key("feature/x")));
6668
6669
    // Pushing it again creates it again, past the deletion's serial.
6670
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
6671
    origin.refresh().unwrap();
6672
    assert!(res[0].ok, "{res:?}");
6673
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
6674
6675
    // Nothing to delete, and never the remote's own bookmark.
6676
    assert!(repo.push_delete("origin", "nope").is_err());
6677
    let res = repo.push_delete("origin", "main").unwrap();
6678
    origin.refresh().unwrap();
6679
    assert!(
6680
        !res[0].ok && res[0].reason.contains("default bookmark"),
6681
        "{res:?}"
6682
    );
6683
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
6684
}
6685
6686
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
6687
/// when the target has the same versions of the files it touches, and is
6688
/// refused, untouched, when it has others.
6689
#[test]
6690
fn switching_bookmarks_carries_uncommitted_work() {
6691
    hermetic();
6692
    let dir = tempfile::tempdir().unwrap();
6693
    let root = dir.path();
6694
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6695
    write(root, "a.txt", b"a\n");
6696
    write(root, "b.txt", b"b\n");
6697
    write(root, "gone.txt", b"gone\n");
6698
    repo.commit("base", &[]).unwrap();
6699
    repo.bookmark_create("feature", None).unwrap();
6700
    // Started on main, belongs on feature: edit, add, remove.
6701
    write(root, "a.txt", b"a\nmore\n");
6702
    write(root, "new.txt", b"new\n");
6703
    fs::remove_file(root.join("gone.txt")).unwrap();
6704
    let (report, carried) = repo.bookmark_switch_carry("feature").unwrap();
6705
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
6706
    // oxygen#120: the new file was carried, not removed.
6707
    assert_eq!(
6708
        (report.removed, report.removed_paths.len()),
6709
        (0, 0),
6710
        "{report:?}"
6711
    );
6712
    assert_eq!(repo.config.bookmark, "feature");
6713
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
6714
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
6715
    assert!(!root.join("gone.txt").exists());
6716
    let snap = repo.snapshot("status").unwrap();
6717
    assert_eq!(
6718
        statuses(&snap),
6719
        vec![
6720
            ("a.txt".to_string(), ChangeStatus::Modified),
6721
            ("gone.txt".to_string(), ChangeStatus::Removed),
6722
            ("new.txt".to_string(), ChangeStatus::Added)
6723
        ]
6724
    );
6725
    repo.commit("the work", &[]).unwrap();
6726
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
6727
6728
    // main moves b.txt on; work on feature touching b.txt cannot follow.
6729
    repo.bookmark_switch("main", false).unwrap();
6730
    write(root, "b.txt", b"b on main\n");
6731
    repo.commit("b on main", &[]).unwrap();
6732
    repo.bookmark_switch("feature", false).unwrap();
6733
    write(root, "b.txt", b"b edited\n");
6734
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
6735
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
6736
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
6737
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
6738
}
6739
6740
/// Merging and checking out (feedback 3): a working copy without changes
6741
/// follows a merge whichever state it sat on; a refused checkout names
6742
/// what is in the way; `checkout --carry` takes the work along.
6743
#[test]
6744
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
6745
    hermetic();
6746
    let dir = tempfile::tempdir().unwrap();
6747
    let root = dir.path();
6748
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6749
    write(root, "a.txt", b"a\n");
6750
    let h1 = repo.commit("a", &[]).unwrap();
6751
    write(root, "b.txt", b"b\n");
6752
    repo.commit("b", &[]).unwrap();
6753
    repo.bookmark_create("feature", None).unwrap();
6754
    repo.bookmark_switch("feature", false).unwrap();
6755
    write(root, "c.txt", b"c\n");
6756
    repo.commit("c on feature", &[]).unwrap();
6757
    repo.bookmark_switch("main", false).unwrap();
6758
    // The working copy sits on an older state than main's heads.
6759
    repo.checkout(&[h1], false, "checkout").unwrap();
6760
    assert!(!root.join("b.txt").exists());
6761
    let m = repo.merge("feature").unwrap();
6762
    assert!(m.checked_out, "a clean working copy follows the merge");
6763
    for f in ["a.txt", "b.txt", "c.txt"] {
6764
        assert!(root.join(f).exists(), "{f}");
6765
    }
6766
6767
    // A refusal says which paths are in the way and what to do.
6768
    fs::remove_file(root.join("b.txt")).unwrap();
6769
    write(root, "a.txt", b"a edited\n");
6770
    let err = repo
6771
        .checkout(&[h1], false, "checkout")
6772
        .unwrap_err()
6773
        .to_string();
6774
    assert!(
6775
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
6776
        "{err}"
6777
    );
6778
    // --carry takes them along: h1 has a.txt as the base has it, and the
6779
    // removed b.txt is already as h1 has it (none), so that is no conflict
6780
    // either (oxygen#100).
6781
    let (_, carried) = repo
6782
        .checkout_carry(&[h1], "the first change", "checkout")
6783
        .unwrap();
6784
    assert_eq!(carried, vec!["a.txt"]);
6785
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
6786
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
6787
}
6788
6789
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
6790
/// user identity not stored in a new repository yet is fine while its
6791
/// secret key is there; an added subrepo is listed as not committed yet.
6792
#[test]
6793
fn a_new_repository_is_healthy_before_its_first_commit() {
6794
    hermetic();
6795
    let dir = tempfile::tempdir().unwrap();
6796
    let root = dir.path();
6797
    let home = root.join("home");
6798
    let mut first = Repo::init(&root.join("first"))
6799
        .unwrap()
6800
        .with_home(home.clone());
6801
    let (key, _) = first
6802
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6803
        .unwrap();
6804
    let repo = Repo::init(&root.join("second"))
6805
        .unwrap()
6806
        .with_home(home.clone());
6807
    // Only the secret key: no identity object anywhere this repository sees.
6808
    let keys = repo.keys_dir.clone();
6809
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
6810
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
6811
    let r = repo.doctor(true);
6812
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
6813
    assert_eq!(id.health, Health::Ok, "{}", id.message);
6814
    assert!(id.message.contains("first signed change"), "{}", id.message);
6815
6816
    // A subrepo added and not committed yet is listed, pinned where it is.
6817
    let lib = root.join("lib");
6818
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
6819
    write(&lib, "x.txt", b"x\n");
6820
    l.commit("x", &[]).unwrap();
6821
    let second = root.join("second");
6822
    write(&second, "a.txt", b"a\n");
6823
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
6824
        .unwrap();
6825
    let subs = repo.subrepos().unwrap();
6826
    assert_eq!(subs.len(), 1);
6827
    assert_eq!(
6828
        (subs[0].path.as_str(), subs[0].committed),
6829
        ("deps/lib", false)
6830
    );
6831
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
6832
    repo.commit("add lib", &[]).unwrap();
6833
    let subs = repo.subrepos().unwrap();
6834
    assert!(subs[0].committed, "committed now");
6835
}
6836
6837
/// Commit, diff, hunks and discard use the partial snapshot: a file
6838
/// unchanged since the manifest is neither read nor rendered, and showing
6839
/// a change renders only what it edits, the same as from a full base.
6840
#[cfg(unix)]
6841
#[test]
6842
fn commits_and_diffs_leave_unchanged_files_alone() {
6843
    use std::os::unix::fs::PermissionsExt;
6844
    hermetic();
6845
    let dir = tempfile::tempdir().unwrap();
6846
    let root = dir.path();
6847
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6848
    write(root, "big.txt", b"lots\nof\nlines\n");
6849
    write(root, "a.txt", b"one\ntwo\n");
6850
    repo.commit("base", &[]).unwrap();
6851
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6852
    for f in ["big.txt", "a.txt"] {
6853
        fs::File::options()
6854
            .write(true)
6855
            .open(root.join(f))
6856
            .unwrap()
6857
            .set_modified(old)
6858
            .unwrap();
6859
    }
6860
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6861
    // big.txt cannot be read at all from here on.
6862
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6863
6864
    write(root, "a.txt", b"one\nTWO\nthree\n");
6865
    let diff = repo.diff_files(None).unwrap();
6866
    assert_eq!(
6867
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
6868
        ["a.txt"]
6869
    );
6870
    let (_, hunks) = repo.hunks().unwrap();
6871
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
6872
    let h = repo.commit("edit a", &[]).unwrap();
6873
6874
    // Showing the change needs only a.txt's graph, and renders as a full base does.
6875
    let c = repo.store().get_change(&h).unwrap();
6876
    let full = repo.load_state(&c.deps).unwrap();
6877
    let want = render_change(&c, &full, &full.materialize());
6878
    assert_eq!(repo.describe_change(&h).unwrap(), want);
6879
    let (base, snap) = repo.change_base(&c).unwrap();
6880
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
6881
6882
    // Discarding works the same way.
6883
    write(root, "a.txt", b"scratch\n");
6884
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
6885
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
6886
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6887
}
6888
6889
/// A replace conflict (spec §9.3) is settled by a change that writes one
6890
/// candidate, or new bytes, at the path when the caller names it; a plain
6891
/// snapshot of a checkout never settles it on its own.
6892
#[test]
6893
fn replace_conflicts_are_settled_when_asked() {
6894
    hermetic();
6895
    let dir = tempfile::tempdir().unwrap();
6896
    let root = dir.path();
6897
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
6898
    let blob = |n: u8| {
6899
        let mut v = vec![0u8; 64];
6900
        v[1] = n;
6901
        v
6902
    };
6903
    write(root, "img.bin", &blob(1));
6904
    repo.commit("add img", &[]).unwrap();
6905
    repo.bookmark_create("other", None).unwrap();
6906
    write(root, "img.bin", &blob(2));
6907
    repo.commit("img two", &[]).unwrap();
6908
    repo.bookmark_switch("other", false).unwrap();
6909
    write(root, "img.bin", &blob(3));
6910
    repo.commit("img three", &[]).unwrap();
6911
    repo.bookmark_switch("main", false).unwrap();
6912
    repo.merge("other").unwrap();
6913
    let heads = repo.bookmark_heads().unwrap();
6914
    let merged = repo.load_state(&heads).unwrap().materialize();
6915
    assert!(
6916
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
6917
        "a replace conflict"
6918
    );
6919
    // A snapshot of the checkout records nothing.
6920
    assert!(repo
6921
        .snapshot("status")
6922
        .unwrap()
6923
        .statuses
6924
        .iter()
6925
        .all(|s| s.path != "img.bin"));
6926
6927
    // Keeping candidate 3 settles it.
6928
    let author = repo.author();
6929
    let edits = [FileEdit {
6930
        path: "img.bin".into(),
6931
        content: Some(blob(3)),
6932
    }];
6933
    let c = repo
6934
        .build_change(&heads, &edits, "keep three", author)
6935
        .unwrap();
6936
    assert_eq!(c.kind, ChangeKind::Resolution);
6937
    let mut st = repo.load_state(&heads).unwrap();
6938
    for d in &c.deps {
6939
        assert!(st.contains(d));
6940
    }
6941
    assert!(
6942
        heads.iter().all(|h| c.deps.contains(h)),
6943
        "depends on both contributors"
6944
    );
6945
    st.add(c).unwrap();
6946
    let after = st.materialize();
6947
    assert!(!after.is_conflicted());
6948
    assert_eq!(
6949
        after.files["img.bin"].content,
6950
        FileContent::Opaque {
6951
            blobs: vec![Repo::blob_ref(&blob(3))]
6952
        }
6953
    );
6954
6955
    // New bytes settle it too.
6956
    let edits = [FileEdit {
6957
        path: "img.bin".into(),
6958
        content: Some(blob(9)),
6959
    }];
6960
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
6961
    let mut st = repo.load_state(&heads).unwrap();
6962
    st.add(c).unwrap();
6963
    assert_eq!(
6964
        st.materialize().files["img.bin"].content,
6965
        FileContent::Opaque {
6966
            blobs: vec![Repo::blob_ref(&blob(9))]
6967
        }
6968
    );
6969
}
6970
6971
/// The history of a range of lines (spec §27): the changes that wrote
6972
/// or deleted its atoms, or deleted atoms from between them; edits outside
6973
/// the range and changes the range's lines survived are not in it.
6974
#[test]
6975
fn line_ranges_have_exact_histories() {
6976
    hermetic();
6977
    let dir = tempfile::tempdir().unwrap();
6978
    let root = dir.path();
6979
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6980
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
6981
    let base = repo.commit("add f", &[]).unwrap();
6982
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
6983
    let outside = repo.commit("change the import", &[]).unwrap();
6984
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
6985
    let inside = repo.commit("edit a line of a", &[]).unwrap();
6986
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
6987
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
6988
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
6989
    let after = repo.commit("add b after a", &[]).unwrap();
6990
    let heads = repo.bookmark_heads().unwrap();
6991
6992
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
6993
    let hist: Vec<ChangeHash> = repo
6994
        .line_history(&heads, "f.rs", 2, 4)
6995
        .unwrap()
6996
        .iter()
6997
        .map(|e| e.hash)
6998
        .collect();
6999
    for (h, what) in [
7000
        (base, "wrote it"),
7001
        (inside, "edited a line"),
7002
        (deleted, "deleted a line from inside"),
7003
    ] {
7004
        assert!(hist.contains(&h), "{what}");
7005
    }
7006
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
7007
        assert!(!hist.contains(&h), "{what}");
7008
    }
7009
    assert_eq!(hist[0], deleted, "newest first");
7010
    // One line: only what touched it.
7011
    let one: Vec<ChangeHash> = repo
7012
        .line_history(&heads, "f.rs", 1, 1)
7013
        .unwrap()
7014
        .iter()
7015
        .map(|e| e.hash)
7016
        .collect();
7017
    assert!(one.contains(&outside) && !one.contains(&inside));
7018
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
7019
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
7020
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
7021
}
7022
7023
#[test]
7024
fn receipts_are_kept_with_their_state_and_verified() {
7025
    use crate::receipt::{Receipt, SignedReceipt};
7026
    hermetic();
7027
    let dir = tempfile::tempdir().unwrap();
7028
    let root = dir.path();
7029
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7030
    write(root, "a.txt", b"1\n");
7031
    repo.commit("A", &[]).unwrap();
7032
    let heads = repo.bookmark_heads().unwrap();
7033
    let state = repo
7034
        .store()
7035
        .put_state(&StateObject::new(heads.clone()))
7036
        .unwrap();
7037
    let out = repo.store_blob(b"built\n").unwrap();
7038
    let receipt = Receipt {
7039
        job_name: "build".into(),
7040
        pipeline_hash: ObjectRef([1; 32]),
7041
        scope_tree_hash: ObjectRef([2; 32]),
7042
        inputs: vec![],
7043
        environment: ObjectRef([3; 32]),
7044
        outputs: vec![out],
7045
        exit_code: 0,
7046
        duration_ms: 42,
7047
    };
7048
    let sk = SecretKey::generate();
7049
    let runner = sk.identity("earth-1", "runner@earth", 1);
7050
    let sr = SignedReceipt::sign(
7051
        receipt.clone(),
7052
        repo.id().unwrap(),
7053
        state,
7054
        "demo#1",
7055
        &runner,
7056
        &sk,
7057
    );
7058
7059
    let r = repo.add_receipt(&sr).unwrap();
7060
    let found = repo.receipts(&heads).unwrap();
7061
    assert_eq!(found.len(), 1);
7062
    assert_eq!(found[0].attest, r);
7063
    assert_eq!(found[0].signed, sr);
7064
    assert!(found[0].problem.is_none() && !found[0].revoked);
7065
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
7066
7067
    // Another repository's receipt, or a forged one, is refused.
7068
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
7069
    assert!(repo
7070
        .add_receipt(&elsewhere)
7071
        .unwrap_err()
7072
        .to_string()
7073
        .contains("another repository"));
7074
    let mut forged = sr.clone();
7075
    forged.receipt.exit_code = 1;
7076
    assert!(repo
7077
        .add_receipt(&forged)
7078
        .unwrap_err()
7079
        .to_string()
7080
        .contains("does not verify"));
7081
7082
    // A receipt signed by a short-lived key keeps its certificate and the
7083
    // issuer's identity, and reads back with them (oxygenhub#241).
7084
    let hub_sk = SecretKey::generate();
7085
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
7086
    let job_sk = SecretKey::generate();
7087
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
7088
    let mut test_receipt = receipt.clone();
7089
    test_receipt.job_name = "test".into();
7090
    let plain = SignedReceipt::sign(
7091
        test_receipt,
7092
        repo.id().unwrap(),
7093
        state,
7094
        "demo#2",
7095
        &job,
7096
        &job_sk,
7097
    );
7098
    let now = plain.attest.hlc.wall_ms;
7099
    let cert = crate::cert::SignedCertificate::sign(
7100
        crate::cert::Certificate {
7101
            key: job.clone(),
7102
            issuer: hub.hash(),
7103
            subject: "repo:andy/demo:bookmark:main".into(),
7104
            claims: vec![],
7105
            scope: crate::identity::Scope::SEAL,
7106
            not_before: now - 1_000,
7107
            expires: now + 600_000,
7108
            grant: None,
7109
        },
7110
        &hub,
7111
        &hub_sk,
7112
    );
7113
    let certified = plain.with_certificate(cert, hub.clone());
7114
    repo.add_receipt(&certified).unwrap();
7115
    let found = repo.receipts(&heads).unwrap();
7116
    let got = found
7117
        .iter()
7118
        .find(|i| i.signed.receipt.job_name == "test")
7119
        .unwrap();
7120
    assert_eq!(got.signed, certified);
7121
    assert!(got.problem.is_none(), "{:?}", got.problem);
7122
7123
    // gc keeps the receipts, their runners, the certificate and its issuer,
7124
    // and the output while the state lives.
7125
    repo.gc(true).unwrap();
7126
    let found = repo.receipts(&heads).unwrap();
7127
    assert_eq!(found.len(), 2);
7128
    let got = found
7129
        .iter()
7130
        .find(|i| i.signed.receipt.job_name == "test")
7131
        .unwrap();
7132
    assert_eq!(got.signed, certified, "the certificate survives gc");
7133
    assert!(got.problem.is_none());
7134
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
7135
    assert!(repo.fsck().unwrap().problems.is_empty());
7136
}
7137
7138
#[test]
7139
fn approvals_are_kept_with_their_state_and_survive_gc() {
7140
    hermetic();
7141
    let dir = tempfile::tempdir().unwrap();
7142
    let root = dir.path();
7143
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7144
    write(root, "a.txt", b"1\n");
7145
    repo.commit("A", &[]).unwrap();
7146
    let heads = repo.bookmark_heads().unwrap();
7147
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
7148
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
7149
    let sk = SecretKey::generate();
7150
    let andy = sk.identity("Andy", "[email protected]", 1);
7151
    let statement = crate::approval::Statement {
7152
        repo: repo.id().unwrap(),
7153
        run: "https://hub.example/andy/infra/flow/8".into(),
7154
        job: "apply".into(),
7155
        job_hash: ObjectRef([1; 32]),
7156
        state,
7157
        inputs: vec![plan],
7158
        environment: "prod".into(),
7159
        approve: true,
7160
    };
7161
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
7162
    let r = repo.add_approval(&sa).unwrap();
7163
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
7164
    // Another repository's approval, or a changed one, is refused.
7165
    let elsewhere = crate::approval::SignedApproval::sign(
7166
        &crate::approval::Statement {
7167
            repo: [0; 16],
7168
            ..statement.clone()
7169
        },
7170
        &andy,
7171
        &sk,
7172
    );
7173
    assert!(repo
7174
        .add_approval(&elsewhere)
7175
        .unwrap_err()
7176
        .to_string()
7177
        .contains("another repository"));
7178
    let mut forged = sa.clone();
7179
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
7180
        *environment = "dev".into();
7181
    }
7182
    assert!(repo
7183
        .add_approval(&forged)
7184
        .unwrap_err()
7185
        .to_string()
7186
        .contains("does not verify"));
7187
    // gc keeps it, its signature and its signer while the state lives.
7188
    repo.gc(true).unwrap();
7189
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
7190
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
7191
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
7192
    assert!(repo.fsck().unwrap().problems.is_empty());
7193
}
7194
7195
#[test]
7196
fn status_leaves_an_unchanged_manifest_alone() {
7197
    hermetic();
7198
    let dir = tempfile::tempdir().unwrap();
7199
    let root = dir.path();
7200
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7201
    write(root, "a.txt", b"1\n");
7202
    write(root, "b.txt", b"2\n");
7203
    repo.commit("A", &[]).unwrap();
7204
    // Files last touched well outside the racy window.
7205
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7206
    for f in ["a.txt", "b.txt"] {
7207
        fs::File::options()
7208
            .write(true)
7209
            .open(root.join(f))
7210
            .unwrap()
7211
            .set_modified(old)
7212
            .unwrap();
7213
    }
7214
    repo.snapshot_status("status").unwrap();
7215
    let path = repo.manifest_path();
7216
    let first = fs::read(&path).unwrap();
7217
    repo.snapshot_status("status").unwrap();
7218
    assert_eq!(
7219
        fs::read(&path).unwrap(),
7220
        first,
7221
        "an unchanged tree does not rewrite the manifest"
7222
    );
7223
    // A change rewrites it.
7224
    write(root, "a.txt", b"1\n2\n");
7225
    repo.snapshot_status("status").unwrap();
7226
    assert_ne!(fs::read(&path).unwrap(), first);
7227
}
7228
7229
#[test]
7230
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
7231
    hermetic();
7232
    let dir = tempfile::tempdir().unwrap();
7233
    let root = dir.path();
7234
    let origin_path = root.join("origin");
7235
    Repo::init(&origin_path).unwrap();
7236
    let origin_url = origin_path.to_string_lossy().to_string();
7237
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
7238
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
7239
    write(&root.join("a"), "big.txt", big.as_bytes());
7240
    write(&root.join("a"), "small.txt", b"small\n");
7241
    let h1 = a.commit("large", &[]).unwrap();
7242
    let (_, body) = a.store().get(&h1).unwrap();
7243
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
7244
    assert!(a.push("origin", false).unwrap()[0].ok);
7245
7246
    // A clone reads the text from the blobs that came with the change.
7247
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
7248
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
7249
    // An edit in the middle of the stored insert is an ordinary change.
7250
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
7251
    write(&root.join("b"), "big.txt", edited.as_bytes());
7252
    let h2 = b.commit("edit", &[]).unwrap();
7253
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
7254
    assert!(b.push("origin", false).unwrap()[0].ok);
7255
    assert!(a.pull("origin").unwrap().checked_out);
7256
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
7257
    assert_eq!(
7258
        a.fsck().unwrap().errors(),
7259
        0,
7260
        "{:?}",
7261
        a.fsck().unwrap().problems
7262
    );
7263
7264
    // With zero retention gc keeps the text blobs of every kept change.
7265
    let mut a = Repo::open(&root.join("a")).unwrap();
7266
    a.config.set("core.op-retention", "0").unwrap();
7267
    a.save_config().unwrap();
7268
    let a = Repo::open(&root.join("a")).unwrap();
7269
    a.gc(true).unwrap();
7270
    let a = Repo::open(&root.join("a")).unwrap();
7271
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
7272
    assert_eq!(
7273
        a.fsck().unwrap().errors(),
7274
        0,
7275
        "{:?}",
7276
        a.fsck().unwrap().problems
7277
    );
7278
    // And a clone of the packed repository reads them from its packs.
7279
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
7280
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
7281
    drop(c);
7282
}
7283
7284
#[test]
7285
fn operations_that_both_replace_a_working_copy_are_not_merged() {
7286
    hermetic();
7287
    let dir = tempfile::tempdir().unwrap();
7288
    let root = dir.path();
7289
    let repo = Repo::init(root).unwrap();
7290
    write(root, "a.txt", b"a\n");
7291
    let a = repo.commit("a", &[]).unwrap();
7292
    write(root, "b.txt", b"b\n");
7293
    repo.commit("b", &[]).unwrap();
7294
    let (x, op) = repo.head_op().unwrap();
7295
    let ws = *op.view.workspaces.keys().next().unwrap();
7296
    let mut one = op.view.clone();
7297
    one.workspaces.insert(ws, a);
7298
    let mut two = op.view.clone();
7299
    two.workspaces.insert(ws, ObjectRef([7; 32]));
7300
    let first = repo.record_op(&[x], "one", one).unwrap();
7301
    let e = repo.record_op(&[x], "two", two).unwrap_err();
7302
    assert!(
7303
        e.to_string()
7304
            .contains("changed this working copy at the same time"),
7305
        "{e}"
7306
    );
7307
    assert_eq!(
7308
        repo.head_op().unwrap().0,
7309
        first,
7310
        "the second is not recorded"
7311
    );
7312
}
7313
7314
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
7315
/// rewrote the working copy recorded the half-written files as edits, and
7316
/// its view replaced the switch's.
7317
#[test]
7318
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
7319
    hermetic();
7320
    let dir = tempfile::tempdir().unwrap();
7321
    let root = dir.path().to_path_buf();
7322
    let mut repo = Repo::init(&root).unwrap();
7323
    write(&root, "keep.txt", b"keep\n");
7324
    repo.commit("base", &[]).unwrap();
7325
    repo.bookmark_create("small", None).unwrap();
7326
    for i in 0..300 {
7327
        write(
7328
            &root,
7329
            &format!("many/f{i}.txt"),
7330
            format!("file {i}\n").as_bytes(),
7331
        );
7332
    }
7333
    repo.commit("many", &[]).unwrap();
7334
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
7335
    let watcher = {
7336
        let (root, stop) = (root.clone(), stop.clone());
7337
        std::thread::spawn(move || {
7338
            let r = Repo::open(&root).unwrap();
7339
            let mut ran = 0;
7340
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
7341
                if r.snapshot_status("oxy status").is_ok() {
7342
                    ran += 1;
7343
                }
7344
            }
7345
            ran
7346
        })
7347
    };
7348
    for i in 0..20 {
7349
        let to = if i % 2 == 0 { "small" } else { "main" };
7350
        repo.bookmark_switch(to, false).unwrap();
7351
    }
7352
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
7353
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
7354
    // Back on main, clean, with every file where main has it.
7355
    let repo = Repo::open(&root).unwrap();
7356
    let s = repo.snapshot_status("oxy status").unwrap();
7357
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
7358
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
7359
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
7360
    assert!(root.join("many/f299.txt").exists());
7361
}
7362
7363
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
7364
/// put a subrepo that was ahead of its pin back at the pin and moved the
7365
/// subrepo's own bookmark backwards.
7366
#[test]
7367
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
7368
    hermetic();
7369
    let dir = tempfile::tempdir().unwrap();
7370
    let root = dir.path();
7371
    Repo::init(&root.join("lib-origin")).unwrap();
7372
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7373
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
7374
    write(&root.join("lib"), "lib.txt", b"v1\n");
7375
    lib.commit("lib v1", &[]).unwrap();
7376
    assert!(lib.push("origin", false).unwrap()[0].ok);
7377
7378
    let app_dir = root.join("app");
7379
    let mut app = Repo::init(&app_dir).unwrap();
7380
    write(&app_dir, "main.txt", b"app\n");
7381
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7382
    app.commit("app with lib", &[]).unwrap();
7383
    app.bookmark_create("feature", None).unwrap();
7384
7385
    // New work in the subrepo, not yet pinned by the parent.
7386
    let nested_dir = app_dir.join("libs/lib");
7387
    let nested = Repo::open(&nested_dir).unwrap();
7388
    write(&nested_dir, "new.txt", b"new\n");
7389
    let l2 = nested.commit("lib: new file", &[]).unwrap();
7390
    drop(nested);
7391
7392
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
7393
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
7394
    let nested = Repo::open(&nested_dir).unwrap();
7395
    assert!(
7396
        nested.bookmark_heads().unwrap().contains(&l2),
7397
        "its bookmark kept its work"
7398
    );
7399
    assert!(nested_dir.join("new.txt").exists(), "and its files");
7400
    let s = app.snapshot("status").unwrap();
7401
    assert_eq!(
7402
        statuses(&s),
7403
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
7404
    );
7405
}
7406
7407
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
7408
/// moving `main` to a change this clone had pushed on another bookmark,
7409
/// the first `pull` said "Already up to date" while `main` was behind.
7410
#[test]
7411
fn pull_takes_a_remote_move_to_changes_already_here() {
7412
    hermetic();
7413
    let dir = tempfile::tempdir().unwrap();
7414
    let root = dir.path();
7415
    let origin_path = root.join("origin");
7416
    let origin = Repo::init(&origin_path).unwrap();
7417
    let url = origin_path.to_string_lossy().to_string();
7418
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
7419
    write(&root.join("b"), "base.txt", b"base\n");
7420
    b.commit("base", &[]).unwrap();
7421
    assert!(b.push("origin", false).unwrap()[0].ok);
7422
    origin.refresh().unwrap();
7423
7424
    // A feature bookmark with one change, pushed.
7425
    b.bookmark_create("feat", None).unwrap();
7426
    b.bookmark_switch("feat", false).unwrap();
7427
    write(&root.join("b"), "x.txt", b"x\n");
7428
    let x = b.commit("x", &[]).unwrap();
7429
    assert!(b.push("origin", false).unwrap()[0].ok);
7430
    origin.refresh().unwrap();
7431
    b.bookmark_switch("main", false).unwrap();
7432
7433
    // The remote lands it: its main moves to the feature's state.
7434
    let feat = origin
7435
        .store()
7436
        .get_state(&origin.view().unwrap().bookmarks["feat"])
7437
        .unwrap()
7438
        .heads;
7439
    origin.bookmark_set("main", &feat).unwrap();
7440
7441
    let r = b.pull("origin").unwrap();
7442
    assert!(r.changed, "{r:?}");
7443
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
7444
    let main = b
7445
        .bookmarks()
7446
        .unwrap()
7447
        .into_iter()
7448
        .find(|m| m.name == "main")
7449
        .unwrap();
7450
    assert_eq!(main.behind, Some(0), "{main:?}");
7451
}
7452
7453
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
7454
/// to one only the remote has makes a local bookmark from it; a pull moves
7455
/// every local bookmark the remote has too; a clone checks out the remote's
7456
/// default bookmark.
7457
#[test]
7458
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
7459
    hermetic();
7460
    let dir = tempfile::tempdir().unwrap();
7461
    let root = dir.path();
7462
    let origin_path = root.join("origin");
7463
    let mut origin = Repo::init(&origin_path).unwrap();
7464
    let url = origin_path.to_string_lossy().to_string();
7465
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
7466
    write(&root.join("a"), "base.txt", b"base\n");
7467
    a.commit("base", &[]).unwrap();
7468
    assert!(a.push("origin", false).unwrap()[0].ok);
7469
    a.bookmark_create("develop", None).unwrap();
7470
    a.bookmark_switch("develop", false).unwrap();
7471
    write(&root.join("a"), "base.txt", b"base\nd1\n");
7472
    let d1 = a.commit("d1", &[]).unwrap();
7473
    assert!(a.push("origin", false).unwrap()[0].ok);
7474
7475
    // A clone has main only; origin/develop is a name all the same.
7476
    let c_root = root.join("c");
7477
    let mut c = Repo::clone(&url, &c_root).unwrap();
7478
    assert_eq!(c.config.bookmark, "main");
7479
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
7480
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
7481
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
7482
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
7483
7484
    // Switching makes the local bookmark from origin's.
7485
    c.bookmark_switch("develop", false).unwrap();
7486
    assert_eq!(c.config.bookmark, "develop");
7487
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
7488
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
7489
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
7490
    assert!(c.bookmark_switch("nowhere", false).is_err());
7491
7492
    // Both bookmarks move on the remote; one pull takes both.
7493
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
7494
    let d2 = a.commit("d2", &[]).unwrap();
7495
    assert!(a.push("origin", false).unwrap()[0].ok);
7496
    a.bookmark_switch("main", false).unwrap();
7497
    write(&root.join("a"), "m.txt", b"m\n");
7498
    let m = a.commit("m", &[]).unwrap();
7499
    assert!(a.push("origin", false).unwrap()[0].ok);
7500
    let r = c.pull("origin").unwrap();
7501
    assert!(r.changed && r.checked_out, "{r:?}");
7502
    assert_eq!(r.heads, vec![d2]);
7503
    assert_eq!(r.others, vec!["main".to_string()]);
7504
    assert!(c.resolve_heads("main").unwrap().contains(&m));
7505
    assert_eq!(
7506
        fs::read(c_root.join("base.txt")).unwrap(),
7507
        b"base\nd1\nd2\n"
7508
    );
7509
    let again = c.pull("origin").unwrap();
7510
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
7511
7512
    // A clone checks out the remote's default bookmark.
7513
    origin.config.set("workspace.bookmark", "develop").unwrap();
7514
    origin.save_config().unwrap();
7515
    let e = Repo::clone(&url, &root.join("e")).unwrap();
7516
    assert_eq!(e.config.bookmark, "develop");
7517
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
7518
    let reopened = Repo::open(&root.join("e")).unwrap();
7519
    assert_eq!(reopened.config.bookmark, "develop");
7520
    // REMOTE/NAME names the remote's bookmark to switch to.
7521
    let mut e = reopened;
7522
    e.bookmark_switch("origin/main", false).unwrap();
7523
    assert_eq!(e.config.bookmark, "main");
7524
    assert!(e.bookmark_heads().unwrap().contains(&m));
7525
}
7526
7527
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
7528
/// op restore goes back to an operation, files included, and undo takes
7529
/// the restore back whole; op revert undoes one operation alone; each
7530
/// operation's changes are described from the views.
7531
#[test]
7532
fn operations_can_be_read_restored_and_reverted() {
7533
    hermetic();
7534
    let dir = tempfile::tempdir().unwrap();
7535
    let root = dir.path();
7536
    let repo = Repo::init(root).unwrap();
7537
    write(root, "a.txt", b"a\n");
7538
    let first = repo.commit("first", &[]).unwrap();
7539
    write(root, "a.txt", b"a\nb\n");
7540
    let second = repo.commit("second", &[]).unwrap();
7541
    let at_second = repo.head_op().unwrap().0.to_hex();
7542
    repo.bookmark_create("keep", None).unwrap();
7543
    let created = repo.head_op().unwrap().0.to_hex();
7544
    write(root, "n.txt", b"n\n");
7545
    let third = repo.commit("third", &[]).unwrap();
7546
7547
    // What each operation changed.
7548
    let ops = repo.op_log().unwrap();
7549
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
7550
    assert!(
7551
        changes
7552
            .iter()
7553
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
7554
        "{changes:?}"
7555
    );
7556
    assert!(changes
7557
        .iter()
7558
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
7559
7560
    // Reading at an earlier operation.
7561
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
7562
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
7563
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
7564
    write(root, "z.txt", b"z\n");
7565
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
7566
    fs::remove_file(root.join("z.txt")).unwrap();
7567
    assert!(repo.resolve_op("zz").is_err());
7568
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
7569
7570
    // Restore goes back, files and all; undo takes it back whole.
7571
    repo.op_restore(&at_second, false).unwrap();
7572
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
7573
    assert!(!root.join("n.txt").exists());
7574
    repo.undo().unwrap();
7575
    let mut heads = repo.bookmark_heads().unwrap();
7576
    heads.sort();
7577
    let mut want = vec![second, third];
7578
    want.sort();
7579
    assert_eq!(heads, want);
7580
    assert!(
7581
        root.join("n.txt").exists(),
7582
        "the files came back with the undo"
7583
    );
7584
7585
    // Revert the bookmark's creation alone: the commit after it stays.
7586
    let r = repo.op_revert(&created).unwrap();
7587
    assert_eq!(r.reverted, vec!["keep".to_string()]);
7588
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
7589
    assert!(repo
7590
        .load_state(&repo.bookmark_heads().unwrap())
7591
        .unwrap()
7592
        .contains(&third));
7593
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
7594
    let _ = first;
7595
}
7596
7597
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
7598
/// from the status cache while every file is as the snapshot left it, and
7599
/// from a snapshot again as soon as one is not.
7600
#[test]
7601
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
7602
    hermetic();
7603
    let dir = tempfile::tempdir().unwrap();
7604
    let root = dir.path();
7605
    let repo = Repo::init(root).unwrap();
7606
    write(root, "a.txt", b"a\n");
7607
    write(root, "b.txt", b"b\n");
7608
    repo.commit("base", &[]).unwrap();
7609
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
7610
7611
    write(root, "a.txt", b"a\nmore\n");
7612
    assert_eq!(
7613
        repo.status_by_manifest().unwrap(),
7614
        None,
7615
        "no snapshot of the edit yet"
7616
    );
7617
    let snap = repo.snapshot_status("oxy status").unwrap();
7618
    assert_eq!(snap.statuses.len(), 1);
7619
    let cached = repo
7620
        .status_by_manifest()
7621
        .unwrap()
7622
        .expect("answered from the cache");
7623
    assert_eq!(cached.len(), 1);
7624
    assert_eq!(
7625
        (cached[0].path.as_str(), cached[0].status),
7626
        ("a.txt", ChangeStatus::Modified)
7627
    );
7628
7629
    // Any further change sends status back to a snapshot.
7630
    write(root, "a.txt", b"a\nmore\nand more\n");
7631
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
7632
    repo.snapshot_status("oxy status").unwrap();
7633
    assert!(repo.status_by_manifest().unwrap().is_some());
7634
    write(root, "new.txt", b"n\n");
7635
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
7636
    fs::remove_file(root.join("new.txt")).unwrap();
7637
    assert!(
7638
        repo.status_by_manifest().unwrap().is_some(),
7639
        "back as it was"
7640
    );
7641
    fs::remove_file(root.join("b.txt")).unwrap();
7642
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
7643
    write(root, "b.txt", b"b\n");
7644
7645
    // A commit leaves nothing uncommitted: clean again, no cache needed.
7646
    repo.snapshot_status("oxy status").unwrap();
7647
    repo.commit("more", &[]).unwrap();
7648
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7649
}
7650
7651
/// oxygen#41: while the status cache holds, the working copy's diff is
7652
/// rendered from the stored working-copy change, and says exactly what a
7653
/// snapshot's diff says.
7654
#[test]
7655
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
7656
    hermetic();
7657
    let dir = tempfile::tempdir().unwrap();
7658
    let root = dir.path();
7659
    let repo = Repo::init(root).unwrap();
7660
    write(root, "a.txt", b"one\ntwo\nthree\n");
7661
    write(root, "gone.txt", b"bye\n");
7662
    repo.commit("base", &[]).unwrap();
7663
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
7664
    write(root, "new.txt", b"hello\n");
7665
    fs::remove_file(root.join("gone.txt")).unwrap();
7666
    let snap = repo.snapshot_status("oxy status").unwrap();
7667
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
7668
    assert!(
7669
        repo.status_by_manifest().unwrap().is_some(),
7670
        "the cache holds"
7671
    );
7672
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
7673
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
7674
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
7675
}
7676
7677
/// oxygen#41: a manifest written from a walk keeps every directory's time;
7678
/// while none has moved, the check stats the tracked files without listing
7679
/// the tree, and a file added or removed anywhere moves its directory's
7680
/// time, so the tree is listed again.
7681
#[test]
7682
fn the_manifest_check_skips_listing_while_no_directory_changed() {
7683
    hermetic();
7684
    let dir = tempfile::tempdir().unwrap();
7685
    let root = dir.path();
7686
    let repo = Repo::init(root).unwrap();
7687
    write(root, "a.txt", b"a\n");
7688
    write(root, "sub/deep/b.txt", b"b\n");
7689
    repo.commit("base", &[]).unwrap();
7690
    // Out of the racy window: every file and directory a minute old.
7691
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7692
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
7693
        fs::File::open(root.join(p))
7694
            .unwrap()
7695
            .set_modified(old)
7696
            .unwrap();
7697
    }
7698
    repo.snapshot_status("oxy status").unwrap();
7699
    repo.write_manifest(false, false).unwrap();
7700
    let m = repo.read_manifest().unwrap().unwrap().2;
7701
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
7702
    assert_eq!(
7703
        repo.disk_differs_by_dirs(&m),
7704
        Some(false),
7705
        "no listing needed"
7706
    );
7707
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7708
7709
    // A same-size edit with a new time: found by its stat.
7710
    write(root, "sub/deep/b.txt", b"c\n");
7711
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
7712
    write(root, "sub/deep/b.txt", b"b\n");
7713
    fs::File::open(root.join("sub/deep/b.txt"))
7714
        .unwrap()
7715
        .set_modified(old)
7716
        .unwrap();
7717
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
7718
7719
    // A new file moves its directory's time: the tree must be listed.
7720
    write(root, "sub/deep/new.txt", b"n\n");
7721
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7722
    assert_eq!(repo.status_by_manifest().unwrap(), None);
7723
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
7724
    // A removed one too.
7725
    fs::remove_file(root.join("a.txt")).unwrap();
7726
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
7727
}
7728
7729
/// oxygen#41: a commit right after a status takes the snapshot the status
7730
/// left (the status cache holds) rather than walking again, and commits
7731
/// exactly what a snapshot would have.
7732
#[test]
7733
fn a_commit_after_a_status_uses_the_cached_snapshot() {
7734
    hermetic();
7735
    let dir = tempfile::tempdir().unwrap();
7736
    let root = dir.path();
7737
    let repo = Repo::init(root).unwrap();
7738
    write(root, "a.txt", b"a\nb\n");
7739
    write(root, ".oxyattributes", b"*.bin binary\n");
7740
    repo.commit("base", &[]).unwrap();
7741
    write(root, "a.txt", b"a\nB\n");
7742
    write(root, "new.txt", b"new\n");
7743
    let snap = repo.snapshot_status("oxy status").unwrap();
7744
    let cached = repo
7745
        .snapshot_from_cache()
7746
        .unwrap()
7747
        .expect("the cache holds");
7748
    assert_eq!(cached.wc_hash, snap.wc_hash);
7749
    assert_eq!(cached.statuses, snap.statuses);
7750
    assert!(
7751
        !cached.attributes.is_empty(),
7752
        "the .oxyattributes file was read"
7753
    );
7754
    let h = repo.commit("edit", &[]).unwrap();
7755
    let c = repo.store().get_change(&h).unwrap();
7756
    assert_eq!(
7757
        c.tree_ops.len() + c.edits.len(),
7758
        snap.wc.tree_ops.len() + snap.wc.edits.len()
7759
    );
7760
    assert_eq!(
7761
        repo.status_by_manifest().unwrap(),
7762
        Some(vec![]),
7763
        "clean after the commit"
7764
    );
7765
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
7766
}
7767
7768
/// oxygen#41: a clean check that verified racy entries restamps the
7769
/// manifest, so later checks can trust them, and a same-size rewrite
7770
/// straight afterwards is still found: entries within two seconds of the
7771
/// new time stay racy.
7772
#[test]
7773
fn a_verified_clean_check_restamps_the_manifest_safely() {
7774
    hermetic();
7775
    let dir = tempfile::tempdir().unwrap();
7776
    let root = dir.path();
7777
    let repo = Repo::init(root).unwrap();
7778
    write(root, "a.txt", b"one\n");
7779
    repo.commit("one", &[]).unwrap();
7780
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
7781
    assert!(repo.clean_by_manifest().unwrap());
7782
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
7783
    assert!(after > before, "restamped");
7784
    write(root, "a.txt", b"two\n");
7785
    assert!(
7786
        !repo.clean_by_manifest().unwrap(),
7787
        "a same-size rewrite is still seen"
7788
    );
7789
}
7790
7791
/// oxygen#35: a history-only state keeps no inserted text. It reads a
7792
/// stored insert's text blob only when it builds that file's graph, and
7793
/// builds the same graph a full load does.
7794
#[test]
7795
fn history_only_states_read_text_only_for_the_graphs_they_build() {
7796
    hermetic();
7797
    let dir = tempfile::tempdir().unwrap();
7798
    let root = dir.path();
7799
    let repo = Repo::init(root).unwrap();
7800
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
7801
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
7802
    write(root, "big.txt", big.as_bytes());
7803
    write(root, "other.txt", other.as_bytes());
7804
    let h = repo.commit("two large files", &[]).unwrap();
7805
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
7806
    let h2 = repo.commit("append", &[]).unwrap();
7807
7808
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
7809
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
7810
        FileContent::Text { bytes, .. } => bytes.clone(),
7811
        other => panic!("{other:?}"),
7812
    };
7813
    // Built on demand, every graph renders as the full load's.
7814
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7815
    let big_node = full.files["big.txt"].node;
7816
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
7817
    repo.load_all_graphs(&mut hist).unwrap();
7818
    let rendered = hist.materialize();
7819
    for p in ["big.txt", "other.txt"] {
7820
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
7821
    }
7822
7823
    // Without other.txt's text blob, history still loads and big.txt still
7824
    // builds: nothing read the other text.
7825
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
7826
    assert_eq!(texts.len(), 2);
7827
    let content = |r: &ObjectRef| -> Vec<u8> {
7828
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
7829
        blob.chunks
7830
            .iter()
7831
            .flat_map(|c| repo.store().get(c).unwrap().1)
7832
            .collect()
7833
    };
7834
    let other_text = texts
7835
        .iter()
7836
        .filter_map(|t| match t {
7837
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
7838
            _ => None,
7839
        })
7840
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
7841
        .unwrap();
7842
    repo.store().remove_loose_for_test(&other_text).unwrap();
7843
    let mut hist = repo.load_state_history(&[h2]).unwrap();
7844
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
7845
    assert!(repo
7846
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
7847
        .is_err());
7848
}
7849
7850
/// oxygen#35: the first status after a commit read and rendered every
7851
/// file (79 s and more than 14 GB on the Linux tree), because the
7852
/// manifest had no graph keys for files the commit added.
7853
#[test]
7854
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
7855
    use std::os::unix::fs::PermissionsExt;
7856
    hermetic();
7857
    let dir = tempfile::tempdir().unwrap();
7858
    let root = dir.path();
7859
    let repo = Repo::init(root).unwrap();
7860
    let files = ["a.txt", "b.txt", "d/c.txt"];
7861
    for p in files {
7862
        write(root, p, format!("{p}\n").as_bytes());
7863
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7864
        fs::File::options()
7865
            .write(true)
7866
            .open(root.join(p))
7867
            .unwrap()
7868
            .set_modified(old)
7869
            .unwrap();
7870
    }
7871
    repo.commit("added", &[]).unwrap();
7872
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
7873
    assert!(
7874
        m.entries.values().all(|e| e.graph.is_some()),
7875
        "keys recorded at commit"
7876
    );
7877
    // Unreadable files prove the next status reads none of them.
7878
    for p in files {
7879
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
7880
    }
7881
    let snap = repo.snapshot_status("status").unwrap();
7882
    for p in files {
7883
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
7884
    }
7885
    assert!(!snap.changed && snap.statuses.is_empty());
7886
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
7887
}
7888
7889
/// oxygen#35: a checkout reads, renders and writes only the files whose
7890
/// graphs differ, and renders the rest a batch at a time.
7891
#[test]
7892
fn checkout_touches_only_what_differs_and_renders_in_batches() {
7893
    use std::os::unix::fs::PermissionsExt;
7894
    hermetic();
7895
    let dir = tempfile::tempdir().unwrap();
7896
    let root = dir.path();
7897
    let origin = root.join("origin");
7898
    let mut repo = Repo::init(&origin).unwrap();
7899
    // More files than one batch holds.
7900
    let n = 2100;
7901
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7902
    for i in 0..n {
7903
        let p = format!("f/{i:04}.txt");
7904
        write(&origin, &p, format!("file {i}\n").as_bytes());
7905
        fs::File::options()
7906
            .write(true)
7907
            .open(origin.join(&p))
7908
            .unwrap()
7909
            .set_modified(old)
7910
            .unwrap();
7911
    }
7912
    repo.commit("many", &[]).unwrap();
7913
    repo.bookmark_create("feature", None).unwrap();
7914
    repo.bookmark_switch("feature", false).unwrap();
7915
    write(&origin, "f/0007.txt", b"changed\n");
7916
    repo.commit("one change", &[]).unwrap();
7917
7918
    // Switching back to main must not read the unchanged files.
7919
    for i in 0..n {
7920
        if i != 7 {
7921
            let p = origin.join(format!("f/{i:04}.txt"));
7922
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
7923
        }
7924
    }
7925
    let r = repo.bookmark_switch("main", false).unwrap();
7926
    for i in 0..n {
7927
        let p = origin.join(format!("f/{i:04}.txt"));
7928
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
7929
    }
7930
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
7931
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
7932
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7933
7934
    // A clone renders every file, across batches.
7935
    let c = root.join("clone");
7936
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
7937
    for i in [0, 2047, 2048, n - 1] {
7938
        assert_eq!(
7939
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
7940
            format!("file {i}\n").as_bytes()
7941
        );
7942
    }
7943
    let cloned = Repo::open(&c).unwrap();
7944
    assert!(cloned
7945
        .snapshot_status("status")
7946
        .unwrap()
7947
        .statuses
7948
        .is_empty());
7949
}
7950
7951
/// A file written just before the manifest (inside the racy window) is
7952
/// checked by its hash: trusted when equal, caught when edited in place
7953
/// with the same size and time.
7954
#[test]
7955
fn a_racy_manifest_entry_is_checked_by_hash() {
7956
    hermetic();
7957
    let dir = tempfile::tempdir().unwrap();
7958
    let root = dir.path();
7959
    let repo = Repo::init(root).unwrap();
7960
    write(root, "a.txt", b"one\n");
7961
    repo.commit("fresh", &[]).unwrap();
7962
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
7963
    let t = fs::metadata(root.join("a.txt"))
7964
        .unwrap()
7965
        .modified()
7966
        .unwrap();
7967
    write(root, "a.txt", b"two\n");
7968
    fs::File::options()
7969
        .write(true)
7970
        .open(root.join("a.txt"))
7971
        .unwrap()
7972
        .set_modified(t)
7973
        .unwrap();
7974
    assert!(
7975
        !repo.clean_by_manifest().unwrap(),
7976
        "same size and time, other bytes"
7977
    );
7978
    assert_eq!(
7979
        statuses(&repo.snapshot_status("status").unwrap()),
7980
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
7981
    );
7982
}
7983
7984
/// A fetch on one machine moves changes as stored, text blobs among the
7985
/// objects; a change whose text blob did not come is refused, not stored.
7986
#[test]
7987
fn a_raw_bundle_without_a_changes_text_is_refused() {
7988
    hermetic();
7989
    let dir = tempfile::tempdir().unwrap();
7990
    let root = dir.path();
7991
    let a = Repo::init(&root.join("a")).unwrap();
7992
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
7993
    write(&root.join("a"), "big.txt", big.as_bytes());
7994
    let h = a.commit("big", &[]).unwrap();
7995
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
7996
    assert_eq!(bundle.raw_changes.len(), 1);
7997
    assert!(bundle.changes.is_empty());
7998
    let b = Repo::init(&root.join("b")).unwrap();
7999
    let mut without = bundle.clone();
8000
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
8001
    let e = b.import_bundle(&without, false).unwrap_err();
8002
    assert!(e.to_string().contains("came without its text blob"), "{e}");
8003
    assert!(!b.store().has(&h));
8004
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
8005
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
8006
}
8007
8008
/// oxygen#30 (vscode): a directory deleted in one line of history and made
8009
/// again was a second node for one Git path, so a file moved into it on
8010
/// another line, where the first node still stood, ended up in two places.
8011
/// An import now brings the directory back rather than make a new one.
8012
#[test]
8013
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
8014
    hermetic();
8015
    if std::process::Command::new("git")
8016
        .arg("--version")
8017
        .output()
8018
        .is_err()
8019
    {
8020
        eprintln!("git not installed; skipping");
8021
        return;
8022
    }
8023
    let dir = tempfile::tempdir().unwrap();
8024
    let root = dir.path();
8025
    let g = root.join("src.git");
8026
    fs::create_dir_all(&g).unwrap();
8027
    let git = |args: &[&str]| -> String {
8028
        let out = std::process::Command::new("git")
8029
            .arg("-C")
8030
            .arg(&g)
8031
            .args([
8032
                "-c",
8033
                "user.name=Grace",
8034
                "-c",
8035
                "[email protected]",
8036
                "-c",
8037
                "commit.gpgsign=false",
8038
            ])
8039
            .args(args)
8040
            .output()
8041
            .unwrap();
8042
        assert!(
8043
            out.status.success(),
8044
            "git {args:?}: {}",
8045
            String::from_utf8_lossy(&out.stderr)
8046
        );
8047
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8048
    };
8049
    git(&["init", "-q", "-b", "main"]);
8050
    write(&g, "d/a.txt", b"a\n");
8051
    write(&g, "c/x.txt", b"x\n");
8052
    git(&["add", "."]);
8053
    git(&["commit", "-qm", "base"]);
8054
    // One line: move x into d while d still stands.
8055
    git(&["checkout", "-qb", "side"]);
8056
    git(&["mv", "c/x.txt", "d/x.txt"]);
8057
    git(&["commit", "-qm", "x into d"]);
8058
    // The other: d goes, comes back, and x moves into it too.
8059
    git(&["checkout", "-q", "main"]);
8060
    git(&["rm", "-q", "d/a.txt"]);
8061
    git(&["commit", "-qm", "d goes"]);
8062
    write(&g, "d/b.txt", b"b\n");
8063
    git(&["add", "."]);
8064
    git(&["commit", "-qm", "d comes back"]);
8065
    git(&["mv", "c/x.txt", "d/x.txt"]);
8066
    git(&["commit", "-qm", "x into d again"]);
8067
    git(&["merge", "-q", "--no-edit", "side"]);
8068
8069
    let repo = Repo::init(&root.join("o")).unwrap();
8070
    repo.import_git(&g, "main").unwrap();
8071
    let v = repo.verify_git_import(&g, "main").unwrap();
8072
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8073
    let st = repo
8074
        .load_state_history(&repo.bookmark_heads().unwrap())
8075
        .unwrap();
8076
    let view = st.tree().view();
8077
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8078
    // The directory is the one the first commit made.
8079
    // Commits made in one second tie on time: find the first by its message.
8080
    let first = repo
8081
        .log()
8082
        .unwrap()
8083
        .into_iter()
8084
        .find(|e| e.change.message.starts_with("base"))
8085
        .unwrap();
8086
    let base = repo
8087
        .load_state_history(&[first.hash])
8088
        .unwrap()
8089
        .tree()
8090
        .view();
8091
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
8092
}
8093
8094
/// oxygen#30, the rest: a placement left under a directory another line
8095
/// removed is out of sight, so no diff reaches it; the merge that settles
8096
/// where the file is retires it.
8097
#[test]
8098
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
8099
    hermetic();
8100
    if std::process::Command::new("git")
8101
        .arg("--version")
8102
        .output()
8103
        .is_err()
8104
    {
8105
        eprintln!("git not installed; skipping");
8106
        return;
8107
    }
8108
    let dir = tempfile::tempdir().unwrap();
8109
    let root = dir.path();
8110
    let g = root.join("src.git");
8111
    fs::create_dir_all(&g).unwrap();
8112
    let run = |args: &[&str]| {
8113
        std::process::Command::new("git")
8114
            .arg("-C")
8115
            .arg(&g)
8116
            .args([
8117
                "-c",
8118
                "user.name=Grace",
8119
                "-c",
8120
                "[email protected]",
8121
                "-c",
8122
                "commit.gpgsign=false",
8123
            ])
8124
            .args(args)
8125
            .output()
8126
            .unwrap()
8127
    };
8128
    let git = |args: &[&str]| {
8129
        let out = run(args);
8130
        assert!(
8131
            out.status.success(),
8132
            "git {args:?}: {}",
8133
            String::from_utf8_lossy(&out.stderr)
8134
        );
8135
    };
8136
    git(&["init", "-q", "-b", "main"]);
8137
    write(&g, "c/x.txt", b"x\n");
8138
    write(&g, "keep.txt", b"k\n");
8139
    git(&["add", "."]);
8140
    git(&["commit", "-qm", "base"]);
8141
    // One line renames the file within c; the other moves it out of c,
8142
    // which goes.
8143
    git(&["checkout", "-qb", "side"]);
8144
    git(&["mv", "c/x.txt", "c/y.txt"]);
8145
    git(&["commit", "-qm", "rename within c"]);
8146
    git(&["checkout", "-q", "main"]);
8147
    fs::create_dir_all(g.join("n")).unwrap();
8148
    git(&["mv", "c/x.txt", "n/x.txt"]);
8149
    git(&["commit", "-qm", "move out of c"]);
8150
    // Git cannot merge the two renames; the merge keeps n/x.txt.
8151
    let _ = run(&["merge", "-q", "side"]);
8152
    let _ = run(&[
8153
        "rm",
8154
        "-q",
8155
        "--cached",
8156
        "--ignore-unmatch",
8157
        "c/y.txt",
8158
        "c/x.txt",
8159
    ]);
8160
    let _ = std::fs::remove_dir_all(g.join("c"));
8161
    write(&g, "n/x.txt", b"x\n");
8162
    git(&["add", "-A"]);
8163
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
8164
8165
    let repo = Repo::init(&root.join("o")).unwrap();
8166
    repo.import_git(&g, "main").unwrap();
8167
    let v = repo.verify_git_import(&g, "main").unwrap();
8168
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8169
    let st = repo
8170
        .load_state_history(&repo.bookmark_heads().unwrap())
8171
        .unwrap();
8172
    let view = st.tree().view();
8173
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8174
    assert!(view.entries.contains_key("n/x.txt"));
8175
}
8176
8177
/// oxygen#30, orphans: a file added on one line into a directory the other
8178
/// line removed is placed where the tree cannot show it; Git's merge keeps
8179
/// the file, and the import's merge leaves exactly one of it.
8180
#[test]
8181
fn git_import_merge_leaves_no_orphan_behind() {
8182
    hermetic();
8183
    if std::process::Command::new("git")
8184
        .arg("--version")
8185
        .output()
8186
        .is_err()
8187
    {
8188
        eprintln!("git not installed; skipping");
8189
        return;
8190
    }
8191
    let dir = tempfile::tempdir().unwrap();
8192
    let root = dir.path();
8193
    let g = root.join("src.git");
8194
    fs::create_dir_all(&g).unwrap();
8195
    let git = |args: &[&str]| {
8196
        let out = std::process::Command::new("git")
8197
            .arg("-C")
8198
            .arg(&g)
8199
            .args([
8200
                "-c",
8201
                "user.name=Grace",
8202
                "-c",
8203
                "[email protected]",
8204
                "-c",
8205
                "commit.gpgsign=false",
8206
            ])
8207
            .args(args)
8208
            .output()
8209
            .unwrap();
8210
        assert!(
8211
            out.status.success(),
8212
            "git {args:?}: {}",
8213
            String::from_utf8_lossy(&out.stderr)
8214
        );
8215
    };
8216
    git(&["init", "-q", "-b", "main"]);
8217
    write(&g, "d/f.txt", b"f\n");
8218
    write(&g, "keep.txt", b"k\n");
8219
    git(&["add", "."]);
8220
    git(&["commit", "-qm", "base"]);
8221
    git(&["checkout", "-qb", "side"]);
8222
    write(&g, "d/new.txt", b"new\n");
8223
    git(&["add", "."]);
8224
    git(&["commit", "-qm", "add into d"]);
8225
    git(&["checkout", "-q", "main"]);
8226
    git(&["rm", "-q", "d/f.txt"]);
8227
    git(&["commit", "-qm", "d goes"]);
8228
    git(&["merge", "-q", "--no-edit", "side"]);
8229
8230
    let repo = Repo::init(&root.join("o")).unwrap();
8231
    repo.import_git(&g, "main").unwrap();
8232
    let v = repo.verify_git_import(&g, "main").unwrap();
8233
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8234
    let st = repo
8235
        .load_state_history(&repo.bookmark_heads().unwrap())
8236
        .unwrap();
8237
    let view = st.tree().view();
8238
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8239
    assert!(view.entries.contains_key("d/new.txt"));
8240
}
8241
8242
/// fsck checks a change's text as the blobs it is stored in, without
8243
/// decoding it: a missing text blob is an error named for the change.
8244
#[test]
8245
fn fsck_names_a_missing_text_blob() {
8246
    hermetic();
8247
    let dir = tempfile::tempdir().unwrap();
8248
    let root = dir.path();
8249
    let repo = Repo::init(root).unwrap();
8250
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
8251
    write(root, "big.txt", big.as_bytes());
8252
    let h = repo.commit("big", &[]).unwrap();
8253
    assert_eq!(repo.fsck().unwrap().errors(), 0);
8254
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
8255
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
8256
        panic!("a stored text")
8257
    };
8258
    repo.store().remove_loose_for_test(&b).unwrap();
8259
    let rep = repo.fsck().unwrap();
8260
    assert!(rep.errors() > 0);
8261
    assert!(
8262
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
8263
        "{:?}",
8264
        rep.problems
8265
    );
8266
}
8267
8268
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
8269
/// reached with that remote's token and CA (a private subrepo then clones
8270
/// for anyone who can read the parent); another hub gets none of them.
8271
#[test]
8272
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
8273
    hermetic();
8274
    let dir = tempfile::tempdir().unwrap();
8275
    let mut repo = Repo::init(dir.path()).unwrap();
8276
    repo.config
8277
        .set(
8278
            "remote.origin.url",
8279
            "https://Hub.example:7343/doomsdayone/metalgear",
8280
        )
8281
        .unwrap();
8282
    repo.config.set("remote.origin.token", "secret").unwrap();
8283
    repo.config
8284
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
8285
        .unwrap();
8286
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
8287
    assert_eq!(same.token.as_deref(), Some("secret"));
8288
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
8289
    for other in [
8290
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
8291
        "https://hub.example/doomsdayone/rstar-api",
8292
        "http://hub.example:7343/doomsdayone/rstar-api",
8293
    ] {
8294
        let o = repo.credentials_for(other);
8295
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
8296
    }
8297
}
8298
8299
/// oxygen#47: a remote with no token of its own uses the user's credential
8300
/// store for its hub, and a nested checkout finds its parent's remote
8301
/// token there instead of keeping a copy.
8302
#[test]
8303
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
8304
    hermetic();
8305
    let home = tempfile::tempdir().unwrap();
8306
    let dir = tempfile::tempdir().unwrap();
8307
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
8308
    parent
8309
        .config
8310
        .set("remote.origin.url", "https://hub.example/o/parent")
8311
        .unwrap();
8312
    parent.save_config().unwrap();
8313
    assert_eq!(parent.remote_options("origin").token, None);
8314
    crate::credentials::Credentials::at(home.path())
8315
        .save("https://hub.example", "stored", Some("andy"), None)
8316
        .unwrap();
8317
    assert_eq!(
8318
        parent.remote_options("origin").token.as_deref(),
8319
        Some("stored")
8320
    );
8321
8322
    let empty_home = tempfile::tempdir().unwrap();
8323
    let nested = dir.path().join("deps").join("child");
8324
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
8325
    child
8326
        .config
8327
        .set("remote.origin.url", "https://hub.example/o/child")
8328
        .unwrap();
8329
    child.save_config().unwrap();
8330
    assert_eq!(child.remote_options("origin").token, None);
8331
    parent
8332
        .config
8333
        .set("remote.origin.token", "checkout")
8334
        .unwrap();
8335
    parent.save_config().unwrap();
8336
    assert_eq!(
8337
        child.remote_options("origin").token.as_deref(),
8338
        Some("checkout")
8339
    );
8340
    // Another hub's checkout token is not borrowed.
8341
    child
8342
        .config
8343
        .set("remote.origin.url", "https://other.example/o/child")
8344
        .unwrap();
8345
    assert_eq!(child.remote_options("origin").token, None);
8346
}
8347
8348
#[test]
8349
fn the_metadata_cache_survives_a_torn_tail() {
8350
    hermetic();
8351
    let dir = tempfile::tempdir().unwrap();
8352
    let root = dir.path();
8353
    let repo = Repo::init(root).unwrap();
8354
    write(root, "a.txt", b"1\n");
8355
    let h = repo.commit("first", &[]).unwrap();
8356
    let meta = repo.store().get_change_meta(&h).unwrap();
8357
    let cache = repo.store().dir().join("metas");
8358
    let len = fs::metadata(&cache).unwrap().len();
8359
    assert!(len > 0, "a change read is cached");
8360
    // A torn record at the end: the cache reads up to it and cuts it off.
8361
    fs::OpenOptions::new()
8362
        .append(true)
8363
        .open(&cache)
8364
        .unwrap()
8365
        .write_all(&[7; 20])
8366
        .unwrap();
8367
    let again = Repo::open(root).unwrap();
8368
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
8369
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
8370
}
8371
8372
#[test]
8373
fn a_manifest_that_does_not_check_reads_as_none() {
8374
    hermetic();
8375
    let dir = tempfile::tempdir().unwrap();
8376
    let root = dir.path();
8377
    let repo = Repo::init(root).unwrap();
8378
    write(root, "a.txt", b"1\n");
8379
    repo.commit("first", &[]).unwrap();
8380
    let path = repo.manifest_path();
8381
    let mut bytes = fs::read(&path).unwrap();
8382
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
8383
    let last = bytes.len() - 1;
8384
    bytes[last] ^= 1;
8385
    fs::write(&path, &bytes).unwrap();
8386
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
8387
    // The next status reads the files and writes it again.
8388
    let again = Repo::open(root).unwrap();
8389
    assert!(!again.snapshot("status").unwrap().changed);
8390
    assert!(again.read_manifest().unwrap().is_some());
8391
}
8392
8393
#[test]
8394
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
8395
    hermetic();
8396
    let dir = tempfile::tempdir().unwrap();
8397
    let root = dir.path();
8398
    let repo = Repo::init(root).unwrap();
8399
    write(root, "a.txt", b"1\n");
8400
    write(root, "b.txt", b"2\n");
8401
    // b.txt outside the racy window, so snapshots take it as unchanged.
8402
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
8403
    fs::File::options()
8404
        .write(true)
8405
        .open(root.join("b.txt"))
8406
        .unwrap()
8407
        .set_modified(old)
8408
        .unwrap();
8409
    repo.commit("first", &[]).unwrap();
8410
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
8411
    repo.snapshot_status("status").unwrap();
8412
    write(root, "a.txt", b"1\n2\n");
8413
    repo.commit("second", &[]).unwrap();
8414
    assert!(
8415
        repo.clean_by_manifest().unwrap(),
8416
        "after a commit of one file"
8417
    );
8418
    // Edited, seen by a status, edited again, then committed: the status
8419
    // left the first edit's stat, which the commit must not keep.
8420
    write(root, "a.txt", b"1\n2\n3\n");
8421
    repo.snapshot_status("status").unwrap();
8422
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
8423
    repo.commit("third", &[]).unwrap();
8424
    assert!(
8425
        repo.clean_by_manifest().unwrap(),
8426
        "after an edit a status saw"
8427
    );
8428
}
8429
8430
#[test]
8431
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
8432
    hermetic();
8433
    let dir = tempfile::tempdir().unwrap();
8434
    let root = dir.path();
8435
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8436
    write(root, "a.txt", b"1\n2\n");
8437
    let a = repo.commit("A", &[]).unwrap();
8438
    repo.bookmark_create("develop", Some(&[a])).unwrap();
8439
    write(root, "a.txt", b"1\nX\n");
8440
    let c = repo.commit("C: 2 to X", &[]).unwrap();
8441
    repo.bookmark_switch("develop", false).unwrap();
8442
    write(root, "a.txt", b"1\nY\n");
8443
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
8444
    repo.bookmark_switch("main", false).unwrap();
8445
8446
    let err = repo.rebase(&c, &[d]).unwrap_err();
8447
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
8448
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
8449
    assert!(r.changed && r.checked_out);
8450
    let snap = repo.snapshot_status("status").unwrap();
8451
    assert!(
8452
        snap.base_snapshot.is_conflicted(),
8453
        "the conflict is in the working copy"
8454
    );
8455
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
8456
    assert!(text.contains('X') && text.contains('Y'), "{text}");
8457
8458
    write(root, "a.txt", b"1\nXY\n");
8459
    repo.commit("Resolve", &[]).unwrap();
8460
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
8461
    assert!(st.contains(&c) && st.contains(&d));
8462
    let files = st.materialize().files;
8463
    assert!(!files["a.txt"].is_conflicted());
8464
    assert!(
8465
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
8466
    );
8467
8468
    // A change the current bookmark does not hold is refused.
8469
    repo.bookmark_switch("develop", false).unwrap();
8470
    write(root, "b.txt", b"b\n");
8471
    let e = repo.commit("E", &[]).unwrap();
8472
    repo.bookmark_switch("main", false).unwrap();
8473
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
8474
    assert!(
8475
        err.to_string().contains("not on the current bookmark"),
8476
        "{err}"
8477
    );
8478
}
8479
8480
#[test]
8481
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
8482
    hermetic();
8483
    let dir = tempfile::tempdir().unwrap();
8484
    let root = dir.path();
8485
    let repo = Repo::init(root).unwrap();
8486
    write(root, "a.txt", b"a\n");
8487
    write(root, "kept.log", b"tracked\n");
8488
    repo.commit("first", &[]).unwrap();
8489
    write(root, "build.log", b"made\n");
8490
    let snap = repo.snapshot_status("status").unwrap();
8491
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
8492
    // A rule written afterwards leaves the added file out again, while the
8493
    // committed one stays tracked.
8494
    write(root, ".gitignore", b"*.log\n");
8495
    let snap = repo.snapshot_status("status").unwrap();
8496
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
8497
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
8498
    write(root, "kept.log", b"tracked, edited\n");
8499
    let snap = repo.snapshot_status("status").unwrap();
8500
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
8501
}
8502
8503
#[test]
8504
fn shed_graphs_come_back_the_same() {
8505
    hermetic();
8506
    let dir = tempfile::tempdir().unwrap();
8507
    let root = dir.path();
8508
    let repo = Repo::init(root).unwrap();
8509
    write(root, "a.txt", b"1\n2\n3\n");
8510
    write(root, "b.txt", b"x\n");
8511
    repo.commit("first", &[]).unwrap();
8512
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
8513
    repo.commit("second", &[]).unwrap();
8514
    let heads = repo.bookmark_heads().unwrap();
8515
    let mut st = repo.load_state_history(&heads).unwrap();
8516
    let view = st.tree().view();
8517
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
8518
        .iter()
8519
        .map(|p| view.entries[*p].node)
8520
        .collect();
8521
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8522
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8523
    assert_eq!(st.built_count(), 2);
8524
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
8525
    assert_eq!((shed, st.built_count()), (2, 0));
8526
    // A later change applies on top of the shed history.
8527
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
8528
    let h3 = repo.commit("third", &[]).unwrap();
8529
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
8530
    st.add_known(h3, skeleton, texts);
8531
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8532
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8533
    assert_eq!(after[1], before[1]);
8534
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
8535
}
8536
8537
#[test]
8538
fn many_edited_files_diff_in_parallel() {
8539
    // Enough edited files that the builder diffs them in parallel; the
8540
    // commit must hold exactly what is on disk, and a second snapshot
8541
    // must find nothing left to commit.
8542
    hermetic();
8543
    let dir = tempfile::tempdir().unwrap();
8544
    let root = dir.path();
8545
    let repo = Repo::init(root).unwrap();
8546
    let text = |i: usize, round: usize| {
8547
        let mut s = String::new();
8548
        for line in 0..50 {
8549
            if round > 0 && line % 7 == i % 7 {
8550
                s.push_str(&format!("edited {round} {i} {line}\n"));
8551
            } else {
8552
                s.push_str(&format!("file {i} line {line}\n"));
8553
            }
8554
        }
8555
        if round > 0 && i.is_multiple_of(3) {
8556
            s.push_str("appended\n");
8557
        }
8558
        s
8559
    };
8560
    for i in 0..40 {
8561
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
8562
    }
8563
    repo.commit("first", &[]).unwrap();
8564
    for i in 0..40 {
8565
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
8566
    }
8567
    let h = repo.commit("edit every file", &[]).unwrap();
8568
    let snap = repo.load_state(&[h]).unwrap().materialize();
8569
    for i in 0..40 {
8570
        let want = text(i, 1);
8571
        assert!(
8572
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
8573
            "d/f{i}.txt as committed"
8574
        );
8575
    }
8576
    assert!(
8577
        repo.commit("nothing", &[]).is_err(),
8578
        "nothing left to commit"
8579
    );
8580
}
8581
8582
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
8583
/// is known (fetch printed "up to date" while main was behind), a change
8584
/// only fetched resolves and says where it is, and a checkout whose only
8585
/// remote is not `origin` uses that one.
8586
#[test]
8587
fn a_fetched_change_shows_as_behind_and_resolves() {
8588
    hermetic();
8589
    let dir = tempfile::tempdir().unwrap();
8590
    let root = dir.path();
8591
    let origin = Repo::init(&root.join("origin")).unwrap();
8592
    drop(origin);
8593
    let url = root.join("origin").to_string_lossy().to_string();
8594
    let a = Repo::clone(&url, &root.join("a"))
8595
        .unwrap()
8596
        .with_home(root.join("home-a"));
8597
    write(&root.join("a"), "f.txt", b"one\n");
8598
    a.commit("one", &[]).unwrap();
8599
    a.push("origin", false).unwrap();
8600
    let b = Repo::clone(&url, &root.join("b"))
8601
        .unwrap()
8602
        .with_home(root.join("home-b"));
8603
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8604
8605
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
8606
    let h2 = a.commit("two", &[]).unwrap();
8607
    a.push("origin", false).unwrap();
8608
    b.fetch("origin").unwrap();
8609
    // Fetched, not pulled: one behind, the change found and placed.
8610
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8611
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
8612
    assert_eq!(
8613
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
8614
            .unwrap(),
8615
        h2
8616
    );
8617
    assert_eq!(
8618
        b.remote_only_location(&h2).unwrap().as_deref(),
8619
        Some("origin/main")
8620
    );
8621
    // Fetching again changes nothing: still behind, which is what the
8622
    // CLI now says rather than "up to date".
8623
    b.fetch("origin").unwrap();
8624
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8625
    b.pull("origin").unwrap();
8626
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8627
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
8628
8629
    // One remote, not called origin: it is the default.
8630
    let mut c = Repo::init(&root.join("c")).unwrap();
8631
    assert_eq!(c.default_remote(), "origin");
8632
    c.config.set("remote.earth.url", &url).unwrap();
8633
    assert_eq!(c.default_remote(), "earth");
8634
    c.config.set("remote.origin.url", &url).unwrap();
8635
    assert_eq!(c.default_remote(), "origin");
8636
}
8637
8638
/// oxygen#57: a clone from a relative local path records the remote as an
8639
/// absolute path, so fetch still finds it from inside the clone.
8640
#[test]
8641
fn a_clone_from_a_relative_path_records_it_absolute() {
8642
    hermetic();
8643
    let dir = tempfile::tempdir().unwrap();
8644
    let root = dir.path();
8645
    Repo::init(&root.join("origin")).unwrap();
8646
    let rel = crate::protocol::stored_url("relative/repo");
8647
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
8648
    assert_eq!(
8649
        crate::protocol::stored_url("https://hub.example/o/n"),
8650
        "https://hub.example/o/n"
8651
    );
8652
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
8653
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
8654
    // A bucket is kept as written: it is not a path.
8655
    assert_eq!(
8656
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
8657
        "s3://bucket/prefix?profile=p"
8658
    );
8659
    let url = root.join("origin").to_string_lossy().to_string();
8660
    let b = Repo::clone(&url, &root.join("b")).unwrap();
8661
    assert_eq!(b.config.remotes["origin"], url);
8662
    b.fetch("origin").unwrap();
8663
}
8664
8665
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
8666
/// and gets its subrepos at their pins from this workspace's copies, with
8667
/// their remotes pointing where the subrepos come from.
8668
#[test]
8669
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
8670
    hermetic();
8671
    let dir = tempfile::tempdir().unwrap();
8672
    let root = dir.path();
8673
    Repo::init(&root.join("lib-origin")).unwrap();
8674
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
8675
    let lib = Repo::clone(&lib_url, &root.join("lib"))
8676
        .unwrap()
8677
        .with_home(root.join("home"));
8678
    write(&root.join("lib"), "lib.txt", b"v1\n");
8679
    let l1 = lib.commit("lib v1", &[]).unwrap();
8680
    assert!(lib.push("origin", false).unwrap()[0].ok);
8681
8682
    let app_dir = root.join("app");
8683
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
8684
    write(&app_dir, "main.txt", b"app\n");
8685
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
8686
    app.commit("app with lib", &[]).unwrap();
8687
    // A second bookmark, and the main workspace on another.
8688
    app.bookmark_create("develop", None).unwrap();
8689
    app.bookmark_create("feature", None).unwrap();
8690
    let mut app = app;
8691
    app.bookmark_switch("feature", false).unwrap();
8692
    assert_eq!(app.config.bookmark, "feature");
8693
8694
    // The library's origin goes away: the subrepo must come from here.
8695
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
8696
    let heads = app.resolve_heads("develop").unwrap();
8697
    let ws = app
8698
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
8699
        .unwrap();
8700
    assert_eq!(
8701
        ws.config.bookmark, "develop",
8702
        "the new workspace is on develop"
8703
    );
8704
    assert_eq!(
8705
        app.config.bookmark, "feature",
8706
        "and this one stays on its own"
8707
    );
8708
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
8709
    assert_eq!(
8710
        sub.config.remotes["origin"], lib_url,
8711
        "its origin is the subrepo's URL"
8712
    );
8713
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
8714
    assert_eq!(
8715
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
8716
        b"v1\n"
8717
    );
8718
}
8719
8720
/// Revsets (docs/revset_query_language.md): symbols, relations, set
8721
/// operators and the predicates, over a small graph with two heads and
8722
/// a rename.
8723
#[test]
8724
fn revsets_select_changes_by_relation_author_text_date_and_path() {
8725
    hermetic();
8726
    let dir = tempfile::tempdir().unwrap();
8727
    let root = dir.path();
8728
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8729
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
8730
        .unwrap();
8731
    write(root, "src/a.rs", b"one\n");
8732
    let a = repo.commit("first: add a", &[]).unwrap();
8733
    write(root, "src/a.rs", b"one\ntwo\n");
8734
    let b = repo.commit("second: grow a", &[]).unwrap();
8735
    // A second head, independent of b: a new file on top of a.
8736
    repo.checkout(&[a], false, "checkout a").unwrap();
8737
    write(root, "docs/notes.md", b"notes\n");
8738
    let c = repo.commit("third: notes", &[]).unwrap();
8739
    // Back to both heads, then rename a.rs: the node keeps its identity.
8740
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
8741
        .unwrap();
8742
    fs::remove_file(root.join("src/a.rs")).unwrap();
8743
    write(root, "src/z.rs", b"one\ntwo\n");
8744
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
8745
    let wc = repo.working_copy().unwrap().0;
8746
    // A saved revset is checked when set.
8747
    repo.set_user_config("revset.mine", "author(me) & ::main")
8748
        .unwrap();
8749
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
8750
    let set = |src: &str| -> Vec<ChangeHash> {
8751
        let mut v = repo.revset(src).unwrap().hashes;
8752
        v.sort();
8753
        v
8754
    };
8755
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
8756
        let mut v = hs.to_vec();
8757
        v.sort();
8758
        v
8759
    };
8760
8761
    // Changes commute: a new file depends on nothing and the rename on the
8762
    // file's creation, so the graph is a, b->a, d->a, c, and the working
8763
    // copy on the three heads b, c, d.
8764
    let heads = sorted(&repo.bookmark_heads().unwrap());
8765
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
8766
    assert!(heads.contains(&d) && heads.contains(&c));
8767
    // Symbols and closures.
8768
    assert_eq!(set("main"), heads);
8769
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
8770
    assert_eq!(set("@"), vec![wc]);
8771
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
8772
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
8773
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
8774
    assert_eq!(
8775
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
8776
        sorted(&[a, b])
8777
    );
8778
    // Ranges: what main has beyond b, and `..` forms.
8779
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
8780
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
8781
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
8782
    // Operators and precedence: ~ binds tighter than &, & than |.
8783
    assert_eq!(
8784
        set(&format!("::main ~ #{}", d.short(12))),
8785
        sorted(&[a, b, c])
8786
    );
8787
    assert_eq!(
8788
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
8789
        sorted(&[b, c])
8790
    );
8791
    assert_eq!(set("all() ~ ::main"), vec![wc]);
8792
    // Relations.
8793
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
8794
    head_deps.sort();
8795
    head_deps.dedup();
8796
    assert_eq!(set("deps(main)"), head_deps);
8797
    let on_a: Vec<ChangeHash> = [b, c, d]
8798
        .into_iter()
8799
        .filter(|h| meta(h).deps.contains(&a))
8800
        .collect();
8801
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
8802
    assert_eq!(set("heads(::main)"), heads);
8803
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
8804
    assert_eq!(
8805
        set(&format!(
8806
            "heads(#{} | #{} | #{})",
8807
            a.short(12),
8808
            b.short(12),
8809
            c.short(12)
8810
        )),
8811
        sorted(&[b, c])
8812
    );
8813
    assert_eq!(set("latest(::main, 1)"), vec![d]);
8814
    assert_eq!(set("kind(working-copy)"), vec![wc]);
8815
    assert_eq!(set("none()"), vec![]);
8816
    // Predicates: author by name, email, key prefix and `me`.
8817
    let key = repo.config.author_key.unwrap();
8818
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
8819
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
8820
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
8821
    assert_eq!(set("author(me) & ::main").len(), 4);
8822
    assert_eq!(set("author(nobody)"), vec![]);
8823
    assert_eq!(set("description(notes)"), vec![c]);
8824
    assert_eq!(set("description(\"rename a\")"), vec![d]);
8825
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
8826
    assert_eq!(set("date(..2000-01-01)"), vec![]);
8827
    // touches follows the node through the rename, in the current state.
8828
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
8829
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
8830
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
8831
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
8832
    // Newest first in the result order.
8833
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
8834
    // The saved revset, and errors that say what is wrong.
8835
    assert_eq!(set("mine()").len(), 4);
8836
    let e = repo.revset("nosuch()").unwrap_err().to_string();
8837
    assert!(e.contains("unknown function nosuch()"), "{e}");
8838
    let e = repo.revset("main &").unwrap_err().to_string();
8839
    assert!(e.contains("at character"), "{e}");
8840
    let e = repo.revset("zzzz").unwrap_err().to_string();
8841
    assert!(e.contains("no change matches"), "{e}");
8842
    let e = repo
8843
        .revset_with_budget("::main", std::time::Duration::ZERO)
8844
        .unwrap_err()
8845
        .to_string();
8846
    assert!(e.contains("budget"), "{e}");
8847
    // The log entries carry the bookmark's heads and the working copy.
8848
    let entries = repo.log_revset("::@").unwrap();
8849
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
8850
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
8851
    // push); then a signed change, a tag, and a revocation.
8852
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
8853
    assert_eq!(set("signed_by(me)"), vec![]);
8854
    repo.sign_change(&d).unwrap();
8855
    assert_eq!(set("signed_by(me)"), vec![d]);
8856
    assert_eq!(set("signed_by([email protected])"), vec![d]);
8857
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
8858
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
8859
    assert_eq!(set("delegated()"), vec![]);
8860
    assert_eq!(set("revoked()"), vec![]);
8861
    assert_eq!(set("attested(tag)"), vec![]);
8862
    repo.tag_create("v1", &[b], "first").unwrap();
8863
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
8864
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
8865
    assert_eq!(set("attested(receipt)"), vec![]);
8866
    assert_eq!(set("built(test)"), vec![]);
8867
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
8868
    assert!(e.contains("tag, receipt or ref"), "{e}");
8869
    repo.revoke_identity(&key, "test").unwrap();
8870
    assert_eq!(set("revoked()"), vec![d]);
8871
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
8872
}
8873
8874
#[test]
8875
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
8876
    let dir = tempfile::tempdir().unwrap();
8877
    let root = dir.path();
8878
    let home = root.join("home");
8879
    // Ada's identity lives in the user file; repository `a` pins the same
8880
    // key in its own file, repository `b` names none.
8881
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
8882
    let (key, _) = a
8883
        .create_identity("Ada", "[email protected]", IdentityScope::User)
8884
        .unwrap();
8885
    a.config.set("author.key", &key.to_hex()).unwrap();
8886
    a.save_config().unwrap();
8887
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
8888
    let r = a
8889
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
8890
        .unwrap();
8891
    assert_eq!(
8892
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
8893
        r.new.to_hex(),
8894
        "the user file follows"
8895
    );
8896
    assert_eq!(
8897
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
8898
        r.new.to_hex(),
8899
        "the pinning repository follows"
8900
    );
8901
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
8902
    assert_eq!(
8903
        b.config.author_key,
8904
        Some(r.new),
8905
        "a checkout without a pin follows the user file"
8906
    );
8907
    // A repository-scoped identity leaves the user file alone.
8908
    let other_home = root.join("home2");
8909
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
8910
    let (ck, _) = c
8911
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
8912
        .unwrap();
8913
    assert!(!other_home.join("config.toml").exists());
8914
    let r2 = c.rotate_identity().unwrap();
8915
    assert_ne!(r2.new, ck);
8916
    assert_eq!(
8917
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
8918
        r2.new.to_hex()
8919
    );
8920
    assert!(
8921
        !other_home.join("config.toml").exists(),
8922
        "a repository-scoped identity stays repository-scoped"
8923
    );
8924
    // Several delegates in one rotation; a repeat is refused.
8925
    let (d1, d2) = (
8926
        SecretKey::generate().identity("D1", "d1@x", 1),
8927
        SecretKey::generate().identity("D2", "d2@x", 1),
8928
    );
8929
    let r3 = c
8930
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
8931
        .unwrap();
8932
    assert_eq!(r3.identity.delegates.len(), 2);
8933
    assert!(c
8934
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
8935
        .is_err());
8936
}
8937
8938
/// Two unrelated histories that both add the same file, joined by two
8939
/// independent merges on two branches, then those branches merged: Git
8940
/// merges identical additions cleanly, and the import must too (#71,
8941
/// found in VS Code's history).
8942
#[test]
8943
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
8944
    // Batches of one: every merge renders apart from the state, where a
8945
    // file whose graph the state had built came out empty (#71).
8946
    crate::repo::git::set_merge_batch_for_tests(Some(1));
8947
    hermetic();
8948
    if std::process::Command::new("git")
8949
        .arg("--version")
8950
        .output()
8951
        .is_err()
8952
    {
8953
        eprintln!("git not installed; skipping");
8954
        return;
8955
    }
8956
    let dir = tempfile::tempdir().unwrap();
8957
    let root = dir.path();
8958
    let g = root.join("src.git");
8959
    fs::create_dir_all(&g).unwrap();
8960
    let git = |args: &[&str]| -> String {
8961
        let out = std::process::Command::new("git")
8962
            .arg("-C")
8963
            .arg(&g)
8964
            .args([
8965
                "-c",
8966
                "user.name=Grace",
8967
                "-c",
8968
                "[email protected]",
8969
                "-c",
8970
                "commit.gpgsign=false",
8971
            ])
8972
            .args(args)
8973
            .output()
8974
            .unwrap();
8975
        assert!(
8976
            out.status.success(),
8977
            "git {args:?}: {}",
8978
            String::from_utf8_lossy(&out.stderr)
8979
        );
8980
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8981
    };
8982
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
8983
    // History A: main.
8984
    git(&["init", "-q", "-b", "main"]);
8985
    write(&g, "gulpfile.js", text);
8986
    write(&g, "a.txt", b"a\n");
8987
    git(&["add", "."]);
8988
    git(&["commit", "-q", "-m", "A root"]);
8989
    // History B: an unrelated root adding the same file, identical.
8990
    git(&["checkout", "-q", "--orphan", "fork"]);
8991
    git(&["rm", "-q", "-r", "--cached", "."]);
8992
    for f in ["gulpfile.js", "a.txt"] {
8993
        let _ = fs::remove_file(g.join(f));
8994
    }
8995
    write(&g, "gulpfile.js", text);
8996
    write(&g, "b.txt", b"b\n");
8997
    git(&["add", "."]);
8998
    git(&["commit", "-q", "-m", "B root"]);
8999
    // Two branches from main, each joining B on its own.
9000
    git(&["checkout", "-q", "-b", "one", "main"]);
9001
    git(&[
9002
        "merge",
9003
        "-q",
9004
        "--no-ff",
9005
        "--allow-unrelated-histories",
9006
        "-m",
9007
        "join on one",
9008
        "fork",
9009
    ]);
9010
    git(&["checkout", "-q", "-b", "two", "main"]);
9011
    write(&g, "a.txt", b"a\ntwo\n");
9012
    git(&["commit", "-q", "-am", "work on two"]);
9013
    git(&[
9014
        "merge",
9015
        "-q",
9016
        "--no-ff",
9017
        "--allow-unrelated-histories",
9018
        "-m",
9019
        "join on two",
9020
        "fork",
9021
    ]);
9022
    // Then the two joins meet, and the file is reformatted after.
9023
    git(&["checkout", "-q", "main"]);
9024
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
9025
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
9026
    write(
9027
        &g,
9028
        "gulpfile.js",
9029
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
9030
    );
9031
    git(&["commit", "-q", "-am", "after"]);
9032
9033
    let dest = root.join("dest");
9034
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
9035
    repo.import_git(&g, "main").unwrap();
9036
    let v = repo.verify_git_import(&g, "main").unwrap();
9037
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9038
    assert_eq!(
9039
        fs::read(dest.join("gulpfile.js")).unwrap(),
9040
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
9041
    );
9042
}
9043
9044
/// As above, but the two joins keep different copies (each branch had a
9045
/// different version when it joined), and later work edits each copy:
9046
/// the shape of VS Code's c67ef57cda90 (#71).
9047
#[test]
9048
fn git_import_joins_where_each_join_kept_a_different_copy() {
9049
    // Batches of one: every merge renders apart from the state, where a
9050
    // file whose graph the state had built came out empty (#71).
9051
    crate::repo::git::set_merge_batch_for_tests(Some(1));
9052
    hermetic();
9053
    if std::process::Command::new("git")
9054
        .arg("--version")
9055
        .output()
9056
        .is_err()
9057
    {
9058
        eprintln!("git not installed; skipping");
9059
        return;
9060
    }
9061
    let dir = tempfile::tempdir().unwrap();
9062
    let root = dir.path();
9063
    let g = root.join("src.git");
9064
    fs::create_dir_all(&g).unwrap();
9065
    let run = |args: &[&str]| {
9066
        std::process::Command::new("git")
9067
            .arg("-C")
9068
            .arg(&g)
9069
            .args([
9070
                "-c",
9071
                "user.name=Grace",
9072
                "-c",
9073
                "[email protected]",
9074
                "-c",
9075
                "commit.gpgsign=false",
9076
            ])
9077
            .args(args)
9078
            .output()
9079
            .unwrap()
9080
    };
9081
    let git = |args: &[&str]| -> String {
9082
        let out = run(args);
9083
        assert!(
9084
            out.status.success(),
9085
            "git {args:?}: {}",
9086
            String::from_utf8_lossy(&out.stderr)
9087
        );
9088
        String::from_utf8_lossy(&out.stdout).trim().to_string()
9089
    };
9090
    git(&["init", "-q", "-b", "main"]);
9091
    write(
9092
        &g,
9093
        "gulpfile.js",
9094
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
9095
    );
9096
    git(&["add", "."]);
9097
    git(&["commit", "-q", "-m", "A root"]);
9098
    write(
9099
        &g,
9100
        "gulpfile.js",
9101
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
9102
    );
9103
    git(&["commit", "-q", "-am", "whitespace"]);
9104
    git(&["checkout", "-q", "--orphan", "fork"]);
9105
    git(&["rm", "-q", "-r", "--cached", "."]);
9106
    let _ = fs::remove_file(g.join("gulpfile.js"));
9107
    write(
9108
        &g,
9109
        "gulpfile.js",
9110
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
9111
    );
9112
    git(&["add", "."]);
9113
    git(&["commit", "-q", "-m", "B root"]);
9114
    // Branch one joins B keeping main's copy; branch two keeps B's.
9115
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
9116
        git(&["checkout", "-q", "-b", branch, "main"]);
9117
        let _ = run(&[
9118
            "merge",
9119
            "-q",
9120
            "--no-ff",
9121
            "--allow-unrelated-histories",
9122
            "-m",
9123
            "join",
9124
            "fork",
9125
        ]);
9126
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
9127
        git(&["add", "gulpfile.js"]);
9128
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
9129
    }
9130
    // Each branch then edits its copy.
9131
    git(&["checkout", "-q", "one"]);
9132
    write(
9133
        &g,
9134
        "gulpfile.js",
9135
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
9136
    );
9137
    git(&["commit", "-q", "-am", "tslint on one"]);
9138
    git(&["checkout", "-q", "two"]);
9139
    write(
9140
        &g,
9141
        "gulpfile.js",
9142
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
9143
    );
9144
    write(&g, "extra.txt", b"x\n");
9145
    write(&g, "more.txt", b"m\n");
9146
    git(&["add", "."]);
9147
    git(&["commit", "-q", "-am", "fmt on two"]);
9148
    // They meet: resolved by hand.
9149
    git(&["checkout", "-q", "one"]);
9150
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
9151
    write(
9152
        &g,
9153
        "gulpfile.js",
9154
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
9155
    );
9156
    git(&["add", "gulpfile.js"]);
9157
    git(&["commit", "-q", "-m", "merge two into one"]);
9158
9159
    let dest = root.join("dest");
9160
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
9161
    repo.import_git(&g, "one").unwrap();
9162
    let v = repo.verify_git_import(&g, "one").unwrap();
9163
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9164
}
9165
9166
/// oxygen#68: on a store that is not this disk's directory, the operation
9167
/// head is the store's reference record, moved by compare-and-swap. Two
9168
/// handles recording from the same head both get through, merged; a swap
9169
/// from a stale version is refused; a second repository cannot start on a
9170
/// store that already holds one.
9171
#[test]
9172
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
9173
    use crate::strata::{MemoryStore, Store as _};
9174
    let backend = std::sync::Arc::new(MemoryStore::new());
9175
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9176
    let dir = tempfile::tempdir().unwrap();
9177
    let a = Repo::init(dir.path()).unwrap();
9178
    assert!(
9179
        !dir.path().join(".oxy/ops/head").exists(),
9180
        "the head is not a file"
9181
    );
9182
    let (h0, op0) = a.head_op().unwrap();
9183
    let record = backend
9184
        .read_ref(HEAD_RECORD)
9185
        .unwrap()
9186
        .expect("the head is the store's record");
9187
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
9188
9189
    let b = Repo::open(dir.path()).unwrap();
9190
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9191
    let mut va = op0.view.clone();
9192
    va.bookmarks.insert("from-a".into(), state);
9193
    let mut vb = op0.view.clone();
9194
    vb.bookmarks.insert("from-b".into(), state);
9195
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
9196
    assert_eq!(b.head_ref().unwrap(), rb);
9197
    // a recorded from h0 too: the head moved, so the two are merged.
9198
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
9199
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
9200
    assert_eq!(head, ra);
9201
    assert!(
9202
        op.command.ends_with("(merged with a concurrent operation)"),
9203
        "{}",
9204
        op.command
9205
    );
9206
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
9207
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
9208
9209
    // A swap from a version that is no longer current moves nothing.
9210
    let (h, v) = a.read_head().unwrap();
9211
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
9212
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
9213
    a.refresh().unwrap();
9214
    assert_eq!(a.head_ref().unwrap(), rb);
9215
9216
    let other = tempfile::tempdir().unwrap();
9217
    let err = Repo::init(other.path())
9218
        .err()
9219
        .expect("the store already holds a log")
9220
        .to_string();
9221
    assert!(
9222
        err.contains("already holds a repository's operation log"),
9223
        "{err}"
9224
    );
9225
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9226
}
9227
9228
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
9229
/// objects and operation head there, with `.oxy/cache` in front: it works
9230
/// as one on disk does, reopens, and survives losing its cache.
9231
#[test]
9232
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
9233
    hermetic();
9234
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
9235
        return;
9236
    }
9237
    let dir = tempfile::tempdir().unwrap();
9238
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
9239
    let url = format!("dir://{}", bucket.display());
9240
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
9241
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
9242
    write(&root, "a.txt", b"one\n");
9243
    let h1 = repo.commit("First", &[]).unwrap();
9244
    write(&root, "a.txt", b"one\ntwo\n");
9245
    let h2 = repo.commit("Second", &[]).unwrap();
9246
    assert!(
9247
        !root.join(".oxy/ops/head").exists(),
9248
        "the head is in the store"
9249
    );
9250
    assert!(bucket.join("ops/head").is_file());
9251
    assert!(root.join(".oxy/cache").is_dir());
9252
    drop(repo);
9253
9254
    // Reopened, and again with no cache at all: everything comes from the store.
9255
    for drop_cache in [false, true] {
9256
        if drop_cache {
9257
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
9258
        }
9259
        let repo = Repo::open(&root).unwrap();
9260
        let log: Vec<String> = repo
9261
            .op_log()
9262
            .unwrap()
9263
            .into_iter()
9264
            .map(|(_, op)| op.command)
9265
            .collect();
9266
        assert!(log.len() >= 3, "{log:?}");
9267
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
9268
        let heads = repo
9269
            .store()
9270
            .get_state(&repo.view().unwrap().bookmarks["main"])
9271
            .unwrap()
9272
            .heads;
9273
        assert_eq!(heads, vec![h2]);
9274
        assert_eq!(
9275
            repo.load_state(&heads).unwrap().materialize().files.len(),
9276
            1
9277
        );
9278
    }
9279
9280
    // A second repository cannot start on the same store.
9281
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
9282
        .err()
9283
        .unwrap()
9284
        .to_string();
9285
    assert!(
9286
        err.contains("already holds a repository's operation log"),
9287
        "{err}"
9288
    );
9289
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
9290
        .err()
9291
        .unwrap()
9292
        .to_string();
9293
    assert!(err.contains("cannot open that kind of store"), "{err}");
9294
}
9295
9296
/// oxygen#75: the prompt's quick check agrees with status in a repository
9297
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
9298
/// another state, clean again once that pin is committed. (It compared the
9299
/// subrepo's directory as if it were a file, so it was always dirty.)
9300
#[test]
9301
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
9302
    hermetic();
9303
    let dir = tempfile::tempdir().unwrap();
9304
    let root = dir.path();
9305
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9306
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9307
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9308
        .unwrap()
9309
        .with_home(root.join("home"));
9310
    write(&root.join("lib"), "lib.txt", b"v1\n");
9311
    lib.commit("lib v1", &[]).unwrap();
9312
    assert!(lib.push("origin", false).unwrap()[0].ok);
9313
    let app_dir = root.join("app");
9314
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9315
    write(&app_dir, "main.txt", b"app\n");
9316
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9317
    app.commit("app with lib", &[]).unwrap();
9318
    // Out of the racy window, so the stat-only path decides.
9319
    std::thread::sleep(std::time::Duration::from_millis(2100));
9320
    let reopen = || Repo::open(&app_dir).unwrap();
9321
    assert_eq!(
9322
        reopen().quick_dirty().unwrap(),
9323
        Some(false),
9324
        "clean, as status says"
9325
    );
9326
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
9327
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
9328
    nested.commit("lib v2", &[]).unwrap();
9329
    assert_eq!(
9330
        reopen().quick_dirty().unwrap(),
9331
        Some(true),
9332
        "the subrepo moved"
9333
    );
9334
    reopen().commit("pin lib v2", &[]).unwrap();
9335
    std::thread::sleep(std::time::Duration::from_millis(2100));
9336
    assert_eq!(
9337
        reopen().quick_dirty().unwrap(),
9338
        Some(false),
9339
        "the new pin is committed"
9340
    );
9341
}
9342
9343
#[test]
9344
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
9345
    // oxygen#72: a .oxymodules section with no subrepo behind it.
9346
    hermetic();
9347
    let dir = tempfile::tempdir().unwrap();
9348
    let root = dir.path();
9349
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9350
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9351
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9352
        .unwrap()
9353
        .with_home(root.join("home"));
9354
    write(&root.join("lib"), "lib.txt", b"v1\n");
9355
    lib.commit("lib v1", &[]).unwrap();
9356
    assert!(lib.push("origin", false).unwrap()[0].ok);
9357
    let app_dir = root.join("app");
9358
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9359
    write(
9360
        &app_dir,
9361
        ".oxymodules",
9362
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
9363
    );
9364
    let unpinned = app.unpinned_modules().unwrap();
9365
    assert_eq!(unpinned.len(), 1);
9366
    assert_eq!(unpinned[0].0, "libs/lib");
9367
    assert_eq!(unpinned[0].1.url, lib_url);
9368
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
9369
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9370
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
9371
}
9372
9373
#[test]
9374
fn the_bookmark_revset_function_names_only_bookmarks() {
9375
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
9376
    hermetic();
9377
    let dir = tempfile::tempdir().unwrap();
9378
    let repo = Repo::init(dir.path()).unwrap();
9379
    write(dir.path(), "a.txt", b"a\n");
9380
    let a = repo.commit("A", &[]).unwrap();
9381
    write(dir.path(), "b.txt", b"b\n");
9382
    let b = repo.commit("B", &[]).unwrap();
9383
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
9384
    heads.sort();
9385
    let mut want = repo.bookmark_heads().unwrap();
9386
    want.sort();
9387
    assert_eq!(heads, want);
9388
    assert!(heads.contains(&b));
9389
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
9390
    // A change prefix is a symbol, not a bookmark.
9391
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
9392
    assert!(repo.revset(&prefix).is_ok());
9393
    let e = repo
9394
        .revset(&format!("bookmark({prefix})"))
9395
        .unwrap_err()
9396
        .to_string();
9397
    assert!(e.contains("no such bookmark"), "{e}");
9398
}
9399
9400
/// oxygen#140: a replace conflict is settled from the working copy, as
9401
/// `oxy resolve PATH` does: the path's content on disk becomes the
9402
/// resolution, and the commit that records it is a Resolution.
9403
#[test]
9404
fn a_replace_conflict_is_settled_from_the_working_copy() {
9405
    hermetic();
9406
    let dir = tempfile::tempdir().unwrap();
9407
    let root = dir.path();
9408
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
9409
    let blob = |n: u8| {
9410
        let mut v = vec![0u8; 64];
9411
        v[1] = n;
9412
        v
9413
    };
9414
    write(root, "img.bin", &blob(1));
9415
    write(root, "a.txt", b"a\n");
9416
    repo.commit("add img", &[]).unwrap();
9417
    repo.bookmark_create("other", None).unwrap();
9418
    write(root, "img.bin", &blob(2));
9419
    repo.commit("img two", &[]).unwrap();
9420
    repo.bookmark_switch("other", false).unwrap();
9421
    write(root, "img.bin", &blob(3));
9422
    repo.commit("img three", &[]).unwrap();
9423
    repo.bookmark_switch("main", false).unwrap();
9424
    repo.merge("other").unwrap();
9425
    // Without a choice, nothing the working copy holds settles it, and
9426
    // other work cannot be committed past it.
9427
    write(root, "img.bin", &blob(9));
9428
    write(root, "a.txt", b"a\nmore\n");
9429
    assert!(
9430
        repo.commit("edit a", &[]).is_err(),
9431
        "refused while conflicted"
9432
    );
9433
    let snap = repo.snapshot("oxy resolve").unwrap();
9434
    assert!(
9435
        repo.choose_resolutions(&snap.base_snapshot, &["a.txt".to_string()])
9436
            .is_err(),
9437
        "a.txt has no replace conflict"
9438
    );
9439
    repo.choose_resolutions(&snap.base_snapshot, &["img.bin".to_string()])
9440
        .unwrap();
9441
    let snap = repo.snapshot("oxy resolve").unwrap();
9442
    assert!(snap
9443
        .statuses
9444
        .iter()
9445
        .any(|s| s.path == "img.bin" && s.status == ChangeStatus::Resolved));
9446
    let c = repo.commit("settle img", &[]).unwrap();
9447
    assert_eq!(
9448
        repo.store().get_change(&c).unwrap().kind,
9449
        ChangeKind::Resolution
9450
    );
9451
    let after = repo
9452
        .load_state(&repo.bookmark_heads().unwrap())
9453
        .unwrap()
9454
        .materialize();
9455
    assert!(!after.is_conflicted());
9456
    assert_eq!(
9457
        after.files["img.bin"].content,
9458
        FileContent::Opaque {
9459
            blobs: vec![Repo::blob_ref(&blob(9))]
9460
        }
9461
    );
9462
    assert!(
9463
        matches!(&after.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nmore\n")
9464
    );
9465
    // Settled: the choice is forgotten, and the working copy is clean.
9466
    let snap = repo.snapshot("status").unwrap();
9467
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
9468
    assert!(repo.resolutions().unwrap().is_empty());
9469
}
9470
9471
/// oxygen#140: the same for a subrepo pin moved two ways at once.
9472
#[test]
9473
fn a_pin_conflict_is_settled_from_the_working_copy() {
9474
    hermetic();
9475
    let dir = tempfile::tempdir().unwrap();
9476
    let root = dir.path();
9477
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9478
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9479
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9480
        .unwrap()
9481
        .with_home(root.join("home"));
9482
    write(&root.join("lib"), "lib.txt", b"v1\n");
9483
    lib.commit("lib v1", &[]).unwrap();
9484
    assert!(lib.push("origin", false).unwrap()[0].ok);
9485
    let app_dir = root.join("app");
9486
    let mut app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9487
    write(&app_dir, "main.txt", b"app\n");
9488
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9489
    app.commit("pin v1", &[]).unwrap();
9490
    let nested = Repo::open(&app_dir.join("libs/lib"))
9491
        .unwrap()
9492
        .with_home(root.join("home"));
9493
    fn pin(app: &Repo, nested: &Repo, text: &[u8], message: &str) {
9494
        write(nested.root(), "lib.txt", text);
9495
        nested.commit(message, &[]).unwrap();
9496
        app.commit(&format!("pin {message}"), &[]).unwrap();
9497
    }
9498
    app.bookmark_create("other", None).unwrap();
9499
    pin(&app, &nested, b"v2\n", "v2");
9500
    app.bookmark_switch("other", false).unwrap();
9501
    pin(&app, &nested, b"v3\n", "v3");
9502
    app.bookmark_switch("main", false).unwrap();
9503
    app.merge("other").unwrap();
9504
    let merged = app
9505
        .load_state(&app.bookmark_heads().unwrap())
9506
        .unwrap()
9507
        .materialize();
9508
    assert!(
9509
        matches!(&merged.files["libs/lib"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
9510
        "a pin conflict"
9511
    );
9512
    // The nested repository moves on once more; that pin is the choice.
9513
    write(&app_dir.join("libs/lib"), "lib.txt", b"v4\n");
9514
    nested.commit("v4", &[]).unwrap();
9515
    let snap = app.snapshot("oxy resolve").unwrap();
9516
    app.choose_resolutions(&snap.base_snapshot, &["libs/lib".to_string()])
9517
        .unwrap();
9518
    let c = app.commit("settle the pin", &[]).unwrap();
9519
    assert_eq!(
9520
        app.store().get_change(&c).unwrap().kind,
9521
        ChangeKind::Resolution
9522
    );
9523
    let after = app
9524
        .load_state(&app.bookmark_heads().unwrap())
9525
        .unwrap()
9526
        .materialize();
9527
    assert!(!after.is_conflicted());
9528
    assert!(app.snapshot("status").unwrap().statuses.is_empty());
9529
}
9530
9531
#[test]
9532
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
9533
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
9534
    // pinning the subrepo, and the nested repository on disk at that pin.
9535
    hermetic();
9536
    let dir = tempfile::tempdir().unwrap();
9537
    let root = dir.path();
9538
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9539
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9540
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9541
        .unwrap()
9542
        .with_home(root.join("home"));
9543
    write(&root.join("lib"), "lib.txt", b"v1\n");
9544
    lib.commit("lib v1", &[]).unwrap();
9545
    assert!(lib.push("origin", false).unwrap()[0].ok);
9546
    let app_dir = root.join("app");
9547
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9548
    write(&app_dir, "main.txt", b"app\n");
9549
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9550
    // The stale state: registered in .oxymodules, never pinned.
9551
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
9552
    app.commit("initial", &[]).unwrap();
9553
    let stale = app.bookmark_heads().unwrap();
9554
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
9555
    app.commit("pin lib", &[]).unwrap();
9556
    let newer = app.bookmark_heads().unwrap();
9557
    app.checkout(&stale, false, "test").unwrap();
9558
    write(&app_dir, "notes.txt", b"mine\n");
9559
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
9560
    assert_eq!(carried, vec!["notes.txt".to_string()]);
9561
    assert!(app_dir.join("notes.txt").exists());
9562
}
9563
9564
/// oxygen#142: a new bookmark made from main sends what main lacks, not
9565
/// its whole history again.
9566
#[test]
9567
fn a_new_bookmark_sends_only_what_the_remote_lacks() {
9568
    hermetic();
9569
    let dir = tempfile::tempdir().unwrap();
9570
    let root = dir.path();
9571
    let _origin = Repo::init(&root.join("origin")).unwrap();
9572
    let url = root.join("origin").to_string_lossy().to_string();
9573
    let mut one = Repo::clone(&url, &root.join("one"))
9574
        .unwrap()
9575
        .with_home(root.join("home"));
9576
    for n in 0..5 {
9577
        write(&root.join("one"), "a.txt", format!("{n}\n").as_bytes());
9578
        one.commit(&format!("main {n}"), &[]).unwrap();
9579
    }
9580
    assert!(one.push("origin", false).unwrap()[0].ok);
9581
    one.bookmark_create("feature", None).unwrap();
9582
    one.bookmark_switch("feature", false).unwrap();
9583
    write(&root.join("one"), "b.txt", b"feature\n");
9584
    let added = one.commit("feature", &[]).unwrap();
9585
    let heads = one.bookmark_heads().unwrap();
9586
    let refs = one
9587
        .open_named_remote("origin")
9588
        .unwrap()
9589
        .refs()
9590
        .unwrap()
9591
        .refs;
9592
    assert!(
9593
        refs.iter().all(|r| r.name != "feature"),
9594
        "new to the remote"
9595
    );
9596
    let sent = one
9597
        .negotiate(&one.remote_holds(&refs, &[]), &heads)
9598
        .unwrap();
9599
    assert_eq!(sent, vec![added], "only the change main lacks");
9600
    assert!(one.push_bookmark("origin", "feature", false).unwrap()[0].ok);
9601
    let two = Repo::clone(&url, &root.join("two")).unwrap();
9602
    assert!(two.store().has(&added));
9603
}
9604
9605
#[test]
9606
fn a_bookmark_only_behind_its_remote_catches_up() {
9607
    // oxygen#74: switch takes the remote's state rather than a stale one.
9608
    hermetic();
9609
    let dir = tempfile::tempdir().unwrap();
9610
    let root = dir.path();
9611
    let _origin = Repo::init(&root.join("origin")).unwrap();
9612
    let url = root.join("origin").to_string_lossy().to_string();
9613
    let one = Repo::clone(&url, &root.join("one"))
9614
        .unwrap()
9615
        .with_home(root.join("home"));
9616
    write(&root.join("one"), "a.txt", b"a\n");
9617
    one.commit("A", &[]).unwrap();
9618
    assert!(one.push("origin", false).unwrap()[0].ok);
9619
    let two = Repo::clone(&url, &root.join("two"))
9620
        .unwrap()
9621
        .with_home(root.join("home"));
9622
    write(&root.join("two"), "b.txt", b"b\n");
9623
    two.commit("B", &[]).unwrap();
9624
    assert!(two.push("origin", false).unwrap()[0].ok);
9625
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
9626
    one.fetch("origin").unwrap();
9627
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
9628
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
9629
    // Local work the remote lacks: left alone.
9630
    write(&root.join("one"), "c.txt", b"c\n");
9631
    one.commit("C", &[]).unwrap();
9632
    write(&root.join("two"), "d.txt", b"d\n");
9633
    two.commit("D", &[]).unwrap();
9634
    assert!(two.push("origin", false).unwrap()[0].ok);
9635
    one.fetch("origin").unwrap();
9636
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
9637
}
9638
9639
#[test]
9640
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
9641
    // oxygen#83: remotes earth and gcs, origin removed.
9642
    hermetic();
9643
    let dir = tempfile::tempdir().unwrap();
9644
    let root = dir.path();
9645
    let _up = Repo::init(&root.join("up")).unwrap();
9646
    let url = root.join("up").to_string_lossy().to_string();
9647
    let other = Repo::clone(&url, &root.join("other"))
9648
        .unwrap()
9649
        .with_home(root.join("home"));
9650
    write(&root.join("other"), "a.txt", b"a\n");
9651
    other.commit("a", &[]).unwrap();
9652
    assert!(other.push("origin", false).unwrap()[0].ok);
9653
    let mut one = Repo::clone(&url, &root.join("one"))
9654
        .unwrap()
9655
        .with_home(root.join("home"));
9656
    one.config.set("remote.earth.url", &url).unwrap();
9657
    one.config.set("remote.gcs.url", &url).unwrap();
9658
    one.config.set("remote.origin.url", "").unwrap();
9659
    one.save_config().unwrap();
9660
    write(&root.join("other"), "b.txt", b"b\n");
9661
    other.commit("b", &[]).unwrap();
9662
    assert!(other.push("origin", false).unwrap()[0].ok);
9663
    one.fetch("earth").unwrap();
9664
    let b = one
9665
        .bookmarks()
9666
        .unwrap()
9667
        .into_iter()
9668
        .find(|b| b.name == "main")
9669
        .unwrap();
9670
    assert_eq!(
9671
        (b.remote.as_deref(), b.behind),
9672
        (Some("earth"), Some(1)),
9673
        "a stale origin copy is not used"
9674
    );
9675
    assert_eq!(
9676
        one.default_remote(),
9677
        "origin",
9678
        "no default chosen among several"
9679
    );
9680
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
9681
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
9682
    one.config.set("core.remote", "earth").unwrap();
9683
    assert_eq!(one.default_remote(), "earth");
9684
}
9685
9686
#[test]
9687
fn a_missing_author_identity_says_how_to_fix_it() {
9688
    // oxygen#82: an agent home's author.key naming an identity the
9689
    // repository does not hold.
9690
    hermetic();
9691
    let dir = tempfile::tempdir().unwrap();
9692
    let mut repo = Repo::init(dir.path()).unwrap();
9693
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
9694
    repo.config.set("author.key", &missing.to_hex()).unwrap();
9695
    let e = repo.identity(&missing).unwrap_err().to_string();
9696
    assert!(
9697
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
9698
        "{e}"
9699
    );
9700
    assert!(e.contains("this repository's config"), "{e}");
9701
}
9702
9703
#[test]
9704
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
9705
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
9706
    // the working copy, a pull with nothing new left it there, and status
9707
    // said "clean".
9708
    hermetic();
9709
    let dir = tempfile::tempdir().unwrap();
9710
    let root = dir.path();
9711
    let _up = Repo::init(&root.join("up")).unwrap();
9712
    let url = root.join("up").to_string_lossy().to_string();
9713
    let other = Repo::clone(&url, &root.join("other"))
9714
        .unwrap()
9715
        .with_home(root.join("home"));
9716
    write(&root.join("other"), "a.txt", b"a\n");
9717
    other.commit("a", &[]).unwrap();
9718
    assert!(other.push("origin", false).unwrap()[0].ok);
9719
    let one = Repo::clone(&url, &root.join("one"))
9720
        .unwrap()
9721
        .with_home(root.join("home"));
9722
    write(&root.join("other"), "b.txt", b"b\n");
9723
    other.commit("b", &[]).unwrap();
9724
    assert!(other.push("origin", false).unwrap()[0].ok);
9725
    one.fetch("origin").unwrap();
9726
    // The bookmark moves; the working copy does not.
9727
    let theirs = one.resolve_heads("origin/main").unwrap();
9728
    one.bookmark_set("main", &theirs).unwrap();
9729
    assert!(!root.join("one/b.txt").exists());
9730
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
9731
    let r = one.pull("origin").unwrap();
9732
    assert!(
9733
        !r.changed && r.checked_out,
9734
        "nothing new, but the working copy caught up"
9735
    );
9736
    assert!(root.join("one/b.txt").exists());
9737
    assert_eq!(one.working_copy_behind().unwrap(), None);
9738
}
9739
9740
#[test]
9741
fn touched_nodes_cache_answers_as_the_changes_do() {
9742
    hermetic();
9743
    let dir = tempfile::tempdir().unwrap();
9744
    let repo = Repo::init(dir.path()).unwrap();
9745
    write(dir.path(), "a.txt", b"one\n");
9746
    write(dir.path(), "b.txt", b"x\n");
9747
    repo.snapshot("t").unwrap();
9748
    let c1 = repo.commit("first", &[]).unwrap();
9749
    write(dir.path(), "b.txt", b"y\n");
9750
    repo.snapshot("t").unwrap();
9751
    repo.commit("b only", &[]).unwrap();
9752
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
9753
    write(dir.path(), "c.txt", b"one\ntwo\n");
9754
    repo.snapshot("t").unwrap();
9755
    let c3 = repo.commit("rename and edit", &[]).unwrap();
9756
    // Uncommitted work, so the working copy touches a file too.
9757
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
9758
    repo.snapshot("t").unwrap();
9759
9760
    let path = dir.path().join(".oxy/index/touched");
9761
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
9762
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
9763
    assert!(path.exists(), "the first query writes the cache");
9764
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
9765
    assert_eq!(cold, warm, "the cache answers as the changes do");
9766
    let (wc, _) = repo.working_copy().unwrap();
9767
    assert_eq!(
9768
        cold,
9769
        vec![wc, c3, c1],
9770
        "renames followed, the working copy included"
9771
    );
9772
9773
    // Working-copy changes are not kept: they are replaced by every snapshot.
9774
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
9775
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
9776
    assert!(cached.contains(&c1) && cached.contains(&c3));
9777
9778
    // A damaged cache is ignored, not trusted.
9779
    let mut bytes = fs::read(&path).unwrap();
9780
    let last = bytes.len() - 40;
9781
    bytes[last] ^= 1;
9782
    fs::write(&path, &bytes).unwrap();
9783
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
9784
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
9785
    assert_eq!(hashes(touches), vec![c3, c1]);
9786
}
9787
9788
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
9789
/// file back where it was leave two placements at one place, which the
9790
/// tree shows as one file. Removing it, and then its directory, retires
9791
/// both, so no copy is left under a directory that is gone.
9792
#[test]
9793
fn git_import_removes_every_copy_of_a_file_at_one_place() {
9794
    hermetic();
9795
    if std::process::Command::new("git")
9796
        .arg("--version")
9797
        .output()
9798
        .is_err()
9799
    {
9800
        eprintln!("git not installed; skipping");
9801
        return;
9802
    }
9803
    let dir = tempfile::tempdir().unwrap();
9804
    let root = dir.path();
9805
    let g = root.join("src.git");
9806
    fs::create_dir_all(&g).unwrap();
9807
    let git = |args: &[&str]| {
9808
        let out = std::process::Command::new("git")
9809
            .arg("-C")
9810
            .arg(&g)
9811
            .args([
9812
                "-c",
9813
                "user.name=Grace",
9814
                "-c",
9815
                "[email protected]",
9816
                "-c",
9817
                "commit.gpgsign=false",
9818
            ])
9819
            .args(args)
9820
            .output()
9821
            .unwrap();
9822
        assert!(
9823
            out.status.success(),
9824
            "git {args:?}: {}",
9825
            String::from_utf8_lossy(&out.stderr)
9826
        );
9827
    };
9828
    git(&["init", "-q", "-b", "main"]);
9829
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
9830
    write(&g, "keep.txt", b"k\n");
9831
    git(&["add", "."]);
9832
    git(&["commit", "-qm", "base"]);
9833
    fs::create_dir_all(g.join("d/sub")).unwrap();
9834
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
9835
    git(&["commit", "-qm", "into sub"]);
9836
    git(&["checkout", "-qb", "side"]);
9837
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9838
    git(&["commit", "-qm", "back, on side"]);
9839
    git(&["checkout", "-q", "main"]);
9840
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
9841
    git(&["commit", "-qm", "back, on main"]);
9842
    git(&["merge", "-q", "--no-edit", "side"]);
9843
    git(&["rm", "-rq", "d"]);
9844
    git(&["commit", "-qm", "d goes"]);
9845
9846
    let repo = Repo::init(&root.join("o")).unwrap();
9847
    repo.import_git(&g, "main").unwrap();
9848
    let v = repo.verify_git_import(&g, "main").unwrap();
9849
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9850
    let st = repo
9851
        .load_state_history(&repo.bookmark_heads().unwrap())
9852
        .unwrap();
9853
    let view = st.tree().view();
9854
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
9855
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
9856
}
9857
9858
/// oxygen#94: a state index's file histories are read, and checked by
9859
/// their own hashes, only when a file is built. One found damaged is an
9860
/// error that says so, the index is removed, and the next read rebuilds it.
9861
#[test]
9862
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
9863
    hermetic();
9864
    let dir = tempfile::tempdir().unwrap();
9865
    let repo = Repo::init(dir.path()).unwrap();
9866
    for i in 0..6 {
9867
        write(
9868
            dir.path(),
9869
            &format!("f{i}.txt"),
9870
            format!("one {i}\n").as_bytes(),
9871
        );
9872
    }
9873
    repo.snapshot("t").unwrap();
9874
    repo.commit("first", &[]).unwrap();
9875
    for i in 0..6 {
9876
        write(
9877
            dir.path(),
9878
            &format!("f{i}.txt"),
9879
            format!("one {i}\ntwo\n").as_bytes(),
9880
        );
9881
    }
9882
    repo.snapshot("t").unwrap();
9883
    repo.commit("second", &[]).unwrap();
9884
    let want: Vec<Vec<u8>> = (0..6)
9885
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
9886
        .collect();
9887
    // The index of the working copy's base, holding every file's history
9888
    // (a few changes behind, an index is replayed onto, not rewritten).
9889
    let (_, wc) = repo.working_copy().unwrap();
9890
    let base = repo.load_state_history(&wc.deps).unwrap();
9891
    repo.write_state_index(&wc.deps, &base);
9892
    for (i, w) in want.iter().enumerate() {
9893
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9894
    }
9895
    let index = repo.state_indexes();
9896
    assert!(!index.is_empty(), "a state index was written");
9897
    // The histories are last in the file: damage the last of them.
9898
    let mut bytes = fs::read(&index[0]).unwrap();
9899
    let last = bytes.len() - 1;
9900
    bytes[last] ^= 0x40;
9901
    fs::write(&index[0], &bytes).unwrap();
9902
9903
    let reads: Vec<_> = (0..6)
9904
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
9905
        .collect();
9906
    let damaged: Vec<String> = reads
9907
        .iter()
9908
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
9909
        .collect();
9910
    assert_eq!(damaged.len(), 1, "{damaged:?}");
9911
    assert!(
9912
        damaged[0].contains("state index was damaged")
9913
            && damaged[0].contains("run the command again"),
9914
        "{}",
9915
        damaged[0]
9916
    );
9917
    // Every file reads right again, from an index rebuilt from history.
9918
    for (i, w) in want.iter().enumerate() {
9919
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
9920
    }
9921
}
9922
9923
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
9924
/// objects alone and in dependency order, and the last moves the bookmark.
9925
/// The remote ends with every change and the same state, and says how each
9926
/// part went.
9927
#[test]
9928
fn a_long_push_goes_in_parts() {
9929
    hermetic();
9930
    let dir = tempfile::tempdir().unwrap();
9931
    let root = dir.path();
9932
    let origin = root.join("origin");
9933
    Repo::init_bare_unbound(&origin).unwrap();
9934
    let main = root.join("main");
9935
    let mut repo = Repo::init(&main).unwrap();
9936
    repo.config
9937
        .set("remote.origin.url", &origin.to_string_lossy())
9938
        .unwrap();
9939
    // One byte: every change is a part of its own.
9940
    repo.config.set("push.batch-bytes", "1").unwrap();
9941
    repo.save_config().unwrap();
9942
    for i in 0..6 {
9943
        write(
9944
            &main,
9945
            &format!("f{i}.txt"),
9946
            format!("file {i}\n").as_bytes(),
9947
        );
9948
        repo.commit(&format!("c{i}"), &[]).unwrap();
9949
    }
9950
    let mut parts = Vec::new();
9951
    let results = repo
9952
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
9953
        .unwrap();
9954
    assert!(
9955
        results.iter().any(|r| r.ok && r.name == "main"),
9956
        "{results:?}"
9957
    );
9958
    assert_eq!(parts.len(), 6, "{parts:?}");
9959
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
9960
9961
    let remote = Repo::open(&origin).unwrap();
9962
    let heads = repo.bookmark_heads().unwrap();
9963
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
9964
    assert_eq!(
9965
        remote.log_state(&heads).unwrap().len(),
9966
        repo.log_state(&heads).unwrap().len()
9967
    );
9968
    // A push of objects alone reports how it went, as `objects`.
9969
    let got = remote
9970
        .receive_push(Bundle::default(), vec![], None, vec![])
9971
        .unwrap();
9972
    assert_eq!(got.len(), 1);
9973
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
9974
}
9975
9976
/// oxygen#133: one change whose blobs pass `push.batch-bytes` sends them
9977
/// first, in parts of objects alone, so no request is larger than about
9978
/// that (a proxy in front of a hub refuses one past 100 MB); the change
9979
/// and the bookmark follow, and a clone has every file.
9980
#[test]
9981
fn a_heavy_change_sends_its_blobs_in_parts() {
9982
    hermetic();
9983
    let dir = tempfile::tempdir().unwrap();
9984
    let root = dir.path();
9985
    let origin = root.join("origin");
9986
    Repo::init_bare_unbound(&origin).unwrap();
9987
    let main = root.join("main");
9988
    let mut repo = Repo::init(&main).unwrap();
9989
    repo.config
9990
        .set("remote.origin.url", &origin.to_string_lossy())
9991
        .unwrap();
9992
    repo.config.set("push.batch-bytes", "50000").unwrap();
9993
    repo.save_config().unwrap();
9994
    let mut x: u64 = 0x9e3779b97f4a7c15;
9995
    let mut noise = |n: usize| -> Vec<u8> {
9996
        (0..n)
9997
            .map(|_| {
9998
                x ^= x << 13;
9999
                x ^= x >> 7;
10000
                x ^= x << 17;
10001
                (x >> 24) as u8
10002
            })
10003
            .collect()
10004
    };
10005
    let files: Vec<Vec<u8>> = (0..4).map(|_| noise(40_000)).collect();
10006
    for (i, f) in files.iter().enumerate() {
10007
        write(&main, &format!("bin{i}.dat"), f);
10008
    }
10009
    repo.commit("four blobs", &[]).unwrap();
10010
    let mut parts = Vec::new();
10011
    let results = repo
10012
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
10013
        .unwrap();
10014
    assert!(
10015
        results.iter().any(|r| r.ok && r.name == "main"),
10016
        "{results:?}"
10017
    );
10018
    assert!(
10019
        parts.len() >= 3 && parts[0].starts_with("objects 1 of"),
10020
        "{parts:?}"
10021
    );
10022
    let back = Repo::clone(&origin.to_string_lossy(), &root.join("back")).unwrap();
10023
    for (i, f) in files.iter().enumerate() {
10024
        assert_eq!(&fs::read(root.join(format!("back/bin{i}.dat"))).unwrap(), f);
10025
    }
10026
    drop(back);
10027
}
10028
10029
/// oxygen#136: a bundle carries a replaced binary file's new content
10030
/// only. Its old content came with the change that added it, so removing
10031
/// or replacing a file sends no old blob again; the remote and a clone of
10032
/// it are whole.
10033
#[test]
10034
fn a_replacement_does_not_send_the_old_content_again() {
10035
    hermetic();
10036
    let dir = tempfile::tempdir().unwrap();
10037
    let root = dir.path();
10038
    let origin = root.join("origin");
10039
    Repo::init_bare_unbound(&origin).unwrap();
10040
    let main = root.join("main");
10041
    let mut repo = Repo::init(&main).unwrap();
10042
    repo.config
10043
        .set("remote.origin.url", &origin.to_string_lossy())
10044
        .unwrap();
10045
    repo.save_config().unwrap();
10046
    let blobs = |b: &Bundle| {
10047
        b.objects
10048
            .iter()
10049
            .filter(|(ty, _)| *ty == ObjectType::Blob)
10050
            .count()
10051
    };
10052
    write(&main, "bin.dat", b"\0\x01first binary");
10053
    write(&main, "gone.dat", b"\0\x02to be removed");
10054
    let added = repo.commit("add", &[]).unwrap();
10055
    assert!(repo.push("origin", false).unwrap()[0].ok);
10056
    write(&main, "bin.dat", b"\0\x01second binary");
10057
    fs::remove_file(main.join("gone.dat")).unwrap();
10058
    let changed = repo.commit("replace and remove", &[]).unwrap();
10059
    assert_eq!(blobs(&repo.bundle_for(&[changed]).unwrap()), 1);
10060
    assert_eq!(blobs(&repo.bundle_for(&[added, changed]).unwrap()), 3);
10061
    assert!(repo.push("origin", false).unwrap()[0].ok);
10062
    let origin = Repo::open(&origin).unwrap();
10063
    assert_eq!(origin.fsck().unwrap().problems, vec![]);
10064
    let back = Repo::clone(&origin.root().to_string_lossy(), &root.join("back")).unwrap();
10065
    assert_eq!(back.fsck().unwrap().problems, vec![]);
10066
    assert_eq!(
10067
        fs::read(root.join("back/bin.dat")).unwrap(),
10068
        b"\0\x01second binary"
10069
    );
10070
    assert!(!root.join("back/gone.dat").exists());
10071
}
10072
10073
/// oxygen#97: with `git.claim`, an import authors the importing identity's
10074
/// own commits (Git author email = its email, any case) with its key, and
10075
/// leaves anyone else's with the zero key; the history verifies as before.
10076
#[test]
10077
fn git_import_claims_your_own_commits() {
10078
    hermetic();
10079
    if std::process::Command::new("git")
10080
        .arg("--version")
10081
        .output()
10082
        .is_err()
10083
    {
10084
        eprintln!("git not installed; skipping");
10085
        return;
10086
    }
10087
    let dir = tempfile::tempdir().unwrap();
10088
    let root = dir.path();
10089
    let g = root.join("src.git");
10090
    fs::create_dir_all(&g).unwrap();
10091
    let git = |who: &str, args: &[&str]| {
10092
        let (name, email) = who.split_once(' ').unwrap();
10093
        let out = std::process::Command::new("git")
10094
            .arg("-C")
10095
            .arg(&g)
10096
            .args([
10097
                "-c",
10098
                &format!("user.name={name}"),
10099
                "-c",
10100
                &format!("user.email={email}"),
10101
                "-c",
10102
                "commit.gpgsign=false",
10103
            ])
10104
            .args(args)
10105
            .output()
10106
            .unwrap();
10107
        assert!(
10108
            out.status.success(),
10109
            "git {args:?}: {}",
10110
            String::from_utf8_lossy(&out.stderr)
10111
        );
10112
    };
10113
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
10114
    write(&g, "a.txt", b"a\n");
10115
    git("Grace [email protected]", &["add", "."]);
10116
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
10117
    write(&g, "b.txt", b"b\n");
10118
    git("Ada [email protected]", &["add", "."]);
10119
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
10120
10121
    let mut repo = Repo::init(&root.join("o")).unwrap();
10122
    let (key, _) = repo
10123
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
10124
        .unwrap();
10125
    repo.config.set("git.claim", "true").unwrap();
10126
    repo.save_config().unwrap();
10127
    let repo = Repo::open(&root.join("o")).unwrap();
10128
    repo.import_git(&g, "main").unwrap();
10129
    let v = repo.verify_git_import(&g, "main").unwrap();
10130
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
10131
    let heads = repo.bookmark_heads().unwrap();
10132
    let by_message: std::collections::HashMap<String, KeyId> = repo
10133
        .log_state(&heads)
10134
        .unwrap()
10135
        .into_iter()
10136
        .map(|e| {
10137
            (
10138
                e.change.message.lines().next().unwrap_or("").to_string(),
10139
                e.change.author,
10140
            )
10141
        })
10142
        .collect();
10143
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
10144
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
10145
}
10146
10147
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
10148
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
10149
#[test]
10150
fn removing_a_remote_leaves_nothing_of_it() {
10151
    hermetic();
10152
    let dir = tempfile::tempdir().unwrap();
10153
    let origin = dir.path().join("origin");
10154
    Repo::init_bare_unbound(&origin).unwrap();
10155
    let main = dir.path().join("main");
10156
    let mut repo = Repo::init(&main).unwrap();
10157
    repo.config
10158
        .set("remote.origin.url", &origin.to_string_lossy())
10159
        .unwrap();
10160
    repo.config
10161
        .set("remote.origin.token", "secret-ish")
10162
        .unwrap();
10163
    repo.config
10164
        .set("remote.keep.url", &origin.to_string_lossy())
10165
        .unwrap();
10166
    repo.save_config().unwrap();
10167
    write(&main, "a.txt", b"a\n");
10168
    repo.commit("a", &[]).unwrap();
10169
    assert!(repo.push("origin", false).unwrap()[0].ok);
10170
    assert!(
10171
        repo.view().unwrap().remotes.contains_key("origin"),
10172
        "a tracking bookmark"
10173
    );
10174
10175
    repo.remove_remote("origin").unwrap();
10176
    let again = Repo::open(&main).unwrap();
10177
    assert!(
10178
        !again
10179
            .config
10180
            .repo_layer()
10181
            .keys()
10182
            .any(|k| k.starts_with("remote.origin.")),
10183
        "{:?}",
10184
        again.config.repo_layer()
10185
    );
10186
    assert!(!again.config.remotes.contains_key("origin"));
10187
    assert!(
10188
        !again.view().unwrap().remotes.contains_key("origin"),
10189
        "its tracking bookmarks go"
10190
    );
10191
    assert!(
10192
        again.config.remotes.contains_key("keep"),
10193
        "another remote stays"
10194
    );
10195
    let mut again = again;
10196
    assert!(
10197
        again.remove_remote("origin").is_err(),
10198
        "a second removal is refused"
10199
    );
10200
}
10201
10202
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
10203
/// unreachable from history, so gc prunes it, unless the host names it:
10204
/// then it and its chunks stay, and it reads back whole.
10205
#[test]
10206
fn gc_keeps_the_blobs_a_host_names() {
10207
    hermetic();
10208
    let dir = tempfile::tempdir().unwrap();
10209
    let repo = Repo::init(dir.path()).unwrap();
10210
    write(dir.path(), "a.txt", b"a\n");
10211
    repo.commit("a", &[]).unwrap();
10212
    // Large enough to be several chunks.
10213
    let body: Vec<u8> = (0..400_000u32)
10214
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
10215
        .collect();
10216
    let kept = repo.store_blob(&body).unwrap();
10217
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
10218
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
10219
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
10220
    assert!(!repo.store().has(&lost), "not named: pruned");
10221
    repo.gc(true).unwrap();
10222
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
10223
}
10224
10225
/// oxygen#99: undo in one workspace undoes that workspace's last command,
10226
/// never another workspace's, says what it undid, and goes further back
10227
/// when run again.
10228
#[test]
10229
fn undo_is_scoped_to_its_workspace() {
10230
    hermetic();
10231
    let dir = tempfile::tempdir().unwrap();
10232
    let root = dir.path().join("main");
10233
    let a = Repo::init(&root).unwrap();
10234
    write(&root, "base.txt", b"base\n");
10235
    let base = a.commit("base", &[]).unwrap();
10236
    a.bookmark_create("feature", None).unwrap();
10237
    let ws_dir = dir.path().join("ws");
10238
    let heads = a.resolve_heads("feature").unwrap();
10239
    let b = a
10240
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
10241
        .unwrap();
10242
10243
    // A commits on main, then B commits on feature: B's is the newest.
10244
    write(&root, "a.txt", b"a\n");
10245
    let ca = a.commit("from a", &[]).unwrap();
10246
    write(&ws_dir, "b.txt", b"b\n");
10247
    let cb = b.commit("from b", &[]).unwrap();
10248
10249
    // A's undo undoes A's commit and leaves B's.
10250
    let u = a.undo().unwrap();
10251
    assert_eq!(u.command, "oxy commit -m \"from a\"");
10252
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
10253
    assert!(!u.changes.is_empty());
10254
    let view = a.view().unwrap();
10255
    // (Independent changes commute, so a bookmark's heads may hold base too.)
10256
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
10257
    assert!(
10258
        a.heads_of(&view, "feature").unwrap().contains(&cb),
10259
        "B's commit stands"
10260
    );
10261
    assert!(
10262
        a.store().get_change(&ca).is_ok(),
10263
        "the change itself is still in the store"
10264
    );
10265
    // A's working copy was clean, so its files followed; B's are untouched.
10266
    assert!(!root.join("a.txt").exists());
10267
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
10268
    assert!(ws_dir.join("b.txt").exists());
10269
10270
    // B's undo still finds B's own commit, under A's undo.
10271
    let u = b.undo().unwrap();
10272
    assert_eq!(u.command, "oxy commit -m \"from b\"");
10273
    assert!(!b
10274
        .heads_of(&b.view().unwrap(), "feature")
10275
        .unwrap()
10276
        .contains(&cb));
10277
    assert_eq!(
10278
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
10279
        vec![base],
10280
        "A's undo stands"
10281
    );
10282
10283
    // A's next undo goes past the commit it already undid, to adding B's
10284
    // workspace: refused, since B has worked there since.
10285
    let e = a.undo().unwrap_err().to_string();
10286
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
10287
}
10288
10289
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
10290
/// own commit's head, and the other workspace's head stays.
10291
#[test]
10292
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
10293
    hermetic();
10294
    let dir = tempfile::tempdir().unwrap();
10295
    let root = dir.path().join("main");
10296
    let a = Repo::init(&root).unwrap();
10297
    write(&root, "base.txt", b"base\n");
10298
    a.commit("base", &[]).unwrap();
10299
    let ws_dir = dir.path().join("ws");
10300
    let b = a.workspace_add(&ws_dir, None).unwrap();
10301
    write(&root, "a.txt", b"a\n");
10302
    let ca = a.commit("from a", &[]).unwrap();
10303
    write(&ws_dir, "b.txt", b"b\n");
10304
    let cb = b.commit("from b", &[]).unwrap();
10305
    let u = a.undo().unwrap();
10306
    assert_eq!(u.command, "oxy commit -m \"from a\"");
10307
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
10308
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
10309
}
10310
10311
/// oxygen#99: an undo that would also take back what another workspace
10312
/// did since to the same bookmark is refused, naming it.
10313
#[test]
10314
fn undo_refuses_to_take_back_another_workspaces_work() {
10315
    hermetic();
10316
    let dir = tempfile::tempdir().unwrap();
10317
    let root = dir.path().join("main");
10318
    let a = Repo::init(&root).unwrap();
10319
    write(&root, "base.txt", b"base\n");
10320
    a.commit("base", &[]).unwrap();
10321
    let ws_dir = dir.path().join("ws");
10322
    let b = a.workspace_add(&ws_dir, None).unwrap();
10323
    // Both on main: A commits, then B builds on it, editing A's file.
10324
    write(&root, "a.txt", b"a\n");
10325
    a.commit("from a", &[]).unwrap();
10326
    b.refresh().unwrap();
10327
    let heads = b.resolve_heads("main").unwrap();
10328
    b.checkout(&heads, false, "oxy checkout").unwrap();
10329
    write(&ws_dir, "a.txt", b"a, then b\n");
10330
    b.commit("from b", &[]).unwrap();
10331
    let e = a.undo().unwrap_err().to_string();
10332
    assert!(
10333
        e.contains("bookmark main") && e.contains("builds on"),
10334
        "{e}"
10335
    );
10336
    assert!(e.contains("oxy op restore"), "{e}");
10337
}
10338
10339
/// oxygen#99: undoing a commit that was already pushed says so: the remote
10340
/// still has it.
10341
#[test]
10342
fn undo_says_when_the_commit_was_pushed() {
10343
    hermetic();
10344
    let dir = tempfile::tempdir().unwrap();
10345
    let root = dir.path();
10346
    Repo::init(&root.join("origin")).unwrap();
10347
    let url = root.join("origin").to_string_lossy().to_string();
10348
    let repo = Repo::clone(&url, &root.join("work"))
10349
        .unwrap()
10350
        .with_home(root.join("home"));
10351
    write(&root.join("work"), "a.txt", b"a\n");
10352
    repo.commit("a", &[]).unwrap();
10353
    assert!(repo.push("origin", false).unwrap()[0].ok);
10354
    // The push itself is passed over: the remote keeps what it was sent.
10355
    let u = repo.undo().unwrap();
10356
    assert_eq!(u.command, "oxy commit -m \"a\"");
10357
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
10358
}
10359
10360
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
10361
/// out of the snapshot and named; tracked files and files already in the
10362
/// working copy are not.
10363
#[test]
10364
fn large_new_files_are_left_out_of_snapshots() {
10365
    hermetic();
10366
    let dir = tempfile::tempdir().unwrap();
10367
    let root = dir.path();
10368
    let mut repo = Repo::init(root).unwrap();
10369
    repo.config.max_new_file = 1024;
10370
    write(root, "small.txt", b"small\n");
10371
    write(root, "big.bin", &vec![0u8; 4096]);
10372
    let s = repo.snapshot("oxy status").unwrap();
10373
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
10374
    assert_eq!(paths, ["small.txt"]);
10375
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
10376
    repo.commit("small", &[]).unwrap();
10377
10378
    // A tracked file may grow past the limit.
10379
    write(root, "small.txt", &vec![b'x'; 4096]);
10380
    let s = repo.snapshot("oxy status").unwrap();
10381
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
10382
    // With no limit the big file is taken in, and stays once it is.
10383
    repo.config.max_new_file = 0;
10384
    let s = repo.snapshot("oxy status").unwrap();
10385
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
10386
    repo.config.max_new_file = 1024;
10387
    let s = repo.snapshot("oxy status").unwrap();
10388
    assert!(
10389
        s.statuses.iter().any(|p| p.path == "big.bin"),
10390
        "already in the working copy"
10391
    );
10392
    assert!(repo.skipped_large().is_empty());
10393
}
10394
10395
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
10396
/// snapshots expire, and kept while they have not.
10397
#[test]
10398
fn gc_prunes_what_only_expired_snapshots_held() {
10399
    hermetic();
10400
    let dir = tempfile::tempdir().unwrap();
10401
    let root = dir.path();
10402
    let mut repo = Repo::init(root).unwrap();
10403
    repo.config.gc_grace_days = 0;
10404
    write(root, "a.txt", b"a\n");
10405
    repo.commit("a", &[]).unwrap();
10406
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
10407
    write(root, "image.tar", &image);
10408
    repo.snapshot("oxy status").unwrap();
10409
    std::fs::remove_file(root.join("image.tar")).unwrap();
10410
    repo.snapshot("oxy status").unwrap();
10411
    let blob = Repo::blob_ref(&image);
10412
    assert!(repo.store().has(&blob));
10413
    repo.gc(true).unwrap();
10414
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
10415
    repo.config.snapshot_retention_days = 0;
10416
    repo.gc(true).unwrap();
10417
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
10418
    assert_eq!(
10419
        repo.file_at("a.txt", None).unwrap(),
10420
        b"a\n",
10421
        "committed files stay"
10422
    );
10423
}
10424
10425
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
10426
/// already has is no conflict: the switch goes through, nothing is lost,
10427
/// and other carried work still comes along.
10428
#[test]
10429
fn carrying_work_the_target_already_has_is_no_conflict() {
10430
    hermetic();
10431
    let dir = tempfile::tempdir().unwrap();
10432
    let root = dir.path();
10433
    let mut repo = Repo::init(root).unwrap();
10434
    write(root, "a.txt", b"one\n");
10435
    write(root, "b.txt", b"b\n");
10436
    repo.commit("one", &[]).unwrap();
10437
    repo.bookmark_create("landed", None).unwrap();
10438
    // On landed, a.txt becomes "two" (as a proposal landing would).
10439
    repo.bookmark_switch("landed", false).unwrap();
10440
    write(root, "a.txt", b"two\n");
10441
    repo.commit("two", &[]).unwrap();
10442
    repo.bookmark_switch("main", false).unwrap();
10443
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
10444
    // The same edit, uncommitted, on main; and another edit besides.
10445
    write(root, "a.txt", b"two\n");
10446
    write(root, "b.txt", b"b, edited\n");
10447
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
10448
    assert_eq!(
10449
        carried,
10450
        vec!["b.txt".to_string()],
10451
        "only the work landed lacks is carried"
10452
    );
10453
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
10454
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
10455
    let s = repo.snapshot("oxy status").unwrap();
10456
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
10457
    assert_eq!(paths, ["b.txt"]);
10458
10459
    // A real difference is still refused.
10460
    repo.bookmark_switch("main", true).unwrap();
10461
    write(root, "a.txt", b"three\n");
10462
    let e = repo
10463
        .bookmark_switch_carry("landed")
10464
        .unwrap_err()
10465
        .to_string();
10466
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
10467
}
10468
10469
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
10470
/// resolves, so JSON output feeds back into commands.
10471
#[test]
10472
fn a_full_hash_resolves_without_its_hash_sign() {
10473
    hermetic();
10474
    let dir = tempfile::tempdir().unwrap();
10475
    let root = dir.path();
10476
    let repo = Repo::init(root).unwrap();
10477
    write(root, "a.txt", b"a\n");
10478
    let h = repo.commit("a", &[]).unwrap();
10479
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
10480
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
10481
    assert!(repo
10482
        .resolve_change(&"0".repeat(64))
10483
        .unwrap_err()
10484
        .to_string()
10485
        .contains("no change matches"));
10486
}
10487
10488
#[test]
10489
fn a_pin_change_moves_only_the_pin() {
10490
    hermetic();
10491
    let dir = tempfile::tempdir().unwrap();
10492
    let root = dir.path();
10493
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
10494
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
10495
    let lib = Repo::clone(&lib_url, &root.join("lib"))
10496
        .unwrap()
10497
        .with_home(root.join("home"));
10498
    write(&root.join("lib"), "lib.txt", b"v1\n");
10499
    lib.commit("lib v1", &[]).unwrap();
10500
    assert!(lib.push("origin", false).unwrap()[0].ok);
10501
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
10502
    let app_dir = root.join("app");
10503
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
10504
        .unwrap()
10505
        .with_home(root.join("home"));
10506
    write(&app_dir, "main.txt", b"app\n");
10507
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
10508
    let a1 = app.commit("app with lib", &[]).unwrap();
10509
    // The library moves on.
10510
    write(&root.join("lib"), "more.txt", b"v2\n");
10511
    let l2 = lib.commit("lib v2", &[]).unwrap();
10512
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
10513
        panic!("an Oxygen pin")
10514
    };
10515
    let pin2 = crate::subrepo::Pin::Oxy {
10516
        repo,
10517
        heads: vec![l2],
10518
        bookmark,
10519
    };
10520
    let author = app.store().get_change(&a1).unwrap().author;
10521
    let change = app
10522
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
10523
        .unwrap();
10524
    let mut state = app.load_state(&[a1]).unwrap();
10525
    state.add(change).unwrap();
10526
    let files = state.materialize().files;
10527
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
10528
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
10529
        panic!("a pin is opaque")
10530
    };
10531
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
10532
    assert_eq!(read, pin2, "the new pin");
10533
    assert!(
10534
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
10535
        "nothing else changes"
10536
    );
10537
    // Only a subrepo's pin can be moved this way.
10538
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
10539
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
10540
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
10541
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
10542
}
10543
10544
/// oxygen#147: a subrepo at its pinned state is unmodified whatever
10545
/// bookmark it sits on, so the parent's status is clean and a bookmark
10546
/// switch goes ahead; a new state in it is still a change.
10547
#[test]
10548
fn a_subrepo_at_its_pinned_state_on_another_bookmark_is_unmodified() {
10549
    hermetic();
10550
    let dir = tempfile::tempdir().unwrap();
10551
    let root = dir.path();
10552
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
10553
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
10554
    let lib = Repo::clone(&lib_url, &root.join("lib"))
10555
        .unwrap()
10556
        .with_home(root.join("home"));
10557
    write(&root.join("lib"), "lib.txt", b"v1\n");
10558
    lib.commit("lib v1", &[]).unwrap();
10559
    assert!(lib.push("origin", false).unwrap()[0].ok);
10560
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
10561
    let app_dir = root.join("app");
10562
    let mut app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
10563
        .unwrap()
10564
        .with_home(root.join("home"));
10565
    write(&app_dir, "main.txt", b"app\n");
10566
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
10567
    let a1 = app.commit("app with lib", &[]).unwrap();
10568
10569
    // The nested repository moves to another bookmark at the same heads.
10570
    let mut nested = Repo::open(&app_dir.join("libs/lib"))
10571
        .unwrap()
10572
        .with_home(root.join("home"));
10573
    let heads = nested.bookmark_heads().unwrap();
10574
    nested.bookmark_create("feature", Some(&heads)).unwrap();
10575
    nested.bookmark_switch("feature", false).unwrap();
10576
    let snap = app.snapshot("status").unwrap();
10577
    assert!(
10578
        !snap.changed,
10579
        "only the bookmark differs: {:?}",
10580
        snap.statuses
10581
    );
10582
    app.bookmark_create("other", Some(&[a1])).unwrap();
10583
    app.bookmark_switch("other", false).unwrap();
10584
10585
    // A new state in it is a change, as before.
10586
    let nested = Repo::open(&app_dir.join("libs/lib"))
10587
        .unwrap()
10588
        .with_home(root.join("home"));
10589
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
10590
    nested.commit("lib v2", &[]).unwrap();
10591
    let snap = app.snapshot("status").unwrap();
10592
    assert_eq!(
10593
        snap.statuses
10594
            .iter()
10595
            .map(|s| (s.path.as_str(), s.status))
10596
            .collect::<Vec<_>>(),
10597
        vec![("libs/lib", ChangeStatus::Modified)]
10598
    );
10599
}
10600
10601
/// oxygenhub#249: a handle reads the operation head once and keeps it,
10602
/// so one command or request never mixes two heads; another handle's
10603
/// operation shows only after `refresh`. Its own operations move it, and
10604
/// one recorded from the head it kept merges with what landed since, as
10605
/// any concurrent operation does.
10606
#[test]
10607
fn one_handle_keeps_one_head_until_it_refreshes() {
10608
    hermetic();
10609
    let dir = tempfile::tempdir().unwrap();
10610
    let root = dir.path();
10611
    let writer = Repo::init(root).unwrap();
10612
    write(root, "a.txt", b"one\n");
10613
    let h1 = writer.commit("one", &[]).unwrap();
10614
    let reader = Repo::open(root).unwrap();
10615
    let before = reader.view().unwrap();
10616
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
10617
    write(root, "a.txt", b"two\n");
10618
    let h2 = writer.commit("two", &[]).unwrap();
10619
    assert_eq!(
10620
        writer.bookmark_heads().unwrap(),
10621
        vec![h2],
10622
        "its own operation"
10623
    );
10624
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
10625
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
10626
    reader.refresh().unwrap();
10627
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
10628
10629
    // A handle recording from an older head merges with the newer one.
10630
    let stale = Repo::open(root).unwrap();
10631
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
10632
    write(root, "a.txt", b"three\n");
10633
    let h3 = writer.commit("three", &[]).unwrap();
10634
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
10635
    let view = stale.view().unwrap();
10636
    assert!(view.bookmarks.contains_key("feature"));
10637
    assert_eq!(
10638
        stale.bookmark_heads().unwrap(),
10639
        vec![h3],
10640
        "merged, not lost"
10641
    );
10642
    let fresh = Repo::open(root).unwrap();
10643
    assert_eq!(fresh.view().unwrap(), view);
10644
}
10645
10646
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
10647
#[test]
10648
fn over_a_store_one_handle_keeps_one_head() {
10649
    hermetic();
10650
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
10651
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
10652
    let dir = tempfile::tempdir().unwrap();
10653
    let a = Repo::init(dir.path()).unwrap();
10654
    let (h0, _) = a.head_op().unwrap();
10655
    let b = Repo::open(dir.path()).unwrap();
10656
    assert_eq!(b.head_op().unwrap().0, h0);
10657
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
10658
    let mut view = a.view().unwrap();
10659
    view.bookmarks.insert("x".into(), state);
10660
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
10661
    assert_eq!(a.head_op().unwrap().0, r);
10662
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
10663
    b.refresh().unwrap();
10664
    assert_eq!(b.head_op().unwrap().0, r);
10665
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
10666
}
10667
10668
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
10669
/// reader opened before reads on, then and after the next gc deletes the
10670
/// retired files once their hour is up. Younger ones are kept.
10671
#[test]
10672
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
10673
    hermetic();
10674
    let dir = tempfile::tempdir().unwrap();
10675
    let root = dir.path();
10676
    let repo = Repo::init(root).unwrap();
10677
    let mut heads = Vec::new();
10678
    for i in 0..4 {
10679
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
10680
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
10681
    }
10682
    let reader = Repo::open(root).unwrap();
10683
    assert_eq!(reader.log().unwrap().len(), 5);
10684
    let r = repo.gc(true).unwrap();
10685
    assert_eq!(r.retired, crate::store::RetiredReport::default());
10686
    assert_eq!(repo.store().loose_count().unwrap(), 0);
10687
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
10688
    // Nothing is an hour old yet: a gc keeps it all.
10689
    let r = repo.gc(true).unwrap();
10690
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
10691
    assert!(r.retired.kept > 0, "{r:?}");
10692
    write(root, "f9.txt", b"9\n");
10693
    heads.push(repo.commit("c9", &[]).unwrap());
10694
    crate::store::reader_tests::age_retired(
10695
        repo.store(),
10696
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
10697
    );
10698
    let r = repo.gc(true).unwrap();
10699
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
10700
    assert_eq!(r.retired.kept, 0, "{r:?}");
10701
    let r = repo.gc(true).unwrap();
10702
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
10703
    assert!(r.retired.kept > 0, "what the last gc retired is young");
10704
    // The reader opened before all of it still reads everything, from
10705
    // the packs it finds when what it loaded is gone.
10706
    assert_eq!(reader.log().unwrap().len(), 5);
10707
    for h in &heads[..4] {
10708
        reader.store().get_change(h).unwrap();
10709
    }
10710
    reader.refresh().unwrap();
10711
    assert_eq!(reader.log().unwrap().len(), 6);
10712
    let fresh = Repo::open(root).unwrap();
10713
    assert_eq!(
10714
        fresh.store().pack_count(),
10715
        1,
10716
        "retired packs are not loaded"
10717
    );
10718
}
10719
10720
/// oxygenhub#249: a repository opens when its store's pack listing names
10721
/// an index that is not there (deleted between the listing and the read).
10722
#[test]
10723
fn a_repository_opens_when_a_listed_index_is_gone() {
10724
    hermetic();
10725
    let backend = crate::store::reader_tests::racing(true);
10726
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
10727
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
10728
    let dir = tempfile::tempdir().unwrap();
10729
    let repo = Repo::init(dir.path()).unwrap();
10730
    write(dir.path(), "a.txt", b"a\n");
10731
    let h = repo.commit("a", &[]).unwrap();
10732
    repo.gc(true).unwrap();
10733
    let again = Repo::open(dir.path()).unwrap();
10734
    assert_eq!(again.store().pack_count(), 1);
10735
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
10736
    // And when one is deleted between the listing and the read: a copy of
10737
    // the live pack, whose index goes as the store opens.
10738
    use crate::strata::Store as _;
10739
    let idx = backend
10740
        .list("pack-")
10741
        .unwrap()
10742
        .into_iter()
10743
        .map(|e| e.key)
10744
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
10745
        .unwrap();
10746
    let stem = idx.trim_end_matches(".idx");
10747
    for ext in ["pack", "idx"] {
10748
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
10749
        backend
10750
            .put_new(&format!("pack-copy.{ext}"), &bytes)
10751
            .unwrap();
10752
    }
10753
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
10754
    let again = Repo::open(dir.path()).unwrap();
10755
    assert_eq!(again.store().pack_count(), 1);
10756
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
10757
    assert!(!backend.has("pack-copy.idx").unwrap());
10758
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
10759
}
10760
10761
/// oxygen#82: a home with `author.for` authors as the identity its hub
10762
/// last named (kept in `keys/author.for`), not its stale `author.key`; a
10763
/// repository's own `author.key` pin still wins, and without `author.for`
10764
/// the note is ignored.
10765
#[test]
10766
fn author_for_follows_the_key_the_hub_named() {
10767
    let dir = tempfile::tempdir().unwrap();
10768
    let home = dir.path().join("home");
10769
    fs::create_dir_all(home.join("keys")).unwrap();
10770
    let user = home.join("config.toml");
10771
    let repo_cfg = dir.path().join("config");
10772
    let (old, new, pin) = (
10773
        KeyId::from_hex(&"a".repeat(64)).unwrap(),
10774
        KeyId::from_hex(&"b".repeat(64)).unwrap(),
10775
        KeyId::from_hex(&"c".repeat(64)).unwrap(),
10776
    );
10777
    fs::write(&user, format!("author.key = \"{}\"\n", old.to_hex())).unwrap();
10778
    fs::write(
10779
        home.join("keys").join(super::config::AUTHOR_FOR_FILE),
10780
        format!("{}\n", new.to_hex()),
10781
    )
10782
    .unwrap();
10783
    fs::write(&repo_cfg, "").unwrap();
10784
    assert_eq!(
10785
        Config::load(Some(&user), &repo_cfg).unwrap().author_key,
10786
        Some(old),
10787
        "no author.for: the note is ignored"
10788
    );
10789
    fs::write(
10790
        &user,
10791
        format!(
10792
            "author.key = \"{}\"\nauthor.for = \"andymccall\"\n",
10793
            old.to_hex()
10794
        ),
10795
    )
10796
    .unwrap();
10797
    assert_eq!(
10798
        Config::load(Some(&user), &repo_cfg).unwrap().author_key,
10799
        Some(new)
10800
    );
10801
    fs::write(&repo_cfg, format!("author.key = \"{}\"\n", pin.to_hex())).unwrap();
10802
    assert_eq!(
10803
        Config::load(Some(&user), &repo_cfg).unwrap().author_key,
10804
        Some(pin),
10805
        "a repository's pin wins"
10806
    );
10807
}