OXYGENHUB
◆ push-notes oxygen / crates / oxy-core / src / repo / tests.rs
413.6 KiB · Rust · last changed author.for: a keyless home follows its owner's newest identity (refs #82) 9 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!(
138
        d.lines()
139
            .any(|l| l.starts_with("M ") && l.ends_with("main.rs")),
140
        "a modified file is in the summary too: {d}"
141
    );
142
    assert!(d.contains("+    println!(\"hi\");"), "{d}");
143
    assert!(d.contains("-fn main() {}"), "{d}");
144
145
    // Resolution by prefix.
146
    assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
147
    assert_eq!(
148
        repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(),
149
        h1
150
    );
151
    assert!(repo.resolve_change("zzzz").is_err());
152
153
    // Undo the commit: bookmark and working copy go back.
154
    repo.undo().unwrap();
155
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
156
    let s = repo.snapshot("oxy status").unwrap();
157
    assert!(
158
        !s.changed,
159
        "files on disk still match the pre-commit working copy"
160
    );
161
    assert_eq!(s.statuses.len(), 3);
162
}
163
164
/// Make `main` conflicted: two commits on the same base that edit the same line.
165
fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
166
    let dir = tempfile::tempdir().unwrap();
167
    let root = dir.path();
168
    let repo = Repo::init(root).unwrap();
169
    write(root, "f.txt", b"a\nb\nc\n");
170
    let h1 = repo.commit("base", &[]).unwrap();
171
    write(root, "f.txt", b"a\nB\nc\n");
172
    let h2 = repo.commit("upper", &[]).unwrap();
173
    repo.checkout(&[h1], false, "checkout").unwrap();
174
    write(root, "f.txt", b"a\nX\nc\n");
175
    let h3 = repo.commit("ex", &[]).unwrap();
176
    (dir, repo, h1, h2, h3)
177
}
178
179
/// oxygen#126: a file whose text includes an example of oxy's markers (as
180
/// the spec's §9.5 does) can still have its conflict resolved; a real
181
/// marker left behind is still caught.
182
#[test]
183
fn marker_like_text_does_not_block_a_resolution() {
184
    hermetic();
185
    let dir = tempfile::tempdir().unwrap();
186
    let root = dir.path();
187
    let repo = Repo::init(root).unwrap();
188
    let example = "```\n<<<<<<< oxy conflict 1 of 2, side 1: change k7m2p9 \"Add retry loop\"\n... lines ...\n======= oxy conflict 1 of 2, side 2: change q3x8w1 \"Refactor client\"\n>>>>>>> oxy conflict 1 of 2 end\n```\n";
189
    write(
190
        root,
191
        "doc.md",
192
        format!("intro\n{example}b\nend\n").as_bytes(),
193
    );
194
    let h1 = repo.commit("base", &[]).unwrap();
195
    write(
196
        root,
197
        "doc.md",
198
        format!("intro\n{example}B\nend\n").as_bytes(),
199
    );
200
    repo.commit("upper", &[]).unwrap();
201
    repo.checkout(&[h1], false, "checkout").unwrap();
202
    write(
203
        root,
204
        "doc.md",
205
        format!("intro\n{example}X\nend\n").as_bytes(),
206
    );
207
    repo.commit("ex", &[]).unwrap();
208
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
209
        .unwrap();
210
    let marked = fs::read_to_string(root.join("doc.md")).unwrap();
211
    assert!(marked.contains("oxy conflict 1 of 1"), "{marked}");
212
    // A real marker left: still caught.
213
    write(root, "doc.md", marked.replace("B\n", "BB\n").as_bytes());
214
    let s = repo.snapshot("status").unwrap();
215
    assert_eq!(
216
        statuses(&s),
217
        vec![("doc.md".into(), ChangeStatus::ConflictEdited)]
218
    );
219
    // Resolved, the example kept: a resolution.
220
    write(
221
        root,
222
        "doc.md",
223
        format!("intro\n{example}X\nend\n").as_bytes(),
224
    );
225
    let s = repo.snapshot("status").unwrap();
226
    assert_eq!(
227
        statuses(&s),
228
        vec![("doc.md".into(), ChangeStatus::Resolved)]
229
    );
230
    let h = repo.commit("resolve", &[]).unwrap();
231
    assert_eq!(
232
        repo.store().get_change(&h).unwrap().kind,
233
        ChangeKind::Resolution
234
    );
235
    assert!(!repo.load_state(&[h]).unwrap().materialize().is_conflicted());
236
}
237
238
/// oxygen#121: two changes each adding a line after the same line conflict;
239
/// the markers list the earlier change first, and `oxy resolve --both`
240
/// keeps both lines in that order (or the other with `--reverse`).
241
#[test]
242
fn adjacent_insertions_are_settled_by_keeping_both() {
243
    hermetic();
244
    for reverse in [false, true] {
245
        let dir = tempfile::tempdir().unwrap();
246
        let root = dir.path();
247
        let repo = Repo::init(root).unwrap();
248
        write(root, "f.txt", b"a\nb\n");
249
        let h1 = repo.commit("base", &[]).unwrap();
250
        write(root, "f.txt", b"a\nfirst\nb\n");
251
        repo.commit("first", &[]).unwrap();
252
        repo.checkout(&[h1], false, "checkout").unwrap();
253
        write(root, "f.txt", b"a\nsecond\nb\n");
254
        repo.commit("second", &[]).unwrap();
255
        repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
256
            .unwrap();
257
        let marked = fs::read_to_string(root.join("f.txt")).unwrap();
258
        let (f, s) = (
259
            marked.find("first\n").unwrap(),
260
            marked.find("second\n").unwrap(),
261
        );
262
        assert!(f < s, "the earlier change's side comes first: {marked}");
263
264
        let snap = repo.snapshot("status").unwrap();
265
        let node = snap.base_snapshot.files["f.txt"].node;
266
        assert_eq!(snap.base.both_sides(&node).iter().flatten().count(), 1);
267
        let kept = repo.keep_both(&snap, &[], reverse).unwrap();
268
        assert_eq!(
269
            kept,
270
            vec![KeptBoth {
271
                path: "f.txt".into(),
272
                settled: vec![1],
273
                left: vec![]
274
            }]
275
        );
276
        let want: &[u8] = if reverse {
277
            b"a\nsecond\nfirst\nb\n"
278
        } else {
279
            b"a\nfirst\nsecond\nb\n"
280
        };
281
        assert_eq!(fs::read(root.join("f.txt")).unwrap(), want);
282
        let s = repo.snapshot("status").unwrap();
283
        assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
284
        let h = repo.commit("both", &[]).unwrap();
285
        assert_eq!(
286
            repo.store().get_change(&h).unwrap().kind,
287
            ChangeKind::Resolution
288
        );
289
        assert!(!repo.load_state(&[h]).unwrap().materialize().is_conflicted());
290
    }
291
}
292
293
/// oxygen#145: a file marked `merge=union` has its adjacent insertions
294
/// settled by the checkout itself, both kept, earliest first; the next
295
/// commit records the resolution. Other files keep their markers.
296
#[test]
297
fn union_files_keep_both_sides_on_checkout() {
298
    hermetic();
299
    let dir = tempfile::tempdir().unwrap();
300
    let root = dir.path();
301
    let repo = Repo::init(root).unwrap();
302
    write(root, ".oxyattributes", b"CHANGELOG.md merge=union\n");
303
    write(
304
        root,
305
        "CHANGELOG.md",
306
        b"# Changelog\n## Unreleased\n## 1.0\n",
307
    );
308
    write(root, "f.txt", b"a\nb\n");
309
    let h1 = repo.commit("base", &[]).unwrap();
310
    write(
311
        root,
312
        "CHANGELOG.md",
313
        b"# Changelog\n## Unreleased\n- one\n## 1.0\n",
314
    );
315
    write(root, "f.txt", b"a\none\nb\n");
316
    repo.commit("one", &[]).unwrap();
317
    repo.checkout(&[h1], false, "checkout").unwrap();
318
    write(
319
        root,
320
        "CHANGELOG.md",
321
        b"# Changelog\n## Unreleased\n- two\n## 1.0\n",
322
    );
323
    write(root, "f.txt", b"a\ntwo\nb\n");
324
    repo.commit("two", &[]).unwrap();
325
    let r = repo
326
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
327
        .unwrap();
328
    assert!(r.conflicted);
329
    assert_eq!(r.kept_both.len(), 1, "{:?}", r.kept_both);
330
    assert_eq!(r.kept_both[0].path, "CHANGELOG.md");
331
    assert_eq!(
332
        fs::read_to_string(root.join("CHANGELOG.md")).unwrap(),
333
        "# Changelog\n## Unreleased\n- one\n- two\n## 1.0\n"
334
    );
335
    assert!(has_conflict_markers(&fs::read(root.join("f.txt")).unwrap()));
336
    let s = repo.snapshot("status").unwrap();
337
    assert_eq!(
338
        statuses(&s),
339
        vec![("CHANGELOG.md".into(), ChangeStatus::Resolved)]
340
    );
341
}
342
343
/// oxygen#145: a host (OxygenHub landing a proposal) settles a state whose
344
/// only conflicts are adjacent insertions in union files; any other
345
/// conflict needs a person.
346
#[test]
347
fn a_host_settles_a_state_whose_conflicts_are_all_union() {
348
    hermetic();
349
    let dir = tempfile::tempdir().unwrap();
350
    let root = dir.path();
351
    let repo = Repo::init(root).unwrap();
352
    write(root, ".oxyattributes", b"*.md merge=union\n");
353
    write(root, "A.md", b"a\nb\n");
354
    write(root, "B.md", b"x\ny\n");
355
    let h1 = repo.commit("base", &[]).unwrap();
356
    write(root, "A.md", b"a\none\nb\n");
357
    write(root, "B.md", b"x\nY1\n");
358
    let h2 = repo.commit("one", &[]).unwrap();
359
    repo.checkout(&[h1], false, "checkout").unwrap();
360
    write(root, "A.md", b"a\ntwo\nb\n");
361
    let h3 = repo.commit("two", &[]).unwrap();
362
    let st = repo.load_state(&[h2, h3]).unwrap();
363
    assert_eq!(
364
        Repo::union_resolution(&st, &st.materialize()),
365
        Some(vec![("A.md".into(), b"a\none\ntwo\nb\n".to_vec())])
366
    );
367
    // B.md's line replaced two ways: a person decides.
368
    repo.checkout(&[h3], false, "checkout").unwrap();
369
    write(root, "B.md", b"x\nY2\n");
370
    let h4 = repo.commit("Y2", &[]).unwrap();
371
    let st = repo.load_state(&[h2, h4]).unwrap();
372
    assert!(st.materialize().is_conflicted());
373
    assert_eq!(Repo::union_resolution(&st, &st.materialize()), None);
374
}
375
376
/// oxygen#121: two changes that each replaced the same line are not an
377
/// adjacent insertion: keeping both would keep two versions of the line,
378
/// so `--both` leaves the markers, as it does for markers already edited.
379
#[test]
380
fn keeping_both_refuses_replaced_or_edited_lines() {
381
    hermetic();
382
    let (dir, repo, _, _, _) = conflicted_repo();
383
    let root = dir.path();
384
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
385
        .unwrap();
386
    let marked = fs::read(root.join("f.txt")).unwrap();
387
    let snap = repo.snapshot("status").unwrap();
388
    let node = snap.base_snapshot.files["f.txt"].node;
389
    assert_eq!(snap.base.both_sides(&node), vec![None]);
390
    let kept = repo.keep_both(&snap, &["f.txt".into()], false).unwrap();
391
    assert!(kept[0].settled.is_empty());
392
    assert_eq!(kept[0].left[0].0, 1);
393
    assert!(kept[0].left[0].1.contains("both sides changed"), "{kept:?}");
394
    assert_eq!(fs::read(root.join("f.txt")).unwrap(), marked);
395
396
    // An adjacent insertion whose lines were edited between the markers.
397
    let sides = vec![Some(vec![b"x\n".to_vec(), b"y\n".to_vec()])];
398
    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";
399
    let (out, settled, left) = super::snapshot::keep_both_text(text, &sides, false);
400
    assert_eq!(out, text.to_vec());
401
    assert!(settled.is_empty());
402
    assert!(left[0].1.contains("edited"), "{left:?}");
403
    // Unedited, in either order on disk: kept in the graph's order.
404
    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";
405
    let (out, settled, _) = super::snapshot::keep_both_text(text, &sides, false);
406
    assert_eq!(out, b"a\nx\ny\nb\n".to_vec());
407
    assert_eq!(settled, vec![1]);
408
}
409
410
#[test]
411
fn concurrent_edits_conflict_and_can_be_resolved() {
412
    hermetic();
413
    let (dir, repo, h1, h2, h3) = conflicted_repo();
414
    let root = dir.path();
415
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
416
    assert_eq!(heads, [h2, h3].into_iter().collect());
417
    let st = repo.load_state(&[h2, h3]).unwrap();
418
    assert!(st.materialize().is_conflicted());
419
420
    // Checking out main writes markers.
421
    let r = repo
422
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
423
        .unwrap();
424
    assert!(r.conflicted);
425
    let marked = fs::read_to_string(root.join("f.txt")).unwrap();
426
    assert!(
427
        marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"),
428
        "{marked}"
429
    );
430
    assert!(
431
        marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"),
432
        "{marked}"
433
    );
434
    assert!(has_conflict_markers(marked.as_bytes()));
435
    // Untouched markers: clean working copy; commit has nothing to do.
436
    let s = repo.snapshot("status").unwrap();
437
    assert!(s.statuses.is_empty());
438
    assert!(!s.resolves);
439
440
    // Partially edited file that still has markers cannot be committed.
441
    write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
442
    let s = repo.snapshot("status").unwrap();
443
    assert_eq!(
444
        statuses(&s),
445
        vec![("f.txt".into(), ChangeStatus::ConflictEdited)]
446
    );
447
    assert!(repo.commit("no", &[]).is_err());
448
449
    // Resolve by keeping one side and adding a line elsewhere.
450
    write(root, "f.txt", b"a\nX\nc\nd\n");
451
    let s = repo.snapshot("status").unwrap();
452
    assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
453
    assert!(s.resolves);
454
    let h4 = repo.commit("resolve", &[]).unwrap();
455
    let c4 = repo.store().get_change(&h4).unwrap();
456
    assert_eq!(c4.kind, ChangeKind::Resolution);
457
    let mut want = vec![h1, h2, h3];
458
    want.sort();
459
    assert_eq!(
460
        c4.deps, want,
461
        "a resolution depends on exactly the contributors and what it references"
462
    );
463
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
464
    let snap = repo.load_state(&[h4]).unwrap().materialize();
465
    assert!(!snap.is_conflicted());
466
    assert!(
467
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
468
    );
469
    assert!(!repo.snapshot("status").unwrap().changed);
470
    // A peer holding only h2 and h3 and receiving h4 sees the same result,
471
    // whatever order the changes arrive in.
472
    let mut st = State::new();
473
    for h in [h4, h3, h1, h2] {
474
        st.add_unchecked(repo.store().get_change(&h).unwrap());
475
    }
476
    st.validate().unwrap();
477
    assert!(
478
        matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n")
479
    );
480
}
481
482
/// oxygen#118 (Metal Gear): a resolution commits by paths, leaving other
483
/// work uncommitted, so long as it takes every file it resolves; and
484
/// `amend PATHS` folds only those paths into the head.
485
#[test]
486
fn resolutions_and_amends_take_paths() {
487
    hermetic();
488
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
489
    let root = dir.path();
490
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
491
        .unwrap();
492
    // The conflict resolved, and other work beside it.
493
    write(root, "f.txt", b"a\nX\nc\n");
494
    write(root, "notes.txt", b"pending\n");
495
    let s = repo.snapshot("status").unwrap();
496
    assert!(s.resolves);
497
    let err = repo
498
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["notes.txt".into()]))
499
        .unwrap_err()
500
        .to_string();
501
    assert!(
502
        err.contains("takes every file it resolves") && err.contains("f.txt"),
503
        "{err}"
504
    );
505
    let (h4, partial) = repo
506
        .commit_selection_partial("resolve", &[], &Selection::Paths(vec!["f.txt".into()]))
507
        .unwrap();
508
    assert!(partial);
509
    assert_eq!(
510
        repo.store().get_change(&h4).unwrap().kind,
511
        ChangeKind::Resolution
512
    );
513
    assert!(!repo
514
        .load_state(&[h4])
515
        .unwrap()
516
        .materialize()
517
        .is_conflicted());
518
    let s = repo.snapshot("status").unwrap();
519
    assert_eq!(
520
        statuses(&s),
521
        vec![("notes.txt".into(), ChangeStatus::Added)],
522
        "the other work waits"
523
    );
524
525
    // amend PATHS: only those paths join the head; it keeps its ChangeId.
526
    // On the resolution, so the bookmark has one head to amend.
527
    let h5 = repo.commit("notes", &[h4]).unwrap();
528
    let id5 = repo.store().get_change(&h5).unwrap().change_id;
529
    write(root, "notes.txt", b"pending\nmore\n");
530
    write(root, "other.txt", b"later\n");
531
    let h6 = repo
532
        .amend_paths(Some("notes, amended"), &["notes.txt".into()])
533
        .unwrap();
534
    let c6 = repo.store().get_change(&h6).unwrap();
535
    assert_eq!((c6.change_id, c6.message.as_str()), (id5, "notes, amended"));
536
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h6]);
537
    let snap6 = repo.load_state(&[h6]).unwrap().materialize();
538
    assert!(
539
        matches!(&snap6.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"pending\nmore\n")
540
    );
541
    assert!(
542
        !snap6.files.contains_key("other.txt"),
543
        "other.txt stays out"
544
    );
545
    let s = repo.snapshot("status").unwrap();
546
    assert_eq!(
547
        statuses(&s),
548
        vec![("other.txt".into(), ChangeStatus::Added)]
549
    );
550
}
551
552
#[test]
553
fn resolution_may_keep_both_sides_or_neither() {
554
    hermetic();
555
    let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
556
    let root = dir.path();
557
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
558
        .unwrap();
559
    // Keep both sides in a chosen order.
560
    write(root, "f.txt", b"a\nX\nB\nc\n");
561
    let h = repo.commit("both", &[]).unwrap();
562
    let snap = repo.load_state(&[h]).unwrap().materialize();
563
    assert!(!snap.is_conflicted());
564
    assert!(
565
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n")
566
    );
567
    // Undo and instead drop the whole region.
568
    repo.undo().unwrap();
569
    write(root, "f.txt", b"a\nc\n");
570
    let h = repo.commit("neither", &[]).unwrap();
571
    let snap = repo.load_state(&[h]).unwrap().materialize();
572
    assert!(!snap.is_conflicted());
573
    assert!(
574
        matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n")
575
    );
576
}
577
578
#[test]
579
fn name_conflict_resolved_by_removing_a_candidate() {
580
    hermetic();
581
    let dir = tempfile::tempdir().unwrap();
582
    let root = dir.path();
583
    let repo = Repo::init(root).unwrap();
584
    write(root, "keep.txt", b"k\n");
585
    let h1 = repo.commit("base", &[]).unwrap();
586
    write(root, "new.txt", b"one\n");
587
    repo.commit("one", &[]).unwrap();
588
    repo.checkout(&[h1], false, "checkout").unwrap();
589
    write(root, "new.txt", b"two\n");
590
    repo.commit("two", &[]).unwrap();
591
    let r = repo
592
        .checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
593
        .unwrap();
594
    assert!(r.conflicted);
595
    assert!(
596
        root.join("new.txt.oxy-conflict-1").exists()
597
            && root.join("new.txt.oxy-conflict-2").exists()
598
    );
599
    assert!(!root.join("new.txt").exists());
600
    // Candidate numbering follows change-hash order, so pick by content:
601
    // keep the "two" candidate under the real name and drop the other.
602
    let (keep, drop) = if fs::read(root.join("new.txt.oxy-conflict-1")).unwrap() == b"two\n" {
603
        (1, 2)
604
    } else {
605
        (2, 1)
606
    };
607
    fs::remove_file(root.join(format!("new.txt.oxy-conflict-{drop}"))).unwrap();
608
    fs::rename(
609
        root.join(format!("new.txt.oxy-conflict-{keep}")),
610
        root.join("new.txt"),
611
    )
612
    .unwrap();
613
    let h = repo.commit("pick two", &[]).unwrap();
614
    assert_eq!(
615
        repo.store().get_change(&h).unwrap().kind,
616
        ChangeKind::Resolution
617
    );
618
    // The resolution does not touch keep.txt, so it does not depend on h1;
619
    // the bookmark keeps both as heads and their union is the state.
620
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
621
    assert_eq!(heads, [h1, h].into_iter().collect());
622
    let snap = repo
623
        .load_state(&repo.bookmark_heads().unwrap())
624
        .unwrap()
625
        .materialize();
626
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
627
    assert_eq!(
628
        snap.files.keys().cloned().collect::<Vec<_>>(),
629
        ["keep.txt", "new.txt"]
630
    );
631
    assert!(
632
        matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n")
633
    );
634
}
635
636
/// Each of two bookmarks adds `path` (a file written by `side` on each)
637
/// from the same base, and the second is merged into the first. Returns
638
/// the repository on `main`, the merge's heads, and the three changes.
639
fn merged_additions(
640
    side: impl Fn(&Path, bool),
641
) -> (tempfile::TempDir, Repo, Vec<ChangeHash>, [ChangeHash; 3]) {
642
    let dir = tempfile::tempdir().unwrap();
643
    let root = dir.path().to_path_buf();
644
    let mut repo = Repo::init(&root).unwrap();
645
    write(&root, "keep.txt", b"k\n");
646
    let h1 = repo.commit("base", &[]).unwrap();
647
    repo.bookmark_create("side", None).unwrap();
648
    side(&root, false);
649
    let ha = repo.commit("add on main", &[]).unwrap();
650
    repo.bookmark_switch("side", false).unwrap();
651
    side(&root, true);
652
    let hb = repo.commit("add on side", &[]).unwrap();
653
    repo.bookmark_switch("main", false).unwrap();
654
    let m = repo.merge("side").unwrap();
655
    assert!(m.changed && m.checked_out);
656
    (dir, repo, m.heads, [h1, ha, hb])
657
}
658
659
fn conflict_copies(root: &Path) -> Vec<String> {
660
    let mut out: Vec<String> = fs::read_dir(root)
661
        .unwrap()
662
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
663
        .filter(|n| n.contains(".oxy-conflict-"))
664
        .collect();
665
    out.sort();
666
    out
667
}
668
669
/// The same path added on two bookmarks with identical content is one
670
/// file after the merge (oxygen#101): no conflict, nothing to resolve,
671
/// nothing recorded; and editing or removing it later keeps it one.
672
#[test]
673
fn identical_additions_unify_on_merge() {
674
    hermetic();
675
    let (dir, repo, heads, [h1, ha, hb]) =
676
        merged_additions(|root, _| write(root, "x.txt", b"same\nlines\n"));
677
    let root = dir.path();
678
    // The tree graph has the name conflict; every reader sees one file.
679
    let st = repo.load_state(&heads).unwrap();
680
    assert!(st
681
        .tree()
682
        .view()
683
        .conflicts
684
        .iter()
685
        .any(|c| matches!(c, crate::tree::TreeConflict::Name { .. })));
686
    let snap = st.materialize();
687
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
688
    assert_eq!(
689
        snap.files.keys().cloned().collect::<Vec<_>>(),
690
        ["keep.txt", "x.txt"]
691
    );
692
    assert!(
693
        matches!(&snap.files["x.txt"].content, FileContent::Text { bytes, .. } if bytes == b"same\nlines\n")
694
    );
695
    assert_eq!(snap.tree.unified.len(), 1);
696
    // On disk once, the working copy clean, nothing to commit.
697
    assert_eq!(fs::read(root.join("x.txt")).unwrap(), b"same\nlines\n");
698
    assert!(
699
        conflict_copies(root).is_empty(),
700
        "{:?}",
701
        conflict_copies(root)
702
    );
703
    let s = repo.snapshot("status").unwrap();
704
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
705
    assert!(!s.changed && !s.resolves);
706
    assert!(!s.base_snapshot.is_conflicted());
707
    assert!(s.wc.tree_ops.is_empty() && s.wc.edits.is_empty());
708
    let json = repo.status_json(&s).unwrap();
709
    assert!(json.contains("\"conflicted\":false"), "{json}");
710
    assert!(repo.commit("nothing", &[]).is_err());
711
    assert_eq!(repo.file_at("x.txt", None).unwrap(), b"same\nlines\n");
712
    // A peer holding the same changes, added in another order, agrees.
713
    let mut peer = State::new();
714
    for h in [hb, ha, h1] {
715
        peer.add_unchecked(repo.store().get_change(&h).unwrap());
716
    }
717
    peer.validate().unwrap();
718
    let ps = peer.materialize();
719
    assert!(!ps.is_conflicted());
720
    assert_eq!(ps.tree.entries["x.txt"], snap.tree.entries["x.txt"]);
721
    assert_eq!(ps.tree.unified, snap.tree.unified);
722
    // The file's history is both additions.
723
    let log: Vec<ChangeHash> = repo
724
        .log_for_path("x.txt")
725
        .unwrap()
726
        .iter()
727
        .map(|e| e.hash)
728
        .collect();
729
    assert!(log.contains(&ha) && log.contains(&hb), "{log:?}");
730
731
    // Edited and committed: one file still, the duplicate retired with it.
732
    write(root, "x.txt", b"same\nedited\n");
733
    let s = repo.snapshot("status").unwrap();
734
    assert_eq!(statuses(&s), vec![("x.txt".into(), ChangeStatus::Modified)]);
735
    let he = repo.commit("edit x", &[]).unwrap();
736
    let c = repo.store().get_change(&he).unwrap();
737
    assert_eq!(c.kind, ChangeKind::Normal);
738
    let (dup, _) = snap.tree.unified.iter().next().unwrap();
739
    assert!(
740
        c.tree_ops
741
            .iter()
742
            .any(|o| matches!(o, TreeOp::RemoveNode { node, .. } if node == dup)),
743
        "{:?}",
744
        c.tree_ops
745
    );
746
    let d = repo.describe_change(&he).unwrap();
747
    assert!(!d.contains("D x.txt"), "{d}");
748
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
749
    assert!(
750
        st.tree().view().conflicts.is_empty(),
751
        "nothing left to unify"
752
    );
753
    let snap = st.materialize();
754
    assert!(!snap.is_conflicted());
755
    assert!(
756
        matches!(&snap.files["x.txt"].content, FileContent::Text { bytes, .. } if bytes == b"same\nedited\n")
757
    );
758
    assert!(!repo.snapshot("status").unwrap().changed);
759
760
    // Removed and committed: gone.
761
    fs::remove_file(root.join("x.txt")).unwrap();
762
    repo.commit("drop x", &[]).unwrap();
763
    let snap = repo
764
        .load_state(&repo.bookmark_heads().unwrap())
765
        .unwrap()
766
        .materialize();
767
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
768
    assert_eq!(snap.files.keys().cloned().collect::<Vec<_>>(), ["keep.txt"]);
769
    assert!(!root.join("x.txt").exists());
770
}
771
772
/// Removing, renaming, or committing just the path of a unified file
773
/// retires its duplicate with it, so the conflict never comes back.
774
#[test]
775
fn unified_additions_stay_one_when_removed_renamed_or_committed_alone() {
776
    hermetic();
777
    let add = |root: &Path, _: bool| write(root, "x.txt", b"same\n");
778
    for how in ["remove", "rename", "path", "hunk"] {
779
        let (dir, repo, _, _) = merged_additions(add);
780
        let root = dir.path();
781
        match how {
782
            "remove" => fs::remove_file(root.join("x.txt")).unwrap(),
783
            "rename" => fs::rename(root.join("x.txt"), root.join("y.txt")).unwrap(),
784
            _ => {
785
                write(root, "x.txt", b"same\nmore\n");
786
                write(root, "other.txt", b"o\n");
787
            }
788
        }
789
        let s = repo.snapshot("status").unwrap();
790
        let h = match how {
791
            "path" => repo
792
                .commit_selection("x alone", &[], &Selection::Paths(vec!["x.txt".into()]))
793
                .unwrap(),
794
            "hunk" => {
795
                let (_, hunks) = repo.hunks().unwrap();
796
                // The duplicate's retirement is no hunk of its own.
797
                assert!(hunks.iter().all(|h| !h.text.starts_with("D ")), "{hunks:?}");
798
                let x: Vec<usize> = hunks
799
                    .iter()
800
                    .filter(|h| h.path == "x.txt")
801
                    .map(|h| h.index)
802
                    .collect();
803
                assert!(!x.is_empty());
804
                repo.commit_selection("x hunks", &[], &Selection::Hunks(x))
805
                    .unwrap()
806
            }
807
            _ => repo.commit(how, &[]).unwrap(),
808
        };
809
        assert!(!s.base_snapshot.is_conflicted());
810
        let heads = repo.bookmark_heads().unwrap();
811
        assert!(heads.contains(&h));
812
        let snap = repo.load_state(&heads).unwrap().materialize();
813
        assert!(!snap.is_conflicted(), "{how}: {:?}", snap.tree.conflicts);
814
        let want: &[&str] = match how {
815
            "remove" => &["keep.txt"],
816
            "rename" => &["keep.txt", "y.txt"],
817
            _ => &["keep.txt", "x.txt"],
818
        };
819
        assert_eq!(
820
            snap.files.keys().cloned().collect::<Vec<_>>(),
821
            want,
822
            "{how}"
823
        );
824
        assert!(conflict_copies(root).is_empty(), "{how}");
825
    }
826
}
827
828
/// The same path added with different content, or a different mode, is a
829
/// name conflict as before.
830
#[test]
831
fn additions_that_differ_still_conflict() {
832
    hermetic();
833
    #[cfg(unix)]
834
    use std::os::unix::fs::PermissionsExt;
835
    let content =
836
        |root: &Path, side: bool| write(root, "x.txt", if side { b"two\n" } else { b"one\n" });
837
    let mode = |root: &Path, side: bool| {
838
        write(root, "x.txt", b"same\n");
839
        #[cfg(unix)]
840
        if side {
841
            fs::set_permissions(root.join("x.txt"), fs::Permissions::from_mode(0o755)).unwrap();
842
        }
843
    };
844
    let check = |what: &str, side: &dyn Fn(&Path, bool)| {
845
        let (dir, repo, heads, _) = merged_additions(side);
846
        let snap = repo.load_state(&heads).unwrap().materialize();
847
        assert!(snap.tree.unified.is_empty(), "{what}");
848
        assert!(
849
            snap.tree.conflicts.iter().any(
850
                |c| matches!(c, crate::tree::TreeConflict::Name { name, .. } if name == "x.txt")
851
            ),
852
            "{what}: {:?}",
853
            snap.tree.conflicts
854
        );
855
        assert_eq!(
856
            conflict_copies(dir.path()),
857
            ["x.txt.oxy-conflict-1", "x.txt.oxy-conflict-2"],
858
            "{what}"
859
        );
860
        assert!(!dir.path().join("x.txt").exists(), "{what}");
861
    };
862
    check("content", &content);
863
    #[cfg(unix)]
864
    check("mode", &mode);
865
    #[cfg(not(unix))]
866
    let _ = mode;
867
}
868
869
/// The same subrepo at the same pin, added on two bookmarks, is one
870
/// subrepo after the merge (oxygen#101), as is the identical
871
/// `.oxymodules` beside it.
872
#[test]
873
fn the_same_subrepo_added_on_two_bookmarks_unifies() {
874
    hermetic();
875
    let dir = tempfile::tempdir().unwrap();
876
    let root = dir.path();
877
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
878
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
879
    let lib = Repo::clone(&lib_url, &root.join("lib"))
880
        .unwrap()
881
        .with_home(root.join("home"));
882
    write(&root.join("lib"), "lib.txt", b"v1\n");
883
    lib.commit("lib v1", &[]).unwrap();
884
    assert!(lib.push("origin", false).unwrap()[0].ok);
885
    let _ = lib_origin;
886
887
    let app_dir = root.join("app");
888
    let mut app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
889
    write(&app_dir, "main.txt", b"app\n");
890
    app.commit("base", &[]).unwrap();
891
    app.bookmark_create("side", None).unwrap();
892
    app.submodule_add(&lib_url, "rstar-api", None).unwrap();
893
    let modules = fs::read(app_dir.join(".oxymodules")).unwrap();
894
    app.commit("rstar-api on main", &[]).unwrap();
895
    // On the other bookmark the nested repository is still there (it is
896
    // never deleted); registering it again adds it at the same pin.
897
    app.bookmark_switch("side", false).unwrap();
898
    assert!(app_dir.join("rstar-api/.oxy").is_dir());
899
    write(&app_dir, ".oxymodules", &modules);
900
    let s = app.snapshot("status").unwrap();
901
    assert_eq!(
902
        statuses(&s),
903
        vec![
904
            (".oxymodules".into(), ChangeStatus::Added),
905
            ("rstar-api".into(), ChangeStatus::Added)
906
        ]
907
    );
908
    app.commit("rstar-api on side", &[]).unwrap();
909
    app.bookmark_switch("main", false).unwrap();
910
911
    let m = app.merge("side").unwrap();
912
    assert!(m.changed && m.checked_out);
913
    let snap = app.load_state(&m.heads).unwrap().materialize();
914
    assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
915
    assert_eq!(snap.tree.unified.len(), 2);
916
    assert_eq!(snap.files["rstar-api"].kind, NodeKind::Subrepo);
917
    assert!(conflict_copies(&app_dir).is_empty());
918
    let s = app.snapshot("status").unwrap();
919
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
920
    assert!(!s.base_snapshot.is_conflicted());
921
    assert_eq!(
922
        fs::read_to_string(app_dir.join("rstar-api/lib.txt")).unwrap(),
923
        "v1\n"
924
    );
925
}
926
927
#[test]
928
fn identities_and_signed_commits() {
929
    hermetic();
930
    let dir = tempfile::tempdir().unwrap();
931
    let root = dir.path();
932
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
933
    write(root, "a.txt", b"a\n");
934
    let h0 = repo.commit("unsigned", &[]).unwrap();
935
    assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
936
    assert_eq!(
937
        repo.store().get_change(&h0).unwrap().author,
938
        ObjectRef::ZERO
939
    );
940
941
    let (key, id) = repo
942
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
943
        .unwrap();
944
    assert_eq!(id.hash(), key);
945
    assert_eq!(repo.config.author_key, Some(key));
946
    // Config survives reopen; the secret key is found again.
947
    let reopened = Repo::open(root).unwrap().with_home(root.join("home"));
948
    assert_eq!(reopened.config.author_key, Some(key));
949
    assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
950
951
    // Default core.sign = seal: commits carry the author but no signature.
952
    write(root, "a.txt", b"a\nb\n");
953
    let h1 = repo.commit("authored", &[]).unwrap();
954
    assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
955
    assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
956
    // Signing later works too.
957
    repo.sign_change(&h1).unwrap();
958
    assert!(
959
        matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
960
    );
961
962
    repo.config.set("core.sign", "change").unwrap();
963
    repo.save_config().unwrap();
964
    write(root, "a.txt", b"a\nb\nc\n");
965
    let h2 = repo.commit("signed", &[]).unwrap();
966
    assert_eq!(
967
        repo.verify_change(&h2).unwrap(),
968
        SignatureStatus::Valid {
969
            key,
970
            name: "Ada".into(),
971
            email: "[email protected]".into(),
972
            sealed: false,
973
            revoked: false
974
        }
975
    );
976
977
    // A signature by a key that is not the author or a delegate is rejected
978
    // when the change names an author; an anonymous change (made before any
979
    // identity, author zero) is adopted by whoever signs it (spec §14.4).
980
    let other = SecretKey::generate();
981
    let other_id = other.identity("Mallory", "[email protected]", 0);
982
    let other_key = repo.store().put_identity(&other_id).unwrap();
983
    write(root, "a.txt", b"a\nb\nc\nd\n");
984
    repo.config.set("core.sign", "seal").unwrap();
985
    let h3 = repo.commit("ada's, unsigned", &[]).unwrap();
986
    let forged = other.sign(Domain::Change, &other_key, &h3);
987
    repo.store().put_signature(&h3, &forged).unwrap();
988
    assert!(
989
        matches!(repo.verify_change(&h3).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author"))
990
    );
991
    let adopted = other.sign(Domain::Change, &other_key, &h0);
992
    repo.store().put_signature(&h0, &adopted).unwrap();
993
    assert!(
994
        matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Valid { name, .. } if name == "Mallory")
995
    );
996
997
    // Tampering with the stored signature invalidates it.
998
    let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
999
    sig.ed[0] ^= 1;
1000
    repo.store().put_signature(&h2, &sig).unwrap();
1001
    assert!(matches!(
1002
        repo.verify_change(&h2).unwrap(),
1003
        SignatureStatus::Invalid(_)
1004
    ));
1005
1006
    // Without the secret key, signing at commit fails cleanly.
1007
    let no_keys = Repo::open(root).unwrap().with_home(root.join("nowhere"));
1008
    write(root, "a.txt", b"z\n");
1009
    assert!(no_keys.commit("cannot sign", &[]).is_err());
1010
}
1011
1012
#[test]
1013
fn checkout_moves_the_working_copy() {
1014
    hermetic();
1015
    let dir = tempfile::tempdir().unwrap();
1016
    let root = dir.path();
1017
    let repo = Repo::init(root).unwrap();
1018
    write(root, "a.txt", b"one\n");
1019
    write(root, "sub/deep/b.txt", b"b\n");
1020
    let h1 = repo.commit("first", &[]).unwrap();
1021
    write(root, "a.txt", b"two\n");
1022
    fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
1023
    write(root, "bin.dat", &[0, 1, 2, 3]);
1024
    let h2 = repo.commit("second", &[]).unwrap();
1025
1026
    let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
1027
    assert_eq!(
1028
        r,
1029
        CheckoutReport {
1030
            written: 2,
1031
            removed: 1,
1032
            removed_paths: vec!["bin.dat".into()],
1033
            conflicted: false,
1034
            notes: vec![],
1035
            lacks: 1,
1036
            kept_both: vec![],
1037
        }
1038
    );
1039
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1040
    assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
1041
    assert!(!root.join("bin.dat").exists());
1042
    let (_, wc) = repo.working_copy().unwrap();
1043
    assert_eq!(wc.deps, vec![h1]);
1044
    assert!(
1045
        !repo.snapshot("status").unwrap().changed,
1046
        "checkout leaves a clean working copy"
1047
    );
1048
    // The bookmark still points at h2.
1049
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1050
1051
    // Dirty working copy refuses without --discard.
1052
    write(root, "a.txt", b"dirty\n");
1053
    assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
1054
    let r = repo
1055
        .checkout(&[h2], true, "oxy checkout --discard")
1056
        .unwrap();
1057
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
1058
    assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
1059
    assert!(!root.join("sub").exists(), "empty directories are pruned");
1060
    assert_eq!(r.removed, 1);
1061
    assert!(!repo.snapshot("status").unwrap().changed);
1062
1063
    // Refuses to write through a symlinked directory.
1064
    #[cfg(unix)]
1065
    {
1066
        fs::remove_dir_all(root.join("sub")).ok();
1067
        std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
1068
        assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
1069
    }
1070
}
1071
1072
#[test]
1073
fn large_files_are_chunked_and_read_back() {
1074
    hermetic();
1075
    let dir = tempfile::tempdir().unwrap();
1076
    let repo = Repo::init(dir.path()).unwrap();
1077
    let mut big = vec![0u8; 700 * 1024];
1078
    for (i, b) in big.iter_mut().enumerate() {
1079
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
1080
    }
1081
    let r = repo.store_blob(&big).unwrap();
1082
    let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
1083
    assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
1084
    assert_eq!(repo.read_blob(&r).unwrap(), big);
1085
    assert_eq!(Repo::blob_ref(&big), r);
1086
}
1087
1088
#[test]
1089
fn clone_push_pull_with_seals_and_attestations() {
1090
    hermetic();
1091
    let dir = tempfile::tempdir().unwrap();
1092
    let root = dir.path();
1093
    let origin_path = root.join("origin");
1094
    let origin = Repo::init(&origin_path).unwrap();
1095
    let origin_url = origin_path.to_string_lossy().to_string();
1096
1097
    // A clones, creates an identity (default core.sign = seal), commits, pushes.
1098
    let mut a = Repo::clone(&origin_url, &root.join("a"))
1099
        .unwrap()
1100
        .with_home(root.join("home-a"));
1101
    assert_eq!(a.id().unwrap(), origin.id().unwrap());
1102
    let (key_a, _) = a
1103
        .create_identity("Ada", "[email protected]", IdentityScope::Repo)
1104
        .unwrap();
1105
    write(&root.join("a"), "f.txt", b"a\n");
1106
    let h1 = a.commit("first", &[]).unwrap();
1107
    let results = a.push("origin", false).unwrap();
1108
    origin.refresh().unwrap();
1109
    assert!(results[0].ok, "{}", results[0].reason);
1110
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
1111
    // The change was sealed at push and the reference attested.
1112
    assert!(
1113
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a)
1114
    );
1115
    assert_eq!(
1116
        origin.verify_change(&h1).unwrap(),
1117
        SignatureStatus::Unsigned
1118
    );
1119
    let serial_of = |att: &SignedAttest| match att.attest.body {
1120
        AttestBody::Ref { serial, .. } => serial,
1121
        _ => unreachable!(),
1122
    };
1123
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
1124
    // A bookmark new to the remote starts at the clock (past any deleted
1125
    // namesake's serial); later updates count up from there.
1126
    let first = serial_of(&att);
1127
    assert!(first > 1_000_000_000_000, "{first}");
1128
    let again = a.push("origin", false).unwrap();
1129
    origin.refresh().unwrap();
1130
    assert!(again[0].ok && again[0].reason.contains("up to date"));
1131
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
1132
    assert_eq!(serial_of(&att), first, "a no-op push does not attest again");
1133
1134
    // B clones and sees the file and the seal.
1135
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
1136
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
1137
    assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
1138
    assert!(matches!(
1139
        b.authenticate_change(&h1).unwrap(),
1140
        SignatureStatus::Valid { sealed: true, .. }
1141
    ));
1142
1143
    // B (no identity) commits and pushes unsigned; the unverified origin accepts.
1144
    write(&root.join("b"), "f.txt", b"a\nb\n");
1145
    let h2 = b.commit("second", &[]).unwrap();
1146
    assert!(b.push("origin", false).unwrap()[0].ok);
1147
    origin.refresh().unwrap();
1148
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
1149
1150
    // A commits an independent change; push is refused until A pulls.
1151
    write(&root.join("a"), "g.txt", b"g\n");
1152
    let h3 = a.commit("third", &[]).unwrap();
1153
    assert!(a.push("origin", false).is_err());
1154
    let pr = a.pull("origin").unwrap();
1155
    assert!(pr.changed && pr.checked_out);
1156
    let mut want = vec![h2, h3];
1157
    want.sort();
1158
    assert_eq!(pr.heads, want);
1159
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
1160
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
1161
    let results = a.push("origin", false).unwrap();
1162
    origin.refresh().unwrap();
1163
    assert!(results[0].ok, "{}", results[0].reason);
1164
    let mut origin_heads = origin.bookmark_heads().unwrap();
1165
    origin_heads.sort();
1166
    assert_eq!(origin_heads, want);
1167
    let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
1168
    assert_eq!(serial_of(&att), first + 1);
1169
1170
    // B pulls and ends up identical.
1171
    let pr = b.pull("origin").unwrap();
1172
    assert_eq!(pr.heads, want);
1173
    assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
1174
    assert!(!b.snapshot("status").unwrap().changed);
1175
1176
    // Concurrent edits of the same line: the union is a reified conflict.
1177
    write(&root.join("a"), "f.txt", b"a\nA\n");
1178
    a.commit("a-edit", &[]).unwrap();
1179
    a.push("origin", false).unwrap();
1180
    origin.refresh().unwrap();
1181
    write(&root.join("b"), "f.txt", b"a\nB\n");
1182
    b.commit("b-edit", &[]).unwrap();
1183
    let pr = b.pull("origin").unwrap();
1184
    assert!(pr.changed && pr.checked_out);
1185
    let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
1186
    assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
1187
    write(&root.join("b"), "f.txt", b"a\nAB\n");
1188
    let hr = b.commit("resolve", &[]).unwrap();
1189
    assert_eq!(
1190
        b.store().get_change(&hr).unwrap().kind,
1191
        ChangeKind::Resolution
1192
    );
1193
    assert!(b.push("origin", false).unwrap()[0].ok);
1194
    origin.refresh().unwrap();
1195
    a.pull("origin").unwrap();
1196
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
1197
    // The resolution depends on the conflicting edits, but nothing depends
1198
    // on "third" (it only added g.txt), so it stays a head beside it.
1199
    let mut want = vec![hr, h3];
1200
    want.sort();
1201
    assert_eq!(a.bookmark_heads().unwrap(), want);
1202
    assert!(!a.load_state(&want).unwrap().materialize().is_conflicted());
1203
}
1204
1205
#[test]
1206
fn receive_push_rejects_bad_updates() {
1207
    hermetic();
1208
    let dir = tempfile::tempdir().unwrap();
1209
    let root = dir.path();
1210
    let origin = Repo::init(&root.join("origin")).unwrap();
1211
    let url = root.join("origin").to_string_lossy().to_string();
1212
    let mut a = Repo::clone(&url, &root.join("a"))
1213
        .unwrap()
1214
        .with_home(root.join("home"));
1215
    let (key, _) = a
1216
        .create_identity("Ada", "a@b", IdentityScope::Repo)
1217
        .unwrap();
1218
    write(&root.join("a"), "f.txt", b"x\n");
1219
    let h1 = a.commit("one", &[]).unwrap();
1220
    assert!(a.push("origin", false).unwrap()[0].ok);
1221
    let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
1222
    let s1 = origin
1223
        .store()
1224
        .put_state(&StateObject::new(vec![h1]))
1225
        .unwrap();
1226
1227
    // Missing head.
1228
    let ghost = origin
1229
        .store()
1230
        .put_state(&StateObject::new(vec![ObjectRef([9; 32])]))
1231
        .unwrap();
1232
    let r = origin
1233
        .receive_push(
1234
            Bundle::default(),
1235
            vec![RefUpdate {
1236
                name: "main".into(),
1237
                old_state: s1,
1238
                new_state: ghost,
1239
                force: false,
1240
                attestation: None,
1241
            }],
1242
            None,
1243
            vec![],
1244
        )
1245
        .unwrap();
1246
    assert!(
1247
        !r[0].ok && r[0].reason.contains("missing"),
1248
        "{}",
1249
        r[0].reason
1250
    );
1251
1252
    // Stale old_state.
1253
    let r = origin
1254
        .receive_push(
1255
            Bundle::default(),
1256
            vec![RefUpdate {
1257
                name: "main".into(),
1258
                old_state: empty,
1259
                new_state: s1,
1260
                force: false,
1261
                attestation: None,
1262
            }],
1263
            None,
1264
            vec![],
1265
        )
1266
        .unwrap();
1267
    assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
1268
1269
    // Non-fast-forward without force is refused; with force it passes.
1270
    let r = origin
1271
        .receive_push(
1272
            Bundle::default(),
1273
            vec![RefUpdate {
1274
                name: "main".into(),
1275
                old_state: s1,
1276
                new_state: empty,
1277
                force: false,
1278
                attestation: None,
1279
            }],
1280
            None,
1281
            vec![],
1282
        )
1283
        .unwrap();
1284
    assert!(
1285
        !r[0].ok && r[0].reason.contains("fast-forward"),
1286
        "{}",
1287
        r[0].reason
1288
    );
1289
    let r = origin
1290
        .receive_push(
1291
            Bundle::default(),
1292
            vec![RefUpdate {
1293
                name: "main".into(),
1294
                old_state: s1,
1295
                new_state: empty,
1296
                force: true,
1297
                attestation: None,
1298
            }],
1299
            None,
1300
            vec![],
1301
        )
1302
        .unwrap();
1303
    assert!(r[0].ok);
1304
    assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
1305
1306
    // Attestation with a stale serial is a rollback and is refused.
1307
    let sa = a
1308
        .sign_attest(&Attest {
1309
            repo: a.id().unwrap(),
1310
            hlc: Hlc::now(),
1311
            body: AttestBody::Ref {
1312
                name: "main".into(),
1313
                old_state: empty,
1314
                new_state: s1,
1315
                serial: 1,
1316
            },
1317
        })
1318
        .unwrap();
1319
    let r = origin
1320
        .receive_push(
1321
            Bundle::default(),
1322
            vec![RefUpdate {
1323
                name: "main".into(),
1324
                old_state: empty,
1325
                new_state: s1,
1326
                force: false,
1327
                attestation: Some(sa.clone()),
1328
            }],
1329
            None,
1330
            vec![],
1331
        )
1332
        .unwrap();
1333
    assert!(
1334
        !r[0].ok && r[0].reason.contains("serial"),
1335
        "{}",
1336
        r[0].reason
1337
    );
1338
    // An attestation for a different update is refused too.
1339
    let sa2 = a
1340
        .sign_attest(&Attest {
1341
            repo: a.id().unwrap(),
1342
            hlc: Hlc::now(),
1343
            body: AttestBody::Ref {
1344
                name: "main".into(),
1345
                old_state: s1,
1346
                new_state: empty,
1347
                serial: 5,
1348
            },
1349
        })
1350
        .unwrap();
1351
    let r = origin
1352
        .receive_push(
1353
            Bundle::default(),
1354
            vec![RefUpdate {
1355
                name: "main".into(),
1356
                old_state: empty,
1357
                new_state: s1,
1358
                force: false,
1359
                attestation: Some(sa2),
1360
            }],
1361
            None,
1362
            vec![],
1363
        )
1364
        .unwrap();
1365
    assert!(
1366
        !r[0].ok && r[0].reason.contains("describe"),
1367
        "{}",
1368
        r[0].reason
1369
    );
1370
    let _ = key;
1371
}
1372
1373
#[test]
1374
fn user_config_supplies_defaults_and_clones_sign() {
1375
    hermetic();
1376
    let dir = tempfile::tempdir().unwrap();
1377
    let root = dir.path();
1378
    let home = root.join("home");
1379
    let origin = Repo::init(&root.join("origin")).unwrap();
1380
    let url = root.join("origin").to_string_lossy().to_string();
1381
1382
    // Identity at user scope: the repository file stays free of author keys.
1383
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
1384
    let (key, _) = a
1385
        .create_identity("Ada", "[email protected]", IdentityScope::User)
1386
        .unwrap();
1387
    assert!(!a.config.repo_layer().contains_key("author.key"));
1388
    assert_eq!(a.config.author_key, Some(key));
1389
    assert!(home.join("config.toml").exists());
1390
    a.set_user_config("core.sign", "change").unwrap();
1391
    assert!(a.config.sign_changes);
1392
1393
    // Repository settings override user settings and are the only ones saved.
1394
    a.config.set("core.sign", "seal").unwrap();
1395
    a.save_config().unwrap();
1396
    let again = Repo::open(&root.join("a")).unwrap().with_home(&home);
1397
    assert!(!again.config.sign_changes);
1398
    assert_eq!(again.config.author_key, Some(key));
1399
    assert_eq!(
1400
        read_config_file(&root.join("a/.oxy/config"))
1401
            .unwrap()
1402
            .get("core.sign")
1403
            .map(String::as_str),
1404
        Some("seal")
1405
    );
1406
1407
    // A fresh clone made by this user signs with the user-level identity,
1408
    // even though the clone's store has never seen the identity object.
1409
    let b = Repo::clone(&url, &root.join("b")).unwrap().with_home(&home);
1410
    assert!(b.config.sign_changes);
1411
    write(&root.join("b"), "f.txt", b"f\n");
1412
    let h = b.commit("signed from a clone", &[]).unwrap();
1413
    assert!(
1414
        matches!(b.verify_change(&h).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key)
1415
    );
1416
    assert!(b.push("origin", false).unwrap()[0].ok);
1417
    assert!(matches!(
1418
        origin.verify_change(&h).unwrap(),
1419
        SignatureStatus::Valid { .. }
1420
    ));
1421
}
1422
1423
#[test]
1424
fn format1_repositories_are_migrated_on_open() {
1425
    hermetic();
1426
    use crate::oplog::{Format1Op, Format1View};
1427
    let dir = tempfile::tempdir().unwrap();
1428
    let root = dir.path();
1429
    let repo = Repo::init(root).unwrap();
1430
    write(root, "a.txt", b"a\n");
1431
    let h1 = repo.commit("one", &[]).unwrap();
1432
    let (wc_hash, _) = repo.working_copy().unwrap();
1433
    // Rewrite the op log the way format 1 stored it: two ops, head lists.
1434
    let mut v1 = Format1View::default();
1435
    v1.bookmarks.insert("main".into(), vec![]);
1436
    v1.workspaces.insert(repo.workspace(), wc_hash);
1437
    let init = Format1Op {
1438
        parents: vec![],
1439
        hlc: Hlc::default(),
1440
        command: "oxy init".into(),
1441
        view: v1.clone(),
1442
    };
1443
    let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
1444
    v1.bookmarks.insert("main".into(), vec![h1]);
1445
    let commit = Format1Op {
1446
        parents: vec![init_ref],
1447
        hlc: Hlc::default(),
1448
        command: "oxy commit".into(),
1449
        view: v1,
1450
    };
1451
    let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
1452
    write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
1453
    write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
1454
    drop(repo);
1455
1456
    let repo = Repo::open(root).unwrap();
1457
    assert_eq!(
1458
        fs::read_to_string(root.join(".oxy/format")).unwrap(),
1459
        FORMAT_LINE
1460
    );
1461
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
1462
    let ops = repo.op_log().unwrap();
1463
    assert_eq!(
1464
        ops.iter()
1465
            .map(|(_, o)| o.command.as_str())
1466
            .collect::<Vec<_>>(),
1467
        ["oxy commit", "oxy init"]
1468
    );
1469
    assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
1470
    assert!(!repo.snapshot("status").unwrap().changed);
1471
    // Reopening again is a no-op.
1472
    assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
1473
}
1474
1475
#[test]
1476
fn undo_skips_snapshot_operations() {
1477
    hermetic();
1478
    let dir = tempfile::tempdir().unwrap();
1479
    let root = dir.path();
1480
    let repo = Repo::init(root).unwrap();
1481
    write(root, "a.txt", b"a\n");
1482
    let h1 = repo.commit("a", &[]).unwrap();
1483
    // A later command snapshots new edits on top of the commit.
1484
    write(root, "b.txt", b"b\n");
1485
    let s = repo.snapshot("oxy status").unwrap();
1486
    assert!(s.changed);
1487
    assert!(repo.head_op().unwrap().1.is_snapshot());
1488
    assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
1489
    // Undo must undo the commit, not the snapshot.
1490
    repo.undo().unwrap();
1491
    assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
1492
    let s = repo.snapshot("oxy status").unwrap();
1493
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
1494
    assert_eq!(
1495
        paths,
1496
        ["a.txt", "b.txt"],
1497
        "both files are back in the working copy"
1498
    );
1499
    assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
1500
    // Only snapshots remain above `init`, so there is nothing left to undo.
1501
    assert_eq!(repo.last_command().unwrap().command, "oxy init");
1502
    assert!(repo.undo().is_err());
1503
}
1504
1505
#[test]
1506
fn independent_changes_commute_and_make_multiple_heads() {
1507
    hermetic();
1508
    let dir = tempfile::tempdir().unwrap();
1509
    let root = dir.path();
1510
    let repo = Repo::init(root).unwrap();
1511
    write(root, "a.txt", b"a\n");
1512
    let h1 = repo.commit("a", &[]).unwrap();
1513
    write(root, "b.txt", b"b\n");
1514
    let h2 = repo.commit("b", &[]).unwrap();
1515
    let c2 = repo.store().get_change(&h2).unwrap();
1516
    assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
1517
    let mut heads = repo.bookmark_heads().unwrap();
1518
    heads.sort();
1519
    let mut want = vec![h1, h2];
1520
    want.sort();
1521
    assert_eq!(heads, want);
1522
    // Editing a.txt depends on h1 only.
1523
    write(root, "a.txt", b"a\na2\n");
1524
    let h3 = repo.commit("a2", &[]).unwrap();
1525
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
1526
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1527
    assert_eq!(heads, [h2, h3].into_iter().collect());
1528
    // Explicit dependency.
1529
    write(root, "c.txt", b"c\n");
1530
    let h4 = repo.commit("c", &[h2]).unwrap();
1531
    assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
1532
}
1533
1534
#[test]
1535
fn mode_change_and_text_binary_switch() {
1536
    hermetic();
1537
    let dir = tempfile::tempdir().unwrap();
1538
    let root = dir.path();
1539
    let repo = Repo::init(root).unwrap();
1540
    write(root, "run.sh", b"#!/bin/sh\n");
1541
    repo.commit("add script", &[]).unwrap();
1542
    #[cfg(unix)]
1543
    {
1544
        use std::os::unix::fs::PermissionsExt;
1545
        fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1546
        let s = repo.snapshot("status").unwrap();
1547
        assert_eq!(
1548
            statuses(&s),
1549
            vec![("run.sh".into(), ChangeStatus::ModeChanged)]
1550
        );
1551
        let h = repo.commit("exec", &[]).unwrap();
1552
        let snap = repo.load_state(&[h]).unwrap().materialize();
1553
        assert!(snap.files["run.sh"].mode.exec);
1554
    }
1555
    // Text → binary → text.
1556
    write(root, "run.sh", b"\0binary");
1557
    let h = repo.commit("binary", &[]).unwrap();
1558
    let snap = repo.load_state(&[h]).unwrap().materialize();
1559
    assert!(snap.files["run.sh"].mode.opaque);
1560
    write(root, "run.sh", b"text again\n");
1561
    let h = repo.commit("text", &[]).unwrap();
1562
    let snap = repo.load_state(&[h]).unwrap().materialize();
1563
    assert!(!snap.files["run.sh"].mode.opaque);
1564
    assert!(
1565
        matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n")
1566
    );
1567
    assert!(!snap.is_conflicted());
1568
}
1569
1570
/// oxygen#87: a binary file given new contents and the executable bit in
1571
/// one commit kept the contents and lost the bit.
1572
#[cfg(unix)]
1573
#[test]
1574
fn a_binary_file_changed_and_made_executable_at_once_keeps_both() {
1575
    use std::os::unix::fs::PermissionsExt;
1576
    hermetic();
1577
    let dir = tempfile::tempdir().unwrap();
1578
    let root = dir.path();
1579
    let repo = Repo::init(root).unwrap();
1580
    write(root, "tool.exe", b"MZ\0one");
1581
    repo.commit("add", &[]).unwrap();
1582
    write(root, "tool.exe", b"MZ\0two");
1583
    fs::set_permissions(root.join("tool.exe"), fs::Permissions::from_mode(0o755)).unwrap();
1584
    let h = repo.commit("update and +x", &[]).unwrap();
1585
    let snap = repo.load_state(&[h]).unwrap().materialize();
1586
    let f = &snap.files["tool.exe"];
1587
    assert!(f.mode.opaque && f.mode.exec, "{:?}", f.mode);
1588
    assert!(
1589
        repo.snapshot("status").unwrap().statuses.is_empty(),
1590
        "nothing left to commit"
1591
    );
1592
}
1593
1594
/// Keyless step 4 (oxygenhub#241): an agent signing with a short-lived
1595
/// key whose certificate an issuer gave pushes when the policy grants its
1596
/// subject, and a fetch accepts what it attested; an expired certificate,
1597
/// or a subject the policy does not grant, may not move the bookmark.
1598
#[test]
1599
fn a_certified_key_pushes_under_a_subject_grant() {
1600
    use crate::cert::{Certificate, SignedCertificate};
1601
    use crate::identity::Scope;
1602
    hermetic();
1603
    let dir = tempfile::tempdir().unwrap();
1604
    let root = dir.path();
1605
    let _origin = Repo::init(&root.join("origin")).unwrap();
1606
    let url = root.join("origin").to_string_lossy().to_string();
1607
    let mut a = Repo::clone(&url, &root.join("a"))
1608
        .unwrap()
1609
        .with_home(root.join("home-a"));
1610
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1611
        .unwrap();
1612
    write(&root.join("a"), "a.txt", b"a\n");
1613
    a.commit("a", &[]).unwrap();
1614
    a.policy_init().unwrap();
1615
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1616
    let hub_sk = SecretKey::generate();
1617
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1618
    a.policy_grant_subject(
1619
        "agent:claude@ada",
1620
        hub.clone(),
1621
        Scope::CHANGES | Scope::REFS,
1622
        None,
1623
    )
1624
    .unwrap();
1625
    assert!(a
1626
        .push("origin", false)
1627
        .unwrap()
1628
        .iter()
1629
        .any(|r| r.name == "policy" && r.ok));
1630
1631
    let now = Hlc::now().wall_ms;
1632
    // An agent repository whose key the hub certified for `subject`, from
1633
    // `from` to `to`.
1634
    let agent = |name: &str, subject: &str, from: u64, to: u64| {
1635
        let mut r = Repo::clone(&url, &root.join(name))
1636
            .unwrap()
1637
            .with_home(root.join(format!("home-{name}")));
1638
        let (_, id) = r
1639
            .create_identity(name, "[email protected]", IdentityScope::User)
1640
            .unwrap();
1641
        let cert = SignedCertificate::sign(
1642
            Certificate {
1643
                key: id,
1644
                issuer: hub.hash(),
1645
                subject: subject.into(),
1646
                claims: vec![],
1647
                scope: Scope::CHANGES | Scope::REFS,
1648
                not_before: from,
1649
                expires: to,
1650
                grant: None,
1651
            },
1652
            &hub,
1653
            &hub_sk,
1654
        );
1655
        r.store().put_identity(&hub).unwrap();
1656
        r.store().put_certificate(&cert).unwrap();
1657
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
1658
        r.commit("work", &[]).unwrap();
1659
        r
1660
    };
1661
1662
    let claude = agent("claude", "agent:claude@ada", now - 60_000, now + 600_000);
1663
    let r = claude.push("origin", false).unwrap();
1664
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1665
    // Ada's fetch accepts the bookmark the certified key attested.
1666
    a.pull("origin").unwrap();
1667
    assert!(a.bookmark_heads().unwrap().iter().any(|h| a
1668
        .store()
1669
        .get_change(h)
1670
        .map(|c| c.message == "work")
1671
        .unwrap_or(false)));
1672
1673
    // Step 4c: a host with an acceptor key records when it accepted the
1674
    // certified update and serves it; a fetch checks the certificate at
1675
    // that time only when the certificate's issuer signed it for exactly
1676
    // this attestation, else at the attestation's own time.
1677
    let host = Repo::open(&root.join("origin"))
1678
        .unwrap()
1679
        .with_acceptor(hub.clone(), hub_sk.clone());
1680
    let (attest_ref, sa) = host.latest_ref_attest("main").unwrap().unwrap();
1681
    host.record_acceptance(&attest_ref).unwrap();
1682
    let served = host.remote_refs().unwrap();
1683
    let acc = served
1684
        .refs
1685
        .iter()
1686
        .find(|r| r.name == "main")
1687
        .unwrap()
1688
        .accepted
1689
        .clone()
1690
        .expect("served with the refs");
1691
    let signer = sa.sigs[0].key;
1692
    assert_eq!(
1693
        a.certified_time(&signer, &sa, Some(&acc)),
1694
        acc.attest.hlc.wall_ms
1695
    );
1696
    assert_eq!(a.certified_time(&signer, &sa, None), sa.attest.hlc.wall_ms);
1697
    let stranger_sk = SecretKey::generate();
1698
    let stranger = stranger_sk.identity("stranger", "s@x", 1);
1699
    let mut forged = acc.clone();
1700
    forged.sigs = vec![stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.attest.hash())];
1701
    assert_eq!(
1702
        a.certified_time(&signer, &sa, Some(&forged)),
1703
        sa.attest.hlc.wall_ms,
1704
        "not the issuer's"
1705
    );
1706
    let mut elsewhere = acc.clone();
1707
    elsewhere.attest.body = AttestBody::Accepted {
1708
        attest: ObjectRef([7; 32]),
1709
    };
1710
    elsewhere.sigs = vec![hub_sk.sign(Domain::Attest, &hub.hash(), &elsewhere.attest.hash())];
1711
    assert_eq!(
1712
        a.certified_time(&signer, &sa, Some(&elsewhere)),
1713
        sa.attest.hlc.wall_ms,
1714
        "another attestation's"
1715
    );
1716
    a.pull("origin").unwrap();
1717
    // gc keeps the acceptance with the attestation.
1718
    host.gc(true).unwrap();
1719
    assert!(host.acceptance_of(&attest_ref).unwrap().is_some());
1720
1721
    let late = agent("late", "agent:claude@ada", now - 1_200_000, now - 600_000);
1722
    let r = late.push("origin", false).unwrap();
1723
    assert!(
1724
        !r[0].ok && r[0].reason.contains("may not update"),
1725
        "an expired certificate: {r:?}"
1726
    );
1727
    let other = agent("other", "agent:mallory@ada", now - 60_000, now + 600_000);
1728
    let r = other.push("origin", false).unwrap();
1729
    assert!(
1730
        !r[0].ok && r[0].reason.contains("may not update"),
1731
        "a subject not granted: {r:?}"
1732
    );
1733
}
1734
1735
/// A tag made under one short-lived key and pushed under another: its
1736
/// signer travels with the push (identity and certificate), so a receiver
1737
/// that has never seen that key accepts it. A tag-only push by a keyless
1738
/// agent was refused "unknown key" (found releasing OxygenFlow 0.2.0).
1739
#[test]
1740
fn a_tag_signed_by_an_earlier_short_lived_key_is_pushed() {
1741
    use crate::cert::{Certificate, SignedCertificate};
1742
    use crate::identity::Scope;
1743
    hermetic();
1744
    let dir = tempfile::tempdir().unwrap();
1745
    let root = dir.path();
1746
    let _origin = Repo::init(&root.join("origin")).unwrap();
1747
    let url = root.join("origin").to_string_lossy().to_string();
1748
    let mut a = Repo::clone(&url, &root.join("a"))
1749
        .unwrap()
1750
        .with_home(root.join("home-a"));
1751
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1752
        .unwrap();
1753
    write(&root.join("a"), "a.txt", b"a\n");
1754
    a.commit("a", &[]).unwrap();
1755
    a.policy_init().unwrap();
1756
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1757
    let hub_sk = SecretKey::generate();
1758
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1759
    a.policy_grant_subject(
1760
        "agent:claude@ada",
1761
        hub.clone(),
1762
        Scope::CHANGES | Scope::REFS,
1763
        Some("*"),
1764
    )
1765
    .unwrap();
1766
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1767
1768
    let now = Hlc::now().wall_ms;
1769
    let mut agent = Repo::clone(&url, &root.join("agent"))
1770
        .unwrap()
1771
        .with_home(root.join("home-agent"));
1772
    agent.store().put_identity(&hub).unwrap();
1773
    let certify = |agent: &Repo, id| {
1774
        let cert = SignedCertificate::sign(
1775
            Certificate {
1776
                key: id,
1777
                issuer: hub.hash(),
1778
                subject: "agent:claude@ada".into(),
1779
                claims: vec![],
1780
                scope: Scope::CHANGES | Scope::REFS,
1781
                not_before: now - 60_000,
1782
                expires: now + 600_000,
1783
                grant: None,
1784
            },
1785
            &hub,
1786
            &hub_sk,
1787
        );
1788
        agent.store().put_certificate(&cert).unwrap();
1789
    };
1790
    // The tag, under the first short-lived key.
1791
    let (first, first_id) = agent
1792
        .create_identity("claude", "[email protected]", IdentityScope::User)
1793
        .unwrap();
1794
    certify(&agent, first_id);
1795
    let heads = agent.bookmark_heads().unwrap();
1796
    agent.tag_create("v1", &heads, "first").unwrap();
1797
    // The push, under a second one (a later process's ten-minute key).
1798
    let (second, second_id) = agent
1799
        .create_identity("claude", "[email protected]", IdentityScope::User)
1800
        .unwrap();
1801
    assert_ne!(first, second);
1802
    certify(&agent, second_id);
1803
    agent
1804
        .set_user_config("author.signer", &second.to_hex())
1805
        .unwrap();
1806
    let host = Repo::open(&root.join("origin")).unwrap();
1807
    assert!(
1808
        host.store().get_identity(&first).is_err(),
1809
        "the host has never seen the tag's key"
1810
    );
1811
    let r = agent.push("origin", false).unwrap();
1812
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1813
    let host = Repo::open(&root.join("origin")).unwrap();
1814
    assert!(
1815
        host.tag_refs().unwrap().iter().any(|t| t.name == "v1"),
1816
        "the tag arrived"
1817
    );
1818
}
1819
1820
/// oxygen#129: a short-lived key's tag is checked on a fetch at a time its
1821
/// signer did not choose, its issuer's acceptance, never at the time it
1822
/// claims nor at the fetch's (when the ten-minute certificate has long
1823
/// expired). Without an acceptance it is left out and said so; with one
1824
/// inside the certificate's window it is fetched however much later, and
1825
/// a host it is pushed on to keeps and serves the acceptance.
1826
#[test]
1827
fn a_short_lived_key_s_tag_is_fetched_at_its_issuer_s_acceptance() {
1828
    use crate::cert::{Certificate, SignedCertificate};
1829
    use crate::identity::Scope;
1830
    hermetic();
1831
    let dir = tempfile::tempdir().unwrap();
1832
    let root = dir.path();
1833
    let _origin = Repo::init(&root.join("origin")).unwrap();
1834
    let url = root.join("origin").to_string_lossy().to_string();
1835
    let mut a = Repo::clone(&url, &root.join("a"))
1836
        .unwrap()
1837
        .with_home(root.join("home-a"));
1838
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
1839
        .unwrap();
1840
    write(&root.join("a"), "a.txt", b"a\n");
1841
    a.commit("a", &[]).unwrap();
1842
    a.policy_init().unwrap();
1843
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1844
    let hub_sk = SecretKey::generate();
1845
    let hub = hub_sk.identity("hub", "[email protected]", 1);
1846
    a.policy_grant_subject(
1847
        "agent:claude@ada",
1848
        hub.clone(),
1849
        Scope::CHANGES | Scope::REFS,
1850
        Some("*"),
1851
    )
1852
    .unwrap();
1853
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
1854
1855
    let now = Hlc::now().wall_ms;
1856
    // An agent whose key the hub certified from `from` to `to`.
1857
    let agent = |name: &str, from: u64, to: u64| {
1858
        let mut r = Repo::clone(&url, &root.join(name))
1859
            .unwrap()
1860
            .with_home(root.join(format!("home-{name}")));
1861
        r.store().put_identity(&hub).unwrap();
1862
        let (_, id) = r
1863
            .create_identity(name, "[email protected]", IdentityScope::User)
1864
            .unwrap();
1865
        let cert = SignedCertificate::sign(
1866
            Certificate {
1867
                key: id,
1868
                issuer: hub.hash(),
1869
                subject: "agent:claude@ada".into(),
1870
                claims: vec![],
1871
                scope: Scope::CHANGES | Scope::REFS,
1872
                not_before: from,
1873
                expires: to,
1874
                grant: None,
1875
            },
1876
            &hub,
1877
            &hub_sk,
1878
        );
1879
        r.store().put_certificate(&cert).unwrap();
1880
        r
1881
    };
1882
1883
    // A tag by a key certified now, pushed to a host that records no
1884
    // acceptance (a path on disk): it lands, but a fetch has no time to
1885
    // check its certificate at, so it is left out and the fetch goes on.
1886
    let claude = agent("claude", now - 60_000, now + 600_000);
1887
    let heads = claude.bookmark_heads().unwrap();
1888
    claude.tag_create("v1", &heads, "one").unwrap();
1889
    let r = claude.push("origin", false).unwrap();
1890
    assert!(r.iter().all(|x| x.ok), "{r:?}");
1891
    let b = Repo::clone(&url, &root.join("b"))
1892
        .unwrap()
1893
        .with_home(root.join("home-b"));
1894
    let rep = b.fetch("origin").unwrap();
1895
    assert!(
1896
        rep.skipped
1897
            .iter()
1898
            .any(|(n, why)| n == "tags/v1" && why.contains("no time to check its certificate at")),
1899
        "{rep:?}"
1900
    );
1901
    assert_eq!(b.tag_heads("v1").unwrap(), None);
1902
1903
    // The host's acceptance, signed by the certificate's issuer, served
1904
    // with the tag: fetched.
1905
    let host = Repo::open(&root.join("origin"))
1906
        .unwrap()
1907
        .with_acceptor(hub.clone(), hub_sk.clone());
1908
    let (v1, _) = host.tag_attest("v1").unwrap().unwrap();
1909
    host.record_acceptance(&v1).unwrap();
1910
    let served = host.tag_refs().unwrap();
1911
    assert!(served
1912
        .iter()
1913
        .any(|t| t.name == "v1" && t.accepted.is_some()));
1914
    let rep = b.fetch("origin").unwrap();
1915
    assert!(rep.skipped.is_empty(), "{rep:?}");
1916
    assert_eq!(b.tag_heads("v1").unwrap(), Some(heads.clone()));
1917
    // gc keeps the acceptance with the tag.
1918
    host.gc(true).unwrap();
1919
    assert!(host.acceptance_of(&v1).unwrap().is_some());
1920
1921
    // Long after: a key whose certificate expired an hour ago may not
1922
    // create a tag now.
1923
    let late = agent("late", now - 7_200_000, now - 3_600_000);
1924
    late.tag_create("v2", &heads, "two").unwrap();
1925
    let r = late.push("origin", false).unwrap();
1926
    assert!(
1927
        r.iter()
1928
            .any(|x| x.name == "tags/v2" && !x.ok && x.reason.contains("may not create")),
1929
        "{r:?}"
1930
    );
1931
    // With its issuer's acceptance from inside the window (as a hub gave
1932
    // it then, passed on to another host), it is taken at that time: by
1933
    // the host it is pushed to, which keeps it, and by a fresh clone.
1934
    let (v2, _) = late.tag_attest("v2").unwrap().unwrap();
1935
    let acc = Attest {
1936
        repo: late.id().unwrap(),
1937
        hlc: Hlc {
1938
            wall_ms: now - 5_400_000,
1939
            logical: 0,
1940
        },
1941
        body: AttestBody::Accepted { attest: v2 },
1942
    };
1943
    let sig = hub_sk.sign(Domain::Attest, &hub.hash(), &acc.hash());
1944
    // One by any other key gives no time.
1945
    let stranger_sk = SecretKey::generate();
1946
    let stranger = stranger_sk.identity("stranger", "[email protected]", 1);
1947
    let forged = stranger_sk.sign(Domain::Attest, &stranger.hash(), &acc.hash());
1948
    late.keep_acceptance(
1949
        &v2,
1950
        &SignedAttest {
1951
            attest: acc.clone(),
1952
            sigs: vec![forged],
1953
        },
1954
    )
1955
    .unwrap();
1956
    let r = late.push("origin", false).unwrap();
1957
    assert!(
1958
        r.iter().any(|x| x.name == "tags/v2" && !x.ok),
1959
        "not the issuer's: {r:?}"
1960
    );
1961
    let theirs = SignedAttest {
1962
        attest: acc,
1963
        sigs: vec![sig],
1964
    };
1965
    // Kept beside the stranger's: the issuer's is the one sent.
1966
    late.keep_acceptance(&v2, &theirs).unwrap();
1967
    let r = late.push("origin", false).unwrap();
1968
    // (Its re-attestation of main is refused: an expired key moves no
1969
    // bookmark.)
1970
    assert!(r.iter().any(|x| x.name == "tags/v2" && x.ok), "{r:?}");
1971
    let host = Repo::open(&root.join("origin")).unwrap();
1972
    let (hv2, _) = host.tag_attest("v2").unwrap().unwrap();
1973
    assert_eq!(hv2, v2);
1974
    assert!(host
1975
        .store()
1976
        .index_get_pub("accepted", &v2)
1977
        .unwrap()
1978
        .contains(&theirs.attest.hash()));
1979
    let c = Repo::clone(&url, &root.join("c"))
1980
        .unwrap()
1981
        .with_home(root.join("home-c"));
1982
    assert_eq!(c.tag_heads("v2").unwrap(), Some(heads.clone()));
1983
    assert_eq!(c.tag_heads("v1").unwrap(), Some(heads));
1984
}
1985
1986
/// oxygenhub#266: a short-lived key its issuer certified moves a bookmark
1987
/// and signs no change (a keyless agent naming a bookmark). A third
1988
/// party's clone gets the key's identity, its certificate and the
1989
/// issuer's identity with the fetch, so the policy's subject grant
1990
/// authorizes the move and the signature verifies.
1991
#[test]
1992
fn a_bookmark_moved_by_a_certified_key_alone_is_fetched() {
1993
    use crate::cert::{Certificate, SignedCertificate};
1994
    use crate::identity::Scope;
1995
    hermetic();
1996
    let dir = tempfile::tempdir().unwrap();
1997
    let root = dir.path();
1998
    let _origin = Repo::init(&root.join("origin")).unwrap();
1999
    let url = root.join("origin").to_string_lossy().to_string();
2000
    let mut a = Repo::clone(&url, &root.join("a"))
2001
        .unwrap()
2002
        .with_home(root.join("home-a"));
2003
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
2004
        .unwrap();
2005
    write(&root.join("a"), "a.txt", b"a\n");
2006
    a.commit("a", &[]).unwrap();
2007
    a.policy_init().unwrap();
2008
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2009
    let hub_sk = SecretKey::generate();
2010
    let hub = hub_sk.identity("hub", "[email protected]", 1);
2011
    a.policy_grant_subject(
2012
        "agent:claude@ada",
2013
        hub.clone(),
2014
        Scope::CHANGES | Scope::REFS,
2015
        None,
2016
    )
2017
    .unwrap();
2018
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2019
2020
    let now = Hlc::now().wall_ms;
2021
    let mut agent = Repo::clone(&url, &root.join("agent"))
2022
        .unwrap()
2023
        .with_home(root.join("home-agent"));
2024
    let (key, id) = agent
2025
        .create_identity("claude", "[email protected]", IdentityScope::User)
2026
        .unwrap();
2027
    let cert = SignedCertificate::sign(
2028
        Certificate {
2029
            key: id,
2030
            issuer: hub.hash(),
2031
            subject: "agent:claude@ada".into(),
2032
            claims: vec![],
2033
            scope: Scope::CHANGES | Scope::REFS,
2034
            not_before: now - 60_000,
2035
            expires: now + 600_000,
2036
            grant: None,
2037
        },
2038
        &hub,
2039
        &hub_sk,
2040
    );
2041
    agent.store().put_identity(&hub).unwrap();
2042
    agent.store().put_certificate(&cert).unwrap();
2043
    let heads = agent.bookmark_heads().unwrap();
2044
    agent.bookmark_create("agent-work", Some(&heads)).unwrap();
2045
    let r = agent.push_bookmark("origin", "agent-work", false).unwrap();
2046
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2047
    let host = Repo::open(&root.join("origin")).unwrap();
2048
    let (_, sa) = host.latest_ref_attest("agent-work").unwrap().unwrap();
2049
    assert_eq!(sa.sigs[0].key, key, "the certified key alone moved it");
2050
2051
    // A fetch naming no change brings the certificate and both identities.
2052
    let bundle = host.bundle_raw_for(&[], None).unwrap();
2053
    assert!(bundle.changes.is_empty() && bundle.raw_changes.is_empty());
2054
    assert_eq!(bundle.certificates.len(), 1);
2055
    for k in [key, hub.hash()] {
2056
        assert!(bundle
2057
            .objects
2058
            .iter()
2059
            .any(|(t, b)| *t == ObjectType::Identity && hash_object(*t, b) == k));
2060
    }
2061
2062
    let c = Repo::clone(&url, &root.join("c")).unwrap();
2063
    let tracked = c.view().unwrap().remotes["origin"].clone();
2064
    assert_eq!(
2065
        tracked.get("agent-work"),
2066
        host.view().unwrap().bookmarks.get("agent-work")
2067
    );
2068
    assert!(c.store().certificate_of(&key).unwrap().is_some());
2069
}
2070
2071
/// Trusted time (oxygenhub#240, spec §14.8): a fetched attestation by a
2072
/// short-lived key is judged at its integrated time, the earliest time a
2073
/// pinned witness cosigned a checkpoint holding it. A certificate valid
2074
/// then but expired now passes; a witness this user does not trust gives
2075
/// no time (the earlier rule, said so); a backdated attestation is noted;
2076
/// an answer without the new fields is judged as before.
2077
#[test]
2078
fn a_fetched_attestation_is_judged_at_its_integrated_time() {
2079
    use super::transparency::LogCheck;
2080
    use crate::cert::{Certificate, SignedCertificate};
2081
    use crate::identity::Scope;
2082
    use crate::protocol::{Integration, Logged, RefsResponse, RemoteRef};
2083
    use crate::tlog::{self, Checkpoint, Entry, Hash, Integrated, Note};
2084
    hermetic();
2085
    let dir = tempfile::tempdir().unwrap();
2086
    let root = dir.path();
2087
    let mut a = Repo::init(&root.join("a"))
2088
        .unwrap()
2089
        .with_home(root.join("home-a"));
2090
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
2091
        .unwrap();
2092
    write(&root.join("a"), "a.txt", b"a\n");
2093
    a.commit("a", &[]).unwrap();
2094
    a.policy_init().unwrap();
2095
    let issuer_sk = SecretKey::generate();
2096
    let issuer = issuer_sk.identity("hub", "[email protected]", 1);
2097
    a.policy_grant_subject(
2098
        "agent:claude@ada",
2099
        issuer.clone(),
2100
        Scope::CHANGES | Scope::REFS,
2101
        None,
2102
    )
2103
    .unwrap();
2104
    let p = a.current_policy().unwrap().unwrap().1.policy;
2105
2106
    // An agent key the issuer certified for ten minutes two hours ago.
2107
    let now = Hlc::now().wall_ms;
2108
    let t0 = now - 2 * 3_600_000;
2109
    let agent_sk = SecretKey::generate();
2110
    let agent = agent_sk.identity("claude", "[email protected]", t0);
2111
    let cert = SignedCertificate::sign(
2112
        Certificate {
2113
            key: agent.clone(),
2114
            issuer: issuer.hash(),
2115
            subject: "agent:claude@ada".into(),
2116
            claims: vec![],
2117
            scope: Scope::CHANGES | Scope::REFS,
2118
            not_before: t0,
2119
            expires: t0 + 600_000,
2120
            grant: None,
2121
        },
2122
        &issuer,
2123
        &issuer_sk,
2124
    );
2125
    a.store().put_identity(&agent).unwrap();
2126
    a.store().put_certificate(&cert).unwrap();
2127
    let signer = agent.hash();
2128
    let attested = |claimed: u64| {
2129
        let attest = Attest {
2130
            repo: a.id().unwrap(),
2131
            hlc: Hlc {
2132
                wall_ms: claimed,
2133
                logical: 0,
2134
            },
2135
            body: AttestBody::Ref {
2136
                name: "main".into(),
2137
                old_state: ObjectRef([1; 32]),
2138
                new_state: ObjectRef([2; 32]),
2139
                serial: 1,
2140
            },
2141
        };
2142
        let sig = agent_sk.sign(Domain::Attest, &signer, &attest.hash());
2143
        SignedAttest {
2144
            attest,
2145
            sigs: vec![sig],
2146
        }
2147
    };
2148
2149
    // The hub's log: eight entries, the attestation's at 3, the latest
2150
    // checkpoint of 8, and one of 4 that witnesses cosigned.
2151
    let log_sk = SecretKey::generate();
2152
    let log_key = log_sk.identity("hub.example", "[email protected]", 1);
2153
    let origin = "hub.example/log";
2154
    let hub = "https://hub.example";
2155
    let url = "https://hub.example/ada/a";
2156
    let w_sk = SecretKey::generate();
2157
    let w = w_sk.identity("w", "[email protected]", 1);
2158
    let stranger_sk = SecretKey::generate();
2159
    let stranger = stranger_sk.identity("s", "[email protected]", 1);
2160
    let sa = attested(t0 + 300_000);
2161
    let entry_of = |i: u64| {
2162
        let (kind, object) = if i == 3 {
2163
            ("ref", sa.attest.hash())
2164
        } else {
2165
            ("seal", ObjectRef([i as u8; 32]))
2166
        };
2167
        Entry {
2168
            kind: kind.into(),
2169
            repo: sa.attest.repo,
2170
            object,
2171
            signers: vec![signer],
2172
            received: t0 + 300_000,
2173
        }
2174
        .encode()
2175
    };
2176
    let mut stored: Vec<Hash> = Vec::new();
2177
    for i in 0..8 {
2178
        let add = tlog::stored_hashes_for_leaf(i, tlog::leaf_hash(&entry_of(i)), &stored).unwrap();
2179
        stored.extend(add);
2180
    }
2181
    let note_of = |n: u64, cosigners: &[(&str, &Identity, &SecretKey, u64)]| {
2182
        let mut note = Checkpoint {
2183
            origin: origin.into(),
2184
            size: n,
2185
            root: tlog::tree_hash(n, &stored).unwrap(),
2186
            extensions: vec![],
2187
        }
2188
        .sign(&log_key, &log_sk)
2189
        .unwrap();
2190
        for (name, id, sk, t) in cosigners {
2191
            note.sigs
2192
                .extend(tlog::cosign(&note.text, name, id, sk, *t).unwrap());
2193
        }
2194
        note.encode()
2195
    };
2196
    let latest = note_of(8, &[]);
2197
    let witnessed_at = (t0 + 360_000) / 1000;
2198
    let cosigned = note_of(
2199
        4,
2200
        &[
2201
            ("w.example", &w, &w_sk, witnessed_at),
2202
            ("s.example", &stranger, &stranger_sk, 1),
2203
        ],
2204
    );
2205
    let answer = |integration: Vec<Integration>, witnesses: Vec<(String, Vec<u8>)>| RefsResponse {
2206
        refs: vec![RemoteRef {
2207
            name: "main".into(),
2208
            state: ObjectRef([2; 32]),
2209
            heads: vec![],
2210
            attestation: Some(sa.clone()),
2211
            last_serial: None,
2212
            accepted: None,
2213
            logged: Some(Logged {
2214
                index: 3,
2215
                entry: entry_of(3),
2216
                proof: tlog::prove_inclusion(8, 3, &stored).unwrap(),
2217
            }),
2218
            integration,
2219
        }],
2220
        log: Some(latest.clone()),
2221
        witnesses,
2222
        ..RefsResponse::default()
2223
    };
2224
    let proof4 = tlog::prove_inclusion(4, 3, &stored).unwrap();
2225
    let served = vec![Integration {
2226
        note: cosigned.clone(),
2227
        proof: proof4.clone(),
2228
    }];
2229
    let listed = vec![("w.example".to_string(), w.encode())];
2230
    // This user saw the hub's log before (pinned, so nothing is fetched).
2231
    a.remember_log(hub, &log_key, &Note::parse(&latest).unwrap())
2232
        .unwrap();
2233
2234
    // The witness is pinned on first sight, silently; the stranger's
2235
    // earlier cosignature counts for nothing.
2236
    let resp = answer(served.clone(), listed.clone());
2237
    let lc = a.check_log(url, None, &resp).unwrap();
2238
    assert!(lc.notes.is_empty(), "{:?}", lc.notes);
2239
    let t = lc.time_of("main").unwrap();
2240
    assert_eq!((t.time, t.witness.as_str()), (witnessed_at, "w.example"));
2241
    // The certificate expired an hour and fifty minutes ago, but covered
2242
    // the integrated time: accepted, and nothing to say.
2243
    assert!(cert.cert.expires < now);
2244
    let mut notes = Vec::new();
2245
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
2246
        .unwrap();
2247
    assert!(notes.is_empty(), "{notes:?}");
2248
2249
    // Only the stranger cosigned: no witnessed time, so the earlier rule
2250
    // (the attestation's own time, inside the window), said so.
2251
    let lonely = vec![Integration {
2252
        note: note_of(4, &[("s.example", &stranger, &stranger_sk, 1)]),
2253
        proof: proof4.clone(),
2254
    }];
2255
    let resp = answer(lonely, vec![]);
2256
    let lc = a.check_log(url, None, &resp).unwrap();
2257
    assert!(lc
2258
        .time_of("main")
2259
        .unwrap_err()
2260
        .contains("no witness this user trusts"));
2261
    let mut notes = Vec::new();
2262
    a.authorize_in_time(&p, "origin", &resp.refs[0], &sa, &signer, &lc, &mut notes)
2263
        .unwrap();
2264
    assert!(
2265
        notes.len() == 1 && notes[0].contains("not at a witnessed time"),
2266
        "{notes:?}"
2267
    );
2268
2269
    // A witness listed later under the pinned name with another key is
2270
    // pinned with a note, as a new log key is.
2271
    let resp = answer(
2272
        served.clone(),
2273
        vec![("w.example".into(), stranger.encode())],
2274
    );
2275
    let lc = a.check_log(url, None, &resp).unwrap();
2276
    assert!(
2277
        lc.notes.iter().any(|n| n.contains("another key")),
2278
        "{:?}",
2279
        lc.notes
2280
    );
2281
    assert!(
2282
        lc.time_of("main").is_err(),
2283
        "w's cosignature is by its old key"
2284
    );
2285
    a.check_log(url, None, &answer(served.clone(), listed.clone()))
2286
        .unwrap();
2287
2288
    // An old peer's answer: no log, no witnesses, no integration. Judged
2289
    // as before, silently.
2290
    let mut old = answer(vec![], vec![]);
2291
    old.log = None;
2292
    old.refs[0].logged = None;
2293
    let lc = a.check_log(url, None, &old).unwrap();
2294
    assert!(!lc.kept && lc.notes.is_empty());
2295
    let mut notes = Vec::new();
2296
    a.authorize_in_time(&p, "origin", &old.refs[0], &sa, &signer, &lc, &mut notes)
2297
        .unwrap();
2298
    assert!(notes.is_empty(), "{notes:?}");
2299
2300
    // Judged at given integrated times.
2301
    let at = |secs_after_t0: u64| {
2302
        let mut times = std::collections::HashMap::new();
2303
        times.insert(
2304
            "main".to_string(),
2305
            Ok(Integrated {
2306
                time: (t0 + secs_after_t0 * 1000) / 1000,
2307
                witness: "w.example".into(),
2308
                size: 4,
2309
            }),
2310
        );
2311
        LogCheck {
2312
            kept: true,
2313
            times,
2314
            ..LogCheck::default()
2315
        }
2316
    };
2317
    let judged = |sa: &SignedAttest, lc: &LogCheck| {
2318
        let mut notes = Vec::new();
2319
        a.authorize_in_time(&p, "origin", &old.refs[0], sa, &signer, lc, &mut notes)
2320
            .map(|_| notes)
2321
    };
2322
    // Claimed inside the window, first witnessed an hour later, after
2323
    // the certificate expired: backdated, or held back. Accepted by the
2324
    // earlier rule while logs are new, with both said.
2325
    let notes = judged(&sa, &at(3600)).unwrap();
2326
    assert!(
2327
        notes
2328
            .iter()
2329
            .any(|n| n.contains("had lapsed when witness w.example"))
2330
            && notes
2331
                .iter()
2332
                .any(|n| n.contains("55 minutes before witness")),
2333
        "{notes:?}"
2334
    );
2335
    // Claimed after the certificate expired, but witnessed inside its
2336
    // window: the clock the signer did not choose decides. The gap is
2337
    // still noted.
2338
    let fast = attested(now);
2339
    let notes = judged(&fast, &at(400)).unwrap();
2340
    assert!(
2341
        notes.len() == 1 && notes[0].contains("after witness w.example saw it"),
2342
        "{notes:?}"
2343
    );
2344
    // Claimed and witnessed after it expired: refused, as before.
2345
    assert!(judged(&fast, &at(3600)).is_err());
2346
    // A gap within ten minutes is nothing to note.
2347
    assert!(judged(&sa, &at(500)).unwrap().is_empty());
2348
}
2349
2350
/// Keyless step 5 (oxygenhub#241): an agent's fresh key, certified for a
2351
/// subject the author granted, seals changes in the author's name; with
2352
/// no grant, a stranger's, or one that had ended, it is neither the
2353
/// author nor a delegate.
2354
/// oxygen#135: an owner renews or rotates with every delegation, and a
2355
/// repository may name the newest key as the author; the agent's grant by
2356
/// the earlier key still counts, but not one that key made after.
2357
#[test]
2358
fn a_grant_outlives_its_owner_s_rotation() {
2359
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
2360
    use crate::identity::Scope;
2361
    hermetic();
2362
    let dir = tempfile::tempdir().unwrap();
2363
    let root = dir.path();
2364
    let mut a = Repo::init(&root.join("a"))
2365
        .unwrap()
2366
        .with_home(root.join("home-a"));
2367
    let (old, _) = a
2368
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2369
        .unwrap();
2370
    let (_, old_sk) = a.secret_key().unwrap().unwrap();
2371
    let old_id = a.identity(&old).unwrap();
2372
    let hub_sk = SecretKey::generate();
2373
    let hub = hub_sk.identity("hub", "[email protected]", 1);
2374
    let now = Hlc::now().wall_ms;
2375
    let grant = |from: u64| {
2376
        SignedGrant::sign(
2377
            Grant {
2378
                grantor: old,
2379
                subject: "agent:claude@ada".into(),
2380
                issuer: hub.hash(),
2381
                scope: Scope::CHANGES | Scope::SEAL,
2382
                not_before: from,
2383
                expires: now + 86_400_000,
2384
            },
2385
            &old_id,
2386
            &old_sk,
2387
        )
2388
    };
2389
    let before = grant(now - 60_000);
2390
    let after = grant(now + 60_000);
2391
    let rot = a.renew_identity(None).unwrap();
2392
    assert_ne!(rot.new, old);
2393
    let agent = |name: &str, g: SignedGrant| {
2394
        let mut r = Repo::init(&root.join(name))
2395
            .unwrap()
2396
            .with_home(root.join(format!("home-{name}")));
2397
        let (key, id) = r
2398
            .create_identity(name, "[email protected]", IdentityScope::User)
2399
            .unwrap();
2400
        for i in [&old_id, &rot.identity, &hub] {
2401
            r.store().put_identity(i).unwrap();
2402
        }
2403
        r.set_user_config("author.key", &rot.new.to_hex()).unwrap();
2404
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
2405
        let cert = SignedCertificate::sign(
2406
            Certificate {
2407
                key: id,
2408
                issuer: hub.hash(),
2409
                subject: "agent:claude@ada".into(),
2410
                claims: vec![],
2411
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
2412
                not_before: now - 60_000,
2413
                expires: now + 600_000,
2414
                grant: Some(g),
2415
            },
2416
            &hub,
2417
            &hub_sk,
2418
        );
2419
        r.store().put_certificate(&cert).unwrap();
2420
        write(&root.join(name), "work.txt", b"agent work\n");
2421
        let h = r.commit("work", &[]).unwrap();
2422
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, rot.new);
2423
        r.seal(&[h]).unwrap();
2424
        (r, h)
2425
    };
2426
    let (r, h) = agent("kept", before);
2427
    assert!(
2428
        matches!(
2429
            r.authenticate_change(&h).unwrap(),
2430
            SignatureStatus::Valid { .. }
2431
        ),
2432
        "{:?}",
2433
        r.authenticate_change(&h).unwrap()
2434
    );
2435
    let (r, h) = agent("late", after);
2436
    assert!(
2437
        matches!(r.authenticate_change(&h).unwrap(), SignatureStatus::Invalid(e) if e.contains("neither")),
2438
        "a grant the old key made after the rotation: {:?}",
2439
        r.authenticate_change(&h).unwrap()
2440
    );
2441
}
2442
2443
#[test]
2444
fn a_certified_key_acts_for_its_author_under_a_grant() {
2445
    use crate::cert::{Certificate, Grant, SignedCertificate, SignedGrant};
2446
    use crate::identity::{Identity, Scope};
2447
    hermetic();
2448
    let dir = tempfile::tempdir().unwrap();
2449
    let root = dir.path();
2450
    let _origin = Repo::init(&root.join("origin")).unwrap();
2451
    let url = root.join("origin").to_string_lossy().to_string();
2452
    let mut a = Repo::clone(&url, &root.join("a"))
2453
        .unwrap()
2454
        .with_home(root.join("home-a"));
2455
    let (ada, _) = a
2456
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2457
        .unwrap();
2458
    write(&root.join("a"), "a.txt", b"a\n");
2459
    a.commit("a", &[]).unwrap();
2460
    a.policy_init().unwrap();
2461
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2462
    let hub_sk = SecretKey::generate();
2463
    let hub = hub_sk.identity("hub", "[email protected]", 1);
2464
    a.policy_grant_subject(
2465
        "agent:claude@ada",
2466
        hub.clone(),
2467
        Scope::CHANGES | Scope::REFS,
2468
        None,
2469
    )
2470
    .unwrap();
2471
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
2472
    let (_, ada_sk) = a.secret_key().unwrap().unwrap();
2473
    let ada_id = a.identity(&ada).unwrap();
2474
2475
    let now = Hlc::now().wall_ms;
2476
    let grant = |by: &Identity, sk: &SecretKey, from: u64, to: u64| {
2477
        SignedGrant::sign(
2478
            Grant {
2479
                grantor: by.hash(),
2480
                subject: "agent:claude@ada".into(),
2481
                issuer: hub.hash(),
2482
                scope: Scope::CHANGES | Scope::SEAL,
2483
                not_before: from,
2484
                expires: to,
2485
            },
2486
            by,
2487
            sk,
2488
        )
2489
    };
2490
    // Ada's work as an agent runs it: Ada the author, a fresh key the hub
2491
    // certified (with `g` inside) the signer.
2492
    let agent = |name: &str, g: Option<SignedGrant>| {
2493
        let mut r = Repo::clone(&url, &root.join(name))
2494
            .unwrap()
2495
            .with_home(root.join(format!("home-{name}")));
2496
        let (key, id) = r
2497
            .create_identity(name, "[email protected]", IdentityScope::User)
2498
            .unwrap();
2499
        r.set_user_config("author.key", &ada.to_hex()).unwrap();
2500
        r.set_user_config("author.signer", &key.to_hex()).unwrap();
2501
        let cert = SignedCertificate::sign(
2502
            Certificate {
2503
                key: id,
2504
                issuer: hub.hash(),
2505
                subject: "agent:claude@ada".into(),
2506
                claims: vec![],
2507
                scope: Scope::CHANGES | Scope::REFS | Scope::SEAL,
2508
                not_before: now - 60_000,
2509
                expires: now + 600_000,
2510
                grant: g,
2511
            },
2512
            &hub,
2513
            &hub_sk,
2514
        );
2515
        r.store().put_identity(&hub).unwrap();
2516
        r.store().put_certificate(&cert).unwrap();
2517
        write(&root.join(name), &format!("{name}.txt"), b"agent work\n");
2518
        let h = r.commit("work", &[]).unwrap();
2519
        assert_eq!(r.store().get_change_meta(&h).unwrap().author, ada);
2520
        (r, key, h)
2521
    };
2522
2523
    let (claude, key, h) = agent(
2524
        "claude",
2525
        Some(grant(&ada_id, &ada_sk, now - 60_000, now + 86_400_000)),
2526
    );
2527
    let r = claude.push("origin", false).unwrap();
2528
    assert!(r.iter().all(|x| x.ok), "{r:?}");
2529
    let host = Repo::open(&root.join("origin")).unwrap();
2530
    assert!(
2531
        matches!(
2532
            host.authenticate_change(&h).unwrap(),
2533
            SignatureStatus::Valid { key: k, sealed: true, name, .. } if k == key && name == "agent:claude@ada"
2534
        ),
2535
        "named by its certificate's subject"
2536
    );
2537
    a.pull("origin").unwrap();
2538
    assert!(matches!(
2539
        a.authenticate_change(&h).unwrap(),
2540
        SignatureStatus::Valid { key: k, .. } if k == key
2541
    ));
2542
2543
    let (none, _, _) = agent("none", None);
2544
    let r = none.push("origin", false).unwrap();
2545
    assert!(r.iter().all(|x| !x.ok), "no grant: {r:?}");
2546
    let mallory_sk = SecretKey::generate();
2547
    let mallory = mallory_sk.identity("Mallory", "[email protected]", 1);
2548
    let (stranger, _, _) = agent(
2549
        "stranger",
2550
        Some(grant(&mallory, &mallory_sk, now - 60_000, now + 600_000)),
2551
    );
2552
    let r = stranger.push("origin", false).unwrap();
2553
    assert!(r.iter().all(|x| !x.ok), "a stranger's grant: {r:?}");
2554
    let (ended, _, eh) = agent(
2555
        "ended",
2556
        Some(grant(&ada_id, &ada_sk, now - 7_200_000, now - 3_600_000)),
2557
    );
2558
    let r = ended.push("origin", false).unwrap();
2559
    assert!(r.iter().all(|x| !x.ok), "an ended grant: {r:?}");
2560
    assert!(matches!(
2561
        ended.authenticate_change(&eh).unwrap(),
2562
        SignatureStatus::Invalid(e) if e.contains("grant did not cover")
2563
    ));
2564
}
2565
2566
#[test]
2567
fn trust_policy_governs_pushes_and_fetches() {
2568
    hermetic();
2569
    let dir = tempfile::tempdir().unwrap();
2570
    let root = dir.path();
2571
    let origin = Repo::init(&root.join("origin")).unwrap();
2572
    let url = root.join("origin").to_string_lossy().to_string();
2573
2574
    // A is the root. Before the policy, an unsigned push from B is fine.
2575
    let mut a = Repo::clone(&url, &root.join("a"))
2576
        .unwrap()
2577
        .with_home(root.join("home-a"));
2578
    let (key_a, _) = a
2579
        .create_identity("Ada", "[email protected]", IdentityScope::User)
2580
        .unwrap();
2581
    let mut b = Repo::clone(&url, &root.join("b"))
2582
        .unwrap()
2583
        .with_home(root.join("home-b"));
2584
    write(&root.join("b"), "b.txt", b"b\n");
2585
    b.commit("unsigned before policy", &[]).unwrap();
2586
    assert!(b.push("origin", false).unwrap()[0].ok);
2587
    origin.refresh().unwrap();
2588
2589
    // A creates the policy and pushes it; origin now enforces it.
2590
    write(&root.join("a"), "a.txt", b"a\n");
2591
    a.commit("a", &[]).unwrap();
2592
    let sp = a.policy_init().unwrap();
2593
    assert_eq!(sp.policy.serial, 1);
2594
    a.pull("origin").unwrap();
2595
    let results = a.push("origin", false).unwrap();
2596
    origin.refresh().unwrap();
2597
    assert!(results.iter().all(|r| r.ok), "{results:?}");
2598
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 1);
2599
2600
    // B pulls the policy. Without an identity B cannot push at all.
2601
    b.pull("origin").unwrap();
2602
    assert!(
2603
        b.current_policy().unwrap().is_some(),
2604
        "the policy arrived with the fetch"
2605
    );
2606
    assert!(b.push("origin", false).is_err());
2607
    // With an identity the policy does not list, the push is rejected by origin.
2608
    let (key_b, id_b) = b
2609
        .create_identity("Bob", "[email protected]", IdentityScope::User)
2610
        .unwrap();
2611
    write(&root.join("b"), "b.txt", b"b2\n");
2612
    let h_b2 = b.commit("b2 as Bob", &[]).unwrap();
2613
    assert_eq!(b.store().get_change(&h_b2).unwrap().author, key_b);
2614
    let r = b.push("origin", false).unwrap();
2615
    origin.refresh().unwrap();
2616
    assert!(
2617
        !r[0].ok && r[0].reason.contains("may not update"),
2618
        "{:?}",
2619
        r
2620
    );
2621
2622
    // A grants B (identity handed over as a file) and publishes the policy.
2623
    let sp = a.policy_grant(id_b.clone(), None).unwrap();
2624
    assert_eq!(sp.policy.serial, 2);
2625
    let r = a.push("origin", false).unwrap();
2626
    origin.refresh().unwrap();
2627
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2628
    // B must fetch the new policy before pushing.
2629
    assert!(b
2630
        .push("origin", false)
2631
        .unwrap_or_else(|e| vec![RefResult {
2632
            name: "main".into(),
2633
            ok: false,
2634
            reason: e.to_string()
2635
        }])
2636
        .iter()
2637
        .all(|x| !x.ok));
2638
    b.pull("origin").unwrap();
2639
    assert_eq!(b.current_policy().unwrap().unwrap().1.policy.serial, 2);
2640
    let r = b.push("origin", false).unwrap();
2641
    origin.refresh().unwrap();
2642
    assert!(r[0].ok, "{:?}", r);
2643
    // Origin verified B's change under the policy.
2644
    let heads = origin.bookmark_heads().unwrap();
2645
    for h in &heads {
2646
        let c = origin.store().get_change(h).unwrap();
2647
        if c.author == key_b {
2648
            origin
2649
                .change_allowed(
2650
                    h,
2651
                    &origin.current_policy().unwrap().unwrap().1.policy,
2652
                    "main",
2653
                )
2654
                .unwrap();
2655
        }
2656
    }
2657
2658
    // A policy signed by a non-root (B) is refused, as is a replayed serial.
2659
    let mut forged = b.current_policy().unwrap().unwrap().1.policy.clone();
2660
    forged.serial = 3;
2661
    forged.roots = vec![key_b];
2662
    let fh = forged.hash();
2663
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
2664
    let forged = SignedPolicy {
2665
        policy: forged,
2666
        sigs: vec![sk_b.sign(Domain::Policy, &key_b, &fh)],
2667
    };
2668
    let r = origin
2669
        .receive_push(Bundle::default(), vec![], Some(forged), vec![])
2670
        .unwrap();
2671
    assert!(!r[0].ok && r[0].reason.contains("root"), "{:?}", r);
2672
    let stale = a.current_policy().unwrap().unwrap().1;
2673
    let mut old = stale.clone();
2674
    old.policy.serial = 1;
2675
    let r = origin
2676
        .receive_push(Bundle::default(), vec![], Some(old), vec![])
2677
        .unwrap();
2678
    assert!(!r[0].ok && r[0].reason.contains("serial"), "{:?}", r);
2679
2680
    // A revokes B; after B pulls the policy, B's pushes are refused again.
2681
    a.pull("origin").unwrap();
2682
    a.policy_revoke(&key_b).unwrap();
2683
    let r = a.push("origin", false).unwrap();
2684
    origin.refresh().unwrap();
2685
    assert!(r.iter().any(|x| x.name == "policy" && x.ok), "{r:?}");
2686
    b.pull("origin").unwrap();
2687
    write(&root.join("b"), "b.txt", b"b3\n");
2688
    b.commit("b3", &[]).unwrap();
2689
    let r = b.push("origin", false).unwrap();
2690
    origin.refresh().unwrap();
2691
    assert!(!r[0].ok, "{:?}", r);
2692
2693
    // A clone by a third party receives and verifies everything.
2694
    let c = Repo::clone(&url, &root.join("c"))
2695
        .unwrap()
2696
        .with_home(root.join("home-c"));
2697
    assert_eq!(c.current_policy().unwrap().unwrap().1.policy.serial, 3);
2698
    assert!(c
2699
        .current_policy()
2700
        .unwrap()
2701
        .unwrap()
2702
        .1
2703
        .policy
2704
        .roots
2705
        .contains(&key_a));
2706
    assert!(!c.snapshot("status").unwrap().changed);
2707
}
2708
2709
/// oxygen#66: a gc says what it is doing, phase by phase.
2710
#[test]
2711
fn gc_reports_its_phases() {
2712
    hermetic();
2713
    let dir = tempfile::tempdir().unwrap();
2714
    let repo = Repo::init(dir.path()).unwrap();
2715
    for i in 0..3 {
2716
        write(
2717
            dir.path(),
2718
            &format!("f{i}.txt"),
2719
            format!("{i}\n").as_bytes(),
2720
        );
2721
        repo.commit(&format!("c{i}"), &[]).unwrap();
2722
    }
2723
    let mut phases = Vec::new();
2724
    repo.gc_with(true, &mut |p| phases.push(p.to_string()))
2725
        .unwrap();
2726
    assert_eq!(phases[0], "finding what is reachable", "{phases:?}");
2727
    assert!(
2728
        phases.iter().any(|p| p.starts_with("pruning")),
2729
        "{phases:?}"
2730
    );
2731
    assert!(
2732
        phases.iter().any(|p| p.starts_with("packing 0 of ")),
2733
        "{phases:?}"
2734
    );
2735
    assert!(
2736
        phases
2737
            .iter()
2738
            .any(|p| p.starts_with("writing the index of ")),
2739
        "{phases:?}"
2740
    );
2741
}
2742
2743
#[test]
2744
fn gc_packs_objects_and_history_still_works() {
2745
    hermetic();
2746
    let dir = tempfile::tempdir().unwrap();
2747
    let root = dir.path();
2748
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2749
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2750
        .unwrap();
2751
    repo.set_user_config("core.sign", "change").unwrap();
2752
    write(root, "a.txt", b"one\n");
2753
    let h1 = repo.commit("one", &[]).unwrap();
2754
    write(root, "a.txt", b"two\n");
2755
    write(root, "big.bin", &vec![0u8; 100_000]);
2756
    let h2 = repo.commit("two", &[]).unwrap();
2757
    // Several snapshots leave superseded working-copy versions behind.
2758
    for i in 0..5 {
2759
        write(root, "a.txt", format!("two\n{i}\n").as_bytes());
2760
        repo.snapshot("status").unwrap();
2761
    }
2762
    write(root, "a.txt", b"two\n");
2763
    repo.snapshot("status").unwrap();
2764
    let before = repo.store().list().unwrap();
2765
    assert!(repo.store().loose_count().unwrap() > 0);
2766
2767
    // With the default retention every operation's view is a root: nothing prunes.
2768
    let r = repo.gc(true).unwrap();
2769
    assert_eq!(r.packed.objects, before.len());
2770
    assert_eq!(r.pruned.objects, 0);
2771
    assert_eq!(repo.store().loose_count().unwrap(), 0);
2772
    assert_eq!(repo.store().list().unwrap(), before);
2773
2774
    // With zero retention only the current view is a root: superseded
2775
    // working copies go, everything reachable stays.
2776
    repo.config.set("core.op-retention", "0").unwrap();
2777
    repo.save_config().unwrap();
2778
    let mut repo = Repo::open(root).unwrap().with_home(root.join("home"));
2779
    let r = repo.gc(true).unwrap();
2780
    assert!(r.pruned.objects >= 5, "{r:?}");
2781
    let after = repo.store().list().unwrap();
2782
    assert!(after.len() < before.len());
2783
    assert!(after.contains(&h1) && after.contains(&h2));
2784
    for (_, op) in repo.op_log().unwrap() {
2785
        assert!(!op.command.is_empty(), "operation objects are all kept");
2786
    }
2787
    // Everything still works from the pruned, packed store.
2788
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
2789
    assert!(matches!(
2790
        repo.verify_change(&h2).unwrap(),
2791
        SignatureStatus::Valid { .. }
2792
    ));
2793
    assert_eq!(repo.log().unwrap().len(), 3);
2794
    repo.checkout(&[h1], false, "checkout").unwrap();
2795
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
2796
    repo.checkout(&[h2], false, "checkout").unwrap();
2797
    assert_eq!(fs::read(root.join("big.bin")).unwrap().len(), 100_000);
2798
    assert!(!repo.snapshot("status").unwrap().changed);
2799
    // Grace period defers pruning of young garbage.
2800
    write(root, "a.txt", b"three\n");
2801
    repo.commit("three", &[]).unwrap();
2802
    let r = repo.gc(false).unwrap();
2803
    assert_eq!(r.pruned.objects, 0);
2804
    assert!(r.pruned.deferred > 0);
2805
    let r = repo.gc(true).unwrap();
2806
    assert!(r.pruned.objects > 0);
2807
    assert_eq!(repo.log().unwrap().len(), 4);
2808
    // Restoring the default retention makes the old views roots again; the
2809
    // working copies they name were pruned, which gc tolerates.
2810
    repo.config.set("core.op-retention", "90").unwrap();
2811
    repo.save_config().unwrap();
2812
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
2813
    let r = repo.gc(false).unwrap();
2814
    assert_eq!(r.pruned.objects, 0);
2815
    assert_eq!(repo.log().unwrap().len(), 4);
2816
}
2817
2818
#[test]
2819
fn describe_amend_abandon_heads() {
2820
    hermetic();
2821
    let dir = tempfile::tempdir().unwrap();
2822
    let root = dir.path();
2823
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
2824
    repo.create_identity("Ada", "a@b", IdentityScope::User)
2825
        .unwrap();
2826
    repo.set_user_config("core.sign", "change").unwrap();
2827
    write(root, "a.txt", b"one\n");
2828
    let h1 = repo.commit("first", &[]).unwrap();
2829
    write(root, "a.txt", b"one\ntwo\n");
2830
    let h2 = repo.commit("secnod", &[]).unwrap();
2831
    let id2 = repo.store().get_change(&h2).unwrap().change_id;
2832
2833
    // describe: same ChangeId, new hash, bookmark and working copy follow.
2834
    let h2b = repo.describe(&h2, "second").unwrap();
2835
    assert_ne!(h2b, h2);
2836
    let c = repo.store().get_change(&h2b).unwrap();
2837
    assert_eq!(
2838
        (c.change_id, c.message.as_str(), c.deps.clone()),
2839
        (id2, "second", vec![h1])
2840
    );
2841
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2b]);
2842
    assert!(matches!(
2843
        repo.verify_change(&h2b).unwrap(),
2844
        SignatureStatus::Valid { .. }
2845
    ));
2846
    let s = repo.snapshot("status").unwrap();
2847
    assert!(s.statuses.is_empty(), "{:?}", s.statuses);
2848
    assert_eq!(
2849
        repo.resolve_change(&id2.short(8)).unwrap(),
2850
        h2b,
2851
        "the old object is no longer reachable from the log"
2852
    );
2853
    // Describing a non-head rewrites its dependents (h2b → h2c') and the working copy.
2854
    let h1b = repo.describe(&h1, "first, described").unwrap();
2855
    assert_ne!(h1b, h1);
2856
    let heads = repo.bookmark_heads().unwrap();
2857
    assert_eq!(heads.len(), 1);
2858
    let top = repo.store().get_change(&heads[0]).unwrap();
2859
    assert_eq!((top.change_id, top.deps.clone()), (id2, vec![h1b]));
2860
    assert!(
2861
        matches!(
2862
            repo.verify_change(&heads[0]).unwrap(),
2863
            SignatureStatus::Valid { .. }
2864
        ),
2865
        "rewritten own change is re-signed"
2866
    );
2867
    let (_, wc) = repo.working_copy().unwrap();
2868
    assert_eq!(
2869
        wc.deps,
2870
        vec![heads[0]],
2871
        "the working copy follows the rewrite"
2872
    );
2873
    assert!(!repo.snapshot("status").unwrap().changed);
2874
    let snap = repo.load_state(&heads).unwrap().materialize();
2875
    assert!(
2876
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n")
2877
    );
2878
2879
    // amend: fold an edit into the head; the result is one change from h1.
2880
    write(root, "a.txt", b"one\ntwo\nthree\n");
2881
    write(root, "b.txt", b"b\n");
2882
    let h2c = repo.amend(None).unwrap();
2883
    let c = repo.store().get_change(&h2c).unwrap();
2884
    assert_eq!(c.change_id, id2);
2885
    assert_eq!(c.message, "second");
2886
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2c]);
2887
    assert_eq!(
2888
        repo.log().unwrap().len(),
2889
        3,
2890
        "working copy, amended head, first"
2891
    );
2892
    let snap = repo.load_state(&[h2c]).unwrap().materialize();
2893
    assert!(
2894
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\nthree\n")
2895
    );
2896
    assert!(snap.files.contains_key("b.txt"));
2897
    assert!(!repo.snapshot("status").unwrap().changed);
2898
    assert!(
2899
        repo.amend(None).is_err(),
2900
        "clean working copy and no message"
2901
    );
2902
    let h2d = repo.amend(Some("second, amended")).unwrap();
2903
    assert_eq!(
2904
        repo.store().get_change(&h2d).unwrap().message,
2905
        "second, amended"
2906
    );
2907
2908
    // abandon: the head goes, its content stays as uncommitted work.
2909
    repo.abandon(&h2d).unwrap();
2910
    assert_eq!(
2911
        repo.bookmark_heads().unwrap(),
2912
        vec![h1b],
2913
        "the described first change is the head again"
2914
    );
2915
    let s = repo.snapshot("status").unwrap();
2916
    let paths: Vec<_> = s
2917
        .statuses
2918
        .iter()
2919
        .map(|p| (p.path.as_str(), p.status))
2920
        .collect();
2921
    assert_eq!(
2922
        paths,
2923
        vec![
2924
            ("a.txt", ChangeStatus::Modified),
2925
            ("b.txt", ChangeStatus::Added)
2926
        ]
2927
    );
2928
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\ntwo\nthree\n");
2929
    let h3 = repo.commit("recommitted", &[]).unwrap();
2930
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h3]);
2931
    // undo brings the abandoned head back.
2932
    repo.undo().unwrap();
2933
    repo.undo().unwrap();
2934
    assert_eq!(repo.bookmark_heads().unwrap(), vec![h2d]);
2935
2936
    // Abandoning a non-head whose dependent references its atoms reifies
2937
    // the references (here: a.txt vanishes with it, so the dependent's edit
2938
    // of a.txt is dropped with a note) instead of refusing; undo restores it.
2939
    let base = repo.bookmark_heads().unwrap()[0];
2940
    let base_change = repo.store().get_change(&base).unwrap();
2941
    let h1_now = base_change.deps[0];
2942
    let notes = repo.abandon(&h1_now).unwrap();
2943
    assert!(
2944
        !notes.is_empty(),
2945
        "the dependent's edit of a.txt was reified"
2946
    );
2947
    let heads = repo.bookmark_heads().unwrap();
2948
    let after = repo.load_state(&heads).unwrap().materialize();
2949
    assert!(
2950
        !after.files.contains_key("a.txt") && after.files.contains_key("b.txt"),
2951
        "{:?}",
2952
        after.files.keys()
2953
    );
2954
    repo.undo().unwrap();
2955
    assert_eq!(repo.bookmark_heads().unwrap(), vec![base]);
2956
    write(root, "c.txt", b"c\n");
2957
    let hc = repo.commit("c", &[]).unwrap();
2958
    write(root, "d.txt", b"d\n");
2959
    let hd = repo.commit("d", &[hc]).unwrap();
2960
    assert_eq!(repo.store().get_change(&hd).unwrap().deps, vec![hc]);
2961
    repo.abandon(&hc).unwrap();
2962
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2963
    assert!(!heads.contains(&hc));
2964
    let d_now = heads
2965
        .iter()
2966
        .find(|h| repo.store().get_change(h).unwrap().message == "d")
2967
        .copied()
2968
        .unwrap();
2969
    assert!(
2970
        repo.store().get_change(&d_now).unwrap().deps.is_empty(),
2971
        "d inherited c's (empty) dependencies"
2972
    );
2973
    let s = repo.snapshot("status").unwrap();
2974
    assert_eq!(
2975
        s.statuses
2976
            .iter()
2977
            .map(|p| p.path.as_str())
2978
            .collect::<Vec<_>>(),
2979
        vec!["c.txt"],
2980
        "c's content is now uncommitted work"
2981
    );
2982
}
2983
2984
#[test]
2985
fn git_export_mirrors_history() {
2986
    hermetic();
2987
    if std::process::Command::new("git")
2988
        .arg("--version")
2989
        .output()
2990
        .is_err()
2991
    {
2992
        eprintln!("git not installed; skipping");
2993
        return;
2994
    }
2995
    let dir = tempfile::tempdir().unwrap();
2996
    let root = dir.path();
2997
    let mut repo = Repo::init(&root.join("r"))
2998
        .unwrap()
2999
        .with_home(root.join("home"));
3000
    repo.create_identity("Ada Lovelace", "[email protected]", IdentityScope::User)
3001
        .unwrap();
3002
    let r = root.join("r");
3003
    write(&r, "README.md", b"hello\n");
3004
    write(&r, "src/main.rs", b"fn main() {}\n");
3005
    let h1 = repo.commit("first", &[]).unwrap();
3006
    write(&r, "src/main.rs", b"fn main() { run(); }\n");
3007
    write(&r, "logo.png", b"\x89PNG\0\0");
3008
    let h2 = repo.commit("second", &[]).unwrap();
3009
3010
    let git_dir = root.join("mirror.git");
3011
    let rep = repo.git_export(&git_dir).unwrap();
3012
    assert_eq!((rep.exported, rep.skipped, rep.heads), (2, 0, 1));
3013
    let git = |args: &[&str]| -> String {
3014
        let out = std::process::Command::new("git")
3015
            .arg("-C")
3016
            .arg(&git_dir)
3017
            .args(args)
3018
            .output()
3019
            .unwrap();
3020
        assert!(
3021
            out.status.success(),
3022
            "{}",
3023
            String::from_utf8_lossy(&out.stderr)
3024
        );
3025
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3026
    };
3027
    assert_eq!(git(&["log", "--format=%s", "main"]), "second\nfirst");
3028
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
3029
    assert_eq!(git(&["show", "main:README.md"]), "hello");
3030
    let body = git(&["log", "-1", "--format=%B", "main"]);
3031
    assert!(
3032
        body.contains(&format!("Oxy-Hash: {}", h2.to_hex())),
3033
        "{body}"
3034
    );
3035
    assert!(body.contains("Change-Id: "), "{body}");
3036
    assert_eq!(
3037
        git(&["log", "-1", "--format=%an <%ae>", "main"]),
3038
        "Ada Lovelace <[email protected]>"
3039
    );
3040
    assert_eq!(
3041
        git(&["ls-tree", "--name-only", "main"]),
3042
        "README.md\nlogo.png\nsrc"
3043
    );
3044
3045
    // Re-export is incremental.
3046
    let rep = repo.git_export(&git_dir).unwrap();
3047
    assert_eq!((rep.exported, rep.skipped), (0, 2));
3048
3049
    // An independent change makes two heads; the next state is one more
3050
    // commit on the linear branch whose tree is the union.
3051
    repo.checkout(&[h1], false, "checkout").unwrap();
3052
    write(&r, "other.txt", b"o\n");
3053
    let h3 = repo.commit("third", &[]).unwrap();
3054
    let rep = repo.git_export(&git_dir).unwrap();
3055
    assert_eq!((rep.exported, rep.heads), (1, 2));
3056
    assert_eq!(git(&["log", "--format=%s", "main"]), "third\nsecond\nfirst");
3057
    let parents = git(&["rev-list", "--parents", "-1", "main"]);
3058
    assert_eq!(parents.split(' ').count(), 2, "one parent: {parents}");
3059
    assert_eq!(git(&["show", "main:other.txt"]), "o");
3060
    assert_eq!(git(&["show", "main:src/main.rs"]), "fn main() { run(); }");
3061
    assert_eq!(
3062
        git(&["ls-tree", "--name-only", "main"]),
3063
        "README.md\nlogo.png\nother.txt\nsrc"
3064
    );
3065
    let body = git(&["log", "-1", "--format=%B", "main"]);
3066
    assert!(
3067
        body.contains(&format!("Oxy-Hash: {}", h3.to_hex())) && body.contains("Oxy-State: "),
3068
        "{body}"
3069
    );
3070
    // A rewrite is a new state whose one new change is the rewritten one.
3071
    repo.describe(&h3, "third, described").unwrap();
3072
    let rep = repo.git_export(&git_dir).unwrap();
3073
    assert_eq!(rep.exported, 1);
3074
    assert_eq!(
3075
        git(&["log", "-1", "--format=%s", "main"]),
3076
        "third, described"
3077
    );
3078
    assert_eq!(git(&["log", "--format=%s", "main"]).lines().count(), 4);
3079
    let _ = h2;
3080
}
3081
3082
#[test]
3083
fn git_import_reproduces_trees() {
3084
    git_import_reproduces_trees_with(None);
3085
}
3086
3087
/// The same import with every merge rendered in batches of one file
3088
/// (oxygen#25): what a merge onto a base of thousands of files takes.
3089
#[test]
3090
fn git_import_reproduces_trees_in_batches() {
3091
    git_import_reproduces_trees_with(Some(1));
3092
}
3093
3094
fn git_import_reproduces_trees_with(batch: Option<usize>) {
3095
    crate::repo::git::set_merge_batch_for_tests(batch);
3096
    hermetic();
3097
    if std::process::Command::new("git")
3098
        .arg("--version")
3099
        .output()
3100
        .is_err()
3101
    {
3102
        eprintln!("git not installed; skipping");
3103
        return;
3104
    }
3105
    let dir = tempfile::tempdir().unwrap();
3106
    let root = dir.path();
3107
    let g = root.join("src.git");
3108
    fs::create_dir_all(&g).unwrap();
3109
    let git = |args: &[&str]| -> String {
3110
        let out = std::process::Command::new("git")
3111
            .arg("-C")
3112
            .arg(&g)
3113
            .args([
3114
                "-c",
3115
                "user.name=Grace",
3116
                "-c",
3117
                "[email protected]",
3118
                "-c",
3119
                "commit.gpgsign=false",
3120
            ])
3121
            .args(args)
3122
            .output()
3123
            .unwrap();
3124
        assert!(
3125
            out.status.success(),
3126
            "git {args:?}: {}",
3127
            String::from_utf8_lossy(&out.stderr)
3128
        );
3129
        String::from_utf8_lossy(&out.stdout).trim().to_string()
3130
    };
3131
    git(&["init", "-q", "-b", "main"]);
3132
    write(&g, "README.md", b"# Hi\n");
3133
    write(&g, "src/lib.rs", b"pub fn a() {}\n");
3134
    git(&["add", "."]);
3135
    git(&["commit", "-q", "-m", "initial"]);
3136
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
3137
    write(&g, "run.sh", b"#!/bin/sh\n");
3138
    #[cfg(unix)]
3139
    {
3140
        use std::os::unix::fs::PermissionsExt;
3141
        fs::set_permissions(g.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
3142
    }
3143
    write(&g, "logo.png", b"\x89PNG\0\0\x01");
3144
    git(&["add", "."]);
3145
    git(&[
3146
        "commit",
3147
        "-q",
3148
        "-m",
3149
        "second\n\nChange-Id: 0123456789abcdef0123456789abcdef",
3150
    ]);
3151
    // A branch that edits README, merged back with a conflict-free merge.
3152
    git(&["checkout", "-q", "-b", "topic", "HEAD~1"]);
3153
    write(&g, "README.md", b"# Hi\n\nMore.\n");
3154
    git(&["commit", "-q", "-am", "readme"]);
3155
    git(&["checkout", "-q", "main"]);
3156
    git(&["merge", "-q", "--no-ff", "-m", "merge topic", "topic"]);
3157
    // A branch from the initial commit inserting at the same place as
3158
    // "second": concurrent in Oxygen too, so the merge commit is a resolution.
3159
    let initial = git(&["rev-list", "--max-parents=0", "HEAD"]);
3160
    git(&["checkout", "-q", "-b", "clash", &initial]);
3161
    write(&g, "src/lib.rs", b"pub fn a() {}\npub fn c() {}\n");
3162
    git(&["commit", "-q", "-am", "clash"]);
3163
    git(&["checkout", "-q", "main"]);
3164
    // Expected to stop at the conflict, so its status is ignored; the
3165
    // identity is passed as for every other git call here, or a machine
3166
    // without one refuses to start the merge at all.
3167
    let _ = std::process::Command::new("git")
3168
        .arg("-C")
3169
        .arg(&g)
3170
        .args([
3171
            "-c",
3172
            "user.name=Grace",
3173
            "-c",
3174
            "[email protected]",
3175
            "merge",
3176
            "-q",
3177
            "clash",
3178
        ])
3179
        .output();
3180
    assert!(
3181
        g.join(".git/MERGE_HEAD").exists(),
3182
        "the clash merge stopped at its conflict"
3183
    );
3184
    write(
3185
        &g,
3186
        "src/lib.rs",
3187
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
3188
    );
3189
    git(&["add", "."]);
3190
    git(&["commit", "-q", "-m", "resolve clash"]);
3191
    git(&["rm", "-q", "logo.png"]);
3192
    git(&["commit", "-q", "-m", "drop logo"]);
3193
    // A rename with a small edit is imported as a move of the same node.
3194
    git(&["mv", "src/lib.rs", "src/lib2.rs"]);
3195
    write(
3196
        &g,
3197
        "src/lib2.rs",
3198
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n",
3199
    );
3200
    git(&["add", "."]);
3201
    git(&["commit", "-q", "-m", "rename lib"]);
3202
    // A branch that edits run.sh, merged keeping main's tree (`-s ours`):
3203
    // run.sh is the same as in the first parent's tree, but the merged
3204
    // change touched it, so the importer must compare it, not skip it.
3205
    git(&["checkout", "-q", "-b", "discarded"]);
3206
    write(&g, "run.sh", b"#!/bin/sh\necho discarded\n");
3207
    git(&["commit", "-q", "-am", "discarded edit"]);
3208
    git(&["checkout", "-q", "main"]);
3209
    git(&[
3210
        "merge",
3211
        "-q",
3212
        "-s",
3213
        "ours",
3214
        "-m",
3215
        "merge discarded, keeping ours",
3216
        "discarded",
3217
    ]);
3218
    let expected_count: usize = git(&["rev-list", "--count", "main"]).parse().unwrap();
3219
3220
    let dest = root.join("oxy");
3221
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
3222
    let rep = repo.import_git(&g, "main").unwrap();
3223
    assert_eq!(rep.commits, expected_count);
3224
    assert_eq!(rep.merges, 3);
3225
    assert_eq!(
3226
        fs::read(dest.join("run.sh")).unwrap(),
3227
        b"#!/bin/sh\n",
3228
        "the ours merge kept main's run.sh"
3229
    );
3230
    let v = repo.verify_git_import(&g, "main").unwrap();
3231
    assert_eq!(v.commits, expected_count, "every commit's tree reproduced");
3232
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
3233
    // The working copy equals the Git tree at main.
3234
    assert_eq!(
3235
        fs::read(dest.join("src/lib2.rs")).unwrap(),
3236
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
3237
    );
3238
    assert!(!dest.join("src/lib.rs").exists());
3239
    assert_eq!(
3240
        fs::read(dest.join("README.md")).unwrap(),
3241
        b"# Hi\n\nMore.\n"
3242
    );
3243
    assert!(!dest.join("logo.png").exists());
3244
    #[cfg(unix)]
3245
    {
3246
        use std::os::unix::fs::PermissionsExt;
3247
        assert!(
3248
            fs::metadata(dest.join("run.sh"))
3249
                .unwrap()
3250
                .permissions()
3251
                .mode()
3252
                & 0o111
3253
                != 0
3254
        );
3255
    }
3256
    assert!(
3257
        !repo.snapshot("status").unwrap().changed,
3258
        "clean after import"
3259
    );
3260
    let heads = repo.bookmark_heads().unwrap();
3261
    let st = repo.load_state(&heads).unwrap();
3262
    assert!(!st.materialize().is_conflicted());
3263
    assert_eq!(st.len(), expected_count);
3264
    let tip = repo
3265
        .log()
3266
        .unwrap()
3267
        .into_iter()
3268
        .find(|e| e.change.message.starts_with("rename lib"))
3269
        .unwrap();
3270
    let c = repo.store().get_change(&tip.hash).unwrap();
3271
    assert!(
3272
        c.tree_ops
3273
            .iter()
3274
            .any(|op| matches!(op, TreeOp::Move { name, .. } if name == "lib2.rs")),
3275
        "{:?}",
3276
        c.tree_ops
3277
    );
3278
    assert!(!c
3279
        .tree_ops
3280
        .iter()
3281
        .any(|op| matches!(op, TreeOp::AddNode { .. })));
3282
    // Messages carry Git trailers; the Change-Id trailer was honoured.
3283
    let log = repo.log().unwrap();
3284
    let second = log
3285
        .iter()
3286
        .find(|e| e.change.message.starts_with("second"))
3287
        .unwrap();
3288
    assert_eq!(
3289
        second.change.change_id,
3290
        ChangeId::from_hex("0123456789abcdef0123456789abcdef").unwrap()
3291
    );
3292
    assert!(second
3293
        .change
3294
        .message
3295
        .contains("Git-Author: Grace <[email protected]>"));
3296
    let resolve = log
3297
        .iter()
3298
        .find(|e| e.change.message.starts_with("resolve clash"))
3299
        .unwrap();
3300
    assert_eq!(
3301
        resolve.change.kind,
3302
        ChangeKind::Resolution,
3303
        "a conflicting Git merge becomes a resolution"
3304
    );
3305
    // Re-importing into another fresh repository gives the same ChangeIds.
3306
    let repo2 = Repo::init(&root.join("oxy2"))
3307
        .unwrap()
3308
        .with_home(root.join("home"));
3309
    repo2.import_git(&g, "main").unwrap();
3310
    // New nodes' identifiers derive from the commit (spec §23), so the
3311
    // re-import is not just the same ChangeIds but the same changes.
3312
    assert_eq!(
3313
        repo2.bookmark_heads().unwrap(),
3314
        repo.bookmark_heads().unwrap()
3315
    );
3316
    let ids: BTreeSet<ChangeId> = repo
3317
        .log()
3318
        .unwrap()
3319
        .iter()
3320
        .filter(|e| !e.is_working_copy)
3321
        .map(|e| e.change.change_id)
3322
        .collect();
3323
    let ids2: BTreeSet<ChangeId> = repo2
3324
        .log()
3325
        .unwrap()
3326
        .iter()
3327
        .filter(|e| !e.is_working_copy)
3328
        .map(|e| e.change.change_id)
3329
        .collect();
3330
    assert_eq!(ids, ids2);
3331
    // Round trip back out to Git reproduces the tip tree.
3332
    let mirror = root.join("mirror.git");
3333
    repo.git_export(&mirror).unwrap();
3334
    let out = std::process::Command::new("git")
3335
        .arg("-C")
3336
        .arg(&mirror)
3337
        .args(["show", "main:src/lib2.rs"])
3338
        .output()
3339
        .unwrap();
3340
    assert_eq!(
3341
        String::from_utf8_lossy(&out.stdout),
3342
        "pub fn a() {}\npub fn b() {}\npub fn c() {}\npub fn d() {}\n"
3343
    );
3344
    let out = std::process::Command::new("git")
3345
        .arg("-C")
3346
        .arg(&mirror)
3347
        .args(["show", "main:src/lib.rs"])
3348
        .output()
3349
        .unwrap();
3350
    assert!(
3351
        !out.status.success(),
3352
        "the old path is gone from the export"
3353
    );
3354
}
3355
3356
#[test]
3357
fn checkpoints_accelerate_loading_and_stay_correct() {
3358
    hermetic();
3359
    let dir = tempfile::tempdir().unwrap();
3360
    let root = dir.path();
3361
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
3362
    repo.config.set("core.checkpoint-interval", "5").unwrap();
3363
    repo.save_config().unwrap();
3364
    let repo = Repo::open(root).unwrap().with_home(root.join("home"));
3365
    let mut hashes = Vec::new();
3366
    for i in 0..12 {
3367
        write(
3368
            root,
3369
            "a.txt",
3370
            format!(
3371
                "{}\n",
3372
                (0..=i)
3373
                    .map(|k| k.to_string())
3374
                    .collect::<Vec<_>>()
3375
                    .join("\n")
3376
            )
3377
            .as_bytes(),
3378
        );
3379
        write(root, &format!("f{i}.txt"), b"x\n");
3380
        hashes.push(repo.commit(&format!("c{i}"), &[]).unwrap());
3381
    }
3382
    let (_, cp) = repo
3383
        .latest_checkpoint("main")
3384
        .unwrap()
3385
        .expect("automatic checkpoint");
3386
    assert!(cp.count >= 5 && cp.count <= 12, "{}", cp.count);
3387
    // Loading through the checkpoint equals loading everything.
3388
    let heads = repo.bookmark_heads().unwrap();
3389
    let fast = repo.load_state(&heads).unwrap();
3390
    let full = repo.load_state_full(&heads).unwrap();
3391
    assert_eq!(fast.len(), full.len());
3392
    assert_eq!(fast.heads(), full.heads());
3393
    let (a, b) = (fast.materialize(), full.materialize());
3394
    assert_eq!(
3395
        a.files.keys().collect::<Vec<_>>(),
3396
        b.files.keys().collect::<Vec<_>>()
3397
    );
3398
    for (p, f) in &a.files {
3399
        assert_eq!(f.content, b.files[p].content, "{p}");
3400
    }
3401
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
3402
    // A head set that does not contain the checkpoint's heads falls back.
3403
    assert!(repo
3404
        .load_state_checkpointed(&[hashes[0]])
3405
        .unwrap()
3406
        .is_none());
3407
    assert_eq!(repo.load_state(&[hashes[0]]).unwrap().len(), 1);
3408
    // Everything else keeps working on top of the checkpoint.
3409
    assert!(!repo.snapshot("status").unwrap().changed);
3410
    let h = repo.describe(&hashes[3], "c3 described").unwrap();
3411
    assert_eq!(repo.store().get_change(&h).unwrap().message, "c3 described");
3412
    let (r, n, bytes) = repo.checkpoint().unwrap();
3413
    assert!(n >= 12 && bytes > 0);
3414
    assert_eq!(repo.latest_checkpoint("main").unwrap().unwrap().0, r);
3415
    write(root, "a.txt", b"after\n");
3416
    let h_after = repo.commit("after", &[]).unwrap();
3417
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
3418
    assert!(st.contains(&h_after));
3419
    assert!(
3420
        matches!(&st.materialize().files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"after\n")
3421
    );
3422
    assert_eq!(repo.log().unwrap().len(), 14);
3423
    // Checkpoints survive gc.
3424
    repo.gc(true).unwrap();
3425
    assert!(repo.latest_checkpoint("main").unwrap().is_some());
3426
    assert!(repo
3427
        .load_state_checkpointed(&repo.bookmark_heads().unwrap())
3428
        .unwrap()
3429
        .is_some());
3430
}
3431
3432
#[test]
3433
fn quick_status_for_prompts() {
3434
    hermetic();
3435
    let dir = tempfile::tempdir().unwrap();
3436
    let root = dir.path();
3437
    let origin = Repo::init(&root.join("origin")).unwrap();
3438
    let url = root.join("origin").to_string_lossy().to_string();
3439
    let a = Repo::clone(&url, &root.join("a"))
3440
        .unwrap()
3441
        .with_home(root.join("home"));
3442
    let ops_before = a.op_log().unwrap().len();
3443
    let info = a.quick_status().unwrap();
3444
    assert_eq!(
3445
        (
3446
            info.bookmark.as_str(),
3447
            info.heads,
3448
            info.dirty,
3449
            info.conflicted,
3450
            info.ahead,
3451
            info.behind
3452
        ),
3453
        ("main", 0, false, false, Some(0), Some(0))
3454
    );
3455
    write(&root.join("a"), "f.txt", b"f\n");
3456
    assert!(a.quick_status().unwrap().dirty, "a new file is dirty");
3457
    assert_eq!(
3458
        a.op_log().unwrap().len(),
3459
        ops_before,
3460
        "quick_status records nothing"
3461
    );
3462
    // A snapshotted but uncommitted change is still dirty.
3463
    a.snapshot("status").unwrap();
3464
    assert!(a.quick_status().unwrap().dirty);
3465
    a.commit("f", &[]).unwrap();
3466
    let info = a.quick_status().unwrap();
3467
    assert!(!info.dirty, "clean right after a commit");
3468
    assert_eq!((info.ahead, info.behind), (Some(1), Some(0)));
3469
    assert_eq!(
3470
        info.format("%b %c%d%x%A%D"),
3471
        format!("main {}+1", info.change_id)
3472
    );
3473
    assert_eq!(info.format("[%h heads] %a/%B %%"), "[1 heads] 1/0 %");
3474
    // Touching a file without changing it is not dirty; changing content of
3475
    // the same size is.
3476
    let p = root.join("a/f.txt");
3477
    let content = fs::read(&p).unwrap();
3478
    fs::write(&p, &content).unwrap();
3479
    assert!(!a.quick_status().unwrap().dirty);
3480
    fs::write(&p, b"g\n").unwrap();
3481
    assert!(a.quick_status().unwrap().dirty);
3482
    fs::write(&p, b"f\n").unwrap();
3483
    // Push, then a second clone commits and pushes: we are behind.
3484
    assert!(a.push("origin", false).unwrap()[0].ok);
3485
    assert_eq!(a.quick_status().unwrap().ahead, Some(0));
3486
    let b = Repo::clone(&url, &root.join("b"))
3487
        .unwrap()
3488
        .with_home(root.join("home-b"));
3489
    write(&root.join("b"), "g.txt", b"g\n");
3490
    b.commit("g", &[]).unwrap();
3491
    b.push("origin", false).unwrap();
3492
    a.fetch("origin").unwrap();
3493
    let info = a.quick_status().unwrap();
3494
    assert_eq!((info.ahead, info.behind), (Some(0), Some(1)));
3495
    assert_eq!(info.format("%A%D"), "-1");
3496
    let _ = origin;
3497
}
3498
3499
#[test]
3500
fn lazy_blobs_are_fetched_on_first_read() {
3501
    hermetic();
3502
    let dir = tempfile::tempdir().unwrap();
3503
    let root = dir.path();
3504
    let origin_dir = root.join("origin");
3505
    let origin = Repo::init(&origin_dir)
3506
        .unwrap()
3507
        .with_home(root.join("home"));
3508
    let url = origin_dir.to_string_lossy().to_string();
3509
    let big: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); // has NUL bytes: opaque
3510
    write(&origin_dir, "big.bin", &big);
3511
    write(&origin_dir, "small.bin", &[0u8, 1, 2]);
3512
    write(&origin_dir, "t.txt", b"t\n");
3513
    let h = origin.commit("blobs", &[]).unwrap();
3514
    let big_ref = Repo::blob_ref(&big);
3515
3516
    // Fetch only (no checkout) with a filter: the big blob stays absent.
3517
    let a = Repo::init_with_id(&root.join("a"), origin.id().unwrap())
3518
        .unwrap()
3519
        .with_home(root.join("home"));
3520
    let a = {
3521
        let mut a = a;
3522
        a.config.set("remote.origin.url", &url).unwrap();
3523
        a.config.set("filter.max-blob", "100K").unwrap();
3524
        a.save_config().unwrap();
3525
        a
3526
    };
3527
    assert_eq!(a.config.max_blob, Some(100 * 1024));
3528
    a.fetch("origin").unwrap();
3529
    assert!(a.store().has(&h));
3530
    assert!(!a.store().has(&big_ref), "withheld");
3531
    assert!(
3532
        a.store().has(&Repo::blob_ref(&[0u8, 1, 2])),
3533
        "small blob came along"
3534
    );
3535
    assert_eq!(a.lazy_remote(&big_ref).as_deref(), Some("origin"));
3536
3537
    // status and commit do not need it: adopt the state, edit a text file, commit.
3538
    let (op_ref, op) = a.head_op().unwrap();
3539
    let mut view = op.view.clone();
3540
    view.bookmarks.insert(
3541
        "main".into(),
3542
        a.store().put_state(&StateObject::new(vec![h])).unwrap(),
3543
    );
3544
    a.record_op(&[op_ref], "adopt", view).unwrap();
3545
    // Checkout reads the blob lazily, which fetches it.
3546
    a.checkout(&[h], true, "checkout").unwrap();
3547
    assert!(a.store().has(&big_ref), "fetched on first read");
3548
    assert_eq!(fs::read(root.join("a/big.bin")).unwrap(), big);
3549
    assert!(a.lazy_remote(&big_ref).is_none(), "no longer registered");
3550
    write(&root.join("a"), "t.txt", b"t2\n");
3551
    a.commit("text edit", &[]).unwrap();
3552
3553
    // clone --max-blob records the filter; the checkout fetches lazily.
3554
    let b = Repo::clone_with(&url, &root.join("b"), Some(1024), &[]).unwrap();
3555
    assert_eq!(b.config.max_blob, Some(1024));
3556
    assert_eq!(fs::read(root.join("b/big.bin")).unwrap(), big);
3557
    assert_eq!(parse_size("2M").unwrap(), 2 << 20);
3558
    assert!(parse_size("lots").is_err());
3559
}
3560
3561
#[test]
3562
fn sparse_checkout_materializes_only_chosen_paths() {
3563
    hermetic();
3564
    let dir = tempfile::tempdir().unwrap();
3565
    let root = dir.path();
3566
    let origin_dir = root.join("origin");
3567
    let origin = Repo::init(&origin_dir)
3568
        .unwrap()
3569
        .with_home(root.join("home"));
3570
    write(&origin_dir, "src/main.rs", b"fn main() {}\n");
3571
    write(&origin_dir, "src/lib.rs", b"pub fn a() {}\n");
3572
    write(&origin_dir, "docs/guide.md", b"# guide\n");
3573
    let logo: Vec<u8> = (0..50_000u32).map(|i| (i % 7) as u8).collect();
3574
    write(&origin_dir, "docs/logo.png", &logo);
3575
    write(&origin_dir, "README.md", b"# top\n");
3576
    let h1 = origin.commit("tree", &[]).unwrap();
3577
    let url = origin_dir.to_string_lossy().to_string();
3578
3579
    let a = Repo::clone_with(&url, &root.join("a"), None, &["src".into()])
3580
        .unwrap()
3581
        .with_home(root.join("home"));
3582
    assert_eq!(a.config.sparse_paths, vec!["src"]);
3583
    assert_eq!(a.config.max_blob, Some(0), "sparse implies lazy blobs");
3584
    assert!(root.join("a/src/main.rs").exists());
3585
    assert!(!root.join("a/docs").exists() && !root.join("a/README.md").exists());
3586
    assert!(
3587
        !a.store().has(&Repo::blob_ref(&logo)),
3588
        "out-of-scope blob never fetched"
3589
    );
3590
    assert!(
3591
        !a.snapshot("status").unwrap().changed,
3592
        "out-of-scope files are not removals"
3593
    );
3594
    assert!(!a.quick_status().unwrap().dirty);
3595
3596
    // Edits in scope commit normally and keep the rest of the tree intact.
3597
    write(
3598
        &root.join("a"),
3599
        "src/lib.rs",
3600
        b"pub fn a() {}\npub fn b() {}\n",
3601
    );
3602
    let h2 = a.commit("edit lib", &[]).unwrap();
3603
    let st = a.load_state(&[h2]).unwrap().materialize();
3604
    assert!(
3605
        st.files.contains_key("docs/guide.md"),
3606
        "the state still has everything"
3607
    );
3608
    assert!(a.push("origin", false).unwrap()[0].ok);
3609
    origin.refresh().unwrap();
3610
    // Files created outside the scope are ignored by status.
3611
    write(&root.join("a"), "docs/new.md", b"ignored\n");
3612
    assert!(a.snapshot("status").unwrap().statuses.is_empty());
3613
3614
    // Widening the filter checks out the rest; narrowing leaves stray files alone.
3615
    let mut a = a;
3616
    a.config.set("filter.paths", "src,docs").unwrap();
3617
    a.save_config().unwrap();
3618
    let r = a
3619
        .checkout(&a.bookmark_heads().unwrap(), true, "widen")
3620
        .unwrap();
3621
    assert!(r.written >= 2);
3622
    assert_eq!(
3623
        fs::read(root.join("a/docs/logo.png")).unwrap(),
3624
        logo,
3625
        "now fetched lazily"
3626
    );
3627
    assert!(!root.join("a/README.md").exists());
3628
    // Origin sees the change made under a sparse checkout with the full tree intact.
3629
    origin.pull("origin").err();
3630
    let full = origin
3631
        .load_state(&origin.bookmark_heads().unwrap())
3632
        .unwrap()
3633
        .materialize();
3634
    assert!(
3635
        matches!(&full.files["src/lib.rs"].content, FileContent::Text { bytes, .. } if bytes == b"pub fn a() {}\npub fn b() {}\n")
3636
    );
3637
    assert!(full.files.contains_key("README.md"));
3638
    let _ = h1;
3639
}
3640
3641
/// #137: a depth-0 clone takes no change, so the blobs of the state's
3642
/// binary files came with nothing and the checkout failed ("object … not
3643
/// found"); they are fetched with the checkpoint, or left lazy under
3644
/// `--max-blob`.
3645
#[test]
3646
fn a_depth_0_clone_brings_its_binary_files() {
3647
    hermetic();
3648
    let dir = tempfile::tempdir().unwrap();
3649
    let root = dir.path();
3650
    let origin_dir = root.join("origin");
3651
    let origin = Repo::init(&origin_dir)
3652
        .unwrap()
3653
        .with_home(root.join("home"));
3654
    let png: Vec<u8> = (0..4000u32)
3655
        .map(|i| (i * 7 % 251) as u8)
3656
        .chain([0, 0xff])
3657
        .collect();
3658
    // The logo comes with a.txt's first line, and the head edits that line,
3659
    // so the change that set the logo is below the head, not a head itself.
3660
    write(&origin_dir, "logo.png", &png);
3661
    write(&origin_dir, "a.txt", b"first\n");
3662
    origin.commit("logo", &[]).unwrap();
3663
    write(&origin_dir, "a.txt", b"later\n");
3664
    origin.commit("later", &[]).unwrap();
3665
    assert_eq!(origin.bookmark_heads().unwrap().len(), 1);
3666
    let url = origin_dir.to_string_lossy().to_string();
3667
    Repo::clone_shallow(&url, &root.join("a"), 0, None, &[]).unwrap();
3668
    assert_eq!(fs::read(root.join("a/logo.png")).unwrap(), png);
3669
    let lazy = Repo::clone_shallow(&url, &root.join("b"), 0, Some(0), &[]).unwrap();
3670
    assert_eq!(fs::read(root.join("b/a.txt")).unwrap(), b"later\n");
3671
    let blob = {
3672
        let heads = lazy.bookmark_heads().unwrap();
3673
        let st = lazy.load_state_history(&heads).unwrap();
3674
        st.opaque_nodes()
3675
            .iter()
3676
            .flat_map(|n| st.live_blobs(n))
3677
            .next()
3678
            .unwrap()
3679
    };
3680
    assert_eq!(lazy.read_blob(&blob).unwrap(), png, "fetched on read");
3681
    // Depth 0 takes no change: the head is the boundary; the log comes from
3682
    // the checkpoint; a change on top commits and pushes.
3683
    let mut a = Repo::open(&root.join("a"))
3684
        .unwrap()
3685
        .with_home(root.join("home"));
3686
    let head = origin.bookmark_heads().unwrap()[0];
3687
    assert!(!a.store().has(&head), "no change fetched");
3688
    assert!(a.boundary().contains(&head));
3689
    assert_eq!(
3690
        a.log()
3691
            .unwrap()
3692
            .iter()
3693
            .filter(|e| !e.is_working_copy)
3694
            .count(),
3695
        2,
3696
        "the log from the checkpoint"
3697
    );
3698
    write(&root.join("a"), "a.txt", b"later\nmine\n");
3699
    a.config.set("remote.origin.url", &url).unwrap();
3700
    a.save_config().unwrap();
3701
    let mine = a.commit("mine", &[]).unwrap();
3702
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
3703
    origin.refresh().unwrap();
3704
    assert!(origin.store().has(&mine));
3705
    assert_eq!(origin.bookmark_heads().unwrap(), vec![mine]);
3706
    // And pulls what comes after.
3707
    origin
3708
        .checkout(&origin.bookmark_heads().unwrap(), false, "co")
3709
        .unwrap();
3710
    write(&origin_dir, "a.txt", b"later\nmine\ntheirs\n");
3711
    origin.snapshot("t").unwrap();
3712
    origin.commit("theirs", &[]).unwrap();
3713
    a.pull("origin").unwrap();
3714
    assert_eq!(
3715
        fs::read(root.join("a/a.txt")).unwrap(),
3716
        b"later\nmine\ntheirs\n"
3717
    );
3718
}
3719
3720
#[test]
3721
fn shallow_clone_and_deepen() {
3722
    hermetic();
3723
    let dir = tempfile::tempdir().unwrap();
3724
    let root = dir.path();
3725
    let origin_dir = root.join("origin");
3726
    let origin = Repo::init(&origin_dir)
3727
        .unwrap()
3728
        .with_home(root.join("home"));
3729
    let mut hashes = Vec::new();
3730
    for i in 0..8 {
3731
        write(
3732
            &origin_dir,
3733
            "a.txt",
3734
            format!(
3735
                "{}\n",
3736
                (0..=i)
3737
                    .map(|k| k.to_string())
3738
                    .collect::<Vec<_>>()
3739
                    .join("\n")
3740
            )
3741
            .as_bytes(),
3742
        );
3743
        hashes.push(origin.commit(&format!("c{i}"), &[]).unwrap());
3744
    }
3745
    let url = origin_dir.to_string_lossy().to_string();
3746
    let a = Repo::clone_shallow(&url, &root.join("a"), 3, None, &[])
3747
        .unwrap()
3748
        .with_home(root.join("home"));
3749
    assert!(a.is_shallow());
3750
    assert_eq!(
3751
        fs::read_to_string(root.join("a/a.txt")).unwrap(),
3752
        "0\n1\n2\n3\n4\n5\n6\n7\n"
3753
    );
3754
    assert!(
3755
        a.store().has(&hashes[7]) && a.store().has(&hashes[5]),
3756
        "three levels present"
3757
    );
3758
    assert!(!a.store().has(&hashes[4]), "beyond the depth is absent");
3759
    assert_eq!(a.boundary(), [hashes[4]].into_iter().collect());
3760
    assert_eq!(
3761
        a.log().unwrap().len(),
3762
        9,
3763
        "the log shows every change from the checkpoint's metadata"
3764
    );
3765
    assert!(!a.snapshot("status").unwrap().changed);
3766
    assert_eq!(a.quick_status().unwrap().heads, 1);
3767
3768
    // Work continues on top of the shallow history and pushes back.
3769
    write(&root.join("a"), "a.txt", b"0\n1\n2\n3\n4\n5\n6\n7\n8\n");
3770
    let h_new = a.commit("c8", &[]).unwrap();
3771
    assert!(a.push("origin", false).unwrap()[0].ok);
3772
    origin.refresh().unwrap();
3773
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h_new]);
3774
    // Fetching new work from origin into the shallow clone works too.
3775
    write(&origin_dir, "b.txt", b"b\n");
3776
    origin.pull("origin").err();
3777
    let (_, wc) = origin.working_copy().unwrap();
3778
    let _ = wc;
3779
    origin
3780
        .checkout(&origin.bookmark_heads().unwrap(), true, "co")
3781
        .unwrap();
3782
    write(&origin_dir, "b.txt", b"b\n");
3783
    let h_b = origin.commit("b", &[]).unwrap();
3784
    let pr = a.pull("origin").unwrap();
3785
    assert!(pr.changed);
3786
    assert!(a.store().has(&h_b));
3787
    assert!(root.join("a/b.txt").exists());
3788
3789
    // Deepening fetches older history until the boundary is gone.
3790
    // Every commit also depends on the change that created the file, so two
3791
    // levels below the boundary hold h4, h3, and the root.
3792
    assert!(a.deepen("origin", 2).unwrap() >= 2);
3793
    assert!(a.store().has(&hashes[3]));
3794
    assert!(a.is_shallow());
3795
    a.deepen("origin", 100).unwrap();
3796
    assert!(!a.is_shallow(), "boundary reached the root");
3797
    assert!(a.store().has(&hashes[0]));
3798
    assert_eq!(
3799
        a.load_state_full(&a.bookmark_heads().unwrap())
3800
            .unwrap()
3801
            .len(),
3802
        10
3803
    );
3804
}
3805
3806
#[test]
3807
fn a_tag_is_withdrawn_by_a_signed_withdrawal() {
3808
    hermetic();
3809
    let dir = tempfile::tempdir().unwrap();
3810
    let root = dir.path();
3811
    let origin = Repo::init(&root.join("origin")).unwrap();
3812
    let url = root.join("origin").to_string_lossy().to_string();
3813
    let mut a = Repo::clone(&url, &root.join("a"))
3814
        .unwrap()
3815
        .with_home(root.join("home-a"));
3816
    a.create_identity("Ada", "[email protected]", IdentityScope::User)
3817
        .unwrap();
3818
    write(&root.join("a"), "f.txt", b"1\n");
3819
    let h1 = a.commit("one", &[]).unwrap();
3820
    a.tag_create("v1", &[h1], "first release").unwrap();
3821
    a.tag_create("v2", &[h1], "").unwrap();
3822
    a.policy_init().unwrap();
3823
    a.push("origin", false).unwrap();
3824
    origin.refresh().unwrap();
3825
    let original = a
3826
        .tag_refs()
3827
        .unwrap()
3828
        .into_iter()
3829
        .find(|t| t.name == "v1")
3830
        .unwrap();
3831
    let b = Repo::clone(&url, &root.join("b"))
3832
        .unwrap()
3833
        .with_home(root.join("home-b"));
3834
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3835
3836
    // A key the policy does not let create the tag may not withdraw it.
3837
    let mut c = Repo::clone(&url, &root.join("c"))
3838
        .unwrap()
3839
        .with_home(root.join("home-c"));
3840
    c.create_identity("Cy", "[email protected]", IdentityScope::User)
3841
        .unwrap();
3842
    let r = c.push_delete("origin", "tags/v1").unwrap();
3843
    assert!(
3844
        !r[0].ok && r[0].reason.contains("may not withdraw"),
3845
        "{r:?}"
3846
    );
3847
    assert_eq!(c.tag_heads("v1").unwrap(), None, "withdrawn there first");
3848
    origin.refresh().unwrap();
3849
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3850
3851
    // Its creator's key may: the tag goes, the withdrawal stays.
3852
    let r = a.push_delete("origin", "tags/v1").unwrap();
3853
    assert!(r[0].ok && r[0].reason == "withdrawn", "{r:?}");
3854
    origin.refresh().unwrap();
3855
    assert_eq!(origin.tag_heads("v1").unwrap(), None);
3856
    assert_eq!(a.tag_heads("v1").unwrap(), None);
3857
    assert!(origin.tag_withdrawal("v1").unwrap().is_some());
3858
    assert!(origin.tag_attest("v1").unwrap().is_some(), "kept beside it");
3859
    let refs = origin.remote_refs().unwrap();
3860
    assert!(refs.tags.iter().all(|t| t.name != "v1"));
3861
    assert_eq!(refs.withdrawn.len(), 1);
3862
    let r = a.push_delete("origin", "tags/v1").unwrap();
3863
    assert!(r[0].ok && r[0].reason == "already withdrawn", "{r:?}");
3864
3865
    // A fetch withdraws it too, and the name is never used again.
3866
    let rep = b.fetch("origin").unwrap();
3867
    assert_eq!(rep.withdrawn_tags, vec!["v1".to_string()]);
3868
    assert_eq!(b.tag_heads("v1").unwrap(), None);
3869
    assert!(b.tag_create("v1", &[h1], "").is_err());
3870
    let r = origin
3871
        .receive_push(Bundle::default(), vec![], None, vec![original])
3872
        .unwrap();
3873
    assert!(!r[0].ok && r[0].reason.contains("withdrawn"), "{r:?}");
3874
3875
    // `oxy tag delete`, then a plain push, sends it.
3876
    a.tag_delete("v2", "tagged too early").unwrap();
3877
    let r = a.push("origin", false).unwrap();
3878
    assert!(
3879
        r.iter()
3880
            .any(|x| x.name == "tags/v2" && x.ok && x.reason == "withdrawn"),
3881
        "{r:?}"
3882
    );
3883
    origin.refresh().unwrap();
3884
    assert_eq!(origin.tag_heads("v2").unwrap(), None);
3885
    let (_, w) = origin.tag_withdrawal("v2").unwrap().unwrap();
3886
    assert!(
3887
        matches!(&w.attest.body, AttestBody::Untag { reason, .. } if reason == "tagged too early")
3888
    );
3889
}
3890
3891
#[test]
3892
fn tags_are_immutable_named_states_and_travel() {
3893
    hermetic();
3894
    let dir = tempfile::tempdir().unwrap();
3895
    let root = dir.path();
3896
    let origin = Repo::init(&root.join("origin")).unwrap();
3897
    let url = root.join("origin").to_string_lossy().to_string();
3898
    let mut a = Repo::clone(&url, &root.join("a"))
3899
        .unwrap()
3900
        .with_home(root.join("home-a"));
3901
    let (key_a, _) = a
3902
        .create_identity("Ada", "[email protected]", IdentityScope::User)
3903
        .unwrap();
3904
    write(&root.join("a"), "f.txt", b"1\n");
3905
    let h1 = a.commit("one", &[]).unwrap();
3906
    write(&root.join("a"), "f.txt", b"1\n2\n");
3907
    let h2 = a.commit("two", &[]).unwrap();
3908
3909
    let t = a.tag_create("v1", &[h1], "first release").unwrap();
3910
    assert_eq!(
3911
        (t.heads.clone(), t.signer.as_deref()),
3912
        (vec![h1], Some("Ada"))
3913
    );
3914
    assert!(a.tag_create("v1", &[h2], "").is_err(), "immutable");
3915
    assert!(a.tag_create("bad/name", &[h2], "").is_err());
3916
    assert_eq!(a.tag_heads("v1").unwrap(), Some(vec![h1]));
3917
    assert_eq!(a.resolve_heads("v1").unwrap(), vec![h1]);
3918
    assert_eq!(a.resolve_heads("main").unwrap(), vec![h2]);
3919
    let (_, sa) = a.tag_attest("v1").unwrap().unwrap();
3920
    assert_eq!(sa.sigs[0].key, key_a);
3921
    // Without a policy every client is sent every tag, whatever features
3922
    // it declares (oxygen#131).
3923
    let mut refs = a.remote_refs().unwrap();
3924
    a.refs_for_client(&mut refs, None);
3925
    assert_eq!(refs.tags.len(), 1);
3926
    // Checkout by tag.
3927
    a.checkout(&a.resolve_heads("v1").unwrap(), false, "co")
3928
        .unwrap();
3929
    assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"1\n");
3930
    a.checkout(&a.bookmark_heads().unwrap(), false, "co")
3931
        .unwrap();
3932
3933
    // Push carries the tag; a second attestation for the name is refused.
3934
    let r = a.push("origin", false).unwrap();
3935
    origin.refresh().unwrap();
3936
    assert!(r.iter().any(|x| x.name == "tags/v1" && x.ok), "{r:?}");
3937
    assert_eq!(origin.tag_heads("v1").unwrap(), Some(vec![h1]));
3938
    let mut forged = a
3939
        .tag_refs()
3940
        .unwrap()
3941
        .into_iter()
3942
        .find(|t| t.name == "v1")
3943
        .unwrap();
3944
    forged.state = origin
3945
        .store()
3946
        .put_state(&StateObject::new(vec![h2]))
3947
        .unwrap();
3948
    forged.heads = vec![h2];
3949
    forged.attestation = None;
3950
    let r = origin
3951
        .receive_push(Bundle::default(), vec![], None, vec![forged])
3952
        .unwrap();
3953
    assert!(!r[0].ok && r[0].reason.contains("immutable"), "{r:?}");
3954
3955
    // A clone gets the tag; a later tag arrives on fetch.
3956
    let b = Repo::clone(&url, &root.join("b"))
3957
        .unwrap()
3958
        .with_home(root.join("home-b"));
3959
    assert_eq!(b.tag_heads("v1").unwrap(), Some(vec![h1]));
3960
    assert!(b.tags().unwrap()[0].signer.as_deref() == Some("Ada"));
3961
    a.tag_create("v2", &[h2], "second").unwrap();
3962
    a.push("origin", false).unwrap();
3963
    origin.refresh().unwrap();
3964
    let rep = b.fetch("origin").unwrap();
3965
    assert_eq!(rep.new_tags, 1);
3966
    assert_eq!(b.tag_heads("v2").unwrap(), Some(vec![h2]));
3967
3968
    // Under a policy, an unattested tag is refused and an attested one by the root passes.
3969
    a.policy_init().unwrap();
3970
    a.push("origin", false).unwrap();
3971
    origin.refresh().unwrap();
3972
    let unattested = crate::protocol::TagRef::new(
3973
        "v3".into(),
3974
        origin
3975
            .store()
3976
            .put_state(&StateObject::new(vec![h2]))
3977
            .unwrap(),
3978
        vec![h2],
3979
        None,
3980
    );
3981
    let r = origin
3982
        .receive_push(Bundle::default(), vec![], None, vec![unattested])
3983
        .unwrap();
3984
    assert!(!r[0].ok && r[0].reason.contains("attestation"), "{r:?}");
3985
    a.tag_create("v3", &[h2], "").unwrap();
3986
    let r = a.push("origin", false).unwrap();
3987
    origin.refresh().unwrap();
3988
    assert!(r.iter().any(|x| x.name == "tags/v3" && x.ok), "{r:?}");
3989
    assert!(a.gc(true).is_ok());
3990
    assert_eq!(a.tags().unwrap().len(), 3, "tags survive gc");
3991
3992
    // After a rotation the policy names only the new key, yet a fresh clone
3993
    // still takes the tags the old key made before it; the old key makes
3994
    // nothing new.
3995
    let rot = a.rotate_identity().unwrap();
3996
    let r = a.push("origin", false).unwrap();
3997
    origin.refresh().unwrap();
3998
    assert!(r.iter().all(|x| x.ok), "{r:?}");
3999
    let c = Repo::clone(&url, &root.join("c"))
4000
        .unwrap()
4001
        .with_home(root.join("home-c"));
4002
    assert_eq!(c.tag_heads("v3").unwrap(), Some(vec![h2]));
4003
    let (_, sp) = c.current_policy().unwrap().unwrap();
4004
    assert!(!sp.policy.authorizes(&key_a, "tags/v9"));
4005
    let made = c.identity(&rot.new).unwrap().created;
4006
    assert!(c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made - 1));
4007
    assert!(!c.predecessor_authorized(&sp.policy, &key_a, "tags/v9", made));
4008
    assert!(!c.predecessor_authorized(&sp.policy, &rot.new, "tags/v9", 0));
4009
}
4010
4011
#[test]
4012
fn multiple_workspaces_share_a_repository() {
4013
    hermetic();
4014
    let dir = tempfile::tempdir().unwrap();
4015
    let root = dir.path();
4016
    let main_dir = root.join("main");
4017
    let repo = Repo::init(&main_dir).unwrap().with_home(root.join("home"));
4018
    write(&main_dir, "a.txt", b"a\n");
4019
    let h1 = repo.commit("a", &[]).unwrap();
4020
    assert_eq!(repo.workspaces().unwrap().len(), 1);
4021
4022
    // A second workspace elsewhere, checked out on the bookmark.
4023
    let ws_dir = root.join("ws2");
4024
    let ops = repo.op_log().unwrap().len();
4025
    let ws = repo.workspace_add(&ws_dir, None).unwrap();
4026
    assert_eq!(
4027
        ws.op_log().unwrap().len(),
4028
        ops + 2,
4029
        "the add and its checkout, and no snapshot finding the tree deleted (oxygen#137)"
4030
    );
4031
    assert!(ws_dir.join(".oxy").is_file());
4032
    assert_eq!(fs::read(ws_dir.join("a.txt")).unwrap(), b"a\n");
4033
    assert_ne!(ws.workspace(), repo.workspace());
4034
    let list = repo.workspaces().unwrap();
4035
    assert_eq!(list.len(), 2);
4036
    assert!(list
4037
        .iter()
4038
        .any(|w| w.id == ws.workspace() && w.path == ws_dir.canonicalize().unwrap() && !w.current));
4039
    assert!(!ws.snapshot("status").unwrap().changed);
4040
4041
    // Work in the second workspace: its own working copy, shared bookmark.
4042
    write(&ws_dir, "b.txt", b"b\n");
4043
    let s = ws.snapshot("status").unwrap();
4044
    assert_eq!(s.statuses.len(), 1);
4045
    assert!(
4046
        !repo.snapshot("status").unwrap().changed,
4047
        "the first workspace is untouched"
4048
    );
4049
    let h2 = ws.commit("b from ws2", &[]).unwrap();
4050
    repo.refresh().unwrap();
4051
    let mut heads = repo.bookmark_heads().unwrap();
4052
    heads.sort();
4053
    let mut want = vec![h1, h2];
4054
    want.sort();
4055
    assert_eq!(heads, want, "both workspaces see the bookmark move");
4056
    assert!(!main_dir.join("b.txt").exists());
4057
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "co")
4058
        .unwrap();
4059
    assert!(main_dir.join("b.txt").exists());
4060
4061
    // Reopening from inside the second workspace finds the shared repository.
4062
    let reopened = Repo::open(&ws_dir).unwrap();
4063
    assert_eq!(reopened.workspace(), ws.workspace());
4064
    assert_eq!(reopened.id().unwrap(), repo.id().unwrap());
4065
    assert_eq!(reopened.quick_status().unwrap().heads, 2);
4066
4067
    // Workspaces cannot nest; forget drops one from the view but keeps files.
4068
    assert!(repo.workspace_add(&main_dir.join("inner"), None).is_err());
4069
    assert!(repo.workspace_forget(&repo.workspace()).is_err());
4070
    repo.workspace_forget(&ws.workspace()).unwrap();
4071
    assert_eq!(repo.workspaces().unwrap().len(), 1);
4072
    assert!(ws_dir.join("b.txt").exists());
4073
    assert!(
4074
        ws.snapshot("status").is_err(),
4075
        "a forgotten workspace is no longer in the view"
4076
    );
4077
4078
    // The working-copy lock: re-entrant in a thread; a lock whose process
4079
    // is gone is taken over, and a live process's is not, however old.
4080
    let lock = repo.lock_snapshot().unwrap();
4081
    let again = repo.lock_working_copy().unwrap();
4082
    drop(again);
4083
    drop(lock);
4084
    let lock_path = main_dir
4085
        .join(".oxy/workspaces")
4086
        .join(repo.workspace().to_hex())
4087
        .join("lock");
4088
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
4089
    let age = |p: &Path| fs::File::open(p).unwrap().set_modified(old).unwrap();
4090
    fs::write(&lock_path, std::process::id().to_string()).unwrap();
4091
    age(&lock_path);
4092
    assert!(
4093
        !super::workspace::lock_is_stale(&lock_path),
4094
        "a live process keeps its lock"
4095
    );
4096
    fs::write(&lock_path, "4294967295").unwrap();
4097
    age(&lock_path);
4098
    assert!(repo.lock_snapshot().is_ok(), "stale lock taken over");
4099
}
4100
4101
#[test]
4102
fn attributes_binary_eol_nocompress_lockable() {
4103
    hermetic();
4104
    let dir = tempfile::tempdir().unwrap();
4105
    let root = dir.path();
4106
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4107
    write(
4108
        root,
4109
        ".oxyattributes",
4110
        b"*.dat binary nocompress\n*.txt eol=crlf\nassets/** lockable\n",
4111
    );
4112
    write(root, "plain.dat", b"no nul bytes here\n");
4113
    write(root, "notes.txt", b"one\r\ntwo\r\n");
4114
    write(root, "assets/model.bin", b"\0model");
4115
    let h = repo.commit("attrs", &[]).unwrap();
4116
    let snap = repo.load_state(&[h]).unwrap().materialize();
4117
    assert!(
4118
        snap.files["plain.dat"].mode.opaque,
4119
        "binary attribute forces opaque without NUL bytes"
4120
    );
4121
    assert!(
4122
        matches!(&snap.files["notes.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
4123
        "stored with LF"
4124
    );
4125
    assert!(
4126
        !repo.snapshot("status").unwrap().changed,
4127
        "CRLF on disk equals LF in the state"
4128
    );
4129
    // nocompress chunks pack raw.
4130
    let r = repo.gc(true).unwrap();
4131
    assert!(r.packed.objects > 0);
4132
    // Checkout writes CRLF for eol=crlf and makes lockable files read-only.
4133
    fs::remove_file(root.join("notes.txt")).unwrap();
4134
    repo.checkout(&[h], true, "co").unwrap();
4135
    assert_eq!(fs::read(root.join("notes.txt")).unwrap(), b"one\r\ntwo\r\n");
4136
    assert!(fs::metadata(root.join("assets/model.bin"))
4137
        .unwrap()
4138
        .permissions()
4139
        .readonly());
4140
    assert!(repo.lock_path("plain.dat").is_err(), "not lockable");
4141
    repo.lock_path("assets/model.bin").unwrap();
4142
    assert!(!fs::metadata(root.join("assets/model.bin"))
4143
        .unwrap()
4144
        .permissions()
4145
        .readonly());
4146
    assert!(repo.is_locked("assets/model.bin"));
4147
    write(root, "assets/model.bin", b"\0model2");
4148
    repo.commit("edit model", &[]).unwrap();
4149
    repo.unlock_path("assets/model.bin").unwrap();
4150
    assert!(fs::metadata(root.join("assets/model.bin"))
4151
        .unwrap()
4152
        .permissions()
4153
        .readonly());
4154
    // A later checkout can still overwrite a read-only lockable file.
4155
    repo.checkout(&[h], true, "co").unwrap();
4156
    assert_eq!(fs::read(root.join("assets/model.bin")).unwrap(), b"\0model");
4157
}
4158
4159
#[cfg(unix)]
4160
#[test]
4161
fn hooks_can_veto_observe_and_add_dependencies() {
4162
    use std::os::unix::fs::PermissionsExt;
4163
    hermetic();
4164
    let dir = tempfile::tempdir().unwrap();
4165
    let root = dir.path();
4166
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4167
    let hooks = root.join(".oxy/hooks");
4168
    fs::create_dir_all(&hooks).unwrap();
4169
    let hook = |name: &str, body: &str| {
4170
        let p = hooks.join(name);
4171
        fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
4172
        fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
4173
    };
4174
    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");
4175
    hook("post-commit", "cat > \"$OXY_ROOT/.last-post-commit\"");
4176
    hook("post-checkout", "cat > \"$OXY_ROOT/.last-post-checkout\"");
4177
    hook("pre-push", "echo pushing blocked >&2; exit 3");
4178
    write(root, ".oxyignore", b".last-*\n");
4179
    write(root, "a.txt", b"a\n");
4180
    let err = repo.commit("WIP: nope", &[]).unwrap_err().to_string();
4181
    assert!(err.contains("pre-commit refused: no WIP commits"), "{err}");
4182
    let h1 = repo.commit("first", &[]).unwrap();
4183
    let pre = fs::read_to_string(root.join(".last-pre-commit")).unwrap();
4184
    assert!(
4185
        pre.contains("\"event\":\"pre-commit\"")
4186
            && pre.contains("\"path\":\"a.txt\"")
4187
            && pre.contains("\"message\":\"first\""),
4188
        "{pre}"
4189
    );
4190
    let post = fs::read_to_string(root.join(".last-post-commit")).unwrap();
4191
    assert!(post.contains(&h1.to_hex()), "{post}");
4192
    repo.checkout(&[h1], false, "co").unwrap();
4193
    assert!(fs::read_to_string(root.join(".last-post-checkout"))
4194
        .unwrap()
4195
        .contains("post-checkout"));
4196
    repo.config.set("remote.origin.url", "/nowhere").unwrap();
4197
    repo.save_config().unwrap();
4198
    let err = repo.push("origin", false).unwrap_err().to_string();
4199
    assert!(err.contains("pre-push refused: pushing blocked"), "{err}");
4200
4201
    // semantic-deps: only when enabled; adds an explicit dependency.
4202
    write(root, "b.txt", b"b\n");
4203
    hook(
4204
        "semantic-deps",
4205
        &format!(
4206
            "cat > \"$OXY_ROOT/.last-semantic\"; echo '{{\"deps\": [\"{}\"]}}'",
4207
            h1.to_hex()
4208
        ),
4209
    );
4210
    let h2 = repo.commit("b without hook", &[]).unwrap();
4211
    assert!(
4212
        repo.store().get_change(&h2).unwrap().deps.is_empty(),
4213
        "hook disabled by default"
4214
    );
4215
    repo.config.set("hooks.semantic-deps", "true").unwrap();
4216
    repo.save_config().unwrap();
4217
    write(root, "c.txt", b"c\n");
4218
    let h3 = repo.commit("c with hook", &[]).unwrap();
4219
    assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
4220
    let sem = fs::read_to_string(root.join(".last-semantic")).unwrap();
4221
    assert!(
4222
        sem.contains("\"touched_paths\":[\"c.txt\"]") && sem.contains("candidate_deps"),
4223
        "{sem}"
4224
    );
4225
    assert_eq!(json_str("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
4226
}
4227
4228
#[test]
4229
fn amend_into_older_change_and_split() {
4230
    hermetic();
4231
    let dir = tempfile::tempdir().unwrap();
4232
    let root = dir.path();
4233
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
4234
    repo.create_identity("Ada", "a@b", IdentityScope::User)
4235
        .unwrap();
4236
    repo.set_user_config("core.sign", "change").unwrap();
4237
    write(root, "a.txt", b"one\ntwo\n");
4238
    let h0 = repo.commit("base", &[]).unwrap();
4239
    write(root, "a.txt", b"one\nTWO\n");
4240
    let h1 = repo.commit("edit two", &[]).unwrap();
4241
    write(root, "a.txt", b"one\nTWO\nthree\n");
4242
    let h2 = repo.commit("add three", &[]).unwrap();
4243
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
4244
4245
    // Fixing the line h1 introduced folds into h1; h2 is rewritten on top.
4246
    write(root, "a.txt", b"one\nTWO!\nthree\n");
4247
    let h1b = repo.amend_into(&h1, None).unwrap();
4248
    assert_ne!(h1b, h1);
4249
    let c1b = repo.store().get_change(&h1b).unwrap();
4250
    assert_eq!(c1b.change_id, id1);
4251
    assert_eq!(c1b.deps, vec![h0]);
4252
    assert!(matches!(
4253
        repo.verify_change(&h1b).unwrap(),
4254
        SignatureStatus::Valid { .. }
4255
    ));
4256
    let heads = repo.bookmark_heads().unwrap();
4257
    assert_eq!(heads.len(), 1);
4258
    let top = repo.store().get_change(&heads[0]).unwrap();
4259
    assert_eq!(top.message, "add three");
4260
    assert_eq!(
4261
        top.deps.iter().copied().collect::<BTreeSet<_>>(),
4262
        [h0, h1b].into_iter().collect(),
4263
        "depends on the file's creator and the rewritten line"
4264
    );
4265
    let snap = repo.load_state(&heads).unwrap().materialize();
4266
    assert!(
4267
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\nthree\n")
4268
    );
4269
    assert!(
4270
        !repo.snapshot("status").unwrap().changed,
4271
        "the working copy is clean after folding"
4272
    );
4273
    // Only h1b's own state shows the fix without "three".
4274
    let only = repo.load_state(&[h1b]).unwrap().materialize();
4275
    assert!(
4276
        matches!(&only.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\nTWO!\n")
4277
    );
4278
    assert_eq!(repo.log().unwrap().len(), 4);
4279
4280
    // An edit to a line introduced by h2 cannot fold into h1.
4281
    write(root, "a.txt", b"one\nTWO!\nthree!\n");
4282
    let err = repo.amend_into(&h1b, None).unwrap_err().to_string();
4283
    assert!(err.contains("introduced after"), "{err}");
4284
    assert!(
4285
        repo.snapshot("status").unwrap().statuses.len() == 1,
4286
        "nothing was changed by the refusal"
4287
    );
4288
    write(root, "a.txt", b"one\nTWO!\nthree\n");
4289
4290
    // Split the head that touches two files.
4291
    write(root, "b.txt", b"b\n");
4292
    write(root, "c.txt", b"c\n");
4293
    let h3 = repo.commit("b and c", &[]).unwrap();
4294
    let id3 = repo.store().get_change(&h3).unwrap().change_id;
4295
    let (p1, p2) = repo.split(&h3, &["b.txt".into()]).unwrap();
4296
    let c_1 = repo.store().get_change(&p1).unwrap();
4297
    let c_2 = repo.store().get_change(&p2).unwrap();
4298
    assert!(c_1.message.contains("part 1: b.txt"));
4299
    assert_eq!(c_2.change_id, id3);
4300
    let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
4301
    assert!(
4302
        heads.contains(&p1) && heads.contains(&p2),
4303
        "independent parts are both heads"
4304
    );
4305
    let snap = repo
4306
        .load_state(&repo.bookmark_heads().unwrap())
4307
        .unwrap()
4308
        .materialize();
4309
    assert!(snap.files.contains_key("b.txt") && snap.files.contains_key("c.txt"));
4310
    let only1 = repo.load_state(&[p1]).unwrap().materialize();
4311
    assert!(only1.files.contains_key("b.txt") && !only1.files.contains_key("c.txt"));
4312
    assert!(!repo.snapshot("status").unwrap().changed);
4313
    assert!(repo.split(&p2, &["nope.txt".into()]).is_err());
4314
    let _ = h2;
4315
}
4316
4317
#[test]
4318
fn identity_lifecycle() {
4319
    hermetic();
4320
    let dir = tempfile::tempdir().unwrap();
4321
    let root = dir.path();
4322
    let origin = Repo::init(&root.join("origin")).unwrap();
4323
    let url = root.join("origin").to_string_lossy().to_string();
4324
    let mut a = Repo::clone(&url, &root.join("a"))
4325
        .unwrap()
4326
        .with_home(root.join("home-a"));
4327
    a.set_user_config("core.sign", "change").unwrap();
4328
    let (key_a, _) = a
4329
        .create_identity("Ada", "[email protected]", IdentityScope::User)
4330
        .unwrap();
4331
    write(&root.join("a"), "a.txt", b"a\n");
4332
    let h1 = a.commit("one", &[]).unwrap();
4333
    assert!(a.policy_init().unwrap().applied);
4334
    assert!(a.push("origin", false).unwrap().iter().all(|r| r.ok));
4335
    origin.refresh().unwrap();
4336
4337
    // Expiry: an identity that had expired when the change was made does not authenticate it.
4338
    let mut e = Repo::init(&root.join("e"))
4339
        .unwrap()
4340
        .with_home(root.join("home-e"));
4341
    e.set_user_config("core.sign", "change").unwrap();
4342
    e.create_identity_with(
4343
        "Eve",
4344
        "[email protected]",
4345
        IdentityScope::User,
4346
        Some(Hlc::now().wall_ms - 1),
4347
    )
4348
    .unwrap();
4349
    write(&root.join("e"), "e.txt", b"e\n");
4350
    let he = e.commit("late", &[]).unwrap();
4351
    assert!(
4352
        matches!(e.verify_change(&he).unwrap(), SignatureStatus::Invalid(m) if m.contains("expired"))
4353
    );
4354
    // Renewal re-issues the identity (same keys, new KeyId) with a later expiry.
4355
    let r = e
4356
        .renew_identity(Some(Hlc::now().wall_ms + 86_400_000))
4357
        .unwrap();
4358
    assert_eq!(e.identity(&r.new).unwrap().previous, Some(r.old));
4359
    write(&root.join("e"), "e.txt", b"e2\n");
4360
    let he2 = e.commit("in time", &[]).unwrap();
4361
    assert!(
4362
        matches!(e.verify_change(&he2).unwrap(), SignatureStatus::Valid { key, .. } if key == r.new)
4363
    );
4364
4365
    // Rotation: a fresh key; the old change still verifies; the policy follows.
4366
    let r = a.rotate_identity().unwrap();
4367
    assert_eq!(r.old, key_a);
4368
    assert_eq!(a.config.author_key, Some(r.new));
4369
    assert_eq!(a.identity(&r.new).unwrap().previous, Some(key_a));
4370
    assert!(r.policy.as_ref().unwrap().applied);
4371
    let (_, sp) = a.current_policy().unwrap().unwrap();
4372
    assert_eq!(
4373
        (sp.policy.serial, sp.policy.roots.clone()),
4374
        (2, vec![r.new])
4375
    );
4376
    assert!(
4377
        !sp.policy.revoked.contains(&key_a) && sp.policy.authorizes(&r.new, "main"),
4378
        "superseded, not revoked"
4379
    );
4380
    assert!(sp.policy.succeeds(&r.new, &key_a) && !sp.policy.succeeds(&key_a, &r.new));
4381
    assert!(
4382
        matches!(a.verify_change(&h1).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == key_a)
4383
    );
4384
    write(&root.join("a"), "a.txt", b"a2\n");
4385
    let h2 = a.commit("two", &[]).unwrap();
4386
    assert!(
4387
        matches!(a.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, revoked: false, .. } if key == r.new)
4388
    );
4389
    // Origin accepts the rotated policy (signed by the old root) and the new key's change.
4390
    let res = a.push("origin", false).unwrap();
4391
    origin.refresh().unwrap();
4392
    assert!(res.iter().all(|x| x.ok), "{res:?}");
4393
    assert_eq!(origin.current_policy().unwrap().unwrap().1.policy.serial, 2);
4394
    let key_a = r.new;
4395
4396
    // Delegation: Bob may sign on Ada's behalf. Delegates live in the
4397
    // identity object, so Ada's KeyId changes while her keys stay the same.
4398
    let mut b = Repo::clone(&url, &root.join("b"))
4399
        .unwrap()
4400
        .with_home(root.join("home-b"));
4401
    let (key_b, id_b) = b
4402
        .create_identity("Bob", "[email protected]", IdentityScope::User)
4403
        .unwrap();
4404
    let r = a.delegate_add(id_b.clone(), Scope::ALL, None).unwrap();
4405
    assert_eq!(r.old, key_a);
4406
    let key_a2 = r.new;
4407
    assert_eq!(
4408
        a.identity(&key_a2).unwrap().delegates,
4409
        vec![Delegate::full(key_b)]
4410
    );
4411
    assert_eq!(
4412
        a.identity(&key_a2).unwrap().ed25519_pk,
4413
        a.identity(&key_a).unwrap().ed25519_pk
4414
    );
4415
    assert!(
4416
        a.delegate_add(id_b.clone(), Scope::ALL, None).is_err(),
4417
        "already a delegate"
4418
    );
4419
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
4420
    origin.refresh().unwrap();
4421
    write(&root.join("a"), "a.txt", b"a3\n");
4422
    let h3 = a.commit("three", &[]).unwrap();
4423
    assert!(
4424
        matches!(a.verify_change(&h3).unwrap(), SignatureStatus::Valid { key, .. } if key == key_a2),
4425
        "the same secret signs under the new KeyId"
4426
    );
4427
    // A change authored by Ada but signed only by Bob verifies through the delegation.
4428
    a.set_user_config("core.sign", "seal").unwrap();
4429
    write(&root.join("a"), "a.txt", b"a4\n");
4430
    let h4 = a.commit("four", &[]).unwrap();
4431
    assert_eq!(a.verify_change(&h4).unwrap(), SignatureStatus::Unsigned);
4432
    let (_, sk_b) = b.secret_key().unwrap().unwrap();
4433
    a.store()
4434
        .put_signature(&h4, &sk_b.sign(Domain::Change, &key_b, &h4))
4435
        .unwrap();
4436
    assert!(
4437
        matches!(a.verify_change(&h4).unwrap(), SignatureStatus::Valid { key, .. } if key == key_b)
4438
    );
4439
    a.set_user_config("core.sign", "change").unwrap();
4440
    // Withdrawing the delegation re-issues the identity again.
4441
    let r = a.delegate_remove(&key_b).unwrap();
4442
    assert!(a.identity(&r.new).unwrap().delegates.is_empty());
4443
    assert!(a.delegate_remove(&key_b).is_err());
4444
    let key_a3 = r.new;
4445
    let res = a.push("origin", false).unwrap();
4446
    origin.refresh().unwrap();
4447
    assert!(res.iter().all(|x| x.ok), "{res:?}");
4448
4449
    // Multi-signer policy: Bob becomes a root and the threshold rises to 2,
4450
    // both applied under the old threshold of 1. A grant then needs Bob too.
4451
    assert!(a.policy_root_add(id_b.clone()).unwrap().applied);
4452
    assert!(a.policy_root_add(id_b.clone()).is_err());
4453
    assert!(a.policy_set_threshold(3).is_err());
4454
    assert!(a.policy_set_threshold(2).unwrap().applied);
4455
    assert!(a.push("origin", false).unwrap().iter().all(|x| x.ok));
4456
    origin.refresh().unwrap();
4457
    b.pull("origin").unwrap();
4458
    assert_eq!(
4459
        b.current_policy().unwrap().unwrap().1.policy.root_threshold,
4460
        2
4461
    );
4462
    let mut c = Repo::init(&root.join("c"))
4463
        .unwrap()
4464
        .with_home(root.join("home-c"));
4465
    let (key_c, id_c) = c
4466
        .create_identity("Cy", "[email protected]", IdentityScope::User)
4467
        .unwrap();
4468
    let serial_before = a.current_policy().unwrap().unwrap().1.policy.serial;
4469
    let proposal = a.policy_grant(id_c, None).unwrap();
4470
    assert!(!proposal.applied && proposal.sigs.len() == 1);
4471
    assert_eq!(proposal.policy.serial, serial_before + 1);
4472
    assert_eq!(
4473
        a.current_policy().unwrap().unwrap().1.policy.serial,
4474
        serial_before,
4475
        "a proposal changes nothing yet"
4476
    );
4477
    // Bob signs the proposal, handed over as a file, and it applies for him.
4478
    let bytes = proposal.signed().encode();
4479
    let signed = b
4480
        .policy_sign(SignedPolicy::decode(&bytes).unwrap())
4481
        .unwrap();
4482
    assert!(signed.applied && signed.sigs.len() == 2);
4483
    assert!(b
4484
        .current_policy()
4485
        .unwrap()
4486
        .unwrap()
4487
        .1
4488
        .policy
4489
        .authorizes(&key_c, "main"));
4490
    assert!(
4491
        b.policy_sign(signed.signed()).is_err(),
4492
        "a stale proposal is refused"
4493
    );
4494
    // Bob publishes it and Ada picks it up.
4495
    assert!(b
4496
        .push("origin", false)
4497
        .unwrap()
4498
        .iter()
4499
        .any(|x| x.name == "policy" && x.ok));
4500
    origin.refresh().unwrap();
4501
    a.pull("origin").unwrap();
4502
    assert_eq!(
4503
        a.current_policy().unwrap().unwrap().1.policy.serial,
4504
        serial_before + 1
4505
    );
4506
    // A root cannot revoke itself; revoking Cy needs both roots but is recorded locally at once.
4507
    assert!(a.policy_revoke(&key_a3).is_err());
4508
    let u = a
4509
        .revoke_identity(&key_c, "left the project")
4510
        .unwrap()
4511
        .unwrap();
4512
    assert!(!u.applied);
4513
    assert!(a.is_revoked(&key_c).unwrap());
4514
    assert!(!b.is_revoked(&key_c).unwrap());
4515
    let u = b.policy_sign(u.signed()).unwrap();
4516
    assert!(u.applied && u.policy.is_revoked(&key_c));
4517
    assert!(b.is_revoked(&key_c).unwrap());
4518
    // Bob can revoke Ada's root key, leaving himself as the only root (threshold 2 would be unmeetable).
4519
    assert!(
4520
        b.policy_revoke(&key_a3).is_err(),
4521
        "would leave one root for a threshold of 2"
4522
    );
4523
    // Revoking one's own key without a policy root works locally: a plain marker plus attestation.
4524
    let key_c_own = c.config.author_key.unwrap();
4525
    assert!(c
4526
        .revoke_identity(&key_c_own, "lost laptop")
4527
        .unwrap()
4528
        .is_none());
4529
    assert!(c.is_revoked(&key_c_own).unwrap());
4530
    assert_eq!(key_c_own, key_c);
4531
}
4532
4533
#[test]
4534
fn renames_are_detected_and_tracked_as_moves() {
4535
    hermetic();
4536
    let dir = tempfile::tempdir().unwrap();
4537
    let root = dir.path();
4538
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4539
    write(
4540
        root,
4541
        "src/old.rs",
4542
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n",
4543
    );
4544
    write(root, "img.bin", b"\x89PNG\0\0\x01\x02");
4545
    write(root, "tiny.txt", b"x\n");
4546
    let h1 = repo.commit("base", &[]).unwrap();
4547
    let node_old = repo.load_state(&[h1]).unwrap().materialize().files["src/old.rs"].node;
4548
    let node_img = repo.load_state(&[h1]).unwrap().materialize().files["img.bin"].node;
4549
4550
    // Rename with a small edit, a binary moved unchanged, and a rewrite
4551
    // that shares nothing with the removed file.
4552
    fs::remove_file(root.join("src/old.rs")).unwrap();
4553
    write(
4554
        root,
4555
        "lib/new.rs",
4556
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n",
4557
    );
4558
    fs::remove_file(root.join("img.bin")).unwrap();
4559
    write(root, "assets/img.bin", b"\x89PNG\0\0\x01\x02");
4560
    fs::remove_file(root.join("tiny.txt")).unwrap();
4561
    write(root, "other.txt", b"completely different\n");
4562
    let snap = repo.snapshot("status").unwrap();
4563
    let statuses: Vec<(&str, ChangeStatus)> = snap
4564
        .statuses
4565
        .iter()
4566
        .map(|s| (s.path.as_str(), s.status))
4567
        .collect();
4568
    assert_eq!(
4569
        statuses,
4570
        vec![
4571
            ("assets/img.bin", ChangeStatus::Renamed),
4572
            ("lib/new.rs", ChangeStatus::Renamed),
4573
            ("other.txt", ChangeStatus::Added),
4574
            ("src", ChangeStatus::Removed),
4575
            ("tiny.txt", ChangeStatus::Removed)
4576
        ]
4577
    );
4578
    let h2 = repo.commit("move things", &[]).unwrap();
4579
    let c = repo.store().get_change(&h2).unwrap();
4580
    let moves: Vec<_> = c
4581
        .tree_ops
4582
        .iter()
4583
        .filter(|op| matches!(op, TreeOp::Move { .. }))
4584
        .collect();
4585
    assert_eq!(moves.len(), 2, "{:?}", c.tree_ops);
4586
    assert!(c.tree_ops.iter().any(
4587
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_old && name == "new.rs")
4588
    ));
4589
    assert!(c.tree_ops.iter().any(
4590
        |op| matches!(op, TreeOp::Move { node, name, .. } if *node == node_img && name == "img.bin")
4591
    ));
4592
    let snap = repo.load_state(&[h2]).unwrap().materialize();
4593
    assert_eq!(
4594
        snap.files["lib/new.rs"].node, node_old,
4595
        "the node survives the rename"
4596
    );
4597
    assert!(
4598
        matches!(&snap.files["lib/new.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n")
4599
    );
4600
    assert!(!snap.files.contains_key("src/old.rs") && !snap.files.contains_key("src"));
4601
    assert!(render_change(
4602
        &c,
4603
        &repo.load_state(&[h1]).unwrap(),
4604
        &repo.load_state(&[h1]).unwrap().materialize()
4605
    )
4606
    .contains("R src/old.rs -> lib/new.rs"));
4607
    // A fresh checkout reproduces the tree.
4608
    let other = tempfile::tempdir().unwrap();
4609
    let clone = Repo::clone(&root.to_string_lossy(), other.path()).unwrap();
4610
    assert_eq!(
4611
        fs::read(other.path().join("lib/new.rs")).unwrap(),
4612
        b"fn a() {}\nfn b() {}\nfn c() {}\nfn e() {}\n"
4613
    );
4614
    assert!(!other.path().join("src").exists());
4615
    assert!(!clone.snapshot("status").unwrap().changed);
4616
    // Similarity is line based, byte weighted.
4617
    assert_eq!(similarity(b"a\nb\n", b"a\nb\n"), 100);
4618
    assert_eq!(similarity(b"a\nb\nc\nd\n", b"a\nb\nx\ny\n"), 50);
4619
    assert_eq!(similarity(b"hello\n", b"world\n"), 0);
4620
    assert_eq!(similarity(b"", b"x\n"), 0);
4621
}
4622
4623
#[test]
4624
fn git_fetch_and_push_round_trip() {
4625
    hermetic();
4626
    if std::process::Command::new("git")
4627
        .arg("--version")
4628
        .output()
4629
        .is_err()
4630
    {
4631
        eprintln!("git not installed; skipping");
4632
        return;
4633
    }
4634
    let dir = tempfile::tempdir().unwrap();
4635
    let root = dir.path();
4636
    let git_in = |d: &Path, args: &[&str]| -> String {
4637
        let out = std::process::Command::new("git")
4638
            .arg("-C")
4639
            .arg(d)
4640
            .args([
4641
                "-c",
4642
                "user.name=Grace",
4643
                "-c",
4644
                "[email protected]",
4645
                "-c",
4646
                "commit.gpgsign=false",
4647
            ])
4648
            .args(args)
4649
            .output()
4650
            .unwrap();
4651
        assert!(
4652
            out.status.success(),
4653
            "git {args:?}: {}",
4654
            String::from_utf8_lossy(&out.stderr)
4655
        );
4656
        String::from_utf8_lossy(&out.stdout).trim().to_string()
4657
    };
4658
    // A bare "remote" and a work tree that pushes to it.
4659
    let remote = root.join("remote.git");
4660
    fs::create_dir_all(&remote).unwrap();
4661
    git_in(&remote, &["init", "-q", "--bare", "-b", "main"]);
4662
    let work = root.join("work");
4663
    git_in(
4664
        root,
4665
        &[
4666
            "clone",
4667
            "-q",
4668
            remote.to_str().unwrap(),
4669
            work.to_str().unwrap(),
4670
        ],
4671
    );
4672
    git_in(&work, &["checkout", "-q", "-b", "main"]);
4673
    write(&work, "README.md", b"# Project\n");
4674
    write(&work, "src/lib.rs", b"pub fn a() {}\n");
4675
    git_in(&work, &["add", "."]);
4676
    git_in(&work, &["commit", "-q", "-m", "initial"]);
4677
    write(&work, "src/lib.rs", b"pub fn a() {}\npub fn b() {}\n");
4678
    git_in(&work, &["commit", "-q", "-am", "second"]);
4679
    git_in(&work, &["push", "-q", "origin", "main"]);
4680
    let tip1 = git_in(&work, &["rev-parse", "HEAD"]);
4681
4682
    // Fetch into a fresh oxy repository.
4683
    let o = root.join("oxy");
4684
    let mut repo = Repo::init(&o).unwrap().with_home(root.join("home"));
4685
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
4686
        .unwrap();
4687
    let url = remote.to_string_lossy().to_string();
4688
    let r = repo.git_fetch(&url, "main").unwrap();
4689
    assert_eq!((r.commits, r.heads), (2, 1));
4690
    assert_eq!(
4691
        fs::read(o.join("src/lib.rs")).unwrap(),
4692
        b"pub fn a() {}\npub fn b() {}\n"
4693
    );
4694
    assert!(!repo.snapshot("status").unwrap().changed);
4695
    assert_eq!(
4696
        repo.git_fetch(&url, "main").unwrap().commits,
4697
        0,
4698
        "nothing new"
4699
    );
4700
4701
    // An oxy change, pushed back: one commit on top of the Git tip.
4702
    write(
4703
        &o,
4704
        "src/lib.rs",
4705
        b"pub fn a() {}\npub fn b() {}\npub fn c() {}\n",
4706
    );
4707
    write(&o, "NOTES.md", b"from oxy\n");
4708
    let h_oxy = repo.commit("add c and notes", &[]).unwrap();
4709
    let r = repo.git_push(&url, "main").unwrap();
4710
    assert_eq!(r.exported, 1, "{r:?}");
4711
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
4712
    assert_eq!(
4713
        git_in(&work, &["log", "--format=%s", "main"]),
4714
        "add c and notes\nsecond\ninitial"
4715
    );
4716
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip1);
4717
    assert_eq!(fs::read(work.join("NOTES.md")).unwrap(), b"from oxy\n");
4718
    assert_eq!(git_in(&work, &["log", "-1", "--format=%an", "main"]), "Ada");
4719
    assert!(git_in(&work, &["log", "-1", "--format=%B", "main"])
4720
        .contains(&format!("Oxy-Hash: {}", h_oxy.to_hex())));
4721
    assert_eq!(
4722
        repo.git_push(&url, "main").unwrap().exported,
4723
        0,
4724
        "already pushed"
4725
    );
4726
4727
    // Git moves on; pushing without fetching is refused, fetching brings
4728
    // the commit in and the working copy follows.
4729
    write(&work, "README.md", b"# Project\n\nMore.\n");
4730
    git_in(&work, &["commit", "-q", "-am", "readme from git"]);
4731
    git_in(&work, &["push", "-q", "origin", "main"]);
4732
    let tip2 = git_in(&work, &["rev-parse", "HEAD"]);
4733
    assert!(repo
4734
        .git_push(&url, "main")
4735
        .unwrap_err()
4736
        .to_string()
4737
        .contains("fetch"));
4738
    let r = repo.git_fetch(&url, "main").unwrap();
4739
    assert_eq!(
4740
        (r.commits, r.heads),
4741
        (1, 2),
4742
        "the Git change and the oxy change commute"
4743
    );
4744
    assert_eq!(
4745
        fs::read(o.join("README.md")).unwrap(),
4746
        b"# Project\n\nMore.\n"
4747
    );
4748
    assert_eq!(fs::read(o.join("NOTES.md")).unwrap(), b"from oxy\n");
4749
    assert!(!repo.snapshot("status").unwrap().changed);
4750
    // Another oxy change pushes on top of Git's newest commit.
4751
    write(&o, "NOTES.md", b"from oxy\nagain\n");
4752
    repo.commit("notes again", &[]).unwrap();
4753
    assert_eq!(repo.git_push(&url, "main").unwrap().exported, 1);
4754
    git_in(&work, &["pull", "-q", "--ff-only", "origin", "main"]);
4755
    assert_eq!(git_in(&work, &["rev-parse", "HEAD~1"]), tip2);
4756
    assert_eq!(
4757
        fs::read(work.join("NOTES.md")).unwrap(),
4758
        b"from oxy\nagain\n"
4759
    );
4760
    assert_eq!(
4761
        git_in(&work, &["log", "--format=%s", "main"])
4762
            .lines()
4763
            .count(),
4764
        5
4765
    );
4766
}
4767
4768
/// Benchmark, not a gate: `cargo test --release -p oxy-core --lib bench_one_gibibyte -- --ignored --nocapture`.
4769
/// Commits, stores, clones, and reads back a 1 GiB incompressible file.
4770
#[test]
4771
#[ignore]
4772
fn bench_one_gibibyte_file() {
4773
    hermetic();
4774
    // /tmp is often a small tmpfs; `OXY_BENCH_DIR` picks a roomier disk.
4775
    let dir = match std::env::var_os("OXY_BENCH_DIR") {
4776
        Some(d) => tempfile::tempdir_in(d).unwrap(),
4777
        None => tempfile::tempdir().unwrap(),
4778
    };
4779
    let root = dir.path();
4780
    let repo = Repo::init(&root.join("r"))
4781
        .unwrap()
4782
        .with_home(root.join("home"));
4783
    let size = 1usize << 30;
4784
    let mut data = vec![0u8; size];
4785
    let mut x = 0x9e3779b97f4a7c15u64;
4786
    for chunk in data.chunks_mut(8) {
4787
        x ^= x << 13;
4788
        x ^= x >> 7;
4789
        x ^= x << 17;
4790
        let b = x.to_le_bytes();
4791
        chunk.copy_from_slice(&b[..chunk.len()]);
4792
    }
4793
    let t = std::time::Instant::now();
4794
    write(&root.join("r"), "big.bin", &data);
4795
    eprintln!("write 1 GiB to disk: {:.2?}", t.elapsed());
4796
    let t = std::time::Instant::now();
4797
    let h = repo.commit("big", &[]).unwrap();
4798
    eprintln!("commit (chunk + hash + store): {:.2?}", t.elapsed());
4799
    let t = std::time::Instant::now();
4800
    assert!(!repo.snapshot("status").unwrap().changed);
4801
    eprintln!("status on a clean 1 GiB working copy: {:.2?}", t.elapsed());
4802
    let t = std::time::Instant::now();
4803
    let objects = repo.store().list().unwrap().len();
4804
    eprintln!("objects stored: {objects} ({:.2?} to list)", t.elapsed());
4805
    let t = std::time::Instant::now();
4806
    let g = repo.gc(true).unwrap();
4807
    eprintln!("gc (pack): {:.2?} {g:?}", t.elapsed());
4808
    let t = std::time::Instant::now();
4809
    let clone = Repo::clone(&root.join("r").to_string_lossy(), &root.join("c")).unwrap();
4810
    eprintln!("clone (fetch + checkout): {:.2?}", t.elapsed());
4811
    let t = std::time::Instant::now();
4812
    let back = fs::read(root.join("c/big.bin")).unwrap();
4813
    assert_eq!(blake3::hash(&back), blake3::hash(&data));
4814
    eprintln!("read back and verify: {:.2?}", t.elapsed());
4815
    assert_eq!(clone.bookmark_heads().unwrap(), vec![h]);
4816
    let store_bytes: u64 = walkdir_size(&root.join("r/.oxy/objects"));
4817
    eprintln!(
4818
        "store size: {:.1} MiB for 1 GiB of data",
4819
        store_bytes as f64 / (1024.0 * 1024.0)
4820
    );
4821
}
4822
4823
fn walkdir_size(p: &Path) -> u64 {
4824
    let mut total = 0;
4825
    if let Ok(rd) = fs::read_dir(p) {
4826
        for e in rd.flatten() {
4827
            let path = e.path();
4828
            if path.is_dir() {
4829
                total += walkdir_size(&path);
4830
            } else if let Ok(m) = fs::metadata(&path) {
4831
                total += m.len();
4832
            }
4833
        }
4834
    }
4835
    total
4836
}
4837
4838
/// An opaque file whose size and mtime match the manifest is not read on
4839
/// the next snapshot: its blob comes from the manifest's stat cache.
4840
#[cfg(unix)]
4841
#[test]
4842
fn stat_cache_skips_reading_unchanged_opaque_files() {
4843
    use std::os::unix::fs::PermissionsExt;
4844
    hermetic();
4845
    let dir = tempfile::tempdir().unwrap();
4846
    let root = dir.path();
4847
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4848
    let mut big = vec![0u8; 300 * 1024];
4849
    for (i, b) in big.iter_mut().enumerate() {
4850
        *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[1];
4851
    }
4852
    big[0] = 0;
4853
    write(root, "big.bin", &big);
4854
    write(root, "a.txt", b"text\n");
4855
    let h1 = repo.commit("base", &[]).unwrap();
4856
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4857
    assert!(
4858
        m.entries["big.bin"].blob.is_some(),
4859
        "opaque files record their blob"
4860
    );
4861
    assert!(m.entries["a.txt"].blob.is_none());
4862
    let blob = m.entries["big.bin"].blob.unwrap();
4863
    assert!(repo.store().has(&blob));
4864
4865
    // Files modified within two seconds of the manifest are racy and still
4866
    // read; age the file so the cache applies, then snapshot to record it.
4867
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
4868
    fs::File::options()
4869
        .write(true)
4870
        .open(root.join("big.bin"))
4871
        .unwrap()
4872
        .set_modified(old)
4873
        .unwrap();
4874
    assert!(!repo.snapshot("status").unwrap().changed);
4875
    // Now the file cannot be read at all; the snapshot succeeds without it.
4876
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o000)).unwrap();
4877
    let snap = repo.snapshot("status").unwrap();
4878
    assert!(
4879
        !snap.changed && snap.statuses.is_empty(),
4880
        "{:?}",
4881
        snap.statuses
4882
    );
4883
    fs::set_permissions(root.join("big.bin"), fs::Permissions::from_mode(0o644)).unwrap();
4884
    // A real change (new mtime, new content) is seen and committed correctly.
4885
    let mut big2 = big.clone();
4886
    big2[10] ^= 0xff;
4887
    write(root, "big.bin", &big2);
4888
    let snap = repo.snapshot("status").unwrap();
4889
    assert_eq!(
4890
        snap.statuses
4891
            .iter()
4892
            .map(|s| (s.path.as_str(), s.status))
4893
            .collect::<Vec<_>>(),
4894
        vec![("big.bin", ChangeStatus::Modified)]
4895
    );
4896
    let h2 = repo.commit("edit", &[]).unwrap();
4897
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
4898
    assert_eq!(
4899
        files["big.bin"].content,
4900
        FileContent::Opaque {
4901
            blobs: vec![Repo::blob_ref(&big2)]
4902
        }
4903
    );
4904
    // Checkout writes a manifest with blobs too, so the next status is cached.
4905
    repo.checkout(&[h1], false, "checkout").unwrap();
4906
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
4907
    assert_eq!(m.entries["big.bin"].blob, Some(Repo::blob_ref(&big)));
4908
    assert!(!repo.snapshot("status").unwrap().changed);
4909
}
4910
4911
#[test]
4912
fn status_json_lists_conflicts_with_contributors() {
4913
    hermetic();
4914
    let dir = tempfile::tempdir().unwrap();
4915
    let root = dir.path();
4916
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4917
    write(root, "a.txt", b"one\n");
4918
    let h1 = repo.commit("base", &[]).unwrap();
4919
    write(root, "a.txt", b"one\nleft\n");
4920
    let ha = repo.commit("left", &[]).unwrap();
4921
    repo.checkout(&[h1], true, "checkout").unwrap();
4922
    write(root, "a.txt", b"one\nright\n");
4923
    let hb = repo.commit("right", &[]).unwrap();
4924
    repo.checkout(&[ha, hb], true, "checkout").unwrap();
4925
    let snap = repo.snapshot("status").unwrap();
4926
    assert!(snap.base_snapshot.is_conflicted());
4927
    let json = repo.status_json(&snap).unwrap();
4928
    let ida = repo.store().get_change(&ha).unwrap().change_id.to_hex();
4929
    let idb = repo.store().get_change(&hb).unwrap().change_id.to_hex();
4930
    assert!(json.contains("\"conflicted\":true"), "{json}");
4931
    assert!(
4932
        json.contains("\"kind\":\"text\",\"path\":\"a.txt\""),
4933
        "{json}"
4934
    );
4935
    assert!(json.contains(&ida) && json.contains(&idb), "{json}");
4936
    assert!(json.contains("\"resolved\":false"), "{json}");
4937
    assert!(json.starts_with('{') && json.ends_with('}'));
4938
    // Resolve and the report says so; a clean copy has no conflicts.
4939
    write(root, "a.txt", b"one\nleft\nright\n");
4940
    let snap = repo.snapshot("status").unwrap();
4941
    let json = repo.status_json(&snap).unwrap();
4942
    assert!(json.contains("\"resolved\":true"), "{json}");
4943
    repo.commit("resolve", &[]).unwrap();
4944
    let snap = repo.snapshot("status").unwrap();
4945
    let json = repo.status_json(&snap).unwrap();
4946
    assert!(
4947
        json.contains("\"clean\":true,\"conflicted\":false,\"paths\":[],\"conflicts\":[]"),
4948
        "{json}"
4949
    );
4950
}
4951
4952
#[test]
4953
fn ignore_rules_do_not_untrack_files() {
4954
    hermetic();
4955
    let dir = tempfile::tempdir().unwrap();
4956
    let root = dir.path();
4957
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
4958
    write(root, "src.c", b"int x;\n");
4959
    write(root, "build/out.o", b"\0obj");
4960
    write(root, "sub/keep.log", b"keep\n");
4961
    write(root, "sub/junk.log", b"junk\n");
4962
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\n");
4963
    let snap = repo.snapshot("status").unwrap();
4964
    let added: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
4965
    assert_eq!(
4966
        added,
4967
        vec![".oxyignore", "src.c", "sub/keep.log"],
4968
        "anchored, glob, and negated rules"
4969
    );
4970
    let h1 = repo.commit("base", &[]).unwrap();
4971
    // Ignoring a tracked file changes nothing about it.
4972
    write(root, ".oxyignore", b"/build\n*.log\n!sub/keep.log\nsrc.c\n");
4973
    let snap = repo.snapshot("status").unwrap();
4974
    assert_eq!(
4975
        snap.statuses
4976
            .iter()
4977
            .map(|s| s.path.as_str())
4978
            .collect::<Vec<_>>(),
4979
        vec![".oxyignore"]
4980
    );
4981
    let h2 = repo.commit("ignore src.c", &[]).unwrap();
4982
    assert!(repo
4983
        .load_state(&[h2])
4984
        .unwrap()
4985
        .materialize()
4986
        .files
4987
        .contains_key("src.c"));
4988
    // Its edits are still seen, by status and by the prompt.
4989
    assert_eq!(repo.quick_dirty().unwrap(), Some(false));
4990
    write(root, "src.c", b"int x, y;\n");
4991
    assert_eq!(repo.quick_dirty().unwrap(), Some(true));
4992
    let snap = repo.snapshot("status").unwrap();
4993
    assert_eq!(
4994
        snap.statuses
4995
            .iter()
4996
            .map(|s| (s.path.as_str(), s.status))
4997
            .collect::<Vec<_>>(),
4998
        vec![("src.c", ChangeStatus::Modified)]
4999
    );
5000
    let h3 = repo.commit("edit src.c", &[]).unwrap();
5001
    assert!(
5002
        matches!(&repo.load_state(&[h3]).unwrap().materialize().files["src.c"].content, FileContent::Text { bytes, .. } if bytes == b"int x, y;\n")
5003
    );
5004
    // Deleting it on disk removes it, ignored or not; a checkout brings it back.
5005
    fs::remove_file(root.join("src.c")).unwrap();
5006
    let snap = repo.snapshot("status").unwrap();
5007
    assert_eq!(
5008
        snap.statuses
5009
            .iter()
5010
            .map(|s| (s.path.as_str(), s.status))
5011
            .collect::<Vec<_>>(),
5012
        vec![("src.c", ChangeStatus::Removed)]
5013
    );
5014
    repo.checkout(&[h3], true, "checkout").unwrap();
5015
    assert_eq!(fs::read(root.join("src.c")).unwrap(), b"int x, y;\n");
5016
    assert!(!repo.snapshot("status").unwrap().changed);
5017
    let _ = h1;
5018
}
5019
5020
#[test]
5021
fn split_works_on_non_heads_by_node() {
5022
    hermetic();
5023
    let dir = tempfile::tempdir().unwrap();
5024
    let root = dir.path();
5025
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5026
    write(root, "a.txt", b"one\n");
5027
    write(root, "junk/x.lock", b"lock\n");
5028
    let h1 = repo.commit("work plus junk", &[]).unwrap();
5029
    write(root, "a.txt", b"one\ntwo\n");
5030
    let h2 = repo.commit("more work", &[]).unwrap();
5031
    assert_eq!(repo.store().get_change(&h2).unwrap().deps, vec![h1]);
5032
    let id1 = repo.store().get_change(&h1).unwrap().change_id;
5033
    // h1 is not a head: split it by node.
5034
    let (hj, h1b) = repo.split(&h1, &["junk".into()]).unwrap();
5035
    assert_ne!(h1b, h1);
5036
    assert_eq!(
5037
        repo.store().get_change(&h1b).unwrap().change_id,
5038
        id1,
5039
        "the rest keeps the ChangeId"
5040
    );
5041
    let junk = repo.store().get_change(&hj).unwrap();
5042
    assert!(junk.tree_ops.iter().all(
5043
        |op| matches!(op, TreeOp::AddNode { name, .. } if name == "junk" || name == "x.lock")
5044
    ));
5045
    let heads = repo.bookmark_heads().unwrap();
5046
    assert!(
5047
        heads.contains(&hj),
5048
        "the split-off part is a head of its own"
5049
    );
5050
    let snap = repo.load_state(&heads).unwrap().materialize();
5051
    assert!(
5052
        matches!(&snap.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"one\ntwo\n"),
5053
        "the dependent was rewritten onto the new hash"
5054
    );
5055
    assert!(snap.files.contains_key("junk/x.lock"));
5056
    let h2b = heads
5057
        .iter()
5058
        .find(|h| repo.store().get_change(h).unwrap().message == "more work")
5059
        .copied()
5060
        .unwrap();
5061
    assert_eq!(repo.store().get_change(&h2b).unwrap().deps, vec![h1b]);
5062
    assert!(!repo.snapshot("status").unwrap().changed);
5063
    // Abandoning the split-off head removes the junk from history.
5064
    repo.abandon(&hj).unwrap();
5065
    let heads = repo.bookmark_heads().unwrap();
5066
    let snap = repo.load_state(&heads).unwrap().materialize();
5067
    assert!(!snap.files.contains_key("junk/x.lock") && !snap.files.contains_key("junk"));
5068
    assert!(snap.files.contains_key("a.txt"));
5069
    // A dependent that touches the split-off paths blocks the split.
5070
    write(root, "junk/y.lock", b"y\n");
5071
    let hb = repo.commit("junk base", &[]).unwrap();
5072
    write(root, "junk/y.lock", b"yy\n");
5073
    write(root, "b.txt", b"b\n");
5074
    repo.commit("touches junk", &[]).unwrap();
5075
    let err = repo.split(&hb, &["junk".into()]).unwrap_err().to_string();
5076
    assert!(err.contains("depends on the split-off paths"), "{err}");
5077
}
5078
5079
#[test]
5080
fn bookmarks_switch_merge_and_push() {
5081
    hermetic();
5082
    let dir = tempfile::tempdir().unwrap();
5083
    let root = dir.path();
5084
    let origin = Repo::init(&root.join("origin")).unwrap();
5085
    let url = root.join("origin").to_string_lossy().to_string();
5086
    let mut repo = Repo::clone(&url, &root.join("r"))
5087
        .unwrap()
5088
        .with_home(root.join("home"));
5089
    let r = root.join("r");
5090
    write(&r, "a.txt", b"a\n");
5091
    let h_a = repo.commit("a", &[]).unwrap();
5092
    assert!(repo.push("origin", false).unwrap()[0].ok);
5093
    origin.refresh().unwrap();
5094
5095
    // A bookmark at the working copy's base, then work on it.
5096
    assert!(repo.bookmark_create("bad name..", None).is_err());
5097
    assert!(repo.bookmark_create("-x", None).is_err());
5098
    assert_eq!(repo.bookmark_create("feature", None).unwrap(), vec![h_a]);
5099
    assert!(repo.bookmark_create("feature", None).is_err(), "exists");
5100
    repo.bookmark_switch("feature", false).unwrap();
5101
    assert_eq!(repo.config.bookmark, "feature");
5102
    write(&r, "a.txt", b"a\nb\n");
5103
    write(&r, "b.txt", b"b\n");
5104
    let h_b = repo.commit("b on feature", &[]).unwrap();
5105
    assert_eq!(
5106
        repo.bookmark_heads().unwrap(),
5107
        vec![h_b],
5108
        "b edits a.txt, so it depends on a"
5109
    );
5110
    assert_eq!(
5111
        repo.resolve_heads("main").unwrap(),
5112
        vec![h_a],
5113
        "main is untouched"
5114
    );
5115
    assert_eq!(
5116
        repo.resolve_change("feature").unwrap(),
5117
        h_b,
5118
        "a one-head bookmark names its change"
5119
    );
5120
    // Reopening keeps the workspace's bookmark.
5121
    let reopened = Repo::open(&r).unwrap().with_home(root.join("home"));
5122
    assert_eq!(reopened.config.bookmark, "feature");
5123
    // Back to main: b.txt goes away; work there.
5124
    repo.bookmark_switch("main", false).unwrap();
5125
    assert!(!r.join("b.txt").exists());
5126
    assert_eq!(fs::read(r.join("a.txt")).unwrap(), b"a\n");
5127
    write(&r, "c.txt", b"c\n");
5128
    let h_c = repo.commit("c on main", &[]).unwrap();
5129
    let list = repo.bookmarks().unwrap();
5130
    assert_eq!(
5131
        list.iter()
5132
            .map(|b| (b.name.as_str(), b.current))
5133
            .collect::<Vec<_>>(),
5134
        vec![("feature", false), ("main", true)]
5135
    );
5136
    assert_eq!(
5137
        list.iter().find(|b| b.name == "main").unwrap().ahead,
5138
        Some(1),
5139
        "c is not on origin yet"
5140
    );
5141
    // Merge feature into main: the union, both heads, no merge change.
5142
    let m = repo.merge("feature").unwrap();
5143
    assert!(m.changed && m.checked_out);
5144
    let mut want = vec![h_b, h_c];
5145
    want.sort();
5146
    assert_eq!(m.heads, want);
5147
    assert_eq!(fs::read(r.join("b.txt")).unwrap(), b"b\n");
5148
    assert!(!repo.merge("feature").unwrap().changed, "already merged");
5149
    assert!(repo.merge("main").is_err());
5150
    // The other bookmark can be pushed by name and appears at origin.
5151
    assert!(repo.push_bookmark("origin", "feature", false).unwrap()[0].ok);
5152
    origin.refresh().unwrap();
5153
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_b]);
5154
    assert!(repo.push("origin", false).unwrap()[0].ok);
5155
    origin.refresh().unwrap();
5156
    assert_eq!(
5157
        repo.bookmarks()
5158
            .unwrap()
5159
            .iter()
5160
            .find(|b| b.name == "main")
5161
            .unwrap()
5162
            .ahead,
5163
        Some(0)
5164
    );
5165
    // A second workspace inherits the current bookmark and can switch independently.
5166
    let ws = repo.workspace_add(&root.join("ws"), None).unwrap();
5167
    assert_eq!(ws.config.bookmark, "main");
5168
    let mut ws = ws;
5169
    ws.bookmark_switch("feature", false).unwrap();
5170
    assert_eq!(
5171
        Repo::open(&r).unwrap().config.bookmark,
5172
        "main",
5173
        "the first workspace is unaffected"
5174
    );
5175
    assert!(
5176
        repo.bookmark_delete("feature").is_err(),
5177
        "current bookmark of another workspace"
5178
    );
5179
    ws.bookmark_switch("main", false).unwrap();
5180
    // Set and delete.
5181
    assert_eq!(repo.bookmark_set("feature", &[h_a]).unwrap(), vec![h_a]);
5182
    assert!(repo.bookmark_delete("main").is_err(), "current here");
5183
    repo.bookmark_delete("feature").unwrap();
5184
    assert!(repo.resolve_heads("feature").is_err());
5185
    assert!(repo.bookmark_set("feature", &[h_a]).is_err());
5186
    assert!(
5187
        repo.checkout(&[h_a], false, "checkout").is_ok(),
5188
        "changes of a deleted bookmark remain"
5189
    );
5190
}
5191
5192
#[test]
5193
fn oxygen_subrepos_pin_follow_and_update() {
5194
    hermetic();
5195
    let dir = tempfile::tempdir().unwrap();
5196
    let root = dir.path();
5197
    // A library repository with two commits, and a bare-ish origin for it.
5198
    let lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
5199
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
5200
    let lib = Repo::clone(&lib_url, &root.join("lib"))
5201
        .unwrap()
5202
        .with_home(root.join("home"));
5203
    write(&root.join("lib"), "lib.txt", b"v1\n");
5204
    let l1 = lib.commit("lib v1", &[]).unwrap();
5205
    assert!(lib.push("origin", false).unwrap()[0].ok);
5206
    let _ = lib_origin;
5207
5208
    // The application (a clone of its own origin) adds it as a subrepo.
5209
    let app_origin = Repo::init(&root.join("app-origin")).unwrap();
5210
    let app_url = root.join("app-origin").to_string_lossy().to_string();
5211
    let _ = app_origin;
5212
    let app_dir = root.join("app");
5213
    let app = Repo::clone(&app_url, &app_dir)
5214
        .unwrap()
5215
        .with_home(root.join("home"));
5216
    write(&app_dir, "main.txt", b"app\n");
5217
    let pin = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
5218
    assert!(matches!(&pin, crate::subrepo::Pin::Oxy { heads, .. } if heads == &vec![l1]));
5219
    assert!(app_dir.join(".oxymodules").exists() && app_dir.join("libs/lib/.oxy").is_dir());
5220
    let snap = app.snapshot("status").unwrap();
5221
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
5222
    assert_eq!(
5223
        paths,
5224
        vec![".oxymodules", "libs/lib", "main.txt"],
5225
        "the nested files are not walked"
5226
    );
5227
    let a1 = app.commit("app with lib", &[]).unwrap();
5228
    let files = app.load_state(&[a1]).unwrap().materialize().files;
5229
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
5230
    assert!(!files.contains_key("libs/lib/lib.txt"));
5231
    assert!(!app.snapshot("status").unwrap().changed);
5232
    let subs = app.subrepos().unwrap();
5233
    assert_eq!(subs.len(), 1);
5234
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
5235
5236
    // Advance the nested repository: the parent sees a modified pin.
5237
    let nested = Repo::open(&app_dir.join("libs/lib"))
5238
        .unwrap()
5239
        .with_home(root.join("home"));
5240
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
5241
    let l2 = nested.commit("lib v2", &[]).unwrap();
5242
    assert!(nested.push("origin", false).unwrap()[0].ok);
5243
    let snap = app.snapshot("status").unwrap();
5244
    assert_eq!(
5245
        snap.statuses
5246
            .iter()
5247
            .map(|s| (s.path.as_str(), s.status))
5248
            .collect::<Vec<_>>(),
5249
        vec![("libs/lib", ChangeStatus::Modified)]
5250
    );
5251
    let a2 = app.commit("bump lib", &[]).unwrap();
5252
    // Checking out the older app state brings the nested working copy back
5253
    // to the older pin, but never moves its bookmark backwards (oxygen#38).
5254
    let r = app.checkout(&[a1], false, "checkout").unwrap();
5255
    assert!(
5256
        r.notes.len() == 1 && r.notes[0].contains("keeps 1 newer change"),
5257
        "{:?}",
5258
        r.notes
5259
    );
5260
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
5261
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
5262
    assert_eq!(nested.bookmark_heads().unwrap(), vec![l2]);
5263
    assert_eq!(nested.working_copy().unwrap().1.deps, vec![l1]);
5264
    assert!(!app.snapshot("status").unwrap().changed);
5265
    // A dirty nested repository is left alone and reported.
5266
    write(&app_dir.join("libs/lib"), "scratch.txt", b"wip\n");
5267
    let r = app.checkout(&[a2], false, "checkout").unwrap();
5268
    assert!(
5269
        r.notes.iter().any(|n| n.contains("uncommitted")),
5270
        "{:?}",
5271
        r.notes
5272
    );
5273
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v1\n");
5274
    fs::remove_file(app_dir.join("libs/lib/scratch.txt")).unwrap();
5275
    let r = app.submodule_update(false, &[]).unwrap();
5276
    assert_eq!(r, vec![("libs/lib".to_string(), SubrepoSync::Updated)]);
5277
    assert_eq!(fs::read(app_dir.join("libs/lib/lib.txt")).unwrap(), b"v2\n");
5278
    let _ = l2;
5279
5280
    // A fresh clone of the app has the pin but no nested repository until update --init.
5281
    assert!(app.push("origin", false).unwrap()[0].ok);
5282
    let clone_dir = root.join("app-clone");
5283
    let clone = Repo::clone(&app_url, &clone_dir)
5284
        .unwrap()
5285
        .with_home(root.join("home"));
5286
    assert!(!clone_dir.join("libs/lib/.oxy").exists());
5287
    assert_eq!(
5288
        clone.submodule_update(false, &[]).unwrap(),
5289
        vec![("libs/lib".to_string(), SubrepoSync::Missing)]
5290
    );
5291
    assert_eq!(
5292
        clone.submodule_update(true, &[]).unwrap(),
5293
        vec![("libs/lib".to_string(), SubrepoSync::Updated)]
5294
    );
5295
    assert_eq!(
5296
        fs::read(clone_dir.join("libs/lib/lib.txt")).unwrap(),
5297
        b"v2\n"
5298
    );
5299
    assert!(!clone.snapshot("status").unwrap().changed);
5300
    // Removing the subrepo leaves the directory and drops the node.
5301
    clone.submodule_remove("libs/lib").unwrap();
5302
    let snap = clone.snapshot("status").unwrap();
5303
    assert!(
5304
        snap.statuses
5305
            .iter()
5306
            .any(|s| s.path == "libs/lib" && s.status == ChangeStatus::Removed),
5307
        "{:?}",
5308
        snap.statuses
5309
    );
5310
    let c = clone.commit("drop lib", &[]).unwrap();
5311
    assert!(!clone
5312
        .load_state(&[c])
5313
        .unwrap()
5314
        .materialize()
5315
        .files
5316
        .contains_key("libs/lib"));
5317
    assert!(clone_dir.join("libs/lib/lib.txt").exists());
5318
    assert!(
5319
        !clone.snapshot("status").unwrap().changed,
5320
        "an unregistered nested repository is ignored"
5321
    );
5322
}
5323
5324
#[test]
5325
fn git_submodules_import_and_export_as_gitlinks() {
5326
    hermetic();
5327
    if std::process::Command::new("git")
5328
        .arg("--version")
5329
        .output()
5330
        .is_err()
5331
    {
5332
        eprintln!("git not installed; skipping");
5333
        return;
5334
    }
5335
    let dir = tempfile::tempdir().unwrap();
5336
    let root = dir.path();
5337
    let git_in = |d: &Path, args: &[&str]| -> String {
5338
        let out = std::process::Command::new("git")
5339
            .arg("-C")
5340
            .arg(d)
5341
            .args([
5342
                "-c",
5343
                "user.name=Grace",
5344
                "-c",
5345
                "[email protected]",
5346
                "-c",
5347
                "commit.gpgsign=false",
5348
                "-c",
5349
                "protocol.file.allow=always",
5350
            ])
5351
            .args(args)
5352
            .output()
5353
            .unwrap();
5354
        assert!(
5355
            out.status.success(),
5356
            "git {args:?}: {}",
5357
            String::from_utf8_lossy(&out.stderr)
5358
        );
5359
        String::from_utf8_lossy(&out.stdout).trim().to_string()
5360
    };
5361
    let sub = root.join("sub");
5362
    fs::create_dir_all(&sub).unwrap();
5363
    git_in(&sub, &["init", "-q", "-b", "main"]);
5364
    write(&sub, "s.txt", b"sub\n");
5365
    git_in(&sub, &["add", "."]);
5366
    git_in(&sub, &["commit", "-q", "-m", "sub initial"]);
5367
    let sub_sha = git_in(&sub, &["rev-parse", "HEAD"]);
5368
    let g = root.join("main.git");
5369
    fs::create_dir_all(&g).unwrap();
5370
    git_in(&g, &["init", "-q", "-b", "main"]);
5371
    write(&g, "README.md", b"# app\n");
5372
    git_in(&g, &["add", "."]);
5373
    git_in(&g, &["commit", "-q", "-m", "initial"]);
5374
    git_in(
5375
        &g,
5376
        &[
5377
            "submodule",
5378
            "add",
5379
            "-q",
5380
            sub.to_str().unwrap(),
5381
            "vendor/sub",
5382
        ],
5383
    );
5384
    git_in(&g, &["commit", "-q", "-m", "add submodule"]);
5385
5386
    let dest = root.join("oxy");
5387
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
5388
    let rep = repo.import_git(&g, "main").unwrap();
5389
    assert_eq!((rep.commits, rep.submodules), (2, 1));
5390
    let files = repo
5391
        .load_state(&repo.bookmark_heads().unwrap())
5392
        .unwrap()
5393
        .materialize()
5394
        .files;
5395
    assert_eq!(files["vendor/sub"].kind, NodeKind::Subrepo);
5396
    let FileContent::Opaque { blobs } = &files["vendor/sub"].content else {
5397
        panic!()
5398
    };
5399
    assert_eq!(
5400
        crate::subrepo::Pin::decode(&repo.read_blob(&blobs[0]).unwrap()).unwrap(),
5401
        crate::subrepo::Pin::Git {
5402
            sha: sub_sha.clone(),
5403
            branch: "HEAD".into()
5404
        }
5405
    );
5406
    let modules =
5407
        crate::subrepo::Modules::parse(&fs::read_to_string(dest.join(".oxymodules")).unwrap());
5408
    assert_eq!(modules.entries["vendor/sub"].url, sub.to_string_lossy());
5409
    assert!(modules.entries["vendor/sub"].git);
5410
    assert!(
5411
        files.contains_key(".gitmodules"),
5412
        "the Git file is kept for round trips"
5413
    );
5414
    assert!(
5415
        !dest.join("vendor/sub/.git").exists(),
5416
        "not cloned until update --init"
5417
    );
5418
    assert!(!repo.snapshot("status").unwrap().changed);
5419
    // update --init clones it at the pinned commit; status is unchanged.
5420
    assert_eq!(
5421
        repo.submodule_update(true, &[]).unwrap(),
5422
        vec![("vendor/sub".to_string(), SubrepoSync::Updated)]
5423
    );
5424
    assert_eq!(
5425
        git_in(&dest.join("vendor/sub"), &["rev-parse", "HEAD"]),
5426
        sub_sha
5427
    );
5428
    assert!(!repo.snapshot("status").unwrap().changed);
5429
    // Export writes the gitlink and .gitmodules back.
5430
    let mirror = root.join("mirror.git");
5431
    let rep = repo.git_export(&mirror).unwrap();
5432
    assert_eq!(rep.skipped_subrepos, 0);
5433
    let ls = git_in(&mirror, &["ls-tree", "main", "vendor/sub"]);
5434
    assert!(
5435
        ls.starts_with("160000 commit ") && ls.contains(&sub_sha),
5436
        "{ls}"
5437
    );
5438
    assert_eq!(
5439
        git_in(&mirror, &["ls-tree", "--name-only", "main"]),
5440
        ".gitmodules\nREADME.md\nvendor"
5441
    );
5442
    let orig_tree = git_in(&g, &["rev-parse", "main^{tree}"]);
5443
    assert_eq!(
5444
        git_in(&mirror, &["rev-parse", "main^{tree}"]),
5445
        orig_tree,
5446
        "tree round trip"
5447
    );
5448
}
5449
5450
#[test]
5451
fn partial_commits_by_path_and_by_hunk() {
5452
    hermetic();
5453
    let dir = tempfile::tempdir().unwrap();
5454
    let root = dir.path();
5455
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5456
    write(root, "a.txt", b"1\n2\n3\n");
5457
    write(root, "b.txt", b"b\n");
5458
    let h0 = repo.commit("base", &[]).unwrap();
5459
    write(root, "a.txt", b"0\n1\n2\n3\n4\n");
5460
    write(root, "b.txt", b"b\nbb\n");
5461
    write(root, "c.txt", b"c\n");
5462
    // By path: only a.txt goes in; the rest stays on disk as uncommitted work.
5463
    let h1 = repo
5464
        .commit_selection("a only", &[], &Selection::Paths(vec!["a.txt".into()]))
5465
        .unwrap();
5466
    let c1 = repo.store().get_change(&h1).unwrap();
5467
    assert!(
5468
        c1.tree_ops.is_empty() && c1.edits.iter().all(|e| e.node() == c1.edits[0].node()),
5469
        "{:?}",
5470
        c1.tree_ops
5471
    );
5472
    assert_eq!(c1.deps, vec![h0]);
5473
    let files = repo.load_state(&[h1]).unwrap().materialize().files;
5474
    assert!(
5475
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n")
5476
    );
5477
    assert!(matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\n"));
5478
    assert!(!files.contains_key("c.txt"));
5479
    let snap = repo.snapshot("status").unwrap();
5480
    assert_eq!(
5481
        snap.statuses
5482
            .iter()
5483
            .map(|s| (s.path.as_str(), s.status))
5484
            .collect::<Vec<_>>(),
5485
        vec![
5486
            ("b.txt", ChangeStatus::Modified),
5487
            ("c.txt", ChangeStatus::Added)
5488
        ]
5489
    );
5490
    assert_eq!(
5491
        fs::read(root.join("b.txt")).unwrap(),
5492
        b"b\nbb\n",
5493
        "disk untouched"
5494
    );
5495
    // By hunk: pick the b.txt insert; c.txt's addition is left.
5496
    let (_, hunks) = repo.hunks().unwrap();
5497
    let b_hunk = hunks
5498
        .iter()
5499
        .find(|h| h.path == "b.txt" && h.text.contains("+bb"))
5500
        .unwrap()
5501
        .index;
5502
    let h2 = repo
5503
        .commit_selection("b only", &[], &Selection::Hunks(vec![b_hunk]))
5504
        .unwrap();
5505
    let files = repo.load_state(&[h2]).unwrap().materialize().files;
5506
    assert!(
5507
        matches!(&files["b.txt"].content, FileContent::Text { bytes, .. } if bytes == b"b\nbb\n")
5508
    );
5509
    assert!(!files.contains_key("c.txt"));
5510
    let snap = repo.snapshot("status").unwrap();
5511
    assert_eq!(
5512
        snap.statuses
5513
            .iter()
5514
            .map(|s| s.path.as_str())
5515
            .collect::<Vec<_>>(),
5516
        vec!["c.txt"]
5517
    );
5518
    // Choosing only the content hunk of a file in a new directory pulls in
5519
    // the directory and file additions it needs.
5520
    write(root, "d/e.txt", b"e\n");
5521
    let (_, hunks) = repo.hunks().unwrap();
5522
    let e_insert = hunks
5523
        .iter()
5524
        .find(|h| h.path == "d/e.txt" && h.text.contains("+e"))
5525
        .unwrap()
5526
        .index;
5527
    let h3 = repo
5528
        .commit_selection("e only", &[], &Selection::Hunks(vec![e_insert]))
5529
        .unwrap();
5530
    let c3 = repo.store().get_change(&h3).unwrap();
5531
    assert_eq!(c3.tree_ops.len(), 2, "{:?}", c3.tree_ops);
5532
    let files = repo.load_state(&[h3]).unwrap().materialize().files;
5533
    assert!(files.contains_key("d/e.txt") && !files.contains_key("c.txt"));
5534
    // Choosing a new file's addition hunk brings its content along.
5535
    write(root, "f/g.txt", b"g\n");
5536
    let (_, hunks) = repo.hunks().unwrap();
5537
    let g_add = hunks
5538
        .iter()
5539
        .find(|h| h.path == "f/g.txt" && h.text.starts_with("A "))
5540
        .unwrap()
5541
        .index;
5542
    let h4 = repo
5543
        .commit_selection("g by addition", &[], &Selection::Hunks(vec![g_add]))
5544
        .unwrap();
5545
    let files = repo.load_state(&[h4]).unwrap().materialize().files;
5546
    assert!(
5547
        matches!(&files["f/g.txt"].content, FileContent::Text { bytes, .. } if bytes == b"g\n")
5548
    );
5549
    assert!(!repo
5550
        .snapshot("status")
5551
        .unwrap()
5552
        .statuses
5553
        .iter()
5554
        .any(|s| s.path == "f/g.txt"));
5555
    // Everything left commits normally; the working copy is then clean.
5556
    repo.commit("the rest", &[]).unwrap();
5557
    assert!(!repo.snapshot("status").unwrap().changed);
5558
    let files = repo
5559
        .load_state(&repo.bookmark_heads().unwrap())
5560
        .unwrap()
5561
        .materialize()
5562
        .files;
5563
    assert!(files.contains_key("c.txt"));
5564
}
5565
5566
#[test]
5567
fn blame_attributes_lines_to_introducing_changes_across_renames() {
5568
    hermetic();
5569
    let dir = tempfile::tempdir().unwrap();
5570
    let root = dir.path();
5571
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
5572
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
5573
        .unwrap();
5574
    write(root, "a.txt", b"one\n");
5575
    let h1 = repo.commit("first", &[]).unwrap();
5576
    write(root, "a.txt", b"one\ntwo\n");
5577
    let h2 = repo.commit("second", &[]).unwrap();
5578
    let b = repo.blame("a.txt").unwrap();
5579
    assert_eq!(
5580
        b.iter()
5581
            .map(|l| (l.line, l.hash, l.text.as_slice()))
5582
            .collect::<Vec<_>>(),
5583
        vec![(1, h1, b"one\n".as_slice()), (2, h2, b"two\n".as_slice())]
5584
    );
5585
    assert!(b.iter().all(|l| l.author == "Ada"));
5586
    assert_eq!(
5587
        b[0].change_id,
5588
        repo.store().get_change(&h1).unwrap().change_id
5589
    );
5590
    fs::rename(root.join("a.txt"), root.join("b.txt")).unwrap();
5591
    repo.commit("rename", &[]).unwrap();
5592
    let b = repo.blame("b.txt").unwrap();
5593
    assert_eq!(
5594
        b.iter().map(|l| l.hash).collect::<Vec<_>>(),
5595
        vec![h1, h2],
5596
        "the node survives the rename"
5597
    );
5598
    assert!(repo.blame("a.txt").is_err());
5599
}
5600
5601
#[test]
5602
fn bisect_finds_the_first_bad_change() {
5603
    hermetic();
5604
    let dir = tempfile::tempdir().unwrap();
5605
    let root = dir.path();
5606
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5607
    let mut content = String::new();
5608
    let mut hashes = Vec::new();
5609
    for i in 1..=8 {
5610
        content.push_str(&format!("line {i}{}\n", if i == 5 { " bug" } else { "" }));
5611
        write(root, "f.txt", content.as_bytes());
5612
        hashes.push(repo.commit(&format!("step {i}"), &[]).unwrap());
5613
    }
5614
    // Each step appends after the previous line, so the chain is linear.
5615
    assert_eq!(repo.bookmark_heads().unwrap(), vec![hashes[7]]);
5616
    repo.bisect_start().unwrap();
5617
    assert!(matches!(
5618
        repo.bisect_mark(Some(true), &[hashes[0]]).unwrap(),
5619
        BisectStep::NeedMarks { good: 1, bad: 0 }
5620
    ));
5621
    let step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5622
    assert!(
5623
        matches!(step, BisectStep::Testing { remaining: 7, .. }),
5624
        "{step:?}"
5625
    );
5626
    // Automated: bad when the bug line is present.
5627
    let step = repo
5628
        .bisect_run(&["sh".into(), "-c".into(), "! grep -q bug f.txt".into()])
5629
        .unwrap();
5630
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
5631
    assert_eq!(
5632
        repo.bisect_status().unwrap(),
5633
        Some(BisectStep::Found { culprit: hashes[4] })
5634
    );
5635
    repo.bisect_reset().unwrap();
5636
    assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), content);
5637
    assert!(repo.bisect_status().unwrap().is_none());
5638
    assert!(!repo.snapshot("status").unwrap().changed);
5639
    // Manual marks and a skip.
5640
    repo.bisect_start().unwrap();
5641
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
5642
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5643
    let mut skipped_once = false;
5644
    let mut guard = 0;
5645
    while let BisectStep::Testing { .. } = step {
5646
        guard += 1;
5647
        assert!(guard < 20);
5648
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
5649
        if !skipped_once && text.contains("line 6") {
5650
            // An untestable state away from the boundary: the search routes around it.
5651
            skipped_once = true;
5652
            step = repo.bisect_mark(None, &[]).unwrap();
5653
            continue;
5654
        }
5655
        step = repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap();
5656
    }
5657
    assert!(skipped_once);
5658
    assert_eq!(step, BisectStep::Found { culprit: hashes[4] });
5659
    repo.bisect_reset().unwrap();
5660
    // Skipping the culprit itself leaves it among the candidates reported.
5661
    repo.bisect_start().unwrap();
5662
    repo.bisect_mark(Some(true), &[hashes[0]]).unwrap();
5663
    let mut step = repo.bisect_mark(Some(false), &[hashes[7]]).unwrap();
5664
    let mut guard = 0;
5665
    while let BisectStep::Testing { heads, .. } = &step {
5666
        guard += 1;
5667
        assert!(guard < 20);
5668
        let text = fs::read_to_string(root.join("f.txt")).unwrap();
5669
        let is_culprit_state =
5670
            heads.contains(&hashes[4]) && !heads.iter().any(|h| hashes[5..].contains(h));
5671
        step = if is_culprit_state {
5672
            repo.bisect_mark(None, &[]).unwrap()
5673
        } else {
5674
            repo.bisect_mark(Some(!text.contains("bug")), &[]).unwrap()
5675
        };
5676
    }
5677
    match step {
5678
        BisectStep::Inconclusive { candidates } => assert!(
5679
            candidates.contains(&hashes[4]) && candidates.len() <= 2,
5680
            "{candidates:?}"
5681
        ),
5682
        other => panic!("{other:?}"),
5683
    }
5684
    repo.bisect_reset().unwrap();
5685
}
5686
5687
#[test]
5688
fn squash_folds_a_change_into_its_dependency() {
5689
    hermetic();
5690
    let dir = tempfile::tempdir().unwrap();
5691
    let root = dir.path();
5692
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5693
    write(root, "a.txt", b"1\n");
5694
    let a = repo.commit("A", &[]).unwrap();
5695
    write(root, "a.txt", b"1\n2\n");
5696
    let c = repo.commit("C", &[]).unwrap();
5697
    write(root, "a.txt", b"1\n2\n3\n");
5698
    let e = repo.commit("E", &[]).unwrap();
5699
    write(root, "b.txt", b"b\n");
5700
    let b = repo.commit("B", &[]).unwrap();
5701
    let id_a = repo.store().get_change(&a).unwrap().change_id;
5702
    let id_e = repo.store().get_change(&e).unwrap().change_id;
5703
    // E depends on C which A lacks: refused, naming it.
5704
    let err = repo.squash(&e, &a).unwrap_err().to_string();
5705
    assert!(err.contains(&c.short(12)), "{err}");
5706
    // C into A: A' has both, C is gone, E follows and still reads the same.
5707
    let a2 = repo.squash(&c, &a).unwrap();
5708
    let a2c = repo.store().get_change(&a2).unwrap();
5709
    assert_eq!(a2c.change_id, id_a);
5710
    assert!(a2c.deps.is_empty());
5711
    let heads = repo.bookmark_heads().unwrap();
5712
    let st = repo.load_state(&heads).unwrap();
5713
    assert!(!st.contains(&c) && !st.contains(&a) && !st.contains(&e));
5714
    let e2 = st
5715
        .changes()
5716
        .find(|(_, m)| m.change_id == id_e)
5717
        .map(|(h, _)| *h)
5718
        .unwrap();
5719
    assert_eq!(
5720
        repo.store().get_change(&e2).unwrap().deps,
5721
        vec![a2],
5722
        "E now depends on A' alone"
5723
    );
5724
    let files = st.materialize().files;
5725
    assert!(
5726
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\n2\n3\n")
5727
    );
5728
    assert!(files.contains_key("b.txt"));
5729
    assert!(st.contains(&b));
5730
    assert!(!repo.snapshot("status").unwrap().changed);
5731
    assert_eq!(repo.log().unwrap().len(), 4, "working copy, B, E', A'");
5732
    // Undo restores the three original changes.
5733
    repo.undo().unwrap();
5734
    repo.undo().unwrap();
5735
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
5736
    assert!(st.contains(&c) && st.contains(&a) && st.contains(&e));
5737
}
5738
5739
#[test]
5740
fn rebase_re_expresses_a_change_against_another_base() {
5741
    hermetic();
5742
    let dir = tempfile::tempdir().unwrap();
5743
    let root = dir.path();
5744
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5745
    write(root, "a.txt", b"1\n2\n");
5746
    let a = repo.commit("A", &[]).unwrap();
5747
    write(root, "a.txt", b"1\n2\n3\n");
5748
    let c = repo.commit("C: append 3", &[]).unwrap();
5749
    write(root, "a.txt", b"1\n2\n3\n4\n");
5750
    let e = repo.commit("E: append 4", &[]).unwrap();
5751
    // A different base: A plus a change that prepends a line.
5752
    repo.checkout(&[a], true, "checkout").unwrap();
5753
    write(root, "a.txt", b"0\n1\n2\n");
5754
    let d = repo.commit("D: prepend 0", &[]).unwrap();
5755
    let id_c = repo.store().get_change(&c).unwrap().change_id;
5756
    let id_e = repo.store().get_change(&e).unwrap().change_id;
5757
    // Rebase C onto D: its effect (append 3) re-derived against D's text.
5758
    let c2 = repo.rebase(&c, &[d]).unwrap();
5759
    let c2c = repo.store().get_change(&c2).unwrap();
5760
    assert_eq!(c2c.change_id, id_c);
5761
    assert!(c2c.deps.contains(&d), "{:?}", c2c.deps);
5762
    let heads = repo.bookmark_heads().unwrap();
5763
    let st = repo.load_state(&heads).unwrap();
5764
    assert!(!st.contains(&c) && st.contains(&d));
5765
    let e2 = st
5766
        .changes()
5767
        .find(|(_, m)| m.change_id == id_e)
5768
        .map(|(h, _)| *h)
5769
        .unwrap();
5770
    let e2deps = repo.store().get_change(&e2).unwrap().deps;
5771
    assert!(
5772
        e2deps.contains(&c2) && !e2deps.contains(&c) && e2deps.contains(&a),
5773
        "E follows C by content and still depends on A, which introduced the file: {e2deps:?}"
5774
    );
5775
    let files = st.materialize().files;
5776
    assert!(
5777
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"0\n1\n2\n3\n4\n"),
5778
        "{:?}",
5779
        files["a.txt"].content
5780
    );
5781
    assert!(!files["a.txt"].is_conflicted());
5782
    // Rebasing onto a state that already contains the change is refused.
5783
    assert!(repo.rebase(&c2, &[c2]).is_err());
5784
    let err = repo.rebase(&e2, &[d]).unwrap_err().to_string();
5785
    assert!(
5786
        err.contains("lacks dependencies"),
5787
        "E needs C, which D's state does not have: {err}"
5788
    );
5789
}
5790
5791
#[test]
5792
fn unsigned_tags_keep_their_message() {
5793
    hermetic();
5794
    let dir = tempfile::tempdir().unwrap();
5795
    let root = dir.path();
5796
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
5797
    write(root, "a.txt", b"a\n");
5798
    repo.commit("a", &[]).unwrap();
5799
    assert!(repo.secret_key().unwrap().is_none());
5800
    repo.tag_create("v1", &repo.bookmark_heads().unwrap(), "first release")
5801
        .unwrap();
5802
    let tags = repo.tags().unwrap();
5803
    assert_eq!(
5804
        (
5805
            tags[0].name.as_str(),
5806
            tags[0].message.as_str(),
5807
            tags[0].signer.as_deref()
5808
        ),
5809
        ("v1", "first release", None)
5810
    );
5811
    assert!(
5812
        repo.tag_refs().unwrap()[0].attestation.is_none(),
5813
        "an unsigned attestation is not advertised"
5814
    );
5815
}
5816
5817
#[test]
5818
fn fsck_passes_a_sound_repository_and_names_each_fault() {
5819
    // Files on disk are what this tests: tampering with them, and the
5820
    // directory store's crash points.
5821
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5822
        return;
5823
    }
5824
    hermetic();
5825
    let dir = tempfile::tempdir().unwrap();
5826
    let root = dir.path();
5827
    let origin_path = root.join("origin");
5828
    let origin = Repo::init(&origin_path).unwrap();
5829
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &root.join("a"))
5830
        .unwrap()
5831
        .with_home(root.join("home-a"));
5832
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5833
        .unwrap();
5834
    write(&root.join("a"), "f.txt", b"one\n");
5835
    write(&root.join("a"), "bin.dat", b"\0\x01\x02binary");
5836
    let h1 = a.commit("first", &[]).unwrap();
5837
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
5838
    let h2 = a.commit("second", &[]).unwrap();
5839
    a.tag_create("v1", &[h2], "first release").unwrap();
5840
    a.checkpoint().unwrap();
5841
    assert!(a.push("origin", false).unwrap()[0].ok);
5842
    origin.refresh().unwrap();
5843
5844
    // Sound: signed changes, a seal, a tag, a checkpoint, a ref attestation.
5845
    for repo in [&a, &origin] {
5846
        let rep = repo.fsck().unwrap();
5847
        assert_eq!(rep.problems, vec![], "{rep:?}");
5848
        // The two commits, plus the working copy's change in `a`.
5849
        assert!(rep.changes >= 2 && rep.signed >= 2, "{rep:?}");
5850
        assert!(rep.ops > 1 && rep.objects > 5);
5851
    }
5852
    assert!(origin.fsck().unwrap().attestations >= 1);
5853
5854
    // A flipped byte in a stored object is corruption, named by hash.
5855
    let c1 = a.store().path_for(&h1);
5856
    let pristine = fs::read(&c1).unwrap();
5857
    let mut bytes = pristine.clone();
5858
    *bytes.last_mut().unwrap() ^= 1;
5859
    fs::write(&c1, &bytes).unwrap();
5860
    let rep = a.fsck().unwrap();
5861
    assert!(rep.errors() >= 1);
5862
    assert!(
5863
        rep.problems
5864
            .iter()
5865
            .any(|p| p.object == Some(h1) && p.what.contains("unreadable")),
5866
        "{rep:?}"
5867
    );
5868
    fs::write(&c1, &pristine).unwrap();
5869
    assert_eq!(a.fsck().unwrap().errors(), 0);
5870
5871
    // A missing change is named with what needed it.
5872
    fs::remove_file(&c1).unwrap();
5873
    let rep = a.fsck().unwrap();
5874
    assert!(
5875
        rep.problems.iter().any(|p| p.severity == Severity::Error
5876
            && p.object == Some(h1)
5877
            && p.what.contains("change missing, needed by change")),
5878
        "{rep:?}"
5879
    );
5880
    fs::write(&c1, &pristine).unwrap();
5881
5882
    // A missing blob is an error in a full clone.
5883
    let c2 = a.store().get_change(&h1).unwrap();
5884
    let blob = c2
5885
        .edits
5886
        .iter()
5887
        .find_map(|e| match e {
5888
            Edit::Replace { new: Some(b), .. } => Some(*b),
5889
            _ => None,
5890
        })
5891
        .expect("the binary file is a blob");
5892
    let bp = a.store().path_for(&blob);
5893
    let blob_bytes = fs::read(&bp).unwrap();
5894
    fs::remove_file(&bp).unwrap();
5895
    let rep = a.fsck().unwrap();
5896
    assert!(
5897
        rep.problems
5898
            .iter()
5899
            .any(|p| p.object == Some(blob) && p.what.contains("blob missing")),
5900
        "{rep:?}"
5901
    );
5902
    fs::write(&bp, &blob_bytes).unwrap();
5903
5904
    // A broken op log head is reported, not a crash.
5905
    let head = root.join("a/.oxy/ops/head");
5906
    let saved = fs::read(&head).unwrap();
5907
    fs::write(&head, b"not a hash").unwrap();
5908
    let rep = a.fsck().unwrap();
5909
    assert!(
5910
        rep.problems.iter().any(|p| p.what.contains("ops/head")),
5911
        "{rep:?}"
5912
    );
5913
    fs::write(&head, saved).unwrap();
5914
    assert_eq!(a.fsck().unwrap().problems, vec![]);
5915
}
5916
5917
/// Copy a directory tree (for restoring a pristine repository).
5918
fn copy_tree(from: &Path, to: &Path) {
5919
    fs::create_dir_all(to).unwrap();
5920
    for e in fs::read_dir(from).unwrap() {
5921
        let e = e.unwrap();
5922
        let target = to.join(e.file_name());
5923
        if e.file_type().unwrap().is_dir() {
5924
            copy_tree(&e.path(), &target);
5925
        } else {
5926
            fs::copy(e.path(), &target).unwrap();
5927
        }
5928
    }
5929
}
5930
5931
/// Spec §13.6: stop `commit` and `push` at every durable step, as a crash
5932
/// would, and check that both repositories still open, pass `fsck`, and
5933
/// accept the same operation again.
5934
#[test]
5935
fn crash_at_every_step_of_commit_and_push_leaves_sound_repositories() {
5936
    // Files on disk are what this tests: tampering with them, and the
5937
    // directory store's crash points.
5938
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
5939
        return;
5940
    }
5941
    use crate::durable::failpoint;
5942
    hermetic();
5943
    let dir = tempfile::tempdir().unwrap();
5944
    let pristine = dir.path().join("pristine");
5945
    let origin_path = pristine.join("origin");
5946
    Repo::init(&origin_path).unwrap();
5947
    let mut a = Repo::clone(&origin_path.to_string_lossy(), &pristine.join("a"))
5948
        .unwrap()
5949
        .with_home(dir.path().join("home"));
5950
    a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
5951
        .unwrap();
5952
    write(&pristine.join("a"), "f.txt", b"one\n");
5953
    a.commit("first", &[]).unwrap();
5954
    assert!(a.push("origin", false).unwrap()[0].ok);
5955
    drop(a);
5956
5957
    type Op = fn(&Repo) -> Result<()>;
5958
    let edit_and_commit: Op = |r| {
5959
        write(r.root(), "f.txt", b"one\ntwo\n");
5960
        write(r.root(), "big.bin", &vec![7u8; 300_000]);
5961
        r.commit("second", &[]).map(|_| ())
5962
    };
5963
    let push: Op = |r| {
5964
        let res = r.push("origin", false)?;
5965
        if res.iter().all(|x| x.ok) {
5966
            Ok(())
5967
        } else {
5968
            Err(RepoError::Msg(format!("{res:?}")))
5969
        }
5970
    };
5971
5972
    for (name, prepare, op) in [
5973
        ("commit", None, edit_and_commit),
5974
        ("push", Some(edit_and_commit), push),
5975
    ] {
5976
        let mut steps = 0;
5977
        for n in 1.. {
5978
            let run = dir.path().join(format!("{name}-{n}"));
5979
            copy_tree(&pristine, &run);
5980
            // Clones record their remote by path; point it at this copy.
5981
            let open = |p: &Path| {
5982
                let mut r = Repo::open(p).unwrap().with_home(dir.path().join("home"));
5983
                r.config
5984
                    .set("remote.origin.url", &run.join("origin").to_string_lossy())
5985
                    .unwrap();
5986
                r.save_config().unwrap();
5987
                r
5988
            };
5989
            let a = open(&run.join("a"));
5990
            if let Some(prep) = prepare {
5991
                prep(&a).unwrap();
5992
            }
5993
            failpoint::crash_after(n);
5994
            let outcome = op(&a);
5995
            let crashed = failpoint::disarm();
5996
            drop(a);
5997
            if !crashed {
5998
                outcome.unwrap_or_else(|e| panic!("{name} failed without a crash: {e}"));
5999
                steps = n - 1;
6000
                break;
6001
            }
6002
            assert!(
6003
                outcome.is_err(),
6004
                "{name}: a crash at step {n} was swallowed"
6005
            );
6006
            for repo in ["a", "origin"] {
6007
                let r = Repo::open(&run.join(repo)).unwrap_or_else(|e| {
6008
                    panic!("{name} crash at step {n}: {repo} no longer opens: {e}")
6009
                });
6010
                let rep = r.fsck().unwrap();
6011
                assert_eq!(
6012
                    rep.errors(),
6013
                    0,
6014
                    "{name} crash at step {n}: {repo} fails fsck: {:?}",
6015
                    rep.problems
6016
                );
6017
            }
6018
            // The interrupted operation can simply be run again.
6019
            let a = open(&run.join("a"));
6020
            // A crash after the commit point leaves the commit done.
6021
            let landed = a
6022
                .bookmark_heads()
6023
                .unwrap()
6024
                .iter()
6025
                .any(|h| a.store().get_change(h).unwrap().message == "second");
6026
            let again = match (name, landed) {
6027
                ("commit", true) => Ok(()),
6028
                ("commit", false) => a.commit("second", &[]).map(|_| ()),
6029
                _ => op(&a),
6030
            };
6031
            again.unwrap_or_else(|e| panic!("{name} crash at step {n}: retry failed: {e}"));
6032
            assert_eq!(a.fsck().unwrap().errors(), 0);
6033
            fs::remove_dir_all(&run).unwrap();
6034
        }
6035
        assert!(steps >= 3, "{name} has only {steps} durable steps?");
6036
    }
6037
}
6038
6039
/// Spec §12.1: commands in two workspaces of one repository, and pushes,
6040
/// running at the same time lose nothing: every commit ends up on the
6041
/// bookmark, locally and on the remote, and the repository passes fsck.
6042
#[test]
6043
fn concurrent_commits_in_two_workspaces_lose_nothing() {
6044
    hermetic();
6045
    let dir = tempfile::tempdir().unwrap();
6046
    let root = dir.path();
6047
    let origin = root.join("origin");
6048
    Repo::init_bare_unbound(&origin).unwrap();
6049
    let main = root.join("main");
6050
    let mut repo = Repo::init(&main).unwrap();
6051
    repo.config
6052
        .set("remote.origin.url", &origin.to_string_lossy())
6053
        .unwrap();
6054
    repo.save_config().unwrap();
6055
    write(&main, "seed.txt", b"seed\n");
6056
    repo.commit("seed", &[]).unwrap();
6057
    let second = root.join("second");
6058
    repo.workspace_add(&second, None).unwrap();
6059
    drop(repo);
6060
6061
    const EACH: usize = 15;
6062
    std::thread::scope(|s| {
6063
        for (tag, dir, push) in [("a", main.clone(), true), ("b", second.clone(), false)] {
6064
            s.spawn(move || {
6065
                let r = Repo::open(&dir).unwrap();
6066
                for i in 0..EACH {
6067
                    write(
6068
                        &dir,
6069
                        &format!("{tag}-{i}.txt"),
6070
                        format!("{tag} {i}\n").as_bytes(),
6071
                    );
6072
                    r.commit(&format!("{tag} {i}"), &[]).unwrap();
6073
                    if push && i % 5 == 4 {
6074
                        // A push may be refused while the other workspace moves the bookmark; nothing may be lost either way.
6075
                        let _ = r.push("origin", false);
6076
                    }
6077
                }
6078
            });
6079
        }
6080
    });
6081
6082
    let repo = Repo::open(&main).unwrap();
6083
    let heads = repo.bookmark_heads().unwrap();
6084
    let state = repo.load_state(&heads).unwrap();
6085
    let messages: BTreeSet<String> = state.changes().map(|(_, m)| m.message.clone()).collect();
6086
    for tag in ["a", "b"] {
6087
        for i in 0..EACH {
6088
            assert!(
6089
                messages.contains(&format!("{tag} {i}")),
6090
                "lost commit {tag} {i}; have {messages:?}"
6091
            );
6092
        }
6093
    }
6094
    let rep = repo.fsck().unwrap();
6095
    assert_eq!(rep.errors(), 0, "{:?}", rep.problems);
6096
    assert!(repo.push("origin", false).unwrap().iter().all(|r| r.ok));
6097
    let hosted = Repo::open(&origin).unwrap();
6098
    let hosted_heads = hosted.bookmark_heads().unwrap();
6099
    assert_eq!(
6100
        hosted.load_state(&hosted_heads).unwrap().len(),
6101
        state.len(),
6102
        "the remote has every commit"
6103
    );
6104
}
6105
6106
/// Two operations recorded from the same parent (what two processes do
6107
/// when they race) are merged: both bookmarks' heads survive, and a
6108
/// change made on one side only is kept.
6109
#[test]
6110
fn operations_from_the_same_parent_are_merged() {
6111
    hermetic();
6112
    let dir = tempfile::tempdir().unwrap();
6113
    let root = dir.path();
6114
    let repo = Repo::init(root).unwrap();
6115
    write(root, "a.txt", b"a\n");
6116
    let a = repo.commit("a", &[]).unwrap();
6117
    write(root, "b.txt", b"b\n");
6118
    let b = repo.commit("b", &[]).unwrap();
6119
    let (x, op) = repo.head_op().unwrap();
6120
    let state = |heads: Vec<ChangeHash>| repo.store().put_state(&StateObject::new(heads)).unwrap();
6121
6122
    // Side one moves main to just `a` and adds a bookmark; side two moves main to just `b`.
6123
    let mut one = op.view.clone();
6124
    one.bookmarks.insert("main".into(), state(vec![a]));
6125
    one.bookmarks.insert("topic".into(), state(vec![a]));
6126
    let mut two = op.view.clone();
6127
    two.bookmarks.insert("main".into(), state(vec![b]));
6128
    repo.record_op(&[x], "one", one).unwrap();
6129
    let merged = repo.record_op(&[x], "two", two).unwrap();
6130
6131
    let (head, op) = repo.head_op().unwrap();
6132
    assert_eq!(head, merged);
6133
    assert_eq!(op.parents.len(), 2, "a merge of the two operations");
6134
    assert!(op.command.contains("merged with a concurrent operation"));
6135
    let mut main = repo
6136
        .store()
6137
        .get_state(&op.view.bookmarks["main"])
6138
        .unwrap()
6139
        .heads;
6140
    main.sort();
6141
    let mut want = vec![a, b];
6142
    want.sort();
6143
    assert_eq!(main, want, "both sides' heads are kept");
6144
    assert!(
6145
        op.view.bookmarks.contains_key("topic"),
6146
        "a one-sided change survives"
6147
    );
6148
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6149
}
6150
6151
#[test]
6152
fn failed_requests_come_with_a_next_step() {
6153
    use crate::protocol::hint_for;
6154
    assert!(hint_for("https://h/x/oxy/v1/push: HTTP 401: bad token")
6155
        .unwrap()
6156
        .contains("token"));
6157
    assert!(hint_for("…: HTTP 403: forbidden")
6158
        .unwrap()
6159
        .contains("repo:write"));
6160
    assert!(hint_for("…: HTTP 404: no such repository")
6161
        .unwrap()
6162
        .contains("owner and repository name"));
6163
    assert!(hint_for("invalid peer certificate: UnknownIssuer")
6164
        .unwrap()
6165
        .contains("oxyhub-ca.pem"));
6166
    assert!(hint_for("Connect error: Connection refused (os error 111)")
6167
        .unwrap()
6168
        .contains("running"));
6169
    assert!(hint_for("Dns Failed: failed to lookup address information")
6170
        .unwrap()
6171
        .contains("resolve"));
6172
    assert_eq!(hint_for("something else entirely"), None);
6173
}
6174
6175
#[test]
6176
fn doctor_names_problems_and_what_to_do() {
6177
    hermetic();
6178
    let dir = tempfile::tempdir().unwrap();
6179
    let root = dir.path();
6180
    let origin = root.join("origin");
6181
    Repo::init_bare_unbound(&origin).unwrap();
6182
    let mut repo = Repo::init(&root.join("r"))
6183
        .unwrap()
6184
        .with_home(root.join("home"));
6185
    let find = |r: &DoctorReport, area: &str, h: Health| {
6186
        r.checks
6187
            .iter()
6188
            .find(|c| c.area == area && c.health == h)
6189
            .cloned()
6190
    };
6191
6192
    let r = repo.doctor(true);
6193
    assert!(find(&r, "identity", Health::Warn)
6194
        .unwrap()
6195
        .hint
6196
        .unwrap()
6197
        .contains("oxy identity create"));
6198
    assert!(find(&r, "repository", Health::Ok).is_some());
6199
    // oxygen#127: no policy is said, with who sets one.
6200
    assert!(find(&r, "trust", Health::Warn)
6201
        .unwrap()
6202
        .hint
6203
        .unwrap()
6204
        .contains("oxy policy init"));
6205
6206
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6207
        .unwrap();
6208
    repo.policy_init().unwrap();
6209
    let r = repo.doctor(false);
6210
    let trust = find(&r, "trust", Health::Ok).expect("a fresh policy is fine");
6211
    assert!(
6212
        trust.message.contains("serial 1") && trust.message.contains("1 root"),
6213
        "{trust:?}"
6214
    );
6215
    repo.config.set("author.name", "Ada").unwrap();
6216
    repo.config.set("author.email", "[email protected]").unwrap();
6217
    repo.config
6218
        .set("remote.origin.url", &origin.to_string_lossy())
6219
        .unwrap();
6220
    repo.config
6221
        .set("remote.down.url", "http://127.0.0.1:9/a/b")
6222
        .unwrap();
6223
    repo.config.set("remote.down.token", "t").unwrap();
6224
    repo.config
6225
        .set("remote.badca.url", "https://example.invalid/a/b")
6226
        .unwrap();
6227
    repo.config
6228
        .set(
6229
            "remote.badca.ca",
6230
            &root.join("missing.pem").to_string_lossy(),
6231
        )
6232
        .unwrap();
6233
    repo.save_config().unwrap();
6234
6235
    let r = repo.doctor(true);
6236
    assert!(find(&r, "identity", Health::Ok).is_some(), "{r:?}");
6237
    assert!(find(&r, "author", Health::Ok).is_some(), "{r:?}");
6238
    assert!(find(&r, "remote origin", Health::Ok)
6239
        .unwrap()
6240
        .message
6241
        .contains("first push binds it"));
6242
    let down = find(&r, "remote down", Health::Fail).unwrap();
6243
    assert!(
6244
        down.hint.as_deref().unwrap_or("").contains("running"),
6245
        "{down:?}"
6246
    );
6247
    let badca = find(&r, "remote badca", Health::Fail).unwrap();
6248
    assert!(
6249
        badca.hint.unwrap().contains("remote.badca.ca"),
6250
        "the remote's own name is in the hint"
6251
    );
6252
    assert_eq!(r.worst(), Health::Fail);
6253
6254
    // Offline, nothing is contacted.
6255
    let r = repo.doctor(false);
6256
    assert!(find(&r, "remote down", Health::Fail).is_none());
6257
    assert!(find(&r, "remote down", Health::Ok)
6258
        .unwrap()
6259
        .message
6260
        .contains("not contacted"));
6261
}
6262
6263
/// Spec §8.1: deleting a line depends on whoever inserted the lines right
6264
/// after it. Inserting after `b` and then deleting `b`, one commit after
6265
/// the other, must not leave a delete/insert conflict.
6266
#[test]
6267
fn deleting_a_line_after_an_insertion_below_it_is_not_a_conflict() {
6268
    hermetic();
6269
    let dir = tempfile::tempdir().unwrap();
6270
    let root = dir.path();
6271
    let repo = Repo::init(root).unwrap();
6272
    write(root, "f", b"a\nb\nc\n");
6273
    repo.commit("base", &[]).unwrap();
6274
    write(root, "f", b"a\nb\nx\nc\n");
6275
    let insert = repo.commit("insert x after b", &[]).unwrap();
6276
    write(root, "f", b"a\nx\nc\n");
6277
    let delete = repo.commit("delete b", &[]).unwrap();
6278
    assert!(
6279
        repo.store()
6280
            .get_change(&delete)
6281
            .unwrap()
6282
            .deps
6283
            .contains(&insert),
6284
        "the deletion depends on the insertion below the deleted line"
6285
    );
6286
    let heads = repo.bookmark_heads().unwrap();
6287
    assert_eq!(heads, vec![delete]);
6288
    let snap = repo.load_state(&heads).unwrap().materialize();
6289
    assert!(!snap.is_conflicted());
6290
    assert!(
6291
        matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes == b"a\nx\nc\n")
6292
    );
6293
}
6294
6295
/// Spec §9.3: a binary file reverted to an earlier blob keeps it, and each
6296
/// replacement depends on the change that set the blob it replaces.
6297
#[test]
6298
fn a_binary_file_reverted_to_an_earlier_blob_keeps_it() {
6299
    hermetic();
6300
    let dir = tempfile::tempdir().unwrap();
6301
    let root = dir.path();
6302
    let repo = Repo::init(root).unwrap();
6303
    write(root, "bin", b"\0A");
6304
    let v1 = repo.commit("v1", &[]).unwrap();
6305
    write(root, "bin", b"\0B");
6306
    let v2 = repo.commit("v2", &[]).unwrap();
6307
    assert!(repo.store().get_change(&v2).unwrap().deps.contains(&v1));
6308
    write(root, "bin", b"\0A");
6309
    let v3 = repo.commit("back to A", &[]).unwrap();
6310
    assert!(repo.store().get_change(&v3).unwrap().deps.contains(&v2));
6311
    assert_eq!(repo.bookmark_heads().unwrap(), vec![v3]);
6312
    let state = repo.load_state(&[v3]).unwrap();
6313
    let snap = state.materialize();
6314
    let FileContent::Opaque { blobs } = &snap.files["bin"].content else {
6315
        panic!("opaque")
6316
    };
6317
    assert_eq!(blobs.len(), 1, "one live blob, not none and not two");
6318
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0A");
6319
}
6320
6321
/// Spec §23: a binary file changed on two branches and merged in Git to
6322
/// one side's version comes back as that version at the merge, and the
6323
/// import verifies commit by commit.
6324
#[test]
6325
fn git_import_resolves_a_binary_merged_in_git_and_verifies() {
6326
    hermetic();
6327
    if std::process::Command::new("git")
6328
        .arg("--version")
6329
        .output()
6330
        .is_err()
6331
    {
6332
        eprintln!("git not installed; skipping");
6333
        return;
6334
    }
6335
    let dir = tempfile::tempdir().unwrap();
6336
    let root = dir.path();
6337
    let g = root.join("src.git");
6338
    fs::create_dir_all(&g).unwrap();
6339
    let git = |args: &[&str]| -> String {
6340
        let out = std::process::Command::new("git")
6341
            .arg("-C")
6342
            .arg(&g)
6343
            .args([
6344
                "-c",
6345
                "user.name=Grace",
6346
                "-c",
6347
                "[email protected]",
6348
                "-c",
6349
                "commit.gpgsign=false",
6350
            ])
6351
            .args(args)
6352
            .output()
6353
            .unwrap();
6354
        assert!(
6355
            out.status.success(),
6356
            "git {args:?}: {}",
6357
            String::from_utf8_lossy(&out.stderr)
6358
        );
6359
        String::from_utf8_lossy(&out.stdout).trim().to_string()
6360
    };
6361
    git(&["init", "-q", "-b", "main"]);
6362
    write(&g, "logo.bin", b"\0base");
6363
    write(&g, "notes.txt", b"a\nb\nc\n");
6364
    git(&["add", "."]);
6365
    git(&["commit", "-qm", "base"]);
6366
    git(&["checkout", "-qb", "side"]);
6367
    write(&g, "logo.bin", b"\0side");
6368
    write(&g, "notes.txt", b"a\nb\nx\nc\n");
6369
    git(&["commit", "-qam", "side"]);
6370
    git(&["checkout", "-q", "main"]);
6371
    write(&g, "logo.bin", b"\0main");
6372
    git(&["commit", "-qam", "main"]);
6373
    // Git cannot merge the binary; the merge takes main's and keeps side's text.
6374
    let _ = std::process::Command::new("git")
6375
        .arg("-C")
6376
        .arg(&g)
6377
        .args([
6378
            "-c",
6379
            "user.name=G",
6380
            "-c",
6381
            "user.email=g@e",
6382
            "merge",
6383
            "-q",
6384
            "side",
6385
        ])
6386
        .output();
6387
    write(&g, "logo.bin", b"\0main");
6388
    git(&["add", "."]);
6389
    git(&["commit", "-qm", "merge side"]);
6390
    // Then a revert of the binary to its first version.
6391
    write(&g, "logo.bin", b"\0base");
6392
    git(&["commit", "-qam", "back to base"]);
6393
6394
    let repo = Repo::init(&root.join("o")).unwrap();
6395
    let rep = repo.import_git(&g, "main").unwrap();
6396
    assert_eq!(rep.merges, 1);
6397
    let v = repo.verify_git_import(&g, "main").unwrap();
6398
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
6399
    assert_eq!(v.commits, 5);
6400
    let snap = repo
6401
        .load_state(&repo.bookmark_heads().unwrap())
6402
        .unwrap()
6403
        .materialize();
6404
    assert!(!snap.is_conflicted());
6405
    let FileContent::Opaque { blobs } = &snap.files["logo.bin"].content else {
6406
        panic!("opaque")
6407
    };
6408
    assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\0base");
6409
}
6410
6411
/// Spec §7.7 on a file system without executable bits or symlinks: the
6412
/// recorded bit is kept, and a symlink checked out as a plain file holding
6413
/// its target is still that symlink.
6414
#[cfg(unix)]
6415
#[test]
6416
fn windows_file_systems_keep_exec_bits_and_symlinks() {
6417
    use crate::portable::Platform;
6418
    use std::os::unix::fs::PermissionsExt;
6419
    hermetic();
6420
    let dir = tempfile::tempdir().unwrap();
6421
    let root = dir.path();
6422
    let repo = Repo::init(root).unwrap();
6423
    write(root, "run.sh", b"#!/bin/sh\n");
6424
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
6425
    std::os::unix::fs::symlink("run.sh", root.join("link")).unwrap();
6426
    repo.commit("script and link", &[]).unwrap();
6427
    drop(repo);
6428
6429
    // What checking out on Windows leaves: no exec bit, the link as a file.
6430
    fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o644)).unwrap();
6431
    fs::remove_file(root.join("link")).unwrap();
6432
    write(root, "link", b"run.sh");
6433
    let win = Repo::open(root).unwrap().with_platform(Platform::windows());
6434
    let s = win.snapshot("oxy status").unwrap();
6435
    assert!(
6436
        s.statuses.is_empty(),
6437
        "nothing changed on Windows: {:?}",
6438
        statuses(&s)
6439
    );
6440
    // Editing the file is a content change, not a mode change; retargeting the link keeps it a link.
6441
    write(root, "run.sh", b"#!/bin/sh\necho hi\n");
6442
    write(root, "link", b"other");
6443
    let h = win.commit("edit on Windows", &[]).unwrap();
6444
    let snap = win.load_state(&[h]).unwrap().materialize();
6445
    assert!(snap.files["run.sh"].mode.exec, "the exec bit survives");
6446
    assert_eq!(snap.files["link"].kind, NodeKind::Symlink);
6447
    // The same working copy read as Linux sees the lost bit and the plain file.
6448
    let linux = Repo::open(root).unwrap();
6449
    assert!(!linux.snapshot("oxy status").unwrap().statuses.is_empty());
6450
}
6451
6452
/// Paths that collide on case-insensitive or Windows file systems are
6453
/// named at checkout there, and by doctor everywhere.
6454
#[test]
6455
fn paths_other_platforms_cannot_hold_are_reported() {
6456
    use crate::portable::Platform;
6457
    hermetic();
6458
    let dir = tempfile::tempdir().unwrap();
6459
    let root = dir.path();
6460
    let repo = Repo::init(root).unwrap();
6461
    write(root, "README.md", b"a\n");
6462
    write(root, "readme.md", b"b\n");
6463
    write(root, "src/aux.c", b"int x;\n");
6464
    let h = repo.commit("unportable", &[]).unwrap();
6465
    let r = repo.doctor(false);
6466
    let port = r.checks.iter().find(|c| c.area == "portability").unwrap();
6467
    assert_eq!(port.health, Health::Warn);
6468
    assert!(
6469
        port.message.contains("differ only in case") && port.message.contains("aux.c"),
6470
        "{}",
6471
        port.message
6472
    );
6473
    let mac = Repo::open(root).unwrap().with_platform(Platform::macos());
6474
    let rep = mac.checkout(&[h], true, "oxy checkout").unwrap();
6475
    assert!(
6476
        rep.notes
6477
            .iter()
6478
            .any(|n| n.contains("README.md and readme.md")),
6479
        "{:?}",
6480
        rep.notes
6481
    );
6482
    assert!(
6483
        !rep.notes.iter().any(|n| n.contains("aux.c")),
6484
        "macOS allows aux.c"
6485
    );
6486
}
6487
6488
#[test]
6489
fn history_and_blame_of_a_loaded_state_match_the_full_walk() {
6490
    hermetic();
6491
    let dir = tempfile::tempdir().unwrap();
6492
    let repo = Repo::init(dir.path()).unwrap();
6493
    write(dir.path(), "a.txt", b"one\n");
6494
    write(dir.path(), "other.txt", b"x\n");
6495
    write(dir.path(), "bin.dat", &[0u8, 1, 2, 0, 255]);
6496
    repo.snapshot("t").unwrap();
6497
    let c1 = repo.commit("first", &[]).unwrap();
6498
    write(dir.path(), "other.txt", b"y\n");
6499
    repo.snapshot("t").unwrap();
6500
    repo.commit("other only", &[]).unwrap();
6501
    write(dir.path(), "a.txt", b"one\ntwo\n");
6502
    repo.snapshot("t").unwrap();
6503
    let c3 = repo.commit("second line", &[]).unwrap();
6504
    write(dir.path(), "other.txt", b"z\n");
6505
    repo.snapshot("t").unwrap();
6506
    repo.commit("other again", &[]).unwrap();
6507
6508
    let heads = repo.bookmark_heads().unwrap();
6509
    let state = repo.load_state(&heads).unwrap();
6510
    let full: Vec<ChangeHash> = repo
6511
        .log_for_path_in("a.txt", &heads)
6512
        .unwrap()
6513
        .iter()
6514
        .map(|e| e.hash)
6515
        .collect();
6516
    assert_eq!(
6517
        full,
6518
        vec![c3, c1],
6519
        "newest first, only changes touching the path"
6520
    );
6521
    let newest: Vec<ChangeHash> = repo
6522
        .log_for_path_of(&state, "a.txt", Some(1))
6523
        .unwrap()
6524
        .iter()
6525
        .map(|e| e.hash)
6526
        .collect();
6527
    assert_eq!(newest, vec![c3], "stops at the first");
6528
    assert_eq!(
6529
        repo.log_for_path_of(&state, "a.txt", None).unwrap().len(),
6530
        2
6531
    );
6532
    assert!(repo
6533
        .log_for_path_of(&state, "missing.txt", Some(1))
6534
        .is_err());
6535
    assert_eq!(
6536
        repo.log_state(&heads).unwrap().len(),
6537
        repo.log_of(&state).len()
6538
    );
6539
6540
    let tree = state.tree().view();
6541
    let via_state = repo.blame_of(&state, &tree, "a.txt").unwrap();
6542
    let via_heads = repo.blame_in("a.txt", &heads).unwrap();
6543
    assert_eq!(
6544
        via_state
6545
            .iter()
6546
            .map(|l| (l.hash, l.text.clone()))
6547
            .collect::<Vec<_>>(),
6548
        via_heads
6549
            .iter()
6550
            .map(|l| (l.hash, l.text.clone()))
6551
            .collect::<Vec<_>>()
6552
    );
6553
    assert_eq!(
6554
        via_state.iter().map(|l| l.hash).collect::<Vec<_>>(),
6555
        vec![c1, c3]
6556
    );
6557
    assert!(repo.blame_of(&state, &tree, "missing.txt").is_err());
6558
}
6559
6560
/// A text file whose stat matches the manifest and whose recorded hash is
6561
/// the base's content is taken from the base without reading it; anything
6562
/// else is read, so no edit is missed (spec §12.3).
6563
#[cfg(unix)]
6564
#[test]
6565
fn stat_cache_takes_unchanged_text_from_the_base_and_misses_no_edit() {
6566
    use std::os::unix::fs::PermissionsExt;
6567
    hermetic();
6568
    let dir = tempfile::tempdir().unwrap();
6569
    let root = dir.path();
6570
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6571
    write(root, "a.txt", b"one\ntwo\n");
6572
    write(root, "b.txt", b"bee\n");
6573
    repo.commit("base", &[]).unwrap();
6574
    let age = |p: &str| {
6575
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6576
        fs::File::options()
6577
            .write(true)
6578
            .open(root.join(p))
6579
            .unwrap()
6580
            .set_modified(old)
6581
            .unwrap();
6582
    };
6583
    age("a.txt");
6584
    age("b.txt");
6585
    assert!(
6586
        !repo.snapshot("status").unwrap().changed,
6587
        "records the aged stat"
6588
    );
6589
6590
    // Clean and equal to the base: not read at all.
6591
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6592
    let snap = repo.snapshot("status").unwrap();
6593
    assert!(
6594
        !snap.changed && snap.statuses.is_empty(),
6595
        "{:?}",
6596
        snap.statuses
6597
    );
6598
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6599
6600
    // An uncommitted edit that is older than the manifest: stat-clean, but
6601
    // its hash is not the base's, so it is read and stays visible.
6602
    write(root, "b.txt", b"bee edited\n");
6603
    age("b.txt");
6604
    let first = repo.snapshot("status").unwrap();
6605
    assert_eq!(
6606
        statuses(&first),
6607
        vec![("b.txt".to_string(), ChangeStatus::Modified)]
6608
    );
6609
    let again = repo.snapshot("status").unwrap();
6610
    assert_eq!(
6611
        statuses(&again),
6612
        vec![("b.txt".to_string(), ChangeStatus::Modified)],
6613
        "still seen once stat-clean"
6614
    );
6615
    assert!(!again.changed, "and the working copy hashes the same");
6616
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6617
    assert!(
6618
        repo.snapshot("status").is_err(),
6619
        "an edited file must be read, never taken from the base"
6620
    );
6621
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6622
6623
    // A same-size edit made just now is racy and read.
6624
    write(root, "a.txt", b"one\nTWO\n");
6625
    assert_eq!(
6626
        statuses(&repo.snapshot("status").unwrap()),
6627
        vec![
6628
            ("a.txt".to_string(), ChangeStatus::Modified),
6629
            ("b.txt".to_string(), ChangeStatus::Modified)
6630
        ]
6631
    );
6632
    // Committing makes the edits the base: both are clean and served from it again.
6633
    repo.commit("edits", &[]).unwrap();
6634
    age("a.txt");
6635
    age("b.txt");
6636
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6637
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6638
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o000)).unwrap();
6639
    let snap = repo.snapshot("status").unwrap();
6640
    assert!(!snap.changed && snap.statuses.is_empty());
6641
    fs::set_permissions(root.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6642
    fs::set_permissions(root.join("b.txt"), fs::Permissions::from_mode(0o644)).unwrap();
6643
}
6644
6645
/// Version 2 checkpoints (spec §11): a large file's graph is a blob of its
6646
/// own, kept by gc, checked by fsck, shared by the next checkpoint when the
6647
/// file is unchanged, and loading through the checkpoint equals a full load.
6648
#[test]
6649
fn checkpoints_keep_large_graphs_as_blobs_of_their_own() {
6650
    hermetic();
6651
    let dir = tempfile::tempdir().unwrap();
6652
    let root = dir.path();
6653
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6654
    let long: String = (0..300)
6655
        .map(|i| format!("line {i} of a long file\n"))
6656
        .collect();
6657
    write(root, "long.txt", long.as_bytes());
6658
    write(root, "short.txt", b"short\n");
6659
    repo.commit("base", &[]).unwrap();
6660
    let (r1, _, _) = repo.checkpoint().unwrap();
6661
    let cp1 = crate::objects::Checkpoint::decode(
6662
        &repo.store().get_typed(&r1, ObjectType::Checkpoint).unwrap(),
6663
    )
6664
    .unwrap();
6665
    let graphs1 = repo.checkpoint_graph_blobs(&cp1).unwrap();
6666
    assert_eq!(graphs1.len(), 1, "only the long file's graph is a blob");
6667
6668
    // gc keeps the graph blob; fsck finds the checkpoint sound.
6669
    repo.gc(true).unwrap();
6670
    assert!(repo.store().has(&graphs1[0]));
6671
    let report = repo.fsck().unwrap();
6672
    assert_eq!(report.errors(), 0, "{:?}", report.problems);
6673
6674
    // Loading through the checkpoint equals a full load.
6675
    write(root, "short.txt", b"short, edited\n");
6676
    repo.commit("edit the short file", &[]).unwrap();
6677
    let heads = repo.bookmark_heads().unwrap();
6678
    let fast = repo.load_state(&heads).unwrap();
6679
    let full = repo.load_state_full(&heads).unwrap();
6680
    assert_eq!(fast.checkpoint_payload(), full.checkpoint_payload());
6681
6682
    // The next checkpoint shares the unchanged long file's graph.
6683
    let (r2, _, _) = repo.checkpoint().unwrap();
6684
    let cp2 = crate::objects::Checkpoint::decode(
6685
        &repo.store().get_typed(&r2, ObjectType::Checkpoint).unwrap(),
6686
    )
6687
    .unwrap();
6688
    assert_eq!(repo.checkpoint_graph_blobs(&cp2).unwrap(), graphs1);
6689
6690
    // A shallow clone's bundle carries the graph blob with the checkpoint.
6691
    let bundle = repo.checkpoint_bundle_for(&heads).unwrap();
6692
    assert!(bundle.objects.iter().any(|(t, body)| *t == ObjectType::Blob
6693
        && crate::hash::hash_object(ObjectType::Blob, body) == graphs1[0]));
6694
6695
    // A version 1 checkpoint written by an older oxy still loads.
6696
    let state = repo.load_state_full(&heads).unwrap();
6697
    let old = repo.store_blob(&state.checkpoint_payload()).unwrap();
6698
    let cp_old = crate::objects::Checkpoint {
6699
        heads: cp2.heads.clone(),
6700
        count: cp2.count,
6701
        payload: old,
6702
    };
6703
    let r_old = repo
6704
        .store()
6705
        .put(ObjectType::Checkpoint, &cp_old.encode())
6706
        .unwrap();
6707
    repo.install_checkpoint("main", &r_old).unwrap();
6708
    assert_eq!(
6709
        repo.load_state(&heads).unwrap().checkpoint_payload(),
6710
        full.checkpoint_payload()
6711
    );
6712
    assert_eq!(repo.fsck().unwrap().errors(), 0);
6713
6714
    // A lost graph blob fails the load loudly rather than dropping the
6715
    // file, and fsck reports it (a fresh repository, objects still loose).
6716
    let dir2 = tempfile::tempdir().unwrap();
6717
    let root2 = dir2.path();
6718
    let repo2 = Repo::init(root2).unwrap().with_home(root2.join("home"));
6719
    write(root2, "long.txt", long.as_bytes());
6720
    repo2.commit("base", &[]).unwrap();
6721
    let (r, _, _) = repo2.checkpoint().unwrap();
6722
    let cp = crate::objects::Checkpoint::decode(
6723
        &repo2.store().get_typed(&r, ObjectType::Checkpoint).unwrap(),
6724
    )
6725
    .unwrap();
6726
    let graph = repo2.checkpoint_graph_blobs(&cp).unwrap()[0];
6727
    repo2.store().remove_loose_for_test(&graph).unwrap();
6728
    assert!(repo2.load_state(&repo2.bookmark_heads().unwrap()).is_err());
6729
    assert!(repo2.fsck().unwrap().errors() > 0, "fsck reports it");
6730
}
6731
6732
/// A new repository has not stored the user's identity yet (that happens
6733
/// at the first signed change); looking it up falls back to the key
6734
/// directory, and a file there that does not hash to the key is refused.
6735
#[test]
6736
fn identity_is_found_in_the_key_directory_for_a_new_repository() {
6737
    hermetic();
6738
    let dir = tempfile::tempdir().unwrap();
6739
    let home = dir.path().join("home");
6740
    let mut first = Repo::init(&dir.path().join("a"))
6741
        .unwrap()
6742
        .with_home(home.clone());
6743
    let (key, _) = first
6744
        .create_identity("Ada", "[email protected]", IdentityScope::User)
6745
        .unwrap();
6746
    let fresh = Repo::init(&dir.path().join("b"))
6747
        .unwrap()
6748
        .with_home(home.clone());
6749
    assert!(!fresh.store().has(&key), "nothing stored yet");
6750
    let id = fresh.identity(&key).unwrap();
6751
    assert_eq!((id.name.as_str(), id.hash()), ("Ada", key));
6752
    // A key file that is not this identity is an error, not a wrong answer.
6753
    let keys = fresh.keys_dir.clone();
6754
    let (other, _) = first
6755
        .create_identity("Bob", "[email protected]", IdentityScope::User)
6756
        .unwrap();
6757
    fs::copy(
6758
        keys.join(format!("{}.identity", other.to_hex())),
6759
        keys.join(format!("{}.identity", key.to_hex())),
6760
    )
6761
    .unwrap();
6762
    assert!(fresh
6763
        .identity(&key)
6764
        .unwrap_err()
6765
        .to_string()
6766
        .contains("does not hold identity"));
6767
}
6768
6769
/// Status snapshots (spec §12.3): a text file whose stat matches the
6770
/// manifest, and whose base graph key is the one the manifest recorded it
6771
/// equal to, is neither read nor rendered; any edit, and any change to the
6772
/// file's graph in the base, brings it back.
6773
#[cfg(unix)]
6774
#[test]
6775
fn status_snapshots_skip_files_unchanged_since_the_manifest() {
6776
    use std::os::unix::fs::PermissionsExt;
6777
    hermetic();
6778
    let dir = tempfile::tempdir().unwrap();
6779
    let root = dir.path();
6780
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6781
    for (p, c) in [("a.txt", "one\n"), ("b.txt", "bee\n"), ("d/c.txt", "sea\n")] {
6782
        write(root, p, c.as_bytes());
6783
    }
6784
    repo.commit("base", &[]).unwrap();
6785
    let age = |p: &str| {
6786
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6787
        fs::File::options()
6788
            .write(true)
6789
            .open(root.join(p))
6790
            .unwrap()
6791
            .set_modified(old)
6792
            .unwrap();
6793
    };
6794
    let lock = |p: &str, mode: u32| {
6795
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(mode)).unwrap()
6796
    };
6797
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6798
        age(p);
6799
    }
6800
    assert!(repo.snapshot("status").unwrap().statuses.is_empty());
6801
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
6802
    assert!(
6803
        m.entries.values().all(|e| e.graph.is_some()),
6804
        "keys recorded"
6805
    );
6806
6807
    // Unreadable files prove they are not read; the status snapshot does
6808
    // not render them either, and its base lacks their graphs.
6809
    lock("a.txt", 0o000);
6810
    lock("b.txt", 0o000);
6811
    let snap = repo.snapshot_status("status").unwrap();
6812
    assert!(!snap.changed && snap.statuses.is_empty());
6813
    assert_eq!(
6814
        snap.base_snapshot
6815
            .unrendered
6816
            .iter()
6817
            .cloned()
6818
            .collect::<Vec<_>>(),
6819
        vec!["a.txt", "b.txt", "d/c.txt"]
6820
    );
6821
    assert!(!snap.base.is_full());
6822
    assert!(!snap.base_snapshot.is_conflicted());
6823
    // A full snapshot does not read them either, but renders everything.
6824
    let full = repo.snapshot("status").unwrap();
6825
    assert!(full.statuses.is_empty() && full.base.is_full());
6826
    assert!(full.base_snapshot.unrendered.is_empty());
6827
    assert!(matches!(&full.base_snapshot.files["a.txt"].content,
6828
        FileContent::Text { bytes, .. } if bytes == b"one\n"));
6829
6830
    // An edit is seen; the file is rendered, the others still are not.
6831
    write(root, "d/c.txt", b"sea edited\n");
6832
    let snap = repo.snapshot_status("status").unwrap();
6833
    assert_eq!(
6834
        statuses(&snap),
6835
        vec![("d/c.txt".to_string(), ChangeStatus::Modified)]
6836
    );
6837
    assert!(!snap.base_snapshot.unrendered.contains("d/c.txt"));
6838
    // So is a mode change of an unread file.
6839
    lock("b.txt", 0o100);
6840
    assert_eq!(
6841
        statuses(&repo.snapshot_status("status").unwrap()),
6842
        vec![
6843
            ("b.txt".to_string(), ChangeStatus::ModeChanged),
6844
            ("d/c.txt".to_string(), ChangeStatus::Modified)
6845
        ]
6846
    );
6847
    lock("b.txt", 0o000);
6848
6849
    // Committing c.txt changes its graph in the base, not a.txt's: a.txt
6850
    // stays unread, c.txt is read once and then skipped too.
6851
    repo.commit_selection("edit c", &[], &Selection::Paths(vec!["d/c.txt".into()]))
6852
        .unwrap();
6853
    age("d/c.txt");
6854
    let snap = repo.snapshot_status("status").unwrap();
6855
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
6856
    assert!(snap.base_snapshot.unrendered.contains("a.txt"));
6857
    lock("d/c.txt", 0o000);
6858
    let snap = repo.snapshot_status("status").unwrap();
6859
    assert!(snap.statuses.is_empty());
6860
    assert!(snap.base_snapshot.unrendered.contains("d/c.txt"));
6861
    for p in ["a.txt", "b.txt", "d/c.txt"] {
6862
        lock(p, 0o644);
6863
    }
6864
}
6865
6866
/// Attributes decide how a file compares with the base, so a changed
6867
/// `.oxyattributes` makes every text file be compared again.
6868
#[cfg(unix)]
6869
#[test]
6870
fn a_changed_attributes_file_disables_skipping_unchanged_files() {
6871
    hermetic();
6872
    let dir = tempfile::tempdir().unwrap();
6873
    let root = dir.path();
6874
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
6875
    write(root, "a.txt", b"crlf\r\n");
6876
    repo.commit("base", &[]).unwrap();
6877
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
6878
    fs::File::options()
6879
        .write(true)
6880
        .open(root.join("a.txt"))
6881
        .unwrap()
6882
        .set_modified(old)
6883
        .unwrap();
6884
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
6885
    assert!(repo
6886
        .snapshot_status("status")
6887
        .unwrap()
6888
        .base_snapshot
6889
        .unrendered
6890
        .contains("a.txt"));
6891
    // With eol=lf, a.txt as stored no longer equals the base.
6892
    write(root, ".oxyattributes", b"*.txt eol=lf\n");
6893
    let snap = repo.snapshot_status("status").unwrap();
6894
    assert_eq!(
6895
        statuses(&snap),
6896
        vec![
6897
            (".oxyattributes".to_string(), ChangeStatus::Added),
6898
            ("a.txt".to_string(), ChangeStatus::Modified)
6899
        ]
6900
    );
6901
}
6902
6903
/// Bookmarks with `/` in their names: pushing records their
6904
/// attestations, and checkpoints are kept for them, beside `feature`
6905
/// itself.
6906
#[test]
6907
fn bookmarks_with_slashes_push_and_checkpoint() {
6908
    hermetic();
6909
    let dir = tempfile::tempdir().unwrap();
6910
    let root = dir.path();
6911
    let origin = Repo::init(&root.join("origin")).unwrap();
6912
    let url = root.join("origin").to_string_lossy().to_string();
6913
    let mut repo = Repo::clone(&url, &root.join("r"))
6914
        .unwrap()
6915
        .with_home(root.join("home"));
6916
    // With an identity, pushes carry reference attestations: the case
6917
    // that failed, since the attestation is a file named after the bookmark.
6918
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6919
        .unwrap();
6920
    let r = root.join("r");
6921
    write(&r, "a.txt", b"a\n");
6922
    let h_a = repo.commit("a", &[]).unwrap();
6923
    assert!(repo.push("origin", false).unwrap()[0].ok);
6924
    origin.refresh().unwrap();
6925
    repo.bookmark_create("feature", None).unwrap();
6926
    repo.bookmark_create("feature/x", None).unwrap();
6927
    repo.bookmark_switch("feature/x", false).unwrap();
6928
    write(&r, "b.txt", b"b\n");
6929
    let h_b = repo.commit("b", &[]).unwrap();
6930
    for name in ["feature", "feature/x"] {
6931
        let res = repo.push_bookmark("origin", name, false).unwrap();
6932
        origin.refresh().unwrap();
6933
        assert!(res[0].ok, "{name}: {res:?}");
6934
    }
6935
    assert_eq!(origin.resolve_heads("feature").unwrap(), vec![h_a]);
6936
    assert_eq!(
6937
        origin.resolve_heads("feature/x").unwrap(),
6938
        repo.resolve_heads("feature/x").unwrap()
6939
    );
6940
    assert!(origin.resolve_heads("feature/x").unwrap().contains(&h_b));
6941
    assert!(origin.latest_ref_attest("feature/x").unwrap().is_some());
6942
    assert!(origin.latest_ref_attest("feature").unwrap().is_some());
6943
6944
    // A checkpoint of feature/x is found again when loading its state.
6945
    let (cp, _, _) = repo.checkpoint().unwrap();
6946
    assert_eq!(repo.latest_checkpoint("feature/x").unwrap().unwrap().0, cp);
6947
    assert!(repo.latest_checkpoint("feature").unwrap().is_none());
6948
    let heads = repo.resolve_heads("feature/x").unwrap();
6949
    assert!(repo.load_state_checkpointed(&heads).unwrap().is_some());
6950
}
6951
6952
/// Deleting a bookmark on a remote (spec §16.4): attested like any update,
6953
/// never the remote's own bookmark, and a bookmark created again later is
6954
/// accepted although the deletion's attestation stays the latest.
6955
#[test]
6956
fn bookmarks_are_deleted_on_a_remote() {
6957
    hermetic();
6958
    let dir = tempfile::tempdir().unwrap();
6959
    let root = dir.path();
6960
    let origin = Repo::init(&root.join("origin")).unwrap();
6961
    let url = root.join("origin").to_string_lossy().to_string();
6962
    let mut repo = Repo::clone(&url, &root.join("r"))
6963
        .unwrap()
6964
        .with_home(root.join("home"));
6965
    repo.create_identity("Ada", "[email protected]", IdentityScope::Repo)
6966
        .unwrap();
6967
    let r = root.join("r");
6968
    write(&r, "a.txt", b"a\n");
6969
    repo.commit("a", &[]).unwrap();
6970
    assert!(repo.push("origin", false).unwrap()[0].ok);
6971
    origin.refresh().unwrap();
6972
    repo.bookmark_create("feature/x", None).unwrap();
6973
    assert!(repo.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
6974
    origin.refresh().unwrap();
6975
    assert!(origin.resolve_heads("feature/x").is_ok());
6976
6977
    let res = repo.push_delete("origin", "feature/x").unwrap();
6978
    origin.refresh().unwrap();
6979
    assert!(res[0].ok, "{res:?}");
6980
    assert!(!origin.view().unwrap().bookmarks.contains_key("feature/x"));
6981
    let (_, att) = origin.latest_ref_attest("feature/x").unwrap().unwrap();
6982
    assert!(
6983
        matches!(att.attest.body, AttestBody::Ref { new_state, .. } if new_state.is_zero()),
6984
        "the deletion is attested"
6985
    );
6986
    assert!(
6987
        repo.view().unwrap().bookmarks.contains_key("feature/x"),
6988
        "the local bookmark stays"
6989
    );
6990
    assert!(!repo
6991
        .view()
6992
        .unwrap()
6993
        .remotes
6994
        .get("origin")
6995
        .is_some_and(|m| m.contains_key("feature/x")));
6996
6997
    // Pushing it again creates it again, past the deletion's serial.
6998
    let res = repo.push_bookmark("origin", "feature/x", false).unwrap();
6999
    origin.refresh().unwrap();
7000
    assert!(res[0].ok, "{res:?}");
7001
    assert!(origin.view().unwrap().bookmarks.contains_key("feature/x"));
7002
7003
    // Nothing to delete, and never the remote's own bookmark.
7004
    assert!(repo.push_delete("origin", "nope").is_err());
7005
    let res = repo.push_delete("origin", "main").unwrap();
7006
    origin.refresh().unwrap();
7007
    assert!(
7008
        !res[0].ok && res[0].reason.contains("default bookmark"),
7009
        "{res:?}"
7010
    );
7011
    assert!(origin.view().unwrap().bookmarks.contains_key("main"));
7012
}
7013
7014
/// `bookmark switch --carry` (spec §10.1): uncommitted work goes along
7015
/// when the target has the same versions of the files it touches, and is
7016
/// refused, untouched, when it has others.
7017
#[test]
7018
fn switching_bookmarks_carries_uncommitted_work() {
7019
    hermetic();
7020
    let dir = tempfile::tempdir().unwrap();
7021
    let root = dir.path();
7022
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7023
    write(root, "a.txt", b"a\n");
7024
    write(root, "b.txt", b"b\n");
7025
    write(root, "gone.txt", b"gone\n");
7026
    repo.commit("base", &[]).unwrap();
7027
    repo.bookmark_create("feature", None).unwrap();
7028
    // Started on main, belongs on feature: edit, add, remove.
7029
    write(root, "a.txt", b"a\nmore\n");
7030
    write(root, "new.txt", b"new\n");
7031
    fs::remove_file(root.join("gone.txt")).unwrap();
7032
    let (report, carried) = repo.bookmark_switch_carry("feature").unwrap();
7033
    assert_eq!(carried, vec!["a.txt", "gone.txt", "new.txt"]);
7034
    // oxygen#120: the new file was carried, not removed.
7035
    assert_eq!(
7036
        (report.removed, report.removed_paths.len()),
7037
        (0, 0),
7038
        "{report:?}"
7039
    );
7040
    assert_eq!(repo.config.bookmark, "feature");
7041
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nmore\n");
7042
    assert_eq!(fs::read(root.join("new.txt")).unwrap(), b"new\n");
7043
    assert!(!root.join("gone.txt").exists());
7044
    let snap = repo.snapshot("status").unwrap();
7045
    assert_eq!(
7046
        statuses(&snap),
7047
        vec![
7048
            ("a.txt".to_string(), ChangeStatus::Modified),
7049
            ("gone.txt".to_string(), ChangeStatus::Removed),
7050
            ("new.txt".to_string(), ChangeStatus::Added)
7051
        ]
7052
    );
7053
    repo.commit("the work", &[]).unwrap();
7054
    assert!(repo.resolve_heads("main").unwrap().len() == 1);
7055
7056
    // main moves b.txt on; work on feature touching b.txt cannot follow.
7057
    repo.bookmark_switch("main", false).unwrap();
7058
    write(root, "b.txt", b"b on main\n");
7059
    repo.commit("b on main", &[]).unwrap();
7060
    repo.bookmark_switch("feature", false).unwrap();
7061
    write(root, "b.txt", b"b edited\n");
7062
    let err = repo.bookmark_switch_carry("main").unwrap_err().to_string();
7063
    assert!(err.contains("b.txt") && err.contains("--discard"), "{err}");
7064
    assert_eq!(repo.config.bookmark, "feature", "nothing happened");
7065
    assert_eq!(fs::read(root.join("b.txt")).unwrap(), b"b edited\n");
7066
}
7067
7068
/// Merging and checking out (feedback 3): a working copy without changes
7069
/// follows a merge whichever state it sat on; a refused checkout names
7070
/// what is in the way; `checkout --carry` takes the work along.
7071
#[test]
7072
fn merges_move_clean_working_copies_and_checkouts_say_what_blocks_them() {
7073
    hermetic();
7074
    let dir = tempfile::tempdir().unwrap();
7075
    let root = dir.path();
7076
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7077
    write(root, "a.txt", b"a\n");
7078
    let h1 = repo.commit("a", &[]).unwrap();
7079
    write(root, "b.txt", b"b\n");
7080
    repo.commit("b", &[]).unwrap();
7081
    repo.bookmark_create("feature", None).unwrap();
7082
    repo.bookmark_switch("feature", false).unwrap();
7083
    write(root, "c.txt", b"c\n");
7084
    repo.commit("c on feature", &[]).unwrap();
7085
    repo.bookmark_switch("main", false).unwrap();
7086
    // The working copy sits on an older state than main's heads.
7087
    repo.checkout(&[h1], false, "checkout").unwrap();
7088
    assert!(!root.join("b.txt").exists());
7089
    let m = repo.merge("feature").unwrap();
7090
    assert!(m.checked_out, "a clean working copy follows the merge");
7091
    for f in ["a.txt", "b.txt", "c.txt"] {
7092
        assert!(root.join(f).exists(), "{f}");
7093
    }
7094
7095
    // A refusal says which paths are in the way and what to do.
7096
    fs::remove_file(root.join("b.txt")).unwrap();
7097
    write(root, "a.txt", b"a edited\n");
7098
    let err = repo
7099
        .checkout(&[h1], false, "checkout")
7100
        .unwrap_err()
7101
        .to_string();
7102
    assert!(
7103
        err.contains("modified a.txt") && err.contains("removed b.txt") && err.contains("--carry"),
7104
        "{err}"
7105
    );
7106
    // --carry takes them along: h1 has a.txt as the base has it, and the
7107
    // removed b.txt is already as h1 has it (none), so that is no conflict
7108
    // either (oxygen#100).
7109
    let (_, carried) = repo
7110
        .checkout_carry(&[h1], "the first change", "checkout")
7111
        .unwrap();
7112
    assert_eq!(carried, vec!["a.txt"]);
7113
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a edited\n");
7114
    assert!(!root.join("b.txt").exists(), "h1 has no b.txt");
7115
}
7116
7117
/// Doctor and subrepos before the first commit (feedback 5 and 8): a
7118
/// user identity not stored in a new repository yet is fine while its
7119
/// secret key is there; an added subrepo is listed as not committed yet.
7120
#[test]
7121
fn a_new_repository_is_healthy_before_its_first_commit() {
7122
    hermetic();
7123
    let dir = tempfile::tempdir().unwrap();
7124
    let root = dir.path();
7125
    let home = root.join("home");
7126
    let mut first = Repo::init(&root.join("first"))
7127
        .unwrap()
7128
        .with_home(home.clone());
7129
    let (key, _) = first
7130
        .create_identity("Ada", "[email protected]", IdentityScope::User)
7131
        .unwrap();
7132
    let repo = Repo::init(&root.join("second"))
7133
        .unwrap()
7134
        .with_home(home.clone());
7135
    // Only the secret key: no identity object anywhere this repository sees.
7136
    let keys = repo.keys_dir.clone();
7137
    let _ = fs::remove_file(keys.join(format!("{}.identity", key.to_hex())));
7138
    assert!(keys.join(format!("{}.secret", key.to_hex())).is_file());
7139
    let r = repo.doctor(true);
7140
    let id = r.checks.iter().find(|c| c.area == "identity").unwrap();
7141
    assert_eq!(id.health, Health::Ok, "{}", id.message);
7142
    assert!(id.message.contains("first signed change"), "{}", id.message);
7143
7144
    // A subrepo added and not committed yet is listed, pinned where it is.
7145
    let lib = root.join("lib");
7146
    let l = Repo::init(&lib).unwrap().with_home(home.clone());
7147
    write(&lib, "x.txt", b"x\n");
7148
    l.commit("x", &[]).unwrap();
7149
    let second = root.join("second");
7150
    write(&second, "a.txt", b"a\n");
7151
    repo.submodule_add(&lib.to_string_lossy(), "deps/lib", None)
7152
        .unwrap();
7153
    let subs = repo.subrepos().unwrap();
7154
    assert_eq!(subs.len(), 1);
7155
    assert_eq!(
7156
        (subs[0].path.as_str(), subs[0].committed),
7157
        ("deps/lib", false)
7158
    );
7159
    assert_eq!(subs[0].actual.as_ref(), Some(&subs[0].pin));
7160
    repo.commit("add lib", &[]).unwrap();
7161
    let subs = repo.subrepos().unwrap();
7162
    assert!(subs[0].committed, "committed now");
7163
}
7164
7165
/// Commit, diff, hunks and discard use the partial snapshot: a file
7166
/// unchanged since the manifest is neither read nor rendered, and showing
7167
/// a change renders only what it edits, the same as from a full base.
7168
#[cfg(unix)]
7169
#[test]
7170
fn commits_and_diffs_leave_unchanged_files_alone() {
7171
    use std::os::unix::fs::PermissionsExt;
7172
    hermetic();
7173
    let dir = tempfile::tempdir().unwrap();
7174
    let root = dir.path();
7175
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7176
    write(root, "big.txt", b"lots\nof\nlines\n");
7177
    write(root, "a.txt", b"one\ntwo\n");
7178
    repo.commit("base", &[]).unwrap();
7179
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
7180
    for f in ["big.txt", "a.txt"] {
7181
        fs::File::options()
7182
            .write(true)
7183
            .open(root.join(f))
7184
            .unwrap()
7185
            .set_modified(old)
7186
            .unwrap();
7187
    }
7188
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
7189
    // big.txt cannot be read at all from here on.
7190
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o000)).unwrap();
7191
7192
    write(root, "a.txt", b"one\nTWO\nthree\n");
7193
    let diff = repo.diff_files(None).unwrap();
7194
    assert_eq!(
7195
        diff.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
7196
        ["a.txt"]
7197
    );
7198
    let (_, hunks) = repo.hunks().unwrap();
7199
    assert!(!hunks.is_empty() && hunks.iter().all(|h| h.path == "a.txt"));
7200
    let h = repo.commit("edit a", &[]).unwrap();
7201
7202
    // Showing the change needs only a.txt's graph, and renders as a full base does.
7203
    let c = repo.store().get_change(&h).unwrap();
7204
    let full = repo.load_state(&c.deps).unwrap();
7205
    let want = render_change(&c, &full, &full.materialize());
7206
    assert_eq!(repo.describe_change(&h).unwrap(), want);
7207
    let (base, snap) = repo.change_base(&c).unwrap();
7208
    assert!(!base.is_full() && snap.unrendered.contains("big.txt"));
7209
7210
    // Discarding works the same way.
7211
    write(root, "a.txt", b"scratch\n");
7212
    assert_eq!(repo.discard(&["a.txt".into()]).unwrap(), 1);
7213
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\nTWO\nthree\n");
7214
    fs::set_permissions(root.join("big.txt"), fs::Permissions::from_mode(0o644)).unwrap();
7215
}
7216
7217
/// A replace conflict (spec §9.3) is settled by a change that writes one
7218
/// candidate, or new bytes, at the path when the caller names it; a plain
7219
/// snapshot of a checkout never settles it on its own.
7220
#[test]
7221
fn replace_conflicts_are_settled_when_asked() {
7222
    hermetic();
7223
    let dir = tempfile::tempdir().unwrap();
7224
    let root = dir.path();
7225
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
7226
    let blob = |n: u8| {
7227
        let mut v = vec![0u8; 64];
7228
        v[1] = n;
7229
        v
7230
    };
7231
    write(root, "img.bin", &blob(1));
7232
    repo.commit("add img", &[]).unwrap();
7233
    repo.bookmark_create("other", None).unwrap();
7234
    write(root, "img.bin", &blob(2));
7235
    repo.commit("img two", &[]).unwrap();
7236
    repo.bookmark_switch("other", false).unwrap();
7237
    write(root, "img.bin", &blob(3));
7238
    repo.commit("img three", &[]).unwrap();
7239
    repo.bookmark_switch("main", false).unwrap();
7240
    repo.merge("other").unwrap();
7241
    let heads = repo.bookmark_heads().unwrap();
7242
    let merged = repo.load_state(&heads).unwrap().materialize();
7243
    assert!(
7244
        matches!(&merged.files["img.bin"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
7245
        "a replace conflict"
7246
    );
7247
    // A snapshot of the checkout records nothing.
7248
    assert!(repo
7249
        .snapshot("status")
7250
        .unwrap()
7251
        .statuses
7252
        .iter()
7253
        .all(|s| s.path != "img.bin"));
7254
7255
    // Keeping candidate 3 settles it.
7256
    let author = repo.author();
7257
    let edits = [FileEdit {
7258
        path: "img.bin".into(),
7259
        content: Some(blob(3)),
7260
    }];
7261
    let c = repo
7262
        .build_change(&heads, &edits, "keep three", author)
7263
        .unwrap();
7264
    assert_eq!(c.kind, ChangeKind::Resolution);
7265
    let mut st = repo.load_state(&heads).unwrap();
7266
    for d in &c.deps {
7267
        assert!(st.contains(d));
7268
    }
7269
    assert!(
7270
        heads.iter().all(|h| c.deps.contains(h)),
7271
        "depends on both contributors"
7272
    );
7273
    st.add(c).unwrap();
7274
    let after = st.materialize();
7275
    assert!(!after.is_conflicted());
7276
    assert_eq!(
7277
        after.files["img.bin"].content,
7278
        FileContent::Opaque {
7279
            blobs: vec![Repo::blob_ref(&blob(3))]
7280
        }
7281
    );
7282
7283
    // New bytes settle it too.
7284
    let edits = [FileEdit {
7285
        path: "img.bin".into(),
7286
        content: Some(blob(9)),
7287
    }];
7288
    let c = repo.build_change(&heads, &edits, "new", author).unwrap();
7289
    let mut st = repo.load_state(&heads).unwrap();
7290
    st.add(c).unwrap();
7291
    assert_eq!(
7292
        st.materialize().files["img.bin"].content,
7293
        FileContent::Opaque {
7294
            blobs: vec![Repo::blob_ref(&blob(9))]
7295
        }
7296
    );
7297
}
7298
7299
/// The history of a range of lines (spec §27): the changes that wrote
7300
/// or deleted its atoms, or deleted atoms from between them; edits outside
7301
/// the range and changes the range's lines survived are not in it.
7302
#[test]
7303
fn line_ranges_have_exact_histories() {
7304
    hermetic();
7305
    let dir = tempfile::tempdir().unwrap();
7306
    let root = dir.path();
7307
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7308
    write(root, "f.rs", b"use x;\nfn a() {\n  one();\n  two();\n}\n");
7309
    let base = repo.commit("add f", &[]).unwrap();
7310
    write(root, "f.rs", b"use y;\nfn a() {\n  one();\n  two();\n}\n");
7311
    let outside = repo.commit("change the import", &[]).unwrap();
7312
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n  two();\n}\n");
7313
    let inside = repo.commit("edit a line of a", &[]).unwrap();
7314
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\n");
7315
    let deleted = repo.commit("delete a line of a", &[]).unwrap();
7316
    write(root, "f.rs", b"use y;\nfn a() {\n  ONE();\n}\nfn b() {}\n");
7317
    let after = repo.commit("add b after a", &[]).unwrap();
7318
    let heads = repo.bookmark_heads().unwrap();
7319
7320
    // Lines 2..4 are `fn a() {`, `ONE();`, `}` now.
7321
    let hist: Vec<ChangeHash> = repo
7322
        .line_history(&heads, "f.rs", 2, 4)
7323
        .unwrap()
7324
        .iter()
7325
        .map(|e| e.hash)
7326
        .collect();
7327
    for (h, what) in [
7328
        (base, "wrote it"),
7329
        (inside, "edited a line"),
7330
        (deleted, "deleted a line from inside"),
7331
    ] {
7332
        assert!(hist.contains(&h), "{what}");
7333
    }
7334
    for (h, what) in [(outside, "an edit above"), (after, "an addition below")] {
7335
        assert!(!hist.contains(&h), "{what}");
7336
    }
7337
    assert_eq!(hist[0], deleted, "newest first");
7338
    // One line: only what touched it.
7339
    let one: Vec<ChangeHash> = repo
7340
        .line_history(&heads, "f.rs", 1, 1)
7341
        .unwrap()
7342
        .iter()
7343
        .map(|e| e.hash)
7344
        .collect();
7345
    assert!(one.contains(&outside) && !one.contains(&inside));
7346
    assert!(repo.line_history(&heads, "f.rs", 3, 9).is_err());
7347
    assert!(repo.line_history(&heads, "f.rs", 0, 1).is_err());
7348
    assert!(repo.line_history(&heads, "nope.rs", 1, 1).is_err());
7349
}
7350
7351
#[test]
7352
fn receipts_are_kept_with_their_state_and_verified() {
7353
    use crate::receipt::{Receipt, SignedReceipt};
7354
    hermetic();
7355
    let dir = tempfile::tempdir().unwrap();
7356
    let root = dir.path();
7357
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7358
    write(root, "a.txt", b"1\n");
7359
    repo.commit("A", &[]).unwrap();
7360
    let heads = repo.bookmark_heads().unwrap();
7361
    let state = repo
7362
        .store()
7363
        .put_state(&StateObject::new(heads.clone()))
7364
        .unwrap();
7365
    let out = repo.store_blob(b"built\n").unwrap();
7366
    let receipt = Receipt {
7367
        job_name: "build".into(),
7368
        pipeline_hash: ObjectRef([1; 32]),
7369
        scope_tree_hash: ObjectRef([2; 32]),
7370
        inputs: vec![],
7371
        environment: ObjectRef([3; 32]),
7372
        outputs: vec![out],
7373
        exit_code: 0,
7374
        duration_ms: 42,
7375
    };
7376
    let sk = SecretKey::generate();
7377
    let runner = sk.identity("earth-1", "runner@earth", 1);
7378
    let sr = SignedReceipt::sign(
7379
        receipt.clone(),
7380
        repo.id().unwrap(),
7381
        state,
7382
        "demo#1",
7383
        &runner,
7384
        &sk,
7385
    );
7386
7387
    let r = repo.add_receipt(&sr).unwrap();
7388
    let found = repo.receipts(&heads).unwrap();
7389
    assert_eq!(found.len(), 1);
7390
    assert_eq!(found[0].attest, r);
7391
    assert_eq!(found[0].signed, sr);
7392
    assert!(found[0].problem.is_none() && !found[0].revoked);
7393
    assert!(repo.receipts(&[ObjectRef([5; 32])]).unwrap().is_empty());
7394
7395
    // Another repository's receipt, or a forged one, is refused.
7396
    let elsewhere = SignedReceipt::sign(receipt.clone(), [0; 16], state, "x", &runner, &sk);
7397
    assert!(repo
7398
        .add_receipt(&elsewhere)
7399
        .unwrap_err()
7400
        .to_string()
7401
        .contains("another repository"));
7402
    let mut forged = sr.clone();
7403
    forged.receipt.exit_code = 1;
7404
    assert!(repo
7405
        .add_receipt(&forged)
7406
        .unwrap_err()
7407
        .to_string()
7408
        .contains("does not verify"));
7409
7410
    // A receipt signed by a short-lived key keeps its certificate and the
7411
    // issuer's identity, and reads back with them (oxygenhub#241).
7412
    let hub_sk = SecretKey::generate();
7413
    let hub = hub_sk.identity("oxygenhub.io", "[email protected]", 1);
7414
    let job_sk = SecretKey::generate();
7415
    let job = job_sk.identity("job 2 test", "[email protected]", 1);
7416
    let mut test_receipt = receipt.clone();
7417
    test_receipt.job_name = "test".into();
7418
    let plain = SignedReceipt::sign(
7419
        test_receipt,
7420
        repo.id().unwrap(),
7421
        state,
7422
        "demo#2",
7423
        &job,
7424
        &job_sk,
7425
    );
7426
    let now = plain.attest.hlc.wall_ms;
7427
    let cert = crate::cert::SignedCertificate::sign(
7428
        crate::cert::Certificate {
7429
            key: job.clone(),
7430
            issuer: hub.hash(),
7431
            subject: "repo:andy/demo:bookmark:main".into(),
7432
            claims: vec![],
7433
            scope: crate::identity::Scope::SEAL,
7434
            not_before: now - 1_000,
7435
            expires: now + 600_000,
7436
            grant: None,
7437
        },
7438
        &hub,
7439
        &hub_sk,
7440
    );
7441
    let certified = plain.with_certificate(cert, hub.clone());
7442
    repo.add_receipt(&certified).unwrap();
7443
    let found = repo.receipts(&heads).unwrap();
7444
    let got = found
7445
        .iter()
7446
        .find(|i| i.signed.receipt.job_name == "test")
7447
        .unwrap();
7448
    assert_eq!(got.signed, certified);
7449
    assert!(got.problem.is_none(), "{:?}", got.problem);
7450
7451
    // gc keeps the receipts, their runners, the certificate and its issuer,
7452
    // and the output while the state lives.
7453
    repo.gc(true).unwrap();
7454
    let found = repo.receipts(&heads).unwrap();
7455
    assert_eq!(found.len(), 2);
7456
    let got = found
7457
        .iter()
7458
        .find(|i| i.signed.receipt.job_name == "test")
7459
        .unwrap();
7460
    assert_eq!(got.signed, certified, "the certificate survives gc");
7461
    assert!(got.problem.is_none());
7462
    assert_eq!(repo.read_blob(&out).unwrap(), b"built\n");
7463
    assert!(repo.fsck().unwrap().problems.is_empty());
7464
}
7465
7466
#[test]
7467
fn approvals_are_kept_with_their_state_and_survive_gc() {
7468
    hermetic();
7469
    let dir = tempfile::tempdir().unwrap();
7470
    let root = dir.path();
7471
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7472
    write(root, "a.txt", b"1\n");
7473
    repo.commit("A", &[]).unwrap();
7474
    let heads = repo.bookmark_heads().unwrap();
7475
    let state = repo.store().put_state(&StateObject::new(heads)).unwrap();
7476
    let plan = repo.store_blob(b"the reviewed plan\n").unwrap();
7477
    let sk = SecretKey::generate();
7478
    let andy = sk.identity("Andy", "[email protected]", 1);
7479
    let statement = crate::approval::Statement {
7480
        repo: repo.id().unwrap(),
7481
        run: "https://hub.example/andy/infra/flow/8".into(),
7482
        job: "apply".into(),
7483
        job_hash: ObjectRef([1; 32]),
7484
        state,
7485
        inputs: vec![plan],
7486
        environment: "prod".into(),
7487
        approve: true,
7488
    };
7489
    let sa = crate::approval::SignedApproval::sign(&statement, &andy, &sk);
7490
    let r = repo.add_approval(&sa).unwrap();
7491
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
7492
    // Another repository's approval, or a changed one, is refused.
7493
    let elsewhere = crate::approval::SignedApproval::sign(
7494
        &crate::approval::Statement {
7495
            repo: [0; 16],
7496
            ..statement.clone()
7497
        },
7498
        &andy,
7499
        &sk,
7500
    );
7501
    assert!(repo
7502
        .add_approval(&elsewhere)
7503
        .unwrap_err()
7504
        .to_string()
7505
        .contains("another repository"));
7506
    let mut forged = sa.clone();
7507
    if let AttestBody::Approval { environment, .. } = &mut forged.attest.body {
7508
        *environment = "dev".into();
7509
    }
7510
    assert!(repo
7511
        .add_approval(&forged)
7512
        .unwrap_err()
7513
        .to_string()
7514
        .contains("does not verify"));
7515
    // gc keeps it, its signature and its signer while the state lives.
7516
    repo.gc(true).unwrap();
7517
    assert_eq!(repo.store().approvals_for(&state).unwrap(), vec![r]);
7518
    assert_eq!(repo.store().get_attest(&r).unwrap(), sa.attest);
7519
    assert_eq!(repo.store().signatures(&r).unwrap(), sa.sigs);
7520
    assert!(repo.fsck().unwrap().problems.is_empty());
7521
}
7522
7523
#[test]
7524
fn status_leaves_an_unchanged_manifest_alone() {
7525
    hermetic();
7526
    let dir = tempfile::tempdir().unwrap();
7527
    let root = dir.path();
7528
    let repo = Repo::init(root).unwrap().with_home(root.join("home"));
7529
    write(root, "a.txt", b"1\n");
7530
    write(root, "b.txt", b"2\n");
7531
    repo.commit("A", &[]).unwrap();
7532
    // Files last touched well outside the racy window.
7533
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
7534
    for f in ["a.txt", "b.txt"] {
7535
        fs::File::options()
7536
            .write(true)
7537
            .open(root.join(f))
7538
            .unwrap()
7539
            .set_modified(old)
7540
            .unwrap();
7541
    }
7542
    repo.snapshot_status("status").unwrap();
7543
    let path = repo.manifest_path();
7544
    let first = fs::read(&path).unwrap();
7545
    repo.snapshot_status("status").unwrap();
7546
    assert_eq!(
7547
        fs::read(&path).unwrap(),
7548
        first,
7549
        "an unchanged tree does not rewrite the manifest"
7550
    );
7551
    // A change rewrites it.
7552
    write(root, "a.txt", b"1\n2\n");
7553
    repo.snapshot_status("status").unwrap();
7554
    assert_ne!(fs::read(&path).unwrap(), first);
7555
}
7556
7557
#[test]
7558
fn large_text_files_travel_and_survive_gc_as_text_blobs() {
7559
    hermetic();
7560
    let dir = tempfile::tempdir().unwrap();
7561
    let root = dir.path();
7562
    let origin_path = root.join("origin");
7563
    Repo::init(&origin_path).unwrap();
7564
    let origin_url = origin_path.to_string_lossy().to_string();
7565
    let a = Repo::clone(&origin_url, &root.join("a")).unwrap();
7566
    let big: String = (0..5000).map(|i| format!("line {i}\n")).collect();
7567
    write(&root.join("a"), "big.txt", big.as_bytes());
7568
    write(&root.join("a"), "small.txt", b"small\n");
7569
    let h1 = a.commit("large", &[]).unwrap();
7570
    let (_, body) = a.store().get(&h1).unwrap();
7571
    assert!(body.len() < 2048, "the change is {} bytes", body.len());
7572
    assert!(a.push("origin", false).unwrap()[0].ok);
7573
7574
    // A clone reads the text from the blobs that came with the change.
7575
    let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
7576
    assert_eq!(fs::read(root.join("b/big.txt")).unwrap(), big.as_bytes());
7577
    // An edit in the middle of the stored insert is an ordinary change.
7578
    let edited = big.replace("line 2500\n", "line 2500, edited\n");
7579
    write(&root.join("b"), "big.txt", edited.as_bytes());
7580
    let h2 = b.commit("edit", &[]).unwrap();
7581
    assert!(b.store().get_change(&h2).unwrap().edits.len() <= 2);
7582
    assert!(b.push("origin", false).unwrap()[0].ok);
7583
    assert!(a.pull("origin").unwrap().checked_out);
7584
    assert_eq!(fs::read(root.join("a/big.txt")).unwrap(), edited.as_bytes());
7585
    assert_eq!(
7586
        a.fsck().unwrap().errors(),
7587
        0,
7588
        "{:?}",
7589
        a.fsck().unwrap().problems
7590
    );
7591
7592
    // With zero retention gc keeps the text blobs of every kept change.
7593
    let mut a = Repo::open(&root.join("a")).unwrap();
7594
    a.config.set("core.op-retention", "0").unwrap();
7595
    a.save_config().unwrap();
7596
    let a = Repo::open(&root.join("a")).unwrap();
7597
    a.gc(true).unwrap();
7598
    let a = Repo::open(&root.join("a")).unwrap();
7599
    assert_eq!(a.store().get_change(&h1).unwrap().message, "large");
7600
    assert_eq!(
7601
        a.fsck().unwrap().errors(),
7602
        0,
7603
        "{:?}",
7604
        a.fsck().unwrap().problems
7605
    );
7606
    // And a clone of the packed repository reads them from its packs.
7607
    let c = Repo::clone(&root.join("a").to_string_lossy(), &root.join("c")).unwrap();
7608
    assert_eq!(fs::read(root.join("c/big.txt")).unwrap(), edited.as_bytes());
7609
    drop(c);
7610
}
7611
7612
#[test]
7613
fn operations_that_both_replace_a_working_copy_are_not_merged() {
7614
    hermetic();
7615
    let dir = tempfile::tempdir().unwrap();
7616
    let root = dir.path();
7617
    let repo = Repo::init(root).unwrap();
7618
    write(root, "a.txt", b"a\n");
7619
    let a = repo.commit("a", &[]).unwrap();
7620
    write(root, "b.txt", b"b\n");
7621
    repo.commit("b", &[]).unwrap();
7622
    let (x, op) = repo.head_op().unwrap();
7623
    let ws = *op.view.workspaces.keys().next().unwrap();
7624
    let mut one = op.view.clone();
7625
    one.workspaces.insert(ws, a);
7626
    let mut two = op.view.clone();
7627
    two.workspaces.insert(ws, ObjectRef([7; 32]));
7628
    let first = repo.record_op(&[x], "one", one).unwrap();
7629
    let e = repo.record_op(&[x], "two", two).unwrap_err();
7630
    assert!(
7631
        e.to_string()
7632
            .contains("changed this working copy at the same time"),
7633
        "{e}"
7634
    );
7635
    assert_eq!(
7636
        repo.head_op().unwrap().0,
7637
        first,
7638
        "the second is not recorded"
7639
    );
7640
}
7641
7642
/// Metalgear, 2026-09-29 (oxygen#36): a status run while a bookmark switch
7643
/// rewrote the working copy recorded the half-written files as edits, and
7644
/// its view replaced the switch's.
7645
#[test]
7646
fn a_snapshot_during_a_switch_never_records_the_switch_as_edits() {
7647
    hermetic();
7648
    let dir = tempfile::tempdir().unwrap();
7649
    let root = dir.path().to_path_buf();
7650
    let mut repo = Repo::init(&root).unwrap();
7651
    write(&root, "keep.txt", b"keep\n");
7652
    repo.commit("base", &[]).unwrap();
7653
    repo.bookmark_create("small", None).unwrap();
7654
    for i in 0..300 {
7655
        write(
7656
            &root,
7657
            &format!("many/f{i}.txt"),
7658
            format!("file {i}\n").as_bytes(),
7659
        );
7660
    }
7661
    repo.commit("many", &[]).unwrap();
7662
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
7663
    let watcher = {
7664
        let (root, stop) = (root.clone(), stop.clone());
7665
        std::thread::spawn(move || {
7666
            let r = Repo::open(&root).unwrap();
7667
            let mut ran = 0;
7668
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
7669
                if r.snapshot_status("oxy status").is_ok() {
7670
                    ran += 1;
7671
                }
7672
            }
7673
            ran
7674
        })
7675
    };
7676
    for i in 0..20 {
7677
        let to = if i % 2 == 0 { "small" } else { "main" };
7678
        repo.bookmark_switch(to, false).unwrap();
7679
    }
7680
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
7681
    assert!(watcher.join().unwrap() > 0, "the watcher snapshotted");
7682
    // Back on main, clean, with every file where main has it.
7683
    let repo = Repo::open(&root).unwrap();
7684
    let s = repo.snapshot_status("oxy status").unwrap();
7685
    assert!(s.statuses.is_empty(), "{:?}", statuses(&s));
7686
    assert!(s.wc.edits.is_empty() && s.wc.tree_ops.is_empty());
7687
    assert_eq!(s.wc.deps, repo.bookmark_heads().unwrap());
7688
    assert!(root.join("many/f299.txt").exists());
7689
}
7690
7691
/// Metalgear, 2026-09-29 (oxygen#38): a parent's `bookmark switch --carry`
7692
/// put a subrepo that was ahead of its pin back at the pin and moved the
7693
/// subrepo's own bookmark backwards.
7694
#[test]
7695
fn a_parent_switch_with_carry_leaves_a_subrepo_ahead_of_its_pin_alone() {
7696
    hermetic();
7697
    let dir = tempfile::tempdir().unwrap();
7698
    let root = dir.path();
7699
    Repo::init(&root.join("lib-origin")).unwrap();
7700
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
7701
    let lib = Repo::clone(&lib_url, &root.join("lib")).unwrap();
7702
    write(&root.join("lib"), "lib.txt", b"v1\n");
7703
    lib.commit("lib v1", &[]).unwrap();
7704
    assert!(lib.push("origin", false).unwrap()[0].ok);
7705
7706
    let app_dir = root.join("app");
7707
    let mut app = Repo::init(&app_dir).unwrap();
7708
    write(&app_dir, "main.txt", b"app\n");
7709
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
7710
    app.commit("app with lib", &[]).unwrap();
7711
    app.bookmark_create("feature", None).unwrap();
7712
7713
    // New work in the subrepo, not yet pinned by the parent.
7714
    let nested_dir = app_dir.join("libs/lib");
7715
    let nested = Repo::open(&nested_dir).unwrap();
7716
    write(&nested_dir, "new.txt", b"new\n");
7717
    let l2 = nested.commit("lib: new file", &[]).unwrap();
7718
    drop(nested);
7719
7720
    let (_, carried) = app.bookmark_switch_carry("feature").unwrap();
7721
    assert!(carried.contains(&"libs/lib".to_string()), "{carried:?}");
7722
    let nested = Repo::open(&nested_dir).unwrap();
7723
    assert!(
7724
        nested.bookmark_heads().unwrap().contains(&l2),
7725
        "its bookmark kept its work"
7726
    );
7727
    assert!(nested_dir.join("new.txt").exists(), "and its files");
7728
    let s = app.snapshot("status").unwrap();
7729
    assert_eq!(
7730
        statuses(&s),
7731
        vec![("libs/lib".to_string(), ChangeStatus::Modified)]
7732
    );
7733
}
7734
7735
/// oxygen#29 (metalgear, rstar-api): after a proposal landed on the hub,
7736
/// moving `main` to a change this clone had pushed on another bookmark,
7737
/// the first `pull` said "Already up to date" while `main` was behind.
7738
#[test]
7739
fn pull_takes_a_remote_move_to_changes_already_here() {
7740
    hermetic();
7741
    let dir = tempfile::tempdir().unwrap();
7742
    let root = dir.path();
7743
    let origin_path = root.join("origin");
7744
    let origin = Repo::init(&origin_path).unwrap();
7745
    let url = origin_path.to_string_lossy().to_string();
7746
    let mut b = Repo::clone(&url, &root.join("b")).unwrap();
7747
    write(&root.join("b"), "base.txt", b"base\n");
7748
    b.commit("base", &[]).unwrap();
7749
    assert!(b.push("origin", false).unwrap()[0].ok);
7750
    origin.refresh().unwrap();
7751
7752
    // A feature bookmark with one change, pushed.
7753
    b.bookmark_create("feat", None).unwrap();
7754
    b.bookmark_switch("feat", false).unwrap();
7755
    write(&root.join("b"), "x.txt", b"x\n");
7756
    let x = b.commit("x", &[]).unwrap();
7757
    assert!(b.push("origin", false).unwrap()[0].ok);
7758
    origin.refresh().unwrap();
7759
    b.bookmark_switch("main", false).unwrap();
7760
7761
    // The remote lands it: its main moves to the feature's state.
7762
    let feat = origin
7763
        .store()
7764
        .get_state(&origin.view().unwrap().bookmarks["feat"])
7765
        .unwrap()
7766
        .heads;
7767
    origin.bookmark_set("main", &feat).unwrap();
7768
7769
    let r = b.pull("origin").unwrap();
7770
    assert!(r.changed, "{r:?}");
7771
    assert!(r.heads.contains(&x) || b.load_state(&r.heads).unwrap().contains(&x));
7772
    let main = b
7773
        .bookmarks()
7774
        .unwrap()
7775
        .into_iter()
7776
        .find(|m| m.name == "main")
7777
        .unwrap();
7778
    assert_eq!(main.behind, Some(0), "{main:?}");
7779
}
7780
7781
/// oxygen#48: a remote's bookmarks are names here (`origin/NAME`); switching
7782
/// to one only the remote has makes a local bookmark from it; a pull moves
7783
/// every local bookmark the remote has too; a clone checks out the remote's
7784
/// default bookmark.
7785
#[test]
7786
fn remote_bookmarks_are_named_switched_to_pulled_and_cloned() {
7787
    hermetic();
7788
    let dir = tempfile::tempdir().unwrap();
7789
    let root = dir.path();
7790
    let origin_path = root.join("origin");
7791
    let mut origin = Repo::init(&origin_path).unwrap();
7792
    let url = origin_path.to_string_lossy().to_string();
7793
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
7794
    write(&root.join("a"), "base.txt", b"base\n");
7795
    a.commit("base", &[]).unwrap();
7796
    assert!(a.push("origin", false).unwrap()[0].ok);
7797
    a.bookmark_create("develop", None).unwrap();
7798
    a.bookmark_switch("develop", false).unwrap();
7799
    write(&root.join("a"), "base.txt", b"base\nd1\n");
7800
    let d1 = a.commit("d1", &[]).unwrap();
7801
    assert!(a.push("origin", false).unwrap()[0].ok);
7802
7803
    // A clone has main only; origin/develop is a name all the same.
7804
    let c_root = root.join("c");
7805
    let mut c = Repo::clone(&url, &c_root).unwrap();
7806
    assert_eq!(c.config.bookmark, "main");
7807
    assert!(!c.view().unwrap().bookmarks.contains_key("develop"));
7808
    assert_eq!(c.resolve_heads("origin/develop").unwrap(), vec![d1]);
7809
    assert_eq!(c.resolve_change("origin/develop").unwrap(), d1);
7810
    assert_eq!(c.remote_only_bookmarks().unwrap().len(), 1);
7811
7812
    // Switching makes the local bookmark from origin's.
7813
    c.bookmark_switch("develop", false).unwrap();
7814
    assert_eq!(c.config.bookmark, "develop");
7815
    assert_eq!(c.bookmark_heads().unwrap(), vec![d1]);
7816
    assert_eq!(fs::read(c_root.join("base.txt")).unwrap(), b"base\nd1\n");
7817
    assert!(c.remote_only_bookmarks().unwrap().is_empty());
7818
    assert!(c.bookmark_switch("nowhere", false).is_err());
7819
7820
    // Both bookmarks move on the remote; one pull takes both.
7821
    write(&root.join("a"), "base.txt", b"base\nd1\nd2\n");
7822
    let d2 = a.commit("d2", &[]).unwrap();
7823
    assert!(a.push("origin", false).unwrap()[0].ok);
7824
    a.bookmark_switch("main", false).unwrap();
7825
    write(&root.join("a"), "m.txt", b"m\n");
7826
    let m = a.commit("m", &[]).unwrap();
7827
    assert!(a.push("origin", false).unwrap()[0].ok);
7828
    // oxygen#117: a remote's bookmark merges without switching to it.
7829
    let f = Repo::clone(&url, &root.join("f")).unwrap();
7830
    assert!(!f.view().unwrap().bookmarks.contains_key("develop"));
7831
    let merged = f.merge("origin/develop").unwrap();
7832
    assert!(merged.changed, "{merged:?}");
7833
    assert!(
7834
        f.load_state_indexed(&f.bookmark_heads().unwrap())
7835
            .unwrap()
7836
            .contains(&d1),
7837
        "main holds develop's change"
7838
    );
7839
    assert!(f
7840
        .merge("origin/nowhere")
7841
        .unwrap_err()
7842
        .to_string()
7843
        .contains("no bookmark origin/nowhere"));
7844
    let r = c.pull("origin").unwrap();
7845
    assert!(r.changed && r.checked_out, "{r:?}");
7846
    assert_eq!(r.heads, vec![d2]);
7847
    assert_eq!(r.others, vec!["main".to_string()]);
7848
    assert!(c.resolve_heads("main").unwrap().contains(&m));
7849
    assert_eq!(
7850
        fs::read(c_root.join("base.txt")).unwrap(),
7851
        b"base\nd1\nd2\n"
7852
    );
7853
    let again = c.pull("origin").unwrap();
7854
    assert!(!again.changed && again.others.is_empty(), "{again:?}");
7855
7856
    // A clone checks out the remote's default bookmark.
7857
    origin.config.set("workspace.bookmark", "develop").unwrap();
7858
    origin.save_config().unwrap();
7859
    let e = Repo::clone(&url, &root.join("e")).unwrap();
7860
    assert_eq!(e.config.bookmark, "develop");
7861
    assert_eq!(e.bookmark_heads().unwrap(), vec![d2]);
7862
    let reopened = Repo::open(&root.join("e")).unwrap();
7863
    assert_eq!(reopened.config.bookmark, "develop");
7864
    // REMOTE/NAME names the remote's bookmark to switch to.
7865
    let mut e = reopened;
7866
    e.bookmark_switch("origin/main", false).unwrap();
7867
    assert_eq!(e.config.bookmark, "main");
7868
    assert!(e.bookmark_heads().unwrap().contains(&m));
7869
}
7870
7871
/// oxygen#51, #52: --at-op reads an earlier view and refuses changes;
7872
/// op restore goes back to an operation, files included, and undo takes
7873
/// the restore back whole; op revert undoes one operation alone; each
7874
/// operation's changes are described from the views.
7875
#[test]
7876
fn operations_can_be_read_restored_and_reverted() {
7877
    hermetic();
7878
    let dir = tempfile::tempdir().unwrap();
7879
    let root = dir.path();
7880
    let repo = Repo::init(root).unwrap();
7881
    write(root, "a.txt", b"a\n");
7882
    let first = repo.commit("first", &[]).unwrap();
7883
    write(root, "a.txt", b"a\nb\n");
7884
    let second = repo.commit("second", &[]).unwrap();
7885
    let at_second = repo.head_op().unwrap().0.to_hex();
7886
    repo.bookmark_create("keep", None).unwrap();
7887
    let created = repo.head_op().unwrap().0.to_hex();
7888
    write(root, "n.txt", b"n\n");
7889
    let third = repo.commit("third", &[]).unwrap();
7890
7891
    // What each operation changed.
7892
    let ops = repo.op_log().unwrap();
7893
    let changes = repo.view_changes(&ops[1].1.view, &ops[0].1.view).unwrap();
7894
    assert!(
7895
        changes
7896
            .iter()
7897
            .any(|c| matches!(c, ViewChange::BookmarkMoved { name, .. } if name == "main")),
7898
        "{changes:?}"
7899
    );
7900
    assert!(changes
7901
        .iter()
7902
        .any(|c| matches!(c, ViewChange::WorkingCopy { .. })));
7903
7904
    // Reading at an earlier operation.
7905
    let old = Repo::open(root).unwrap().at_op(&at_second[..10]).unwrap();
7906
    assert_eq!(old.bookmark_heads().unwrap(), vec![second]);
7907
    assert!(!old.view().unwrap().bookmarks.contains_key("keep"));
7908
    write(root, "z.txt", b"z\n");
7909
    assert!(old.commit("refused", &[]).is_err(), "--at-op is read-only");
7910
    fs::remove_file(root.join("z.txt")).unwrap();
7911
    assert!(repo.resolve_op("zz").is_err());
7912
    assert_eq!(repo.resolve_op("@").unwrap().0, repo.head_op().unwrap().0);
7913
7914
    // Restore goes back, files and all; undo takes it back whole.
7915
    repo.op_restore(&at_second, false).unwrap();
7916
    assert_eq!(repo.bookmark_heads().unwrap(), vec![second]);
7917
    assert!(!root.join("n.txt").exists());
7918
    repo.undo().unwrap();
7919
    let mut heads = repo.bookmark_heads().unwrap();
7920
    heads.sort();
7921
    let mut want = vec![second, third];
7922
    want.sort();
7923
    assert_eq!(heads, want);
7924
    assert!(
7925
        root.join("n.txt").exists(),
7926
        "the files came back with the undo"
7927
    );
7928
7929
    // Revert the bookmark's creation alone: the commit after it stays.
7930
    let r = repo.op_revert(&created).unwrap();
7931
    assert_eq!(r.reverted, vec!["keep".to_string()]);
7932
    assert!(!repo.view().unwrap().bookmarks.contains_key("keep"));
7933
    assert!(repo
7934
        .load_state(&repo.bookmark_heads().unwrap())
7935
        .unwrap()
7936
        .contains(&third));
7937
    assert!(repo.op_revert(&created).is_err(), "nothing left to revert");
7938
    let _ = first;
7939
}
7940
7941
/// oxygen#41: with uncommitted work, a status after a snapshot is answered
7942
/// from the status cache while every file is as the snapshot left it, and
7943
/// from a snapshot again as soon as one is not.
7944
#[test]
7945
fn status_with_uncommitted_work_comes_from_the_cache_until_a_file_changes() {
7946
    hermetic();
7947
    let dir = tempfile::tempdir().unwrap();
7948
    let root = dir.path();
7949
    let repo = Repo::init(root).unwrap();
7950
    write(root, "a.txt", b"a\n");
7951
    write(root, "b.txt", b"b\n");
7952
    repo.commit("base", &[]).unwrap();
7953
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]), "clean");
7954
7955
    write(root, "a.txt", b"a\nmore\n");
7956
    assert_eq!(
7957
        repo.status_by_manifest().unwrap(),
7958
        None,
7959
        "no snapshot of the edit yet"
7960
    );
7961
    let snap = repo.snapshot_status("oxy status").unwrap();
7962
    assert_eq!(snap.statuses.len(), 1);
7963
    let cached = repo
7964
        .status_by_manifest()
7965
        .unwrap()
7966
        .expect("answered from the cache");
7967
    assert_eq!(cached.len(), 1);
7968
    assert_eq!(
7969
        (cached[0].path.as_str(), cached[0].status),
7970
        ("a.txt", ChangeStatus::Modified)
7971
    );
7972
7973
    // Any further change sends status back to a snapshot.
7974
    write(root, "a.txt", b"a\nmore\nand more\n");
7975
    assert_eq!(repo.status_by_manifest().unwrap(), None, "edited again");
7976
    repo.snapshot_status("oxy status").unwrap();
7977
    assert!(repo.status_by_manifest().unwrap().is_some());
7978
    write(root, "new.txt", b"n\n");
7979
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file added");
7980
    fs::remove_file(root.join("new.txt")).unwrap();
7981
    assert!(
7982
        repo.status_by_manifest().unwrap().is_some(),
7983
        "back as it was"
7984
    );
7985
    fs::remove_file(root.join("b.txt")).unwrap();
7986
    assert_eq!(repo.status_by_manifest().unwrap(), None, "a file removed");
7987
    write(root, "b.txt", b"b\n");
7988
7989
    // A commit leaves nothing uncommitted: clean again, no cache needed.
7990
    repo.snapshot_status("oxy status").unwrap();
7991
    repo.commit("more", &[]).unwrap();
7992
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
7993
}
7994
7995
/// oxygen#41: while the status cache holds, the working copy's diff is
7996
/// rendered from the stored working-copy change, and says exactly what a
7997
/// snapshot's diff says.
7998
#[test]
7999
fn the_working_copy_diff_from_the_cache_matches_a_snapshot() {
8000
    hermetic();
8001
    let dir = tempfile::tempdir().unwrap();
8002
    let root = dir.path();
8003
    let repo = Repo::init(root).unwrap();
8004
    write(root, "a.txt", b"one\ntwo\nthree\n");
8005
    write(root, "gone.txt", b"bye\n");
8006
    repo.commit("base", &[]).unwrap();
8007
    write(root, "a.txt", b"one\n2\nthree\nfour\n");
8008
    write(root, "new.txt", b"hello\n");
8009
    fs::remove_file(root.join("gone.txt")).unwrap();
8010
    let snap = repo.snapshot_status("oxy status").unwrap();
8011
    let slow = render_change(&snap.wc, &snap.base, &snap.base_snapshot);
8012
    assert!(
8013
        repo.status_by_manifest().unwrap().is_some(),
8014
        "the cache holds"
8015
    );
8016
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
8017
    assert_eq!(render_change(&wc, &base, &snapshot), slow);
8018
    assert_eq!(repo.diff_files(None).unwrap().len(), 3);
8019
8020
    // Committed, nothing changes: the diff is empty without loading the
8021
    // base (oxygen#94), and the same as rendering it.
8022
    repo.commit("all", &[]).unwrap();
8023
    repo.snapshot_status("oxy status").unwrap();
8024
    assert!(repo.status_by_manifest().unwrap().is_some());
8025
    assert!(repo
8026
        .working_copy_with_base_unless_unchanged()
8027
        .unwrap()
8028
        .is_none());
8029
    let (wc, base, snapshot) = repo.working_copy_with_base().unwrap();
8030
    assert_eq!(render_change(&wc, &base, &snapshot), "");
8031
    assert!(repo.diff_files(None).unwrap().is_empty());
8032
}
8033
8034
/// oxygen#41: a manifest written from a walk keeps every directory's time;
8035
/// while none has moved, the check stats the tracked files without listing
8036
/// the tree, and a file added or removed anywhere moves its directory's
8037
/// time, so the tree is listed again.
8038
#[test]
8039
fn the_manifest_check_skips_listing_while_no_directory_changed() {
8040
    hermetic();
8041
    let dir = tempfile::tempdir().unwrap();
8042
    let root = dir.path();
8043
    let repo = Repo::init(root).unwrap();
8044
    write(root, "a.txt", b"a\n");
8045
    write(root, "sub/deep/b.txt", b"b\n");
8046
    repo.commit("base", &[]).unwrap();
8047
    // Out of the racy window: every file and directory a minute old.
8048
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
8049
    for p in ["a.txt", "sub/deep/b.txt", "sub/deep", "sub", ""] {
8050
        fs::File::open(root.join(p))
8051
            .unwrap()
8052
            .set_modified(old)
8053
            .unwrap();
8054
    }
8055
    repo.snapshot_status("oxy status").unwrap();
8056
    repo.write_manifest(false, false).unwrap();
8057
    let m = repo.read_manifest().unwrap().unwrap().2;
8058
    assert!(m.dirs.iter().any(|(d, _)| d == "sub/deep"), "{:?}", m.dirs);
8059
    assert_eq!(
8060
        repo.disk_differs_by_dirs(&m),
8061
        Some(false),
8062
        "no listing needed"
8063
    );
8064
    assert_eq!(repo.status_by_manifest().unwrap(), Some(vec![]));
8065
8066
    // A same-size edit with a new time: found by its stat.
8067
    write(root, "sub/deep/b.txt", b"c\n");
8068
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(true));
8069
    write(root, "sub/deep/b.txt", b"b\n");
8070
    fs::File::open(root.join("sub/deep/b.txt"))
8071
        .unwrap()
8072
        .set_modified(old)
8073
        .unwrap();
8074
    assert_eq!(repo.disk_differs_by_dirs(&m), Some(false));
8075
8076
    // A new file moves its directory's time: the tree must be listed.
8077
    write(root, "sub/deep/new.txt", b"n\n");
8078
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
8079
    assert_eq!(repo.status_by_manifest().unwrap(), None);
8080
    fs::remove_file(root.join("sub/deep/new.txt")).unwrap();
8081
    // A removed one too.
8082
    fs::remove_file(root.join("a.txt")).unwrap();
8083
    assert_eq!(repo.disk_differs_by_dirs(&m), None);
8084
}
8085
8086
/// oxygen#41: a commit right after a status takes the snapshot the status
8087
/// left (the status cache holds) rather than walking again, and commits
8088
/// exactly what a snapshot would have.
8089
#[test]
8090
fn a_commit_after_a_status_uses_the_cached_snapshot() {
8091
    hermetic();
8092
    let dir = tempfile::tempdir().unwrap();
8093
    let root = dir.path();
8094
    let repo = Repo::init(root).unwrap();
8095
    write(root, "a.txt", b"a\nb\n");
8096
    write(root, ".oxyattributes", b"*.bin binary\n");
8097
    repo.commit("base", &[]).unwrap();
8098
    write(root, "a.txt", b"a\nB\n");
8099
    write(root, "new.txt", b"new\n");
8100
    let snap = repo.snapshot_status("oxy status").unwrap();
8101
    let cached = repo
8102
        .snapshot_from_cache()
8103
        .unwrap()
8104
        .expect("the cache holds");
8105
    assert_eq!(cached.wc_hash, snap.wc_hash);
8106
    assert_eq!(cached.statuses, snap.statuses);
8107
    assert!(
8108
        !cached.attributes.is_empty(),
8109
        "the .oxyattributes file was read"
8110
    );
8111
    let h = repo.commit("edit", &[]).unwrap();
8112
    let c = repo.store().get_change(&h).unwrap();
8113
    assert_eq!(
8114
        c.tree_ops.len() + c.edits.len(),
8115
        snap.wc.tree_ops.len() + snap.wc.edits.len()
8116
    );
8117
    assert_eq!(
8118
        repo.status_by_manifest().unwrap(),
8119
        Some(vec![]),
8120
        "clean after the commit"
8121
    );
8122
    assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"a\nB\n");
8123
}
8124
8125
/// oxygen#41: a clean check that verified racy entries restamps the
8126
/// manifest, so later checks can trust them, and a same-size rewrite
8127
/// straight afterwards is still found: entries within two seconds of the
8128
/// new time stay racy.
8129
#[test]
8130
fn a_verified_clean_check_restamps_the_manifest_safely() {
8131
    hermetic();
8132
    let dir = tempfile::tempdir().unwrap();
8133
    let root = dir.path();
8134
    let repo = Repo::init(root).unwrap();
8135
    write(root, "a.txt", b"one\n");
8136
    repo.commit("one", &[]).unwrap();
8137
    let before = repo.read_manifest().unwrap().unwrap().2.written_ns;
8138
    assert!(repo.clean_by_manifest().unwrap());
8139
    let after = repo.read_manifest().unwrap().unwrap().2.written_ns;
8140
    assert!(after > before, "restamped");
8141
    write(root, "a.txt", b"two\n");
8142
    assert!(
8143
        !repo.clean_by_manifest().unwrap(),
8144
        "a same-size rewrite is still seen"
8145
    );
8146
}
8147
8148
/// oxygen#35: a history-only state keeps no inserted text. It reads a
8149
/// stored insert's text blob only when it builds that file's graph, and
8150
/// builds the same graph a full load does.
8151
#[test]
8152
fn history_only_states_read_text_only_for_the_graphs_they_build() {
8153
    hermetic();
8154
    let dir = tempfile::tempdir().unwrap();
8155
    let root = dir.path();
8156
    let repo = Repo::init(root).unwrap();
8157
    let big: String = (0..3000).map(|i| format!("big line {i}\n")).collect();
8158
    let other: String = (0..3000).map(|i| format!("other line {i}\n")).collect();
8159
    write(root, "big.txt", big.as_bytes());
8160
    write(root, "other.txt", other.as_bytes());
8161
    let h = repo.commit("two large files", &[]).unwrap();
8162
    write(root, "big.txt", format!("{big}one more\n").as_bytes());
8163
    let h2 = repo.commit("append", &[]).unwrap();
8164
8165
    let full = repo.load_state_full(&[h2]).unwrap().materialize();
8166
    let text = |snap: &crate::state::Snapshot, p: &str| match &snap.files[p].content {
8167
        FileContent::Text { bytes, .. } => bytes.clone(),
8168
        other => panic!("{other:?}"),
8169
    };
8170
    // Built on demand, every graph renders as the full load's.
8171
    let mut hist = repo.load_state_history(&[h2]).unwrap();
8172
    let big_node = full.files["big.txt"].node;
8173
    assert!(hist.graph_key(&big_node).is_some(), "not built yet");
8174
    repo.load_all_graphs(&mut hist).unwrap();
8175
    let rendered = hist.materialize();
8176
    for p in ["big.txt", "other.txt"] {
8177
        assert_eq!(text(&rendered, p), text(&full, p), "{p}");
8178
    }
8179
8180
    // Without other.txt's text blob, history still loads and big.txt still
8181
    // builds: nothing read the other text.
8182
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
8183
    assert_eq!(texts.len(), 2);
8184
    let content = |r: &ObjectRef| -> Vec<u8> {
8185
        let blob = crate::objects::Blob::decode(&repo.store().get(r).unwrap().1).unwrap();
8186
        blob.chunks
8187
            .iter()
8188
            .flat_map(|c| repo.store().get(c).unwrap().1)
8189
            .collect()
8190
    };
8191
    let other_text = texts
8192
        .iter()
8193
        .filter_map(|t| match t {
8194
            crate::objects::TextRef::Blob(r, _, _) => Some(*r),
8195
            _ => None,
8196
        })
8197
        .find(|r| content(r).windows(12).any(|w| w == b"other line 1"))
8198
        .unwrap();
8199
    repo.store().remove_loose_for_test(&other_text).unwrap();
8200
    let mut hist = repo.load_state_history(&[h2]).unwrap();
8201
    repo.load_graphs_of(&mut hist, &[big_node]).unwrap();
8202
    assert!(repo
8203
        .load_graphs_of(&mut hist, &[full.files["other.txt"].node])
8204
        .is_err());
8205
}
8206
8207
/// oxygen#35: the first status after a commit read and rendered every
8208
/// file (79 s and more than 14 GB on the Linux tree), because the
8209
/// manifest had no graph keys for files the commit added.
8210
#[test]
8211
fn a_commit_leaves_a_manifest_the_next_status_trusts() {
8212
    use std::os::unix::fs::PermissionsExt;
8213
    hermetic();
8214
    let dir = tempfile::tempdir().unwrap();
8215
    let root = dir.path();
8216
    let repo = Repo::init(root).unwrap();
8217
    let files = ["a.txt", "b.txt", "d/c.txt"];
8218
    for p in files {
8219
        write(root, p, format!("{p}\n").as_bytes());
8220
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
8221
        fs::File::options()
8222
            .write(true)
8223
            .open(root.join(p))
8224
            .unwrap()
8225
            .set_modified(old)
8226
            .unwrap();
8227
    }
8228
    repo.commit("added", &[]).unwrap();
8229
    let (_, _, m) = repo.read_manifest().unwrap().unwrap();
8230
    assert!(
8231
        m.entries.values().all(|e| e.graph.is_some()),
8232
        "keys recorded at commit"
8233
    );
8234
    // Unreadable files prove the next status reads none of them.
8235
    for p in files {
8236
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o000)).unwrap();
8237
    }
8238
    let snap = repo.snapshot_status("status").unwrap();
8239
    for p in files {
8240
        fs::set_permissions(root.join(p), fs::Permissions::from_mode(0o644)).unwrap();
8241
    }
8242
    assert!(!snap.changed && snap.statuses.is_empty());
8243
    assert_eq!(snap.base_snapshot.unrendered.len(), files.len());
8244
}
8245
8246
/// oxygen#35: a checkout reads, renders and writes only the files whose
8247
/// graphs differ, and renders the rest a batch at a time.
8248
#[test]
8249
fn checkout_touches_only_what_differs_and_renders_in_batches() {
8250
    use std::os::unix::fs::PermissionsExt;
8251
    hermetic();
8252
    let dir = tempfile::tempdir().unwrap();
8253
    let root = dir.path();
8254
    let origin = root.join("origin");
8255
    let mut repo = Repo::init(&origin).unwrap();
8256
    // More files than one batch holds.
8257
    let n = 2100;
8258
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(30);
8259
    for i in 0..n {
8260
        let p = format!("f/{i:04}.txt");
8261
        write(&origin, &p, format!("file {i}\n").as_bytes());
8262
        fs::File::options()
8263
            .write(true)
8264
            .open(origin.join(&p))
8265
            .unwrap()
8266
            .set_modified(old)
8267
            .unwrap();
8268
    }
8269
    repo.commit("many", &[]).unwrap();
8270
    repo.bookmark_create("feature", None).unwrap();
8271
    repo.bookmark_switch("feature", false).unwrap();
8272
    write(&origin, "f/0007.txt", b"changed\n");
8273
    repo.commit("one change", &[]).unwrap();
8274
8275
    // Switching back to main must not read the unchanged files.
8276
    for i in 0..n {
8277
        if i != 7 {
8278
            let p = origin.join(format!("f/{i:04}.txt"));
8279
            fs::set_permissions(&p, fs::Permissions::from_mode(0o000)).unwrap();
8280
        }
8281
    }
8282
    let r = repo.bookmark_switch("main", false).unwrap();
8283
    for i in 0..n {
8284
        let p = origin.join(format!("f/{i:04}.txt"));
8285
        fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
8286
    }
8287
    assert_eq!((r.written, r.removed), (1, 0), "{r:?}");
8288
    assert_eq!(fs::read(origin.join("f/0007.txt")).unwrap(), b"file 7\n");
8289
    assert!(repo.snapshot_status("status").unwrap().statuses.is_empty());
8290
8291
    // A clone renders every file, across batches.
8292
    let c = root.join("clone");
8293
    Repo::clone(&origin.to_string_lossy(), &c).unwrap();
8294
    for i in [0, 2047, 2048, n - 1] {
8295
        assert_eq!(
8296
            fs::read(c.join(format!("f/{i:04}.txt"))).unwrap(),
8297
            format!("file {i}\n").as_bytes()
8298
        );
8299
    }
8300
    let cloned = Repo::open(&c).unwrap();
8301
    assert!(cloned
8302
        .snapshot_status("status")
8303
        .unwrap()
8304
        .statuses
8305
        .is_empty());
8306
}
8307
8308
/// A file written just before the manifest (inside the racy window) is
8309
/// checked by its hash: trusted when equal, caught when edited in place
8310
/// with the same size and time.
8311
#[test]
8312
fn a_racy_manifest_entry_is_checked_by_hash() {
8313
    hermetic();
8314
    let dir = tempfile::tempdir().unwrap();
8315
    let root = dir.path();
8316
    let repo = Repo::init(root).unwrap();
8317
    write(root, "a.txt", b"one\n");
8318
    repo.commit("fresh", &[]).unwrap();
8319
    assert!(repo.clean_by_manifest().unwrap(), "fresh but equal");
8320
    let t = fs::metadata(root.join("a.txt"))
8321
        .unwrap()
8322
        .modified()
8323
        .unwrap();
8324
    write(root, "a.txt", b"two\n");
8325
    fs::File::options()
8326
        .write(true)
8327
        .open(root.join("a.txt"))
8328
        .unwrap()
8329
        .set_modified(t)
8330
        .unwrap();
8331
    assert!(
8332
        !repo.clean_by_manifest().unwrap(),
8333
        "same size and time, other bytes"
8334
    );
8335
    assert_eq!(
8336
        statuses(&repo.snapshot_status("status").unwrap()),
8337
        vec![("a.txt".to_string(), ChangeStatus::Modified)]
8338
    );
8339
}
8340
8341
/// A fetch on one machine moves changes as stored, text blobs among the
8342
/// objects; a change whose text blob did not come is refused, not stored.
8343
#[test]
8344
fn a_raw_bundle_without_a_changes_text_is_refused() {
8345
    hermetic();
8346
    let dir = tempfile::tempdir().unwrap();
8347
    let root = dir.path();
8348
    let a = Repo::init(&root.join("a")).unwrap();
8349
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
8350
    write(&root.join("a"), "big.txt", big.as_bytes());
8351
    let h = a.commit("big", &[]).unwrap();
8352
    let bundle = a.bundle_raw_for(&[h], None).unwrap();
8353
    assert_eq!(bundle.raw_changes.len(), 1);
8354
    assert!(bundle.changes.is_empty());
8355
    let b = Repo::init(&root.join("b")).unwrap();
8356
    let mut without = bundle.clone();
8357
    without.objects.retain(|(ty, _)| *ty != ObjectType::Blob);
8358
    let e = b.import_bundle(&without, false).unwrap_err();
8359
    assert!(e.to_string().contains("came without its text blob"), "{e}");
8360
    assert!(!b.store().has(&h));
8361
    assert_eq!(b.import_bundle(&bundle, false).unwrap(), vec![h]);
8362
    assert_eq!(b.store().get_change(&h).unwrap().message, "big");
8363
}
8364
8365
/// oxygen#30 (vscode): a directory deleted in one line of history and made
8366
/// again was a second node for one Git path, so a file moved into it on
8367
/// another line, where the first node still stood, ended up in two places.
8368
/// An import now brings the directory back rather than make a new one.
8369
#[test]
8370
fn git_import_brings_a_directory_back_rather_than_making_a_second() {
8371
    hermetic();
8372
    if std::process::Command::new("git")
8373
        .arg("--version")
8374
        .output()
8375
        .is_err()
8376
    {
8377
        eprintln!("git not installed; skipping");
8378
        return;
8379
    }
8380
    let dir = tempfile::tempdir().unwrap();
8381
    let root = dir.path();
8382
    let g = root.join("src.git");
8383
    fs::create_dir_all(&g).unwrap();
8384
    let git = |args: &[&str]| -> String {
8385
        let out = std::process::Command::new("git")
8386
            .arg("-C")
8387
            .arg(&g)
8388
            .args([
8389
                "-c",
8390
                "user.name=Grace",
8391
                "-c",
8392
                "[email protected]",
8393
                "-c",
8394
                "commit.gpgsign=false",
8395
            ])
8396
            .args(args)
8397
            .output()
8398
            .unwrap();
8399
        assert!(
8400
            out.status.success(),
8401
            "git {args:?}: {}",
8402
            String::from_utf8_lossy(&out.stderr)
8403
        );
8404
        String::from_utf8_lossy(&out.stdout).trim().to_string()
8405
    };
8406
    git(&["init", "-q", "-b", "main"]);
8407
    write(&g, "d/a.txt", b"a\n");
8408
    write(&g, "c/x.txt", b"x\n");
8409
    git(&["add", "."]);
8410
    git(&["commit", "-qm", "base"]);
8411
    // One line: move x into d while d still stands.
8412
    git(&["checkout", "-qb", "side"]);
8413
    git(&["mv", "c/x.txt", "d/x.txt"]);
8414
    git(&["commit", "-qm", "x into d"]);
8415
    // The other: d goes, comes back, and x moves into it too.
8416
    git(&["checkout", "-q", "main"]);
8417
    git(&["rm", "-q", "d/a.txt"]);
8418
    git(&["commit", "-qm", "d goes"]);
8419
    write(&g, "d/b.txt", b"b\n");
8420
    git(&["add", "."]);
8421
    git(&["commit", "-qm", "d comes back"]);
8422
    git(&["mv", "c/x.txt", "d/x.txt"]);
8423
    git(&["commit", "-qm", "x into d again"]);
8424
    git(&["merge", "-q", "--no-edit", "side"]);
8425
8426
    let repo = Repo::init(&root.join("o")).unwrap();
8427
    repo.import_git(&g, "main").unwrap();
8428
    let v = repo.verify_git_import(&g, "main").unwrap();
8429
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8430
    let st = repo
8431
        .load_state_history(&repo.bookmark_heads().unwrap())
8432
        .unwrap();
8433
    let view = st.tree().view();
8434
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8435
    // The directory is the one the first commit made.
8436
    // Commits made in one second tie on time: find the first by its message.
8437
    let first = repo
8438
        .log()
8439
        .unwrap()
8440
        .into_iter()
8441
        .find(|e| e.change.message.starts_with("base"))
8442
        .unwrap();
8443
    let base = repo
8444
        .load_state_history(&[first.hash])
8445
        .unwrap()
8446
        .tree()
8447
        .view();
8448
    assert_eq!(view.entries["d"].node, base.entries["d"].node);
8449
}
8450
8451
/// oxygen#30, the rest: a placement left under a directory another line
8452
/// removed is out of sight, so no diff reaches it; the merge that settles
8453
/// where the file is retires it.
8454
#[test]
8455
fn git_import_merge_retires_a_placement_under_a_removed_directory() {
8456
    hermetic();
8457
    if std::process::Command::new("git")
8458
        .arg("--version")
8459
        .output()
8460
        .is_err()
8461
    {
8462
        eprintln!("git not installed; skipping");
8463
        return;
8464
    }
8465
    let dir = tempfile::tempdir().unwrap();
8466
    let root = dir.path();
8467
    let g = root.join("src.git");
8468
    fs::create_dir_all(&g).unwrap();
8469
    let run = |args: &[&str]| {
8470
        std::process::Command::new("git")
8471
            .arg("-C")
8472
            .arg(&g)
8473
            .args([
8474
                "-c",
8475
                "user.name=Grace",
8476
                "-c",
8477
                "[email protected]",
8478
                "-c",
8479
                "commit.gpgsign=false",
8480
            ])
8481
            .args(args)
8482
            .output()
8483
            .unwrap()
8484
    };
8485
    let git = |args: &[&str]| {
8486
        let out = run(args);
8487
        assert!(
8488
            out.status.success(),
8489
            "git {args:?}: {}",
8490
            String::from_utf8_lossy(&out.stderr)
8491
        );
8492
    };
8493
    git(&["init", "-q", "-b", "main"]);
8494
    write(&g, "c/x.txt", b"x\n");
8495
    write(&g, "keep.txt", b"k\n");
8496
    git(&["add", "."]);
8497
    git(&["commit", "-qm", "base"]);
8498
    // One line renames the file within c; the other moves it out of c,
8499
    // which goes.
8500
    git(&["checkout", "-qb", "side"]);
8501
    git(&["mv", "c/x.txt", "c/y.txt"]);
8502
    git(&["commit", "-qm", "rename within c"]);
8503
    git(&["checkout", "-q", "main"]);
8504
    fs::create_dir_all(g.join("n")).unwrap();
8505
    git(&["mv", "c/x.txt", "n/x.txt"]);
8506
    git(&["commit", "-qm", "move out of c"]);
8507
    // Git cannot merge the two renames; the merge keeps n/x.txt.
8508
    let _ = run(&["merge", "-q", "side"]);
8509
    let _ = run(&[
8510
        "rm",
8511
        "-q",
8512
        "--cached",
8513
        "--ignore-unmatch",
8514
        "c/y.txt",
8515
        "c/x.txt",
8516
    ]);
8517
    let _ = std::fs::remove_dir_all(g.join("c"));
8518
    write(&g, "n/x.txt", b"x\n");
8519
    git(&["add", "-A"]);
8520
    git(&["commit", "-qm", "merge: keep n/x.txt"]);
8521
8522
    let repo = Repo::init(&root.join("o")).unwrap();
8523
    repo.import_git(&g, "main").unwrap();
8524
    let v = repo.verify_git_import(&g, "main").unwrap();
8525
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8526
    let st = repo
8527
        .load_state_history(&repo.bookmark_heads().unwrap())
8528
        .unwrap();
8529
    let view = st.tree().view();
8530
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8531
    assert!(view.entries.contains_key("n/x.txt"));
8532
}
8533
8534
/// oxygen#30, orphans: a file added on one line into a directory the other
8535
/// line removed is placed where the tree cannot show it; Git's merge keeps
8536
/// the file, and the import's merge leaves exactly one of it.
8537
#[test]
8538
fn git_import_merge_leaves_no_orphan_behind() {
8539
    hermetic();
8540
    if std::process::Command::new("git")
8541
        .arg("--version")
8542
        .output()
8543
        .is_err()
8544
    {
8545
        eprintln!("git not installed; skipping");
8546
        return;
8547
    }
8548
    let dir = tempfile::tempdir().unwrap();
8549
    let root = dir.path();
8550
    let g = root.join("src.git");
8551
    fs::create_dir_all(&g).unwrap();
8552
    let git = |args: &[&str]| {
8553
        let out = std::process::Command::new("git")
8554
            .arg("-C")
8555
            .arg(&g)
8556
            .args([
8557
                "-c",
8558
                "user.name=Grace",
8559
                "-c",
8560
                "[email protected]",
8561
                "-c",
8562
                "commit.gpgsign=false",
8563
            ])
8564
            .args(args)
8565
            .output()
8566
            .unwrap();
8567
        assert!(
8568
            out.status.success(),
8569
            "git {args:?}: {}",
8570
            String::from_utf8_lossy(&out.stderr)
8571
        );
8572
    };
8573
    git(&["init", "-q", "-b", "main"]);
8574
    write(&g, "d/f.txt", b"f\n");
8575
    write(&g, "keep.txt", b"k\n");
8576
    git(&["add", "."]);
8577
    git(&["commit", "-qm", "base"]);
8578
    git(&["checkout", "-qb", "side"]);
8579
    write(&g, "d/new.txt", b"new\n");
8580
    git(&["add", "."]);
8581
    git(&["commit", "-qm", "add into d"]);
8582
    git(&["checkout", "-q", "main"]);
8583
    git(&["rm", "-q", "d/f.txt"]);
8584
    git(&["commit", "-qm", "d goes"]);
8585
    git(&["merge", "-q", "--no-edit", "side"]);
8586
8587
    let repo = Repo::init(&root.join("o")).unwrap();
8588
    repo.import_git(&g, "main").unwrap();
8589
    let v = repo.verify_git_import(&g, "main").unwrap();
8590
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
8591
    let st = repo
8592
        .load_state_history(&repo.bookmark_heads().unwrap())
8593
        .unwrap();
8594
    let view = st.tree().view();
8595
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
8596
    assert!(view.entries.contains_key("d/new.txt"));
8597
}
8598
8599
/// fsck checks a change's text as the blobs it is stored in, without
8600
/// decoding it: a missing text blob is an error named for the change.
8601
#[test]
8602
fn fsck_names_a_missing_text_blob() {
8603
    hermetic();
8604
    let dir = tempfile::tempdir().unwrap();
8605
    let root = dir.path();
8606
    let repo = Repo::init(root).unwrap();
8607
    let big: String = (0..3000).map(|i| format!("line {i}\n")).collect();
8608
    write(root, "big.txt", big.as_bytes());
8609
    let h = repo.commit("big", &[]).unwrap();
8610
    assert_eq!(repo.fsck().unwrap().errors(), 0);
8611
    let (_, texts) = repo.store().get_change_lazy(&h).unwrap();
8612
    let Some(crate::objects::TextRef::Blob(b, _, _)) = texts.first().copied() else {
8613
        panic!("a stored text")
8614
    };
8615
    repo.store().remove_loose_for_test(&b).unwrap();
8616
    let rep = repo.fsck().unwrap();
8617
    assert!(rep.errors() > 0);
8618
    assert!(
8619
        rep.problems.iter().any(|p| p.what.contains(&h.short(12))),
8620
        "{:?}",
8621
        rep.problems
8622
    );
8623
}
8624
8625
/// oxygen#32: a subrepo on the same hub as one of the parent's remotes is
8626
/// reached with that remote's token and CA (a private subrepo then clones
8627
/// for anyone who can read the parent); another hub gets none of them.
8628
#[test]
8629
fn a_subrepo_on_the_parents_hub_borrows_its_credentials() {
8630
    hermetic();
8631
    let dir = tempfile::tempdir().unwrap();
8632
    let mut repo = Repo::init(dir.path()).unwrap();
8633
    repo.config
8634
        .set(
8635
            "remote.origin.url",
8636
            "https://Hub.example:7343/doomsdayone/metalgear",
8637
        )
8638
        .unwrap();
8639
    repo.config.set("remote.origin.token", "secret").unwrap();
8640
    repo.config
8641
        .set("remote.origin.ca", "/tmp/hub-ca.pem")
8642
        .unwrap();
8643
    let same = repo.credentials_for("https://hub.example:7343/doomsdayone/rstar-api");
8644
    assert_eq!(same.token.as_deref(), Some("secret"));
8645
    assert_eq!(same.ca.as_deref(), Some(Path::new("/tmp/hub-ca.pem")));
8646
    for other in [
8647
        "https://elsewhere.example:7343/doomsdayone/rstar-api",
8648
        "https://hub.example/doomsdayone/rstar-api",
8649
        "http://hub.example:7343/doomsdayone/rstar-api",
8650
    ] {
8651
        let o = repo.credentials_for(other);
8652
        assert_ne!(o.token.as_deref(), Some("secret"), "{other}");
8653
    }
8654
}
8655
8656
/// oxygen#47: a remote with no token of its own uses the user's credential
8657
/// store for its hub, and a nested checkout finds its parent's remote
8658
/// token there instead of keeping a copy.
8659
#[test]
8660
fn remotes_use_the_credential_store_and_the_enclosing_checkout() {
8661
    hermetic();
8662
    let home = tempfile::tempdir().unwrap();
8663
    let dir = tempfile::tempdir().unwrap();
8664
    let mut parent = Repo::init(dir.path()).unwrap().with_home(home.path());
8665
    parent
8666
        .config
8667
        .set("remote.origin.url", "https://hub.example/o/parent")
8668
        .unwrap();
8669
    parent.save_config().unwrap();
8670
    assert_eq!(parent.remote_options("origin").token, None);
8671
    crate::credentials::Credentials::at(home.path())
8672
        .save("https://hub.example", "stored", Some("andy"), None)
8673
        .unwrap();
8674
    assert_eq!(
8675
        parent.remote_options("origin").token.as_deref(),
8676
        Some("stored")
8677
    );
8678
8679
    let empty_home = tempfile::tempdir().unwrap();
8680
    let nested = dir.path().join("deps").join("child");
8681
    let mut child = Repo::init(&nested).unwrap().with_home(empty_home.path());
8682
    child
8683
        .config
8684
        .set("remote.origin.url", "https://hub.example/o/child")
8685
        .unwrap();
8686
    child.save_config().unwrap();
8687
    assert_eq!(child.remote_options("origin").token, None);
8688
    parent
8689
        .config
8690
        .set("remote.origin.token", "checkout")
8691
        .unwrap();
8692
    parent.save_config().unwrap();
8693
    assert_eq!(
8694
        child.remote_options("origin").token.as_deref(),
8695
        Some("checkout")
8696
    );
8697
    // Another hub's checkout token is not borrowed.
8698
    child
8699
        .config
8700
        .set("remote.origin.url", "https://other.example/o/child")
8701
        .unwrap();
8702
    assert_eq!(child.remote_options("origin").token, None);
8703
}
8704
8705
#[test]
8706
fn the_metadata_cache_survives_a_torn_tail() {
8707
    hermetic();
8708
    let dir = tempfile::tempdir().unwrap();
8709
    let root = dir.path();
8710
    let repo = Repo::init(root).unwrap();
8711
    write(root, "a.txt", b"1\n");
8712
    let h = repo.commit("first", &[]).unwrap();
8713
    let meta = repo.store().get_change_meta(&h).unwrap();
8714
    let cache = repo.store().dir().join("metas");
8715
    let len = fs::metadata(&cache).unwrap().len();
8716
    assert!(len > 0, "a change read is cached");
8717
    // A torn record at the end: the cache reads up to it and cuts it off.
8718
    fs::OpenOptions::new()
8719
        .append(true)
8720
        .open(&cache)
8721
        .unwrap()
8722
        .write_all(&[7; 20])
8723
        .unwrap();
8724
    let again = Repo::open(root).unwrap();
8725
    assert_eq!(again.store().get_change_meta(&h).unwrap(), meta);
8726
    assert_eq!(fs::metadata(&cache).unwrap().len(), len);
8727
}
8728
8729
#[test]
8730
fn a_manifest_that_does_not_check_reads_as_none() {
8731
    hermetic();
8732
    let dir = tempfile::tempdir().unwrap();
8733
    let root = dir.path();
8734
    let repo = Repo::init(root).unwrap();
8735
    write(root, "a.txt", b"1\n");
8736
    repo.commit("first", &[]).unwrap();
8737
    let path = repo.manifest_path();
8738
    let mut bytes = fs::read(&path).unwrap();
8739
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_some());
8740
    let last = bytes.len() - 1;
8741
    bytes[last] ^= 1;
8742
    fs::write(&path, &bytes).unwrap();
8743
    assert!(Repo::open(root).unwrap().read_manifest().unwrap().is_none());
8744
    // The next status reads the files and writes it again.
8745
    let again = Repo::open(root).unwrap();
8746
    assert!(!again.snapshot("status").unwrap().changed);
8747
    assert!(again.read_manifest().unwrap().is_some());
8748
}
8749
8750
#[test]
8751
fn a_commit_leaves_a_manifest_that_proves_the_working_copy_clean() {
8752
    hermetic();
8753
    let dir = tempfile::tempdir().unwrap();
8754
    let root = dir.path();
8755
    let repo = Repo::init(root).unwrap();
8756
    write(root, "a.txt", b"1\n");
8757
    write(root, "b.txt", b"2\n");
8758
    // b.txt outside the racy window, so snapshots take it as unchanged.
8759
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
8760
    fs::File::options()
8761
        .write(true)
8762
        .open(root.join("b.txt"))
8763
        .unwrap()
8764
        .set_modified(old)
8765
        .unwrap();
8766
    repo.commit("first", &[]).unwrap();
8767
    assert!(repo.clean_by_manifest().unwrap(), "after the first commit");
8768
    repo.snapshot_status("status").unwrap();
8769
    write(root, "a.txt", b"1\n2\n");
8770
    repo.commit("second", &[]).unwrap();
8771
    assert!(
8772
        repo.clean_by_manifest().unwrap(),
8773
        "after a commit of one file"
8774
    );
8775
    // Edited, seen by a status, edited again, then committed: the status
8776
    // left the first edit's stat, which the commit must not keep.
8777
    write(root, "a.txt", b"1\n2\n3\n");
8778
    repo.snapshot_status("status").unwrap();
8779
    write(root, "a.txt", b"1\n2\n3\n4\n5\n");
8780
    repo.commit("third", &[]).unwrap();
8781
    assert!(
8782
        repo.clean_by_manifest().unwrap(),
8783
        "after an edit a status saw"
8784
    );
8785
}
8786
8787
#[test]
8788
fn a_conflicted_rebase_can_be_resolved_in_the_working_copy() {
8789
    hermetic();
8790
    let dir = tempfile::tempdir().unwrap();
8791
    let root = dir.path();
8792
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
8793
    write(root, "a.txt", b"1\n2\n");
8794
    let a = repo.commit("A", &[]).unwrap();
8795
    repo.bookmark_create("develop", Some(&[a])).unwrap();
8796
    write(root, "a.txt", b"1\nX\n");
8797
    let c = repo.commit("C: 2 to X", &[]).unwrap();
8798
    repo.bookmark_switch("develop", false).unwrap();
8799
    write(root, "a.txt", b"1\nY\n");
8800
    let d = repo.commit("D: 2 to Y", &[]).unwrap();
8801
    repo.bookmark_switch("main", false).unwrap();
8802
8803
    let err = repo.rebase(&c, &[d]).unwrap_err();
8804
    assert!(matches!(err, RepoError::Conflicted(_)), "{err}");
8805
    let r = repo.rebase_into_working_copy(&c, &[d]).unwrap();
8806
    assert!(r.changed && r.checked_out);
8807
    let snap = repo.snapshot_status("status").unwrap();
8808
    assert!(
8809
        snap.base_snapshot.is_conflicted(),
8810
        "the conflict is in the working copy"
8811
    );
8812
    let text = fs::read_to_string(root.join("a.txt")).unwrap();
8813
    assert!(text.contains('X') && text.contains('Y'), "{text}");
8814
8815
    write(root, "a.txt", b"1\nXY\n");
8816
    repo.commit("Resolve", &[]).unwrap();
8817
    let st = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap();
8818
    assert!(st.contains(&c) && st.contains(&d));
8819
    let files = st.materialize().files;
8820
    assert!(!files["a.txt"].is_conflicted());
8821
    assert!(
8822
        matches!(&files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"1\nXY\n")
8823
    );
8824
8825
    // A change the current bookmark does not hold is refused.
8826
    repo.bookmark_switch("develop", false).unwrap();
8827
    write(root, "b.txt", b"b\n");
8828
    let e = repo.commit("E", &[]).unwrap();
8829
    repo.bookmark_switch("main", false).unwrap();
8830
    let err = repo.rebase_into_working_copy(&e, &[a]).unwrap_err();
8831
    assert!(
8832
        err.to_string().contains("not on the current bookmark"),
8833
        "{err}"
8834
    );
8835
}
8836
8837
#[test]
8838
fn an_ignore_rule_drops_an_added_file_but_not_a_tracked_one() {
8839
    hermetic();
8840
    let dir = tempfile::tempdir().unwrap();
8841
    let root = dir.path();
8842
    let repo = Repo::init(root).unwrap();
8843
    write(root, "a.txt", b"a\n");
8844
    write(root, "kept.log", b"tracked\n");
8845
    repo.commit("first", &[]).unwrap();
8846
    write(root, "build.log", b"made\n");
8847
    let snap = repo.snapshot_status("status").unwrap();
8848
    assert!(snap.statuses.iter().any(|s| s.path == "build.log"));
8849
    // A rule written afterwards leaves the added file out again, while the
8850
    // committed one stays tracked.
8851
    write(root, ".gitignore", b"*.log\n");
8852
    let snap = repo.snapshot_status("status").unwrap();
8853
    let paths: Vec<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
8854
    assert_eq!(paths, vec![".gitignore"], "{paths:?}");
8855
    write(root, "kept.log", b"tracked, edited\n");
8856
    let snap = repo.snapshot_status("status").unwrap();
8857
    assert!(snap.statuses.iter().any(|s| s.path == "kept.log"));
8858
}
8859
8860
#[test]
8861
fn shed_graphs_come_back_the_same() {
8862
    hermetic();
8863
    let dir = tempfile::tempdir().unwrap();
8864
    let root = dir.path();
8865
    let repo = Repo::init(root).unwrap();
8866
    write(root, "a.txt", b"1\n2\n3\n");
8867
    write(root, "b.txt", b"x\n");
8868
    repo.commit("first", &[]).unwrap();
8869
    write(root, "a.txt", b"1\ntwo\n3\n4\n");
8870
    repo.commit("second", &[]).unwrap();
8871
    let heads = repo.bookmark_heads().unwrap();
8872
    let mut st = repo.load_state_history(&heads).unwrap();
8873
    let view = st.tree().view();
8874
    let nodes: Vec<NodeId> = ["a.txt", "b.txt"]
8875
        .iter()
8876
        .map(|p| view.entries[*p].node)
8877
        .collect();
8878
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8879
    let before: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8880
    assert_eq!(st.built_count(), 2);
8881
    let shed = st.shed_graphs(|b| repo.store_blob(b)).unwrap();
8882
    assert_eq!((shed, st.built_count()), (2, 0));
8883
    // A later change applies on top of the shed history.
8884
    write(root, "a.txt", b"1\ntwo\n3\n4\n5\n");
8885
    let h3 = repo.commit("third", &[]).unwrap();
8886
    let (skeleton, texts) = repo.store().get_change_lazy(&h3).unwrap();
8887
    st.add_known(h3, skeleton, texts);
8888
    repo.load_graphs_of(&mut st, &nodes).unwrap();
8889
    let after: Vec<Vec<u8>> = nodes.iter().map(|n| st.render_file(n).0).collect();
8890
    assert_eq!(after[1], before[1]);
8891
    assert_eq!(after[0], b"1\ntwo\n3\n4\n5\n");
8892
}
8893
8894
#[test]
8895
fn many_edited_files_diff_in_parallel() {
8896
    // Enough edited files that the builder diffs them in parallel; the
8897
    // commit must hold exactly what is on disk, and a second snapshot
8898
    // must find nothing left to commit.
8899
    hermetic();
8900
    let dir = tempfile::tempdir().unwrap();
8901
    let root = dir.path();
8902
    let repo = Repo::init(root).unwrap();
8903
    let text = |i: usize, round: usize| {
8904
        let mut s = String::new();
8905
        for line in 0..50 {
8906
            if round > 0 && line % 7 == i % 7 {
8907
                s.push_str(&format!("edited {round} {i} {line}\n"));
8908
            } else {
8909
                s.push_str(&format!("file {i} line {line}\n"));
8910
            }
8911
        }
8912
        if round > 0 && i.is_multiple_of(3) {
8913
            s.push_str("appended\n");
8914
        }
8915
        s
8916
    };
8917
    for i in 0..40 {
8918
        write(root, &format!("d/f{i}.txt"), text(i, 0).as_bytes());
8919
    }
8920
    repo.commit("first", &[]).unwrap();
8921
    for i in 0..40 {
8922
        write(root, &format!("d/f{i}.txt"), text(i, 1).as_bytes());
8923
    }
8924
    let h = repo.commit("edit every file", &[]).unwrap();
8925
    let snap = repo.load_state(&[h]).unwrap().materialize();
8926
    for i in 0..40 {
8927
        let want = text(i, 1);
8928
        assert!(
8929
            matches!(&snap.files[&format!("d/f{i}.txt")].content, FileContent::Text { bytes, .. } if bytes == want.as_bytes()),
8930
            "d/f{i}.txt as committed"
8931
        );
8932
    }
8933
    assert!(
8934
        repo.commit("nothing", &[]).is_err(),
8935
        "nothing left to commit"
8936
    );
8937
}
8938
8939
/// oxygen#56: after a fetch, how a bookmark stands against its remote copy
8940
/// is known (fetch printed "up to date" while main was behind), a change
8941
/// only fetched resolves and says where it is, and a checkout whose only
8942
/// remote is not `origin` uses that one.
8943
#[test]
8944
fn a_fetched_change_shows_as_behind_and_resolves() {
8945
    hermetic();
8946
    let dir = tempfile::tempdir().unwrap();
8947
    let root = dir.path();
8948
    let origin = Repo::init(&root.join("origin")).unwrap();
8949
    drop(origin);
8950
    let url = root.join("origin").to_string_lossy().to_string();
8951
    let a = Repo::clone(&url, &root.join("a"))
8952
        .unwrap()
8953
        .with_home(root.join("home-a"));
8954
    write(&root.join("a"), "f.txt", b"one\n");
8955
    a.commit("one", &[]).unwrap();
8956
    a.push("origin", false).unwrap();
8957
    let b = Repo::clone(&url, &root.join("b"))
8958
        .unwrap()
8959
        .with_home(root.join("home-b"));
8960
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8961
8962
    write(&root.join("a"), "f.txt", b"one\ntwo\n");
8963
    let h2 = a.commit("two", &[]).unwrap();
8964
    a.push("origin", false).unwrap();
8965
    b.fetch("origin").unwrap();
8966
    // Fetched, not pulled: one behind, the change found and placed.
8967
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8968
    assert_eq!(b.tracking("origin", "nope").unwrap(), None);
8969
    assert_eq!(
8970
        b.resolve_change(&format!("#{}", &h2.to_hex()[..12]))
8971
            .unwrap(),
8972
        h2
8973
    );
8974
    assert_eq!(
8975
        b.remote_only_location(&h2).unwrap().as_deref(),
8976
        Some("origin/main")
8977
    );
8978
    // Fetching again changes nothing: still behind, which is what the
8979
    // CLI now says rather than "up to date".
8980
    b.fetch("origin").unwrap();
8981
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 1)));
8982
    b.pull("origin").unwrap();
8983
    assert_eq!(b.tracking("origin", "main").unwrap(), Some((0, 0)));
8984
    assert_eq!(b.remote_only_location(&h2).unwrap(), None);
8985
8986
    // One remote, not called origin: it is the default.
8987
    let mut c = Repo::init(&root.join("c")).unwrap();
8988
    assert_eq!(c.default_remote(), "origin");
8989
    c.config.set("remote.earth.url", &url).unwrap();
8990
    assert_eq!(c.default_remote(), "earth");
8991
    c.config.set("remote.origin.url", &url).unwrap();
8992
    assert_eq!(c.default_remote(), "origin");
8993
}
8994
8995
/// oxygen#57: a clone from a relative local path records the remote as an
8996
/// absolute path, so fetch still finds it from inside the clone.
8997
#[test]
8998
fn a_clone_from_a_relative_path_records_it_absolute() {
8999
    hermetic();
9000
    let dir = tempfile::tempdir().unwrap();
9001
    let root = dir.path();
9002
    Repo::init(&root.join("origin")).unwrap();
9003
    let rel = crate::protocol::stored_url("relative/repo");
9004
    assert!(std::path::Path::new(&rel).is_absolute(), "{rel}");
9005
    assert_eq!(
9006
        crate::protocol::stored_url("https://hub.example/o/n"),
9007
        "https://hub.example/o/n"
9008
    );
9009
    assert!(crate::protocol::stored_url("file://x").starts_with("file:///"));
9010
    assert!(crate::protocol::stored_url("dir://x").starts_with("dir:///"));
9011
    // A bucket is kept as written: it is not a path.
9012
    assert_eq!(
9013
        crate::protocol::stored_url("s3://bucket/prefix?profile=p"),
9014
        "s3://bucket/prefix?profile=p"
9015
    );
9016
    let url = root.join("origin").to_string_lossy().to_string();
9017
    let b = Repo::clone(&url, &root.join("b")).unwrap();
9018
    assert_eq!(b.config.remotes["origin"], url);
9019
    b.fetch("origin").unwrap();
9020
}
9021
9022
/// oxygen#60 and #61: a workspace added on a bookmark is on that bookmark,
9023
/// and gets its subrepos at their pins from this workspace's copies, with
9024
/// their remotes pointing where the subrepos come from.
9025
#[test]
9026
fn a_workspace_added_on_a_bookmark_is_on_it_with_its_subrepos() {
9027
    hermetic();
9028
    let dir = tempfile::tempdir().unwrap();
9029
    let root = dir.path();
9030
    Repo::init(&root.join("lib-origin")).unwrap();
9031
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9032
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9033
        .unwrap()
9034
        .with_home(root.join("home"));
9035
    write(&root.join("lib"), "lib.txt", b"v1\n");
9036
    let l1 = lib.commit("lib v1", &[]).unwrap();
9037
    assert!(lib.push("origin", false).unwrap()[0].ok);
9038
9039
    let app_dir = root.join("app");
9040
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9041
    write(&app_dir, "main.txt", b"app\n");
9042
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9043
    app.commit("app with lib", &[]).unwrap();
9044
    // A second bookmark, and the main workspace on another.
9045
    app.bookmark_create("develop", None).unwrap();
9046
    app.bookmark_create("feature", None).unwrap();
9047
    let mut app = app;
9048
    app.bookmark_switch("feature", false).unwrap();
9049
    assert_eq!(app.config.bookmark, "feature");
9050
9051
    // The library's origin goes away: the subrepo must come from here.
9052
    std::fs::rename(root.join("lib-origin"), root.join("lib-origin-gone")).unwrap();
9053
    let heads = app.resolve_heads("develop").unwrap();
9054
    let ws = app
9055
        .workspace_add_on(&root.join("ws"), Some(&heads), Some("develop"))
9056
        .unwrap();
9057
    assert_eq!(
9058
        ws.config.bookmark, "develop",
9059
        "the new workspace is on develop"
9060
    );
9061
    assert_eq!(
9062
        app.config.bookmark, "feature",
9063
        "and this one stays on its own"
9064
    );
9065
    let sub = Repo::open(&root.join("ws/libs/lib")).unwrap();
9066
    assert_eq!(
9067
        sub.config.remotes["origin"], lib_url,
9068
        "its origin is the subrepo's URL"
9069
    );
9070
    assert_eq!(sub.bookmark_heads().unwrap(), vec![l1], "at its pin");
9071
    assert_eq!(
9072
        std::fs::read(root.join("ws/libs/lib/lib.txt")).unwrap(),
9073
        b"v1\n"
9074
    );
9075
}
9076
9077
/// Revsets (docs/revset_query_language.md): symbols, relations, set
9078
/// operators and the predicates, over a small graph with two heads and
9079
/// a rename.
9080
#[test]
9081
fn revsets_select_changes_by_relation_author_text_date_and_path() {
9082
    hermetic();
9083
    let dir = tempfile::tempdir().unwrap();
9084
    let root = dir.path();
9085
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
9086
    repo.create_identity("Ada", "[email protected]", IdentityScope::User)
9087
        .unwrap();
9088
    write(root, "src/a.rs", b"one\n");
9089
    let a = repo.commit("first: add a", &[]).unwrap();
9090
    write(root, "src/a.rs", b"one\ntwo\n");
9091
    let b = repo.commit("second: grow a", &[]).unwrap();
9092
    // A second head, independent of b: a new file on top of a.
9093
    repo.checkout(&[a], false, "checkout a").unwrap();
9094
    write(root, "docs/notes.md", b"notes\n");
9095
    let c = repo.commit("third: notes", &[]).unwrap();
9096
    // Back to both heads, then rename a.rs: the node keeps its identity.
9097
    repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main")
9098
        .unwrap();
9099
    fs::remove_file(root.join("src/a.rs")).unwrap();
9100
    write(root, "src/z.rs", b"one\ntwo\n");
9101
    let d = repo.commit("fourth: rename a to z", &[]).unwrap();
9102
    let wc = repo.working_copy().unwrap().0;
9103
    // A saved revset is checked when set.
9104
    repo.set_user_config("revset.mine", "author(me) & ::main")
9105
        .unwrap();
9106
    assert!(repo.set_user_config("revset.bad", "a &").is_err());
9107
    let set = |src: &str| -> Vec<ChangeHash> {
9108
        let mut v = repo.revset(src).unwrap().hashes;
9109
        v.sort();
9110
        v
9111
    };
9112
    let sorted = |hs: &[ChangeHash]| -> Vec<ChangeHash> {
9113
        let mut v = hs.to_vec();
9114
        v.sort();
9115
        v
9116
    };
9117
9118
    // Changes commute: a new file depends on nothing and the rename on the
9119
    // file's creation, so the graph is a, b->a, d->a, c, and the working
9120
    // copy on the three heads b, c, d.
9121
    let heads = sorted(&repo.bookmark_heads().unwrap());
9122
    let meta = |h: &ChangeHash| repo.store().get_change_meta(h).unwrap();
9123
    assert!(heads.contains(&d) && heads.contains(&c));
9124
    // Symbols and closures.
9125
    assert_eq!(set("main"), heads);
9126
    assert_eq!(set("::main"), sorted(&[a, b, c, d]));
9127
    assert_eq!(set("@"), vec![wc]);
9128
    assert_eq!(set("::@"), sorted(&[a, b, c, d, wc]));
9129
    assert_eq!(set(&format!("::#{}", b.short(12))), sorted(&[a, b]));
9130
    assert_eq!(set(&format!("#{}::", a.short(12))), sorted(&[a, b, d, wc]));
9131
    assert_eq!(
9132
        set(&format!("#{}::#{}", a.short(12), b.short(12))),
9133
        sorted(&[a, b])
9134
    );
9135
    // Ranges: what main has beyond b, and `..` forms.
9136
    assert_eq!(set(&format!("#{}..main", b.short(12))), sorted(&[c, d]));
9137
    assert_eq!(set(&format!("#{}..", c.short(12))), sorted(&[a, b, d, wc]));
9138
    assert_eq!(set("..main"), sorted(&[a, b, c, d]));
9139
    // Operators and precedence: ~ binds tighter than &, & than |.
9140
    assert_eq!(
9141
        set(&format!("::main ~ #{}", d.short(12))),
9142
        sorted(&[a, b, c])
9143
    );
9144
    assert_eq!(
9145
        set(&format!("::main & #{} | #{}", b.short(12), c.short(12))),
9146
        sorted(&[b, c])
9147
    );
9148
    assert_eq!(set("all() ~ ::main"), vec![wc]);
9149
    // Relations.
9150
    let mut head_deps: Vec<ChangeHash> = heads.iter().flat_map(|h| meta(h).deps).collect();
9151
    head_deps.sort();
9152
    head_deps.dedup();
9153
    assert_eq!(set("deps(main)"), head_deps);
9154
    let on_a: Vec<ChangeHash> = [b, c, d]
9155
        .into_iter()
9156
        .filter(|h| meta(h).deps.contains(&a))
9157
        .collect();
9158
    assert_eq!(set(&format!("dependents(#{})", a.short(12))), sorted(&on_a));
9159
    assert_eq!(set("heads(::main)"), heads);
9160
    assert_eq!(set("roots(::main)"), sorted(&[a, c]));
9161
    assert_eq!(
9162
        set(&format!(
9163
            "heads(#{} | #{} | #{})",
9164
            a.short(12),
9165
            b.short(12),
9166
            c.short(12)
9167
        )),
9168
        sorted(&[b, c])
9169
    );
9170
    assert_eq!(set("latest(::main, 1)"), vec![d]);
9171
    assert_eq!(set("kind(working-copy)"), vec![wc]);
9172
    assert_eq!(set("none()"), vec![]);
9173
    // Predicates: author by name, email, key prefix and `me`.
9174
    let key = repo.config.author_key.unwrap();
9175
    assert_eq!(set("author(ada) & ::main"), sorted(&[a, b, c, d]));
9176
    assert_eq!(set("author(\"[email protected]\") & ::main").len(), 4);
9177
    assert_eq!(set(&format!("author({}) & ::main", key.short(12))).len(), 4);
9178
    assert_eq!(set("author(me) & ::main").len(), 4);
9179
    assert_eq!(set("author(nobody)"), vec![]);
9180
    assert_eq!(set("description(notes)"), vec![c]);
9181
    assert_eq!(set("description(\"rename a\")"), vec![d]);
9182
    assert_eq!(set("date(-1h..) & ::main").len(), 4);
9183
    assert_eq!(set("date(..2000-01-01)"), vec![]);
9184
    // touches follows the node through the rename, in the current state.
9185
    assert_eq!(set("touches(\"src/z.rs\")"), sorted(&[a, b, d]));
9186
    assert_eq!(set("touches(\"src/**\") & ::main"), sorted(&[a, b, d]));
9187
    assert_eq!(set("touches(\"docs/*\")"), vec![c]);
9188
    assert_eq!(set("touches(\"nothing/*\")"), vec![]);
9189
    // Newest first in the result order.
9190
    assert_eq!(repo.revset("::main").unwrap().hashes[0], d);
9191
    // The saved revset, and errors that say what is wrong.
9192
    assert_eq!(set("mine()").len(), 4);
9193
    let e = repo.revset("nosuch()").unwrap_err().to_string();
9194
    assert!(e.contains("unknown function nosuch()"), "{e}");
9195
    let e = repo.revset("main &").unwrap_err().to_string();
9196
    assert!(e.contains("at character"), "{e}");
9197
    let e = repo.revset("zzzz").unwrap_err().to_string();
9198
    assert!(e.contains("no change matches"), "{e}");
9199
    let e = repo
9200
        .revset_with_budget("::main", std::time::Duration::ZERO)
9201
        .unwrap_err()
9202
        .to_string();
9203
    assert!(e.contains("budget"), "{e}");
9204
    // The log entries carry the bookmark's heads and the working copy.
9205
    let entries = repo.log_revset("::@").unwrap();
9206
    assert!(entries[0].is_working_copy && entries.iter().any(|e| e.is_head && e.hash == d));
9207
    // Trust predicates (§2.4): nothing is signed yet (core.sign = seal, no
9208
    // push); then a signed change, a tag, and a revocation.
9209
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c, d]));
9210
    assert_eq!(set("signed_by(me)"), vec![]);
9211
    repo.sign_change(&d).unwrap();
9212
    assert_eq!(set("signed_by(me)"), vec![d]);
9213
    assert_eq!(set("signed_by([email protected])"), vec![d]);
9214
    assert_eq!(set(&format!("signed_by({})", key.short(12))), vec![d]);
9215
    assert_eq!(set("unsigned() & ::main"), sorted(&[a, b, c]));
9216
    assert_eq!(set("delegated()"), vec![]);
9217
    assert_eq!(set("revoked()"), vec![]);
9218
    assert_eq!(set("attested(tag)"), vec![]);
9219
    repo.tag_create("v1", &[b], "first").unwrap();
9220
    assert_eq!(set("attested(tag)"), sorted(&[a, b]));
9221
    assert_eq!(set("attested(tag) & unsigned()"), sorted(&[a, b]));
9222
    assert_eq!(set("attested(receipt)"), vec![]);
9223
    assert_eq!(set("built(test)"), vec![]);
9224
    let e = repo.revset("attested(seal)").unwrap_err().to_string();
9225
    assert!(e.contains("tag, receipt or ref"), "{e}");
9226
    repo.revoke_identity(&key, "test").unwrap();
9227
    assert_eq!(set("revoked()"), vec![d]);
9228
    assert_eq!(set("signed_by(me) ~ revoked()"), vec![]);
9229
    // independent(X, IN): what could ship without X. c and d neither
9230
    // depend on b nor are depended on by it; a is below, the working copy
9231
    // above.
9232
    assert_eq!(
9233
        set(&format!("independent(#{}, ::@)", b.short(12))),
9234
        sorted(&[c, d])
9235
    );
9236
    assert_eq!(
9237
        set(&format!("independent(#{}, ::main)", a.short(12))),
9238
        vec![c]
9239
    );
9240
    // conflicts(S): nothing conflicts yet; then two edits of one line.
9241
    assert_eq!(set("conflicts()"), vec![]);
9242
    assert_eq!(set("conflicts(main)"), vec![]);
9243
    // (The saved revset above edited the user config under the root:
9244
    // discard it.)
9245
    repo.checkout(&[a], true, "checkout a").unwrap();
9246
    write(root, "src/a.rs", b"one\nTWO\n");
9247
    let e = repo
9248
        .commit("fifth: the other edit of line two", &[])
9249
        .unwrap();
9250
    repo.checkout(&repo.bookmark_heads().unwrap(), true, "checkout main")
9251
        .unwrap();
9252
    let conflicted = repo.revset("conflicts()").unwrap().hashes;
9253
    assert!(
9254
        conflicted.contains(&e) && conflicted.contains(&b),
9255
        "{conflicted:?} should hold b and e"
9256
    );
9257
    assert!(!conflicted.contains(&c));
9258
    assert_eq!(set("conflicts() & author(nobody)"), vec![]);
9259
}
9260
9261
#[test]
9262
fn a_rotation_is_recorded_wherever_the_old_key_was_named() {
9263
    let dir = tempfile::tempdir().unwrap();
9264
    let root = dir.path();
9265
    let home = root.join("home");
9266
    // Ada's identity lives in the user file; repository `a` pins the same
9267
    // key in its own file, repository `b` names none.
9268
    let mut a = Repo::init(&root.join("a")).unwrap().with_home(&home);
9269
    let (key, _) = a
9270
        .create_identity("Ada", "[email protected]", IdentityScope::User)
9271
        .unwrap();
9272
    a.config.set("author.key", &key.to_hex()).unwrap();
9273
    a.save_config().unwrap();
9274
    let agent = SecretKey::generate().identity("Agent", "[email protected]", 1);
9275
    let r = a
9276
        .delegate_add(agent.clone(), crate::identity::Scope::CHANGES, None)
9277
        .unwrap();
9278
    assert_eq!(
9279
        read_config_file(&home.join("config.toml")).unwrap()["author.key"],
9280
        r.new.to_hex(),
9281
        "the user file follows"
9282
    );
9283
    assert_eq!(
9284
        read_config_file(&root.join("a/.oxy/config")).unwrap()["author.key"],
9285
        r.new.to_hex(),
9286
        "the pinning repository follows"
9287
    );
9288
    let b = Repo::init(&root.join("b")).unwrap().with_home(&home);
9289
    assert_eq!(
9290
        b.config.author_key,
9291
        Some(r.new),
9292
        "a checkout without a pin follows the user file"
9293
    );
9294
    // A repository-scoped identity leaves the user file alone.
9295
    let other_home = root.join("home2");
9296
    let mut c = Repo::init(&root.join("c")).unwrap().with_home(&other_home);
9297
    let (ck, _) = c
9298
        .create_identity("Cy", "[email protected]", IdentityScope::Repo)
9299
        .unwrap();
9300
    assert!(!other_home.join("config.toml").exists());
9301
    let r2 = c.rotate_identity().unwrap();
9302
    assert_ne!(r2.new, ck);
9303
    assert_eq!(
9304
        read_config_file(&root.join("c/.oxy/config")).unwrap()["author.key"],
9305
        r2.new.to_hex()
9306
    );
9307
    assert!(
9308
        !other_home.join("config.toml").exists(),
9309
        "a repository-scoped identity stays repository-scoped"
9310
    );
9311
    // Several delegates in one rotation; a repeat is refused.
9312
    let (d1, d2) = (
9313
        SecretKey::generate().identity("D1", "d1@x", 1),
9314
        SecretKey::generate().identity("D2", "d2@x", 1),
9315
    );
9316
    let r3 = c
9317
        .delegate_add_many(vec![d1.clone(), d2], crate::identity::Scope::CHANGES, None)
9318
        .unwrap();
9319
    assert_eq!(r3.identity.delegates.len(), 2);
9320
    assert!(c
9321
        .delegate_add(d1, crate::identity::Scope::CHANGES, None)
9322
        .is_err());
9323
}
9324
9325
/// Two unrelated histories that both add the same file, joined by two
9326
/// independent merges on two branches, then those branches merged: Git
9327
/// merges identical additions cleanly, and the import must too (#71,
9328
/// found in VS Code's history).
9329
#[test]
9330
fn git_import_joins_unrelated_histories_that_add_the_same_file() {
9331
    // Batches of one: every merge renders apart from the state, where a
9332
    // file whose graph the state had built came out empty (#71).
9333
    crate::repo::git::set_merge_batch_for_tests(Some(1));
9334
    hermetic();
9335
    if std::process::Command::new("git")
9336
        .arg("--version")
9337
        .output()
9338
        .is_err()
9339
    {
9340
        eprintln!("git not installed; skipping");
9341
        return;
9342
    }
9343
    let dir = tempfile::tempdir().unwrap();
9344
    let root = dir.path();
9345
    let g = root.join("src.git");
9346
    fs::create_dir_all(&g).unwrap();
9347
    let git = |args: &[&str]| -> String {
9348
        let out = std::process::Command::new("git")
9349
            .arg("-C")
9350
            .arg(&g)
9351
            .args([
9352
                "-c",
9353
                "user.name=Grace",
9354
                "-c",
9355
                "[email protected]",
9356
                "-c",
9357
                "commit.gpgsign=false",
9358
            ])
9359
            .args(args)
9360
            .output()
9361
            .unwrap();
9362
        assert!(
9363
            out.status.success(),
9364
            "git {args:?}: {}",
9365
            String::from_utf8_lossy(&out.stderr)
9366
        );
9367
        String::from_utf8_lossy(&out.stdout).trim().to_string()
9368
    };
9369
    let text = b"/* header */\nconst a = 1;\nconst b = 2;\n";
9370
    // History A: main.
9371
    git(&["init", "-q", "-b", "main"]);
9372
    write(&g, "gulpfile.js", text);
9373
    write(&g, "a.txt", b"a\n");
9374
    git(&["add", "."]);
9375
    git(&["commit", "-q", "-m", "A root"]);
9376
    // History B: an unrelated root adding the same file, identical.
9377
    git(&["checkout", "-q", "--orphan", "fork"]);
9378
    git(&["rm", "-q", "-r", "--cached", "."]);
9379
    for f in ["gulpfile.js", "a.txt"] {
9380
        let _ = fs::remove_file(g.join(f));
9381
    }
9382
    write(&g, "gulpfile.js", text);
9383
    write(&g, "b.txt", b"b\n");
9384
    git(&["add", "."]);
9385
    git(&["commit", "-q", "-m", "B root"]);
9386
    // Two branches from main, each joining B on its own.
9387
    git(&["checkout", "-q", "-b", "one", "main"]);
9388
    git(&[
9389
        "merge",
9390
        "-q",
9391
        "--no-ff",
9392
        "--allow-unrelated-histories",
9393
        "-m",
9394
        "join on one",
9395
        "fork",
9396
    ]);
9397
    git(&["checkout", "-q", "-b", "two", "main"]);
9398
    write(&g, "a.txt", b"a\ntwo\n");
9399
    git(&["commit", "-q", "-am", "work on two"]);
9400
    git(&[
9401
        "merge",
9402
        "-q",
9403
        "--no-ff",
9404
        "--allow-unrelated-histories",
9405
        "-m",
9406
        "join on two",
9407
        "fork",
9408
    ]);
9409
    // Then the two joins meet, and the file is reformatted after.
9410
    git(&["checkout", "-q", "main"]);
9411
    git(&["merge", "-q", "--no-ff", "-m", "merge one", "one"]);
9412
    git(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
9413
    write(
9414
        &g,
9415
        "gulpfile.js",
9416
        b"/* header */\nconst a = 1;\nconst b = 3;\n",
9417
    );
9418
    git(&["commit", "-q", "-am", "after"]);
9419
9420
    let dest = root.join("dest");
9421
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
9422
    repo.import_git(&g, "main").unwrap();
9423
    let v = repo.verify_git_import(&g, "main").unwrap();
9424
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9425
    assert_eq!(
9426
        fs::read(dest.join("gulpfile.js")).unwrap(),
9427
        b"/* header */\nconst a = 1;\nconst b = 3;\n"
9428
    );
9429
}
9430
9431
/// As above, but the two joins keep different copies (each branch had a
9432
/// different version when it joined), and later work edits each copy:
9433
/// the shape of VS Code's c67ef57cda90 (#71).
9434
#[test]
9435
fn git_import_joins_where_each_join_kept_a_different_copy() {
9436
    // Batches of one: every merge renders apart from the state, where a
9437
    // file whose graph the state had built came out empty (#71).
9438
    crate::repo::git::set_merge_batch_for_tests(Some(1));
9439
    hermetic();
9440
    if std::process::Command::new("git")
9441
        .arg("--version")
9442
        .output()
9443
        .is_err()
9444
    {
9445
        eprintln!("git not installed; skipping");
9446
        return;
9447
    }
9448
    let dir = tempfile::tempdir().unwrap();
9449
    let root = dir.path();
9450
    let g = root.join("src.git");
9451
    fs::create_dir_all(&g).unwrap();
9452
    let run = |args: &[&str]| {
9453
        std::process::Command::new("git")
9454
            .arg("-C")
9455
            .arg(&g)
9456
            .args([
9457
                "-c",
9458
                "user.name=Grace",
9459
                "-c",
9460
                "[email protected]",
9461
                "-c",
9462
                "commit.gpgsign=false",
9463
            ])
9464
            .args(args)
9465
            .output()
9466
            .unwrap()
9467
    };
9468
    let git = |args: &[&str]| -> String {
9469
        let out = run(args);
9470
        assert!(
9471
            out.status.success(),
9472
            "git {args:?}: {}",
9473
            String::from_utf8_lossy(&out.stderr)
9474
        );
9475
        String::from_utf8_lossy(&out.stdout).trim().to_string()
9476
    };
9477
    git(&["init", "-q", "-b", "main"]);
9478
    write(
9479
        &g,
9480
        "gulpfile.js",
9481
        b"/* header */\nconst a = 1;\nconst b = 2;\n",
9482
    );
9483
    git(&["add", "."]);
9484
    git(&["commit", "-q", "-m", "A root"]);
9485
    write(
9486
        &g,
9487
        "gulpfile.js",
9488
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n",
9489
    );
9490
    git(&["commit", "-q", "-am", "whitespace"]);
9491
    git(&["checkout", "-q", "--orphan", "fork"]);
9492
    git(&["rm", "-q", "-r", "--cached", "."]);
9493
    let _ = fs::remove_file(g.join("gulpfile.js"));
9494
    write(
9495
        &g,
9496
        "gulpfile.js",
9497
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n",
9498
    );
9499
    git(&["add", "."]);
9500
    git(&["commit", "-q", "-m", "B root"]);
9501
    // Branch one joins B keeping main's copy; branch two keeps B's.
9502
    for (branch, keep) in [("one", "ours"), ("two", "theirs")] {
9503
        git(&["checkout", "-q", "-b", branch, "main"]);
9504
        let _ = run(&[
9505
            "merge",
9506
            "-q",
9507
            "--no-ff",
9508
            "--allow-unrelated-histories",
9509
            "-m",
9510
            "join",
9511
            "fork",
9512
        ]);
9513
        git(&["checkout", &format!("--{keep}"), "gulpfile.js"]);
9514
        git(&["add", "gulpfile.js"]);
9515
        git(&["commit", "-q", "-m", &format!("join on {branch}")]);
9516
    }
9517
    // Each branch then edits its copy.
9518
    git(&["checkout", "-q", "one"]);
9519
    write(
9520
        &g,
9521
        "gulpfile.js",
9522
        b"/* header */\nconst a = 1;\n\nconst b = 2;\n// tslint\n",
9523
    );
9524
    git(&["commit", "-q", "-am", "tslint on one"]);
9525
    git(&["checkout", "-q", "two"]);
9526
    write(
9527
        &g,
9528
        "gulpfile.js",
9529
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// fmt\n",
9530
    );
9531
    write(&g, "extra.txt", b"x\n");
9532
    write(&g, "more.txt", b"m\n");
9533
    git(&["add", "."]);
9534
    git(&["commit", "-q", "-am", "fmt on two"]);
9535
    // They meet: resolved by hand.
9536
    git(&["checkout", "-q", "one"]);
9537
    let _ = run(&["merge", "-q", "--no-ff", "-m", "merge two", "two"]);
9538
    write(
9539
        &g,
9540
        "gulpfile.js",
9541
        b"/* header */\nconst a = 1;\nconst b = 2;\nconst c = 3;\n// tslint\n// fmt\n",
9542
    );
9543
    git(&["add", "gulpfile.js"]);
9544
    git(&["commit", "-q", "-m", "merge two into one"]);
9545
9546
    let dest = root.join("dest");
9547
    let repo = Repo::init(&dest).unwrap().with_home(root.join("home"));
9548
    repo.import_git(&g, "one").unwrap();
9549
    let v = repo.verify_git_import(&g, "one").unwrap();
9550
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
9551
}
9552
9553
/// oxygen#68: on a store that is not this disk's directory, the operation
9554
/// head is the store's reference record, moved by compare-and-swap. Two
9555
/// handles recording from the same head both get through, merged; a swap
9556
/// from a stale version is refused; a second repository cannot start on a
9557
/// store that already holds one.
9558
#[test]
9559
fn over_a_store_the_operation_head_moves_by_compare_and_swap() {
9560
    use crate::strata::{MemoryStore, Store as _};
9561
    let backend = std::sync::Arc::new(MemoryStore::new());
9562
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
9563
    let dir = tempfile::tempdir().unwrap();
9564
    let a = Repo::init(dir.path()).unwrap();
9565
    assert!(
9566
        !dir.path().join(".oxy/ops/head").exists(),
9567
        "the head is not a file"
9568
    );
9569
    let (h0, op0) = a.head_op().unwrap();
9570
    let record = backend
9571
        .read_ref(HEAD_RECORD)
9572
        .unwrap()
9573
        .expect("the head is the store's record");
9574
    assert_eq!(String::from_utf8(record.0).unwrap(), h0.to_hex());
9575
9576
    let b = Repo::open(dir.path()).unwrap();
9577
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
9578
    let mut va = op0.view.clone();
9579
    va.bookmarks.insert("from-a".into(), state);
9580
    let mut vb = op0.view.clone();
9581
    vb.bookmarks.insert("from-b".into(), state);
9582
    let rb = b.record_op(&[h0], "bookmark from-b", vb).unwrap();
9583
    assert_eq!(b.head_ref().unwrap(), rb);
9584
    // a recorded from h0 too: the head moved, so the two are merged.
9585
    let ra = a.record_op(&[h0], "bookmark from-a", va).unwrap();
9586
    let (head, op) = Repo::open(dir.path()).unwrap().head_op().unwrap();
9587
    assert_eq!(head, ra);
9588
    assert!(
9589
        op.command.ends_with("(merged with a concurrent operation)"),
9590
        "{}",
9591
        op.command
9592
    );
9593
    assert_eq!(op.parents, vec![rb, op.parents[1]]);
9594
    assert!(op.view.bookmarks.contains_key("from-a") && op.view.bookmarks.contains_key("from-b"));
9595
9596
    // A swap from a version that is no longer current moves nothing.
9597
    let (h, v) = a.read_head().unwrap();
9598
    assert!(b.swap_head(&rb, v.as_ref()).unwrap());
9599
    assert!(!a.swap_head(&h, v.as_ref()).unwrap(), "stale");
9600
    a.refresh().unwrap();
9601
    assert_eq!(a.head_ref().unwrap(), rb);
9602
9603
    let other = tempfile::tempdir().unwrap();
9604
    let err = Repo::init(other.path())
9605
        .err()
9606
        .expect("the store already holds a log")
9607
        .to_string();
9608
    assert!(
9609
        err.contains("already holds a repository's operation log"),
9610
        "{err}"
9611
    );
9612
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
9613
}
9614
9615
/// oxygen#68: a repository kept on a store (`storage.url`) holds its
9616
/// objects and operation head there, with `.oxy/cache` in front: it works
9617
/// as one on disk does, reopens, and survives losing its cache.
9618
#[test]
9619
fn a_repository_runs_on_a_store_with_a_cache_in_front() {
9620
    hermetic();
9621
    if std::env::var_os("OXY_STORE_BACKEND").is_some() {
9622
        return;
9623
    }
9624
    let dir = tempfile::tempdir().unwrap();
9625
    let (root, bucket) = (dir.path().join("work"), dir.path().join("bucket"));
9626
    let url = format!("dir://{}", bucket.display());
9627
    let repo = Repo::init_on(&root, [7; 16], Some(&url)).unwrap();
9628
    assert_eq!(repo.config.storage_url.as_deref(), Some(url.as_str()));
9629
    write(&root, "a.txt", b"one\n");
9630
    let h1 = repo.commit("First", &[]).unwrap();
9631
    write(&root, "a.txt", b"one\ntwo\n");
9632
    let h2 = repo.commit("Second", &[]).unwrap();
9633
    assert!(
9634
        !root.join(".oxy/ops/head").exists(),
9635
        "the head is in the store"
9636
    );
9637
    assert!(bucket.join("ops/head").is_file());
9638
    assert!(root.join(".oxy/cache").is_dir());
9639
    drop(repo);
9640
9641
    // Reopened, and again with no cache at all: everything comes from the store.
9642
    for drop_cache in [false, true] {
9643
        if drop_cache {
9644
            std::fs::remove_dir_all(root.join(".oxy/cache")).unwrap();
9645
        }
9646
        let repo = Repo::open(&root).unwrap();
9647
        let log: Vec<String> = repo
9648
            .op_log()
9649
            .unwrap()
9650
            .into_iter()
9651
            .map(|(_, op)| op.command)
9652
            .collect();
9653
        assert!(log.len() >= 3, "{log:?}");
9654
        assert_eq!(repo.store().get_change(&h1).unwrap().message, "First");
9655
        let heads = repo
9656
            .store()
9657
            .get_state(&repo.view().unwrap().bookmarks["main"])
9658
            .unwrap()
9659
            .heads;
9660
        assert_eq!(heads, vec![h2]);
9661
        assert_eq!(
9662
            repo.load_state(&heads).unwrap().materialize().files.len(),
9663
            1
9664
        );
9665
    }
9666
9667
    // A second repository cannot start on the same store.
9668
    let err = Repo::init_on(&dir.path().join("other"), [8; 16], Some(&url))
9669
        .err()
9670
        .unwrap()
9671
        .to_string();
9672
    assert!(
9673
        err.contains("already holds a repository's operation log"),
9674
        "{err}"
9675
    );
9676
    let err = Repo::init_on(&dir.path().join("third"), [9; 16], Some("nope://x"))
9677
        .err()
9678
        .unwrap()
9679
        .to_string();
9680
    assert!(err.contains("cannot open that kind of store"), "{err}");
9681
}
9682
9683
/// oxygen#75: the prompt's quick check agrees with status in a repository
9684
/// with a subrepo: clean after a commit, dirty when the subrepo moves to
9685
/// another state, clean again once that pin is committed. (It compared the
9686
/// subrepo's directory as if it were a file, so it was always dirty.)
9687
#[test]
9688
fn the_quick_dirty_check_compares_a_subrepo_by_its_pin() {
9689
    hermetic();
9690
    let dir = tempfile::tempdir().unwrap();
9691
    let root = dir.path();
9692
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9693
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9694
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9695
        .unwrap()
9696
        .with_home(root.join("home"));
9697
    write(&root.join("lib"), "lib.txt", b"v1\n");
9698
    lib.commit("lib v1", &[]).unwrap();
9699
    assert!(lib.push("origin", false).unwrap()[0].ok);
9700
    let app_dir = root.join("app");
9701
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9702
    write(&app_dir, "main.txt", b"app\n");
9703
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9704
    app.commit("app with lib", &[]).unwrap();
9705
    // Out of the racy window, so the stat-only path decides.
9706
    std::thread::sleep(std::time::Duration::from_millis(2100));
9707
    let reopen = || Repo::open(&app_dir).unwrap();
9708
    assert_eq!(
9709
        reopen().quick_dirty().unwrap(),
9710
        Some(false),
9711
        "clean, as status says"
9712
    );
9713
    let nested = Repo::open(&app_dir.join("libs/lib")).unwrap();
9714
    write(&app_dir.join("libs/lib"), "lib.txt", b"v2\n");
9715
    nested.commit("lib v2", &[]).unwrap();
9716
    assert_eq!(
9717
        reopen().quick_dirty().unwrap(),
9718
        Some(true),
9719
        "the subrepo moved"
9720
    );
9721
    reopen().commit("pin lib v2", &[]).unwrap();
9722
    std::thread::sleep(std::time::Duration::from_millis(2100));
9723
    assert_eq!(
9724
        reopen().quick_dirty().unwrap(),
9725
        Some(false),
9726
        "the new pin is committed"
9727
    );
9728
}
9729
9730
#[test]
9731
fn a_module_entry_that_was_never_added_is_reported_as_unpinned() {
9732
    // oxygen#72: a .oxymodules section with no subrepo behind it.
9733
    hermetic();
9734
    let dir = tempfile::tempdir().unwrap();
9735
    let root = dir.path();
9736
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9737
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9738
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9739
        .unwrap()
9740
        .with_home(root.join("home"));
9741
    write(&root.join("lib"), "lib.txt", b"v1\n");
9742
    lib.commit("lib v1", &[]).unwrap();
9743
    assert!(lib.push("origin", false).unwrap()[0].ok);
9744
    let app_dir = root.join("app");
9745
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9746
    write(
9747
        &app_dir,
9748
        ".oxymodules",
9749
        format!("[libs/lib]\nurl = {lib_url}\n").as_bytes(),
9750
    );
9751
    let unpinned = app.unpinned_modules().unwrap();
9752
    assert_eq!(unpinned.len(), 1);
9753
    assert_eq!(unpinned[0].0, "libs/lib");
9754
    assert_eq!(unpinned[0].1.url, lib_url);
9755
    assert!(app.submodule_update(true, &[]).unwrap().is_empty());
9756
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9757
    assert!(app.unpinned_modules().unwrap().is_empty(), "added now");
9758
}
9759
9760
#[test]
9761
fn the_bookmark_revset_function_names_only_bookmarks() {
9762
    // oxygen#73: bookmark(NAME) is a bookmark's heads, never a tag or prefix.
9763
    hermetic();
9764
    let dir = tempfile::tempdir().unwrap();
9765
    let repo = Repo::init(dir.path()).unwrap();
9766
    write(dir.path(), "a.txt", b"a\n");
9767
    let a = repo.commit("A", &[]).unwrap();
9768
    write(dir.path(), "b.txt", b"b\n");
9769
    let b = repo.commit("B", &[]).unwrap();
9770
    let mut heads = repo.revset("bookmark(main)").unwrap().hashes;
9771
    heads.sort();
9772
    let mut want = repo.bookmark_heads().unwrap();
9773
    want.sort();
9774
    assert_eq!(heads, want);
9775
    assert!(heads.contains(&b));
9776
    assert_eq!(repo.revset("main").unwrap().hashes.len(), heads.len());
9777
    // A change prefix is a symbol, not a bookmark.
9778
    let prefix = repo.store().get_change_meta(&a).unwrap().change_id.short(8);
9779
    assert!(repo.revset(&prefix).is_ok());
9780
    let e = repo
9781
        .revset(&format!("bookmark({prefix})"))
9782
        .unwrap_err()
9783
        .to_string();
9784
    assert!(e.contains("no such bookmark"), "{e}");
9785
}
9786
9787
/// oxygen#140: a replace conflict is settled from the working copy, as
9788
/// `oxy resolve PATH` does: the path's content on disk becomes the
9789
/// resolution, and the commit that records it is a Resolution.
9790
#[test]
9791
fn a_replace_conflict_is_settled_from_the_working_copy() {
9792
    hermetic();
9793
    let dir = tempfile::tempdir().unwrap();
9794
    let root = dir.path();
9795
    let mut repo = Repo::init(root).unwrap().with_home(root.join("home"));
9796
    let blob = |n: u8| {
9797
        let mut v = vec![0u8; 64];
9798
        v[1] = n;
9799
        v
9800
    };
9801
    write(root, "img.bin", &blob(1));
9802
    write(root, "a.txt", b"a\n");
9803
    repo.commit("add img", &[]).unwrap();
9804
    repo.bookmark_create("other", None).unwrap();
9805
    write(root, "img.bin", &blob(2));
9806
    repo.commit("img two", &[]).unwrap();
9807
    repo.bookmark_switch("other", false).unwrap();
9808
    write(root, "img.bin", &blob(3));
9809
    repo.commit("img three", &[]).unwrap();
9810
    repo.bookmark_switch("main", false).unwrap();
9811
    repo.merge("other").unwrap();
9812
    // Without a choice, nothing the working copy holds settles it, and
9813
    // other work cannot be committed past it.
9814
    write(root, "img.bin", &blob(9));
9815
    write(root, "a.txt", b"a\nmore\n");
9816
    assert!(
9817
        repo.commit("edit a", &[]).is_err(),
9818
        "refused while conflicted"
9819
    );
9820
    let snap = repo.snapshot("oxy resolve").unwrap();
9821
    assert!(
9822
        repo.choose_resolutions(&snap.base_snapshot, &["a.txt".to_string()])
9823
            .is_err(),
9824
        "a.txt has no replace conflict"
9825
    );
9826
    repo.choose_resolutions(&snap.base_snapshot, &["img.bin".to_string()])
9827
        .unwrap();
9828
    let snap = repo.snapshot("oxy resolve").unwrap();
9829
    assert!(snap
9830
        .statuses
9831
        .iter()
9832
        .any(|s| s.path == "img.bin" && s.status == ChangeStatus::Resolved));
9833
    let c = repo.commit("settle img", &[]).unwrap();
9834
    assert_eq!(
9835
        repo.store().get_change(&c).unwrap().kind,
9836
        ChangeKind::Resolution
9837
    );
9838
    let after = repo
9839
        .load_state(&repo.bookmark_heads().unwrap())
9840
        .unwrap()
9841
        .materialize();
9842
    assert!(!after.is_conflicted());
9843
    assert_eq!(
9844
        after.files["img.bin"].content,
9845
        FileContent::Opaque {
9846
            blobs: vec![Repo::blob_ref(&blob(9))]
9847
        }
9848
    );
9849
    assert!(
9850
        matches!(&after.files["a.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nmore\n")
9851
    );
9852
    // Settled: the choice is forgotten, and the working copy is clean.
9853
    let snap = repo.snapshot("status").unwrap();
9854
    assert!(snap.statuses.is_empty(), "{:?}", snap.statuses);
9855
    assert!(repo.resolutions().unwrap().is_empty());
9856
}
9857
9858
/// oxygen#140: the same for a subrepo pin moved two ways at once.
9859
#[test]
9860
fn a_pin_conflict_is_settled_from_the_working_copy() {
9861
    hermetic();
9862
    let dir = tempfile::tempdir().unwrap();
9863
    let root = dir.path();
9864
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9865
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9866
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9867
        .unwrap()
9868
        .with_home(root.join("home"));
9869
    write(&root.join("lib"), "lib.txt", b"v1\n");
9870
    lib.commit("lib v1", &[]).unwrap();
9871
    assert!(lib.push("origin", false).unwrap()[0].ok);
9872
    let app_dir = root.join("app");
9873
    let mut app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9874
    write(&app_dir, "main.txt", b"app\n");
9875
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9876
    app.commit("pin v1", &[]).unwrap();
9877
    let nested = Repo::open(&app_dir.join("libs/lib"))
9878
        .unwrap()
9879
        .with_home(root.join("home"));
9880
    fn pin(app: &Repo, nested: &Repo, text: &[u8], message: &str) {
9881
        write(nested.root(), "lib.txt", text);
9882
        nested.commit(message, &[]).unwrap();
9883
        app.commit(&format!("pin {message}"), &[]).unwrap();
9884
    }
9885
    app.bookmark_create("other", None).unwrap();
9886
    pin(&app, &nested, b"v2\n", "v2");
9887
    app.bookmark_switch("other", false).unwrap();
9888
    pin(&app, &nested, b"v3\n", "v3");
9889
    app.bookmark_switch("main", false).unwrap();
9890
    app.merge("other").unwrap();
9891
    let merged = app
9892
        .load_state(&app.bookmark_heads().unwrap())
9893
        .unwrap()
9894
        .materialize();
9895
    assert!(
9896
        matches!(&merged.files["libs/lib"].content, FileContent::Opaque { blobs } if blobs.len() == 2),
9897
        "a pin conflict"
9898
    );
9899
    // The nested repository moves on once more; that pin is the choice.
9900
    write(&app_dir.join("libs/lib"), "lib.txt", b"v4\n");
9901
    nested.commit("v4", &[]).unwrap();
9902
    let snap = app.snapshot("oxy resolve").unwrap();
9903
    app.choose_resolutions(&snap.base_snapshot, &["libs/lib".to_string()])
9904
        .unwrap();
9905
    let c = app.commit("settle the pin", &[]).unwrap();
9906
    assert_eq!(
9907
        app.store().get_change(&c).unwrap().kind,
9908
        ChangeKind::Resolution
9909
    );
9910
    let after = app
9911
        .load_state(&app.bookmark_heads().unwrap())
9912
        .unwrap()
9913
        .materialize();
9914
    assert!(!after.is_conflicted());
9915
    assert!(app.snapshot("status").unwrap().statuses.is_empty());
9916
}
9917
9918
#[test]
9919
fn carrying_work_over_a_subrepo_already_at_the_target_pin_is_no_conflict() {
9920
    // oxygen#74: a stale state with .oxymodules but no pin, a newer one
9921
    // pinning the subrepo, and the nested repository on disk at that pin.
9922
    hermetic();
9923
    let dir = tempfile::tempdir().unwrap();
9924
    let root = dir.path();
9925
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
9926
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
9927
    let lib = Repo::clone(&lib_url, &root.join("lib"))
9928
        .unwrap()
9929
        .with_home(root.join("home"));
9930
    write(&root.join("lib"), "lib.txt", b"v1\n");
9931
    lib.commit("lib v1", &[]).unwrap();
9932
    assert!(lib.push("origin", false).unwrap()[0].ok);
9933
    let app_dir = root.join("app");
9934
    let app = Repo::init(&app_dir).unwrap().with_home(root.join("home"));
9935
    write(&app_dir, "main.txt", b"app\n");
9936
    app.submodule_add(&lib_url, "libs/lib", None).unwrap();
9937
    // The stale state: registered in .oxymodules, never pinned.
9938
    fs::rename(app_dir.join("libs/lib"), root.join("aside")).unwrap();
9939
    app.commit("initial", &[]).unwrap();
9940
    let stale = app.bookmark_heads().unwrap();
9941
    fs::rename(root.join("aside"), app_dir.join("libs/lib")).unwrap();
9942
    app.commit("pin lib", &[]).unwrap();
9943
    let newer = app.bookmark_heads().unwrap();
9944
    app.checkout(&stale, false, "test").unwrap();
9945
    write(&app_dir, "notes.txt", b"mine\n");
9946
    let (_, carried) = app.checkout_carry(&newer, "main", "test").unwrap();
9947
    assert_eq!(carried, vec!["notes.txt".to_string()]);
9948
    assert!(app_dir.join("notes.txt").exists());
9949
}
9950
9951
/// oxygen#142: a new bookmark made from main sends what main lacks, not
9952
/// its whole history again.
9953
#[test]
9954
fn a_new_bookmark_sends_only_what_the_remote_lacks() {
9955
    hermetic();
9956
    let dir = tempfile::tempdir().unwrap();
9957
    let root = dir.path();
9958
    let _origin = Repo::init(&root.join("origin")).unwrap();
9959
    let url = root.join("origin").to_string_lossy().to_string();
9960
    let mut one = Repo::clone(&url, &root.join("one"))
9961
        .unwrap()
9962
        .with_home(root.join("home"));
9963
    for n in 0..5 {
9964
        write(&root.join("one"), "a.txt", format!("{n}\n").as_bytes());
9965
        one.commit(&format!("main {n}"), &[]).unwrap();
9966
    }
9967
    assert!(one.push("origin", false).unwrap()[0].ok);
9968
    one.bookmark_create("feature", None).unwrap();
9969
    one.bookmark_switch("feature", false).unwrap();
9970
    write(&root.join("one"), "b.txt", b"feature\n");
9971
    let added = one.commit("feature", &[]).unwrap();
9972
    let heads = one.bookmark_heads().unwrap();
9973
    let refs = one
9974
        .open_named_remote("origin")
9975
        .unwrap()
9976
        .refs()
9977
        .unwrap()
9978
        .refs;
9979
    assert!(
9980
        refs.iter().all(|r| r.name != "feature"),
9981
        "new to the remote"
9982
    );
9983
    let sent = one
9984
        .negotiate(&one.remote_holds(&refs, &[]), &heads)
9985
        .unwrap();
9986
    assert_eq!(sent, vec![added], "only the change main lacks");
9987
    assert!(one.push_bookmark("origin", "feature", false).unwrap()[0].ok);
9988
    let two = Repo::clone(&url, &root.join("two")).unwrap();
9989
    assert!(two.store().has(&added));
9990
}
9991
9992
#[test]
9993
fn a_bookmark_only_behind_its_remote_catches_up() {
9994
    // oxygen#74: switch takes the remote's state rather than a stale one.
9995
    hermetic();
9996
    let dir = tempfile::tempdir().unwrap();
9997
    let root = dir.path();
9998
    let _origin = Repo::init(&root.join("origin")).unwrap();
9999
    let url = root.join("origin").to_string_lossy().to_string();
10000
    let one = Repo::clone(&url, &root.join("one"))
10001
        .unwrap()
10002
        .with_home(root.join("home"));
10003
    write(&root.join("one"), "a.txt", b"a\n");
10004
    one.commit("A", &[]).unwrap();
10005
    assert!(one.push("origin", false).unwrap()[0].ok);
10006
    let two = Repo::clone(&url, &root.join("two"))
10007
        .unwrap()
10008
        .with_home(root.join("home"));
10009
    write(&root.join("two"), "b.txt", b"b\n");
10010
    two.commit("B", &[]).unwrap();
10011
    assert!(two.push("origin", false).unwrap()[0].ok);
10012
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None, "not fetched");
10013
    one.fetch("origin").unwrap();
10014
    assert_eq!(one.catch_up_bookmark("main").unwrap(), Some(1));
10015
    assert_eq!(one.bookmarks().unwrap()[0].behind, Some(0));
10016
    // Local work the remote lacks: left alone.
10017
    write(&root.join("one"), "c.txt", b"c\n");
10018
    one.commit("C", &[]).unwrap();
10019
    write(&root.join("two"), "d.txt", b"d\n");
10020
    two.commit("D", &[]).unwrap();
10021
    assert!(two.push("origin", false).unwrap()[0].ok);
10022
    one.fetch("origin").unwrap();
10023
    assert_eq!(one.catch_up_bookmark("main").unwrap(), None);
10024
}
10025
10026
#[test]
10027
fn a_bookmark_is_compared_with_a_remote_that_has_it_when_there_is_no_origin() {
10028
    // oxygen#83: remotes earth and gcs, origin removed.
10029
    hermetic();
10030
    let dir = tempfile::tempdir().unwrap();
10031
    let root = dir.path();
10032
    let _up = Repo::init(&root.join("up")).unwrap();
10033
    let url = root.join("up").to_string_lossy().to_string();
10034
    let other = Repo::clone(&url, &root.join("other"))
10035
        .unwrap()
10036
        .with_home(root.join("home"));
10037
    write(&root.join("other"), "a.txt", b"a\n");
10038
    other.commit("a", &[]).unwrap();
10039
    assert!(other.push("origin", false).unwrap()[0].ok);
10040
    let mut one = Repo::clone(&url, &root.join("one"))
10041
        .unwrap()
10042
        .with_home(root.join("home"));
10043
    one.config.set("remote.earth.url", &url).unwrap();
10044
    one.config.set("remote.gcs.url", &url).unwrap();
10045
    one.config.set("remote.origin.url", "").unwrap();
10046
    one.save_config().unwrap();
10047
    write(&root.join("other"), "b.txt", b"b\n");
10048
    other.commit("b", &[]).unwrap();
10049
    assert!(other.push("origin", false).unwrap()[0].ok);
10050
    one.fetch("earth").unwrap();
10051
    let b = one
10052
        .bookmarks()
10053
        .unwrap()
10054
        .into_iter()
10055
        .find(|b| b.name == "main")
10056
        .unwrap();
10057
    assert_eq!(
10058
        (b.remote.as_deref(), b.behind),
10059
        (Some("earth"), Some(1)),
10060
        "a stale origin copy is not used"
10061
    );
10062
    assert_eq!(
10063
        one.default_remote(),
10064
        "origin",
10065
        "no default chosen among several"
10066
    );
10067
    let e = one.pull(&one.default_remote()).unwrap_err().to_string();
10068
    assert!(e.contains("earth, gcs") && e.contains("core.remote"), "{e}");
10069
    one.config.set("core.remote", "earth").unwrap();
10070
    assert_eq!(one.default_remote(), "earth");
10071
}
10072
10073
#[test]
10074
fn a_missing_author_identity_says_how_to_fix_it() {
10075
    // oxygen#82: an agent home's author.key naming an identity the
10076
    // repository does not hold.
10077
    hermetic();
10078
    let dir = tempfile::tempdir().unwrap();
10079
    let mut repo = Repo::init(dir.path()).unwrap();
10080
    let missing = KeyId::from_hex(&"ab".repeat(32)).unwrap();
10081
    repo.config.set("author.key", &missing.to_hex()).unwrap();
10082
    let e = repo.identity(&missing).unwrap_err().to_string();
10083
    assert!(
10084
        e.contains("this repository has no identity") && e.contains("oxy config author.key"),
10085
        "{e}"
10086
    );
10087
    assert!(e.contains("this repository's config"), "{e}");
10088
}
10089
10090
#[test]
10091
fn a_working_copy_behind_its_bookmark_is_flagged_and_pull_brings_it_up() {
10092
    // oxygen#89 (supermarioland, 2026-10-09): the bookmark moved on without
10093
    // the working copy, a pull with nothing new left it there, and status
10094
    // said "clean".
10095
    hermetic();
10096
    let dir = tempfile::tempdir().unwrap();
10097
    let root = dir.path();
10098
    let _up = Repo::init(&root.join("up")).unwrap();
10099
    let url = root.join("up").to_string_lossy().to_string();
10100
    let other = Repo::clone(&url, &root.join("other"))
10101
        .unwrap()
10102
        .with_home(root.join("home"));
10103
    write(&root.join("other"), "a.txt", b"a\n");
10104
    other.commit("a", &[]).unwrap();
10105
    assert!(other.push("origin", false).unwrap()[0].ok);
10106
    let one = Repo::clone(&url, &root.join("one"))
10107
        .unwrap()
10108
        .with_home(root.join("home"));
10109
    write(&root.join("other"), "b.txt", b"b\n");
10110
    other.commit("b", &[]).unwrap();
10111
    assert!(other.push("origin", false).unwrap()[0].ok);
10112
    one.fetch("origin").unwrap();
10113
    // The bookmark moves; the working copy does not.
10114
    let theirs = one.resolve_heads("origin/main").unwrap();
10115
    one.bookmark_set("main", &theirs).unwrap();
10116
    assert!(!root.join("one/b.txt").exists());
10117
    assert_eq!(one.working_copy_behind().unwrap(), Some(1));
10118
    let r = one.pull("origin").unwrap();
10119
    assert!(
10120
        !r.changed && r.checked_out,
10121
        "nothing new, but the working copy caught up"
10122
    );
10123
    assert!(root.join("one/b.txt").exists());
10124
    assert_eq!(one.working_copy_behind().unwrap(), None);
10125
}
10126
10127
#[test]
10128
fn touched_nodes_cache_answers_as_the_changes_do() {
10129
    hermetic();
10130
    let dir = tempfile::tempdir().unwrap();
10131
    let repo = Repo::init(dir.path()).unwrap();
10132
    write(dir.path(), "a.txt", b"one\n");
10133
    write(dir.path(), "b.txt", b"x\n");
10134
    repo.snapshot("t").unwrap();
10135
    let c1 = repo.commit("first", &[]).unwrap();
10136
    write(dir.path(), "b.txt", b"y\n");
10137
    repo.snapshot("t").unwrap();
10138
    repo.commit("b only", &[]).unwrap();
10139
    fs::rename(dir.path().join("a.txt"), dir.path().join("c.txt")).unwrap();
10140
    write(dir.path(), "c.txt", b"one\ntwo\n");
10141
    repo.snapshot("t").unwrap();
10142
    let c3 = repo.commit("rename and edit", &[]).unwrap();
10143
    // Uncommitted work, so the working copy touches a file too.
10144
    write(dir.path(), "c.txt", b"one\ntwo\nthree\n");
10145
    repo.snapshot("t").unwrap();
10146
10147
    let path = dir.path().join(".oxy/index/touched");
10148
    let hashes = |es: Vec<LogEntry>| es.iter().map(|e| e.hash).collect::<Vec<_>>();
10149
    let cold = hashes(repo.log_for_path("c.txt").unwrap());
10150
    assert!(path.exists(), "the first query writes the cache");
10151
    let warm = hashes(repo.log_for_path("c.txt").unwrap());
10152
    assert_eq!(cold, warm, "the cache answers as the changes do");
10153
    let (wc, _) = repo.working_copy().unwrap();
10154
    assert_eq!(
10155
        cold,
10156
        vec![wc, c3, c1],
10157
        "renames followed, the working copy included"
10158
    );
10159
10160
    // Working-copy changes are not kept: they are replaced by every snapshot.
10161
    let cached = super::touched::read_touched_for_test(&fs::read(&path).unwrap()).unwrap();
10162
    assert!(!cached.contains(&wc), "a working-copy change is not cached");
10163
    assert!(cached.contains(&c1) && cached.contains(&c3));
10164
10165
    // A damaged cache is ignored, not trusted.
10166
    let mut bytes = fs::read(&path).unwrap();
10167
    let last = bytes.len() - 40;
10168
    bytes[last] ^= 1;
10169
    fs::write(&path, &bytes).unwrap();
10170
    assert_eq!(hashes(repo.log_for_path("c.txt").unwrap()), cold);
10171
    let touches = repo.log_revset("touches(\"c.txt\") ~ @").unwrap();
10172
    assert_eq!(hashes(touches), vec![c3, c1]);
10173
}
10174
10175
/// oxygen#88 (vscode 9ab2056393c8): two lines of history that each move a
10176
/// file back where it was leave two placements at one place, which the
10177
/// tree shows as one file. Removing it, and then its directory, retires
10178
/// both, so no copy is left under a directory that is gone.
10179
#[test]
10180
fn git_import_removes_every_copy_of_a_file_at_one_place() {
10181
    hermetic();
10182
    if std::process::Command::new("git")
10183
        .arg("--version")
10184
        .output()
10185
        .is_err()
10186
    {
10187
        eprintln!("git not installed; skipping");
10188
        return;
10189
    }
10190
    let dir = tempfile::tempdir().unwrap();
10191
    let root = dir.path();
10192
    let g = root.join("src.git");
10193
    fs::create_dir_all(&g).unwrap();
10194
    let git = |args: &[&str]| {
10195
        let out = std::process::Command::new("git")
10196
            .arg("-C")
10197
            .arg(&g)
10198
            .args([
10199
                "-c",
10200
                "user.name=Grace",
10201
                "-c",
10202
                "[email protected]",
10203
                "-c",
10204
                "commit.gpgsign=false",
10205
            ])
10206
            .args(args)
10207
            .output()
10208
            .unwrap();
10209
        assert!(
10210
            out.status.success(),
10211
            "git {args:?}: {}",
10212
            String::from_utf8_lossy(&out.stderr)
10213
        );
10214
    };
10215
    git(&["init", "-q", "-b", "main"]);
10216
    write(&g, "d/list.txt", b"one\ntwo\nthree\nfour\n");
10217
    write(&g, "keep.txt", b"k\n");
10218
    git(&["add", "."]);
10219
    git(&["commit", "-qm", "base"]);
10220
    fs::create_dir_all(g.join("d/sub")).unwrap();
10221
    git(&["mv", "d/list.txt", "d/sub/list.txt"]);
10222
    git(&["commit", "-qm", "into sub"]);
10223
    git(&["checkout", "-qb", "side"]);
10224
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
10225
    git(&["commit", "-qm", "back, on side"]);
10226
    git(&["checkout", "-q", "main"]);
10227
    git(&["mv", "d/sub/list.txt", "d/list.txt"]);
10228
    git(&["commit", "-qm", "back, on main"]);
10229
    git(&["merge", "-q", "--no-edit", "side"]);
10230
    git(&["rm", "-rq", "d"]);
10231
    git(&["commit", "-qm", "d goes"]);
10232
10233
    let repo = Repo::init(&root.join("o")).unwrap();
10234
    repo.import_git(&g, "main").unwrap();
10235
    let v = repo.verify_git_import(&g, "main").unwrap();
10236
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
10237
    let st = repo
10238
        .load_state_history(&repo.bookmark_heads().unwrap())
10239
        .unwrap();
10240
    let view = st.tree().view();
10241
    assert!(view.conflicts.is_empty(), "{:?}", view.conflicts);
10242
    assert_eq!(view.entries.keys().collect::<Vec<_>>(), vec!["keep.txt"]);
10243
}
10244
10245
/// oxygen#94: a state index's file histories are read, and checked by
10246
/// their own hashes, only when a file is built. One found damaged is an
10247
/// error that says so, the index is removed, and the next read rebuilds it.
10248
#[test]
10249
fn a_damaged_file_history_in_the_state_index_is_rebuilt() {
10250
    hermetic();
10251
    let dir = tempfile::tempdir().unwrap();
10252
    let repo = Repo::init(dir.path()).unwrap();
10253
    for i in 0..6 {
10254
        write(
10255
            dir.path(),
10256
            &format!("f{i}.txt"),
10257
            format!("one {i}\n").as_bytes(),
10258
        );
10259
    }
10260
    repo.snapshot("t").unwrap();
10261
    repo.commit("first", &[]).unwrap();
10262
    for i in 0..6 {
10263
        write(
10264
            dir.path(),
10265
            &format!("f{i}.txt"),
10266
            format!("one {i}\ntwo\n").as_bytes(),
10267
        );
10268
    }
10269
    repo.snapshot("t").unwrap();
10270
    repo.commit("second", &[]).unwrap();
10271
    let want: Vec<Vec<u8>> = (0..6)
10272
        .map(|i| format!("one {i}\ntwo\n").into_bytes())
10273
        .collect();
10274
    // The index of the working copy's base, holding every file's history
10275
    // (a few changes behind, an index is replayed onto, not rewritten).
10276
    let (_, wc) = repo.working_copy().unwrap();
10277
    let base = repo.load_state_history(&wc.deps).unwrap();
10278
    repo.write_state_index(&wc.deps, &base);
10279
    for (i, w) in want.iter().enumerate() {
10280
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
10281
    }
10282
    let index = repo.state_indexes();
10283
    assert!(!index.is_empty(), "a state index was written");
10284
    // The histories are last in the file: damage the last of them.
10285
    let mut bytes = fs::read(&index[0]).unwrap();
10286
    let last = bytes.len() - 1;
10287
    bytes[last] ^= 0x40;
10288
    fs::write(&index[0], &bytes).unwrap();
10289
10290
    let reads: Vec<_> = (0..6)
10291
        .map(|i| repo.file_at(&format!("f{i}.txt"), None))
10292
        .collect();
10293
    let damaged: Vec<String> = reads
10294
        .iter()
10295
        .filter_map(|r| r.as_ref().err().map(|e| e.to_string()))
10296
        .collect();
10297
    assert_eq!(damaged.len(), 1, "{damaged:?}");
10298
    assert!(
10299
        damaged[0].contains("state index was damaged")
10300
            && damaged[0].contains("run the command again"),
10301
        "{}",
10302
        damaged[0]
10303
    );
10304
    // Every file reads right again, from an index rebuilt from history.
10305
    for (i, w) in want.iter().enumerate() {
10306
        assert_eq!(&repo.file_at(&format!("f{i}.txt"), None).unwrap(), w);
10307
    }
10308
}
10309
10310
/// oxygen#95: a push longer than `push.batch-bytes` goes in parts, each
10311
/// objects alone and in dependency order, and the last moves the bookmark.
10312
/// The remote ends with every change and the same state, and says how each
10313
/// part went.
10314
#[test]
10315
fn a_long_push_goes_in_parts() {
10316
    hermetic();
10317
    let dir = tempfile::tempdir().unwrap();
10318
    let root = dir.path();
10319
    let origin = root.join("origin");
10320
    Repo::init_bare_unbound(&origin).unwrap();
10321
    let main = root.join("main");
10322
    let mut repo = Repo::init(&main).unwrap();
10323
    repo.config
10324
        .set("remote.origin.url", &origin.to_string_lossy())
10325
        .unwrap();
10326
    // One byte: every change is a part of its own.
10327
    repo.config.set("push.batch-bytes", "1").unwrap();
10328
    repo.save_config().unwrap();
10329
    for i in 0..6 {
10330
        write(
10331
            &main,
10332
            &format!("f{i}.txt"),
10333
            format!("file {i}\n").as_bytes(),
10334
        );
10335
        repo.commit(&format!("c{i}"), &[]).unwrap();
10336
    }
10337
    let mut parts = Vec::new();
10338
    let results = repo
10339
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
10340
        .unwrap();
10341
    assert!(
10342
        results.iter().any(|r| r.ok && r.name == "main"),
10343
        "{results:?}"
10344
    );
10345
    assert_eq!(parts.len(), 6, "{parts:?}");
10346
    assert_eq!(parts[0], "part 1 of 6: 1 changes");
10347
10348
    let remote = Repo::open(&origin).unwrap();
10349
    let heads = repo.bookmark_heads().unwrap();
10350
    assert_eq!(remote.bookmark_heads().unwrap(), heads);
10351
    assert_eq!(
10352
        remote.log_state(&heads).unwrap().len(),
10353
        repo.log_state(&heads).unwrap().len()
10354
    );
10355
    // A push of objects alone reports how it went, as `objects`.
10356
    let got = remote
10357
        .receive_push(Bundle::default(), vec![], None, vec![])
10358
        .unwrap();
10359
    assert_eq!(got.len(), 1);
10360
    assert!(got[0].ok && got[0].name == OBJECTS_RESULT, "{got:?}");
10361
}
10362
10363
/// oxygen#133: one change whose blobs pass `push.batch-bytes` sends them
10364
/// first, in parts of objects alone, so no request is larger than about
10365
/// that (a proxy in front of a hub refuses one past 100 MB); the change
10366
/// and the bookmark follow, and a clone has every file.
10367
#[test]
10368
fn a_heavy_change_sends_its_blobs_in_parts() {
10369
    hermetic();
10370
    let dir = tempfile::tempdir().unwrap();
10371
    let root = dir.path();
10372
    let origin = root.join("origin");
10373
    Repo::init_bare_unbound(&origin).unwrap();
10374
    let main = root.join("main");
10375
    let mut repo = Repo::init(&main).unwrap();
10376
    repo.config
10377
        .set("remote.origin.url", &origin.to_string_lossy())
10378
        .unwrap();
10379
    repo.config.set("push.batch-bytes", "50000").unwrap();
10380
    repo.save_config().unwrap();
10381
    let mut x: u64 = 0x9e3779b97f4a7c15;
10382
    let mut noise = |n: usize| -> Vec<u8> {
10383
        (0..n)
10384
            .map(|_| {
10385
                x ^= x << 13;
10386
                x ^= x >> 7;
10387
                x ^= x << 17;
10388
                (x >> 24) as u8
10389
            })
10390
            .collect()
10391
    };
10392
    let files: Vec<Vec<u8>> = (0..4).map(|_| noise(40_000)).collect();
10393
    for (i, f) in files.iter().enumerate() {
10394
        write(&main, &format!("bin{i}.dat"), f);
10395
    }
10396
    repo.commit("four blobs", &[]).unwrap();
10397
    let mut parts = Vec::new();
10398
    let results = repo
10399
        .push_bookmark_with("origin", "main", false, &mut |m| parts.push(m.to_string()))
10400
        .unwrap();
10401
    assert!(
10402
        results.iter().any(|r| r.ok && r.name == "main"),
10403
        "{results:?}"
10404
    );
10405
    assert!(
10406
        parts.len() >= 3 && parts[0].starts_with("objects 1 of"),
10407
        "{parts:?}"
10408
    );
10409
    let back = Repo::clone(&origin.to_string_lossy(), &root.join("back")).unwrap();
10410
    for (i, f) in files.iter().enumerate() {
10411
        assert_eq!(&fs::read(root.join(format!("back/bin{i}.dat"))).unwrap(), f);
10412
    }
10413
    drop(back);
10414
}
10415
10416
/// oxygen#136: a bundle carries a replaced binary file's new content
10417
/// only. Its old content came with the change that added it, so removing
10418
/// or replacing a file sends no old blob again; the remote and a clone of
10419
/// it are whole.
10420
#[test]
10421
fn a_replacement_does_not_send_the_old_content_again() {
10422
    hermetic();
10423
    let dir = tempfile::tempdir().unwrap();
10424
    let root = dir.path();
10425
    let origin = root.join("origin");
10426
    Repo::init_bare_unbound(&origin).unwrap();
10427
    let main = root.join("main");
10428
    let mut repo = Repo::init(&main).unwrap();
10429
    repo.config
10430
        .set("remote.origin.url", &origin.to_string_lossy())
10431
        .unwrap();
10432
    repo.save_config().unwrap();
10433
    let blobs = |b: &Bundle| {
10434
        b.objects
10435
            .iter()
10436
            .filter(|(ty, _)| *ty == ObjectType::Blob)
10437
            .count()
10438
    };
10439
    write(&main, "bin.dat", b"\0\x01first binary");
10440
    write(&main, "gone.dat", b"\0\x02to be removed");
10441
    let added = repo.commit("add", &[]).unwrap();
10442
    assert!(repo.push("origin", false).unwrap()[0].ok);
10443
    write(&main, "bin.dat", b"\0\x01second binary");
10444
    fs::remove_file(main.join("gone.dat")).unwrap();
10445
    let changed = repo.commit("replace and remove", &[]).unwrap();
10446
    assert_eq!(blobs(&repo.bundle_for(&[changed]).unwrap()), 1);
10447
    assert_eq!(blobs(&repo.bundle_for(&[added, changed]).unwrap()), 3);
10448
    assert!(repo.push("origin", false).unwrap()[0].ok);
10449
    let origin = Repo::open(&origin).unwrap();
10450
    assert_eq!(origin.fsck().unwrap().problems, vec![]);
10451
    let back = Repo::clone(&origin.root().to_string_lossy(), &root.join("back")).unwrap();
10452
    assert_eq!(back.fsck().unwrap().problems, vec![]);
10453
    assert_eq!(
10454
        fs::read(root.join("back/bin.dat")).unwrap(),
10455
        b"\0\x01second binary"
10456
    );
10457
    assert!(!root.join("back/gone.dat").exists());
10458
}
10459
10460
/// oxygen#97: with `git.claim`, an import authors the importing identity's
10461
/// own commits (Git author email = its email, any case) with its key, and
10462
/// leaves anyone else's with the zero key; the history verifies as before.
10463
#[test]
10464
fn git_import_claims_your_own_commits() {
10465
    hermetic();
10466
    if std::process::Command::new("git")
10467
        .arg("--version")
10468
        .output()
10469
        .is_err()
10470
    {
10471
        eprintln!("git not installed; skipping");
10472
        return;
10473
    }
10474
    let dir = tempfile::tempdir().unwrap();
10475
    let root = dir.path();
10476
    let g = root.join("src.git");
10477
    fs::create_dir_all(&g).unwrap();
10478
    let git = |who: &str, args: &[&str]| {
10479
        let (name, email) = who.split_once(' ').unwrap();
10480
        let out = std::process::Command::new("git")
10481
            .arg("-C")
10482
            .arg(&g)
10483
            .args([
10484
                "-c",
10485
                &format!("user.name={name}"),
10486
                "-c",
10487
                &format!("user.email={email}"),
10488
                "-c",
10489
                "commit.gpgsign=false",
10490
            ])
10491
            .args(args)
10492
            .output()
10493
            .unwrap();
10494
        assert!(
10495
            out.status.success(),
10496
            "git {args:?}: {}",
10497
            String::from_utf8_lossy(&out.stderr)
10498
        );
10499
    };
10500
    git("Grace [email protected]", &["init", "-q", "-b", "main"]);
10501
    write(&g, "a.txt", b"a\n");
10502
    git("Grace [email protected]", &["add", "."]);
10503
    git("Grace [email protected]", &["commit", "-qm", "mine"]);
10504
    write(&g, "b.txt", b"b\n");
10505
    git("Ada [email protected]", &["add", "."]);
10506
    git("Ada [email protected]", &["commit", "-qm", "someone else's"]);
10507
10508
    let mut repo = Repo::init(&root.join("o")).unwrap();
10509
    let (key, _) = repo
10510
        .create_identity("Grace", "[email protected]", IdentityScope::Repo)
10511
        .unwrap();
10512
    repo.config.set("git.claim", "true").unwrap();
10513
    repo.save_config().unwrap();
10514
    let repo = Repo::open(&root.join("o")).unwrap();
10515
    repo.import_git(&g, "main").unwrap();
10516
    let v = repo.verify_git_import(&g, "main").unwrap();
10517
    assert!(v.mismatches.is_empty(), "{:?}", v.mismatches);
10518
    let heads = repo.bookmark_heads().unwrap();
10519
    let by_message: std::collections::HashMap<String, KeyId> = repo
10520
        .log_state(&heads)
10521
        .unwrap()
10522
        .into_iter()
10523
        .map(|e| {
10524
            (
10525
                e.change.message.lines().next().unwrap_or("").to_string(),
10526
                e.change.author,
10527
            )
10528
        })
10529
        .collect();
10530
    assert_eq!(by_message["mine"], key, "her own commit, any case of email");
10531
    assert_eq!(by_message["someone else's"], ObjectRef::ZERO, "not hers");
10532
}
10533
10534
/// oxygen#86: removing a remote removes all of it: every `remote.NAME.*`
10535
/// key (URL, token, CA), its tracking bookmarks, and nothing else.
10536
#[test]
10537
fn removing_a_remote_leaves_nothing_of_it() {
10538
    hermetic();
10539
    let dir = tempfile::tempdir().unwrap();
10540
    let origin = dir.path().join("origin");
10541
    Repo::init_bare_unbound(&origin).unwrap();
10542
    let main = dir.path().join("main");
10543
    let mut repo = Repo::init(&main).unwrap();
10544
    repo.config
10545
        .set("remote.origin.url", &origin.to_string_lossy())
10546
        .unwrap();
10547
    repo.config
10548
        .set("remote.origin.token", "secret-ish")
10549
        .unwrap();
10550
    repo.config
10551
        .set("remote.keep.url", &origin.to_string_lossy())
10552
        .unwrap();
10553
    repo.save_config().unwrap();
10554
    write(&main, "a.txt", b"a\n");
10555
    repo.commit("a", &[]).unwrap();
10556
    assert!(repo.push("origin", false).unwrap()[0].ok);
10557
    assert!(
10558
        repo.view().unwrap().remotes.contains_key("origin"),
10559
        "a tracking bookmark"
10560
    );
10561
10562
    repo.remove_remote("origin").unwrap();
10563
    let again = Repo::open(&main).unwrap();
10564
    assert!(
10565
        !again
10566
            .config
10567
            .repo_layer()
10568
            .keys()
10569
            .any(|k| k.starts_with("remote.origin.")),
10570
        "{:?}",
10571
        again.config.repo_layer()
10572
    );
10573
    assert!(!again.config.remotes.contains_key("origin"));
10574
    assert!(
10575
        !again.view().unwrap().remotes.contains_key("origin"),
10576
        "its tracking bookmarks go"
10577
    );
10578
    assert!(
10579
        again.config.remotes.contains_key("keep"),
10580
        "another remote stays"
10581
    );
10582
    let mut again = again;
10583
    assert!(
10584
        again.remove_remote("origin").is_err(),
10585
        "a second removal is refused"
10586
    );
10587
}
10588
10589
/// oxygenhub#126: a blob a host stored for itself (a job's artifact) is
10590
/// unreachable from history, so gc prunes it, unless the host names it:
10591
/// then it and its chunks stay, and it reads back whole.
10592
#[test]
10593
fn gc_keeps_the_blobs_a_host_names() {
10594
    hermetic();
10595
    let dir = tempfile::tempdir().unwrap();
10596
    let repo = Repo::init(dir.path()).unwrap();
10597
    write(dir.path(), "a.txt", b"a\n");
10598
    repo.commit("a", &[]).unwrap();
10599
    // Large enough to be several chunks.
10600
    let body: Vec<u8> = (0..400_000u32)
10601
        .flat_map(|i| (i.wrapping_mul(2654435761)).to_le_bytes())
10602
        .collect();
10603
    let kept = repo.store_blob(&body).unwrap();
10604
    let lost = repo.store_blob(b"an artifact nobody names").unwrap();
10605
    repo.gc_keeping(true, &[kept], &mut |_| {}).unwrap();
10606
    assert_eq!(repo.read_blob(&kept).unwrap(), body, "named: kept whole");
10607
    assert!(!repo.store().has(&lost), "not named: pruned");
10608
    repo.gc(true).unwrap();
10609
    assert!(!repo.store().has(&kept), "a plain gc prunes it");
10610
}
10611
10612
/// oxygen#99: undo in one workspace undoes that workspace's last command,
10613
/// never another workspace's, says what it undid, and goes further back
10614
/// when run again.
10615
#[test]
10616
fn undo_is_scoped_to_its_workspace() {
10617
    hermetic();
10618
    let dir = tempfile::tempdir().unwrap();
10619
    let root = dir.path().join("main");
10620
    let a = Repo::init(&root).unwrap();
10621
    write(&root, "base.txt", b"base\n");
10622
    let base = a.commit("base", &[]).unwrap();
10623
    a.bookmark_create("feature", None).unwrap();
10624
    let ws_dir = dir.path().join("ws");
10625
    let heads = a.resolve_heads("feature").unwrap();
10626
    let b = a
10627
        .workspace_add_on(&ws_dir, Some(&heads), Some("feature"))
10628
        .unwrap();
10629
10630
    // A commits on main, then B commits on feature: B's is the newest.
10631
    write(&root, "a.txt", b"a\n");
10632
    let ca = a.commit("from a", &[]).unwrap();
10633
    write(&ws_dir, "b.txt", b"b\n");
10634
    let cb = b.commit("from b", &[]).unwrap();
10635
10636
    // A's undo undoes A's commit and leaves B's.
10637
    let u = a.undo().unwrap();
10638
    assert_eq!(u.command, "oxy commit -m \"from a\"");
10639
    assert_eq!(u.others_kept, 1, "B's newer commit is left");
10640
    assert!(!u.changes.is_empty());
10641
    let view = a.view().unwrap();
10642
    // (Independent changes commute, so a bookmark's heads may hold base too.)
10643
    assert_eq!(a.heads_of(&view, "main").unwrap(), vec![base]);
10644
    assert!(
10645
        a.heads_of(&view, "feature").unwrap().contains(&cb),
10646
        "B's commit stands"
10647
    );
10648
    assert!(
10649
        a.store().get_change(&ca).is_ok(),
10650
        "the change itself is still in the store"
10651
    );
10652
    // A's working copy was clean, so its files followed; B's are untouched.
10653
    assert!(!root.join("a.txt").exists());
10654
    assert!(a.snapshot("oxy status").unwrap().statuses.is_empty());
10655
    assert!(ws_dir.join("b.txt").exists());
10656
10657
    // B's undo still finds B's own commit, under A's undo.
10658
    let u = b.undo().unwrap();
10659
    assert_eq!(u.command, "oxy commit -m \"from b\"");
10660
    assert!(!b
10661
        .heads_of(&b.view().unwrap(), "feature")
10662
        .unwrap()
10663
        .contains(&cb));
10664
    assert_eq!(
10665
        a.heads_of(&a.view().unwrap(), "main").unwrap(),
10666
        vec![base],
10667
        "A's undo stands"
10668
    );
10669
10670
    // A's next undo goes past the commit it already undid, to adding B's
10671
    // workspace: refused, since B has worked there since.
10672
    let e = a.undo().unwrap_err().to_string();
10673
    assert!(e.contains("the workspace at") && e.contains("ws"), "{e}");
10674
}
10675
10676
/// oxygen#99: two workspaces on one bookmark: an undo takes back only its
10677
/// own commit's head, and the other workspace's head stays.
10678
#[test]
10679
fn undo_on_a_shared_bookmark_keeps_the_other_workspaces_head() {
10680
    hermetic();
10681
    let dir = tempfile::tempdir().unwrap();
10682
    let root = dir.path().join("main");
10683
    let a = Repo::init(&root).unwrap();
10684
    write(&root, "base.txt", b"base\n");
10685
    a.commit("base", &[]).unwrap();
10686
    let ws_dir = dir.path().join("ws");
10687
    let b = a.workspace_add(&ws_dir, None).unwrap();
10688
    write(&root, "a.txt", b"a\n");
10689
    let ca = a.commit("from a", &[]).unwrap();
10690
    write(&ws_dir, "b.txt", b"b\n");
10691
    let cb = b.commit("from b", &[]).unwrap();
10692
    let u = a.undo().unwrap();
10693
    assert_eq!(u.command, "oxy commit -m \"from a\"");
10694
    let heads = a.heads_of(&a.view().unwrap(), "main").unwrap();
10695
    assert!(heads.contains(&cb) && !heads.contains(&ca), "{heads:?}");
10696
}
10697
10698
/// oxygen#99: an undo that would also take back what another workspace
10699
/// did since to the same bookmark is refused, naming it.
10700
#[test]
10701
fn undo_refuses_to_take_back_another_workspaces_work() {
10702
    hermetic();
10703
    let dir = tempfile::tempdir().unwrap();
10704
    let root = dir.path().join("main");
10705
    let a = Repo::init(&root).unwrap();
10706
    write(&root, "base.txt", b"base\n");
10707
    a.commit("base", &[]).unwrap();
10708
    let ws_dir = dir.path().join("ws");
10709
    let b = a.workspace_add(&ws_dir, None).unwrap();
10710
    // Both on main: A commits, then B builds on it, editing A's file.
10711
    write(&root, "a.txt", b"a\n");
10712
    a.commit("from a", &[]).unwrap();
10713
    b.refresh().unwrap();
10714
    let heads = b.resolve_heads("main").unwrap();
10715
    b.checkout(&heads, false, "oxy checkout").unwrap();
10716
    write(&ws_dir, "a.txt", b"a, then b\n");
10717
    b.commit("from b", &[]).unwrap();
10718
    let e = a.undo().unwrap_err().to_string();
10719
    assert!(
10720
        e.contains("bookmark main") && e.contains("builds on"),
10721
        "{e}"
10722
    );
10723
    assert!(e.contains("oxy op restore"), "{e}");
10724
}
10725
10726
/// oxygen#99: undoing a commit that was already pushed says so: the remote
10727
/// still has it.
10728
#[test]
10729
fn undo_says_when_the_commit_was_pushed() {
10730
    hermetic();
10731
    let dir = tempfile::tempdir().unwrap();
10732
    let root = dir.path();
10733
    Repo::init(&root.join("origin")).unwrap();
10734
    let url = root.join("origin").to_string_lossy().to_string();
10735
    let repo = Repo::clone(&url, &root.join("work"))
10736
        .unwrap()
10737
        .with_home(root.join("home"));
10738
    write(&root.join("work"), "a.txt", b"a\n");
10739
    repo.commit("a", &[]).unwrap();
10740
    assert!(repo.push("origin", false).unwrap()[0].ok);
10741
    // The push itself is passed over: the remote keeps what it was sent.
10742
    let u = repo.undo().unwrap();
10743
    assert_eq!(u.command, "oxy commit -m \"a\"");
10744
    assert_eq!(u.pushed, vec![("main".to_string(), "origin".to_string())]);
10745
}
10746
10747
/// oxygen#98: a new untracked file over snapshot.max-new-file-size is left
10748
/// out of the snapshot and named; tracked files and files already in the
10749
/// working copy are not.
10750
#[test]
10751
fn large_new_files_are_left_out_of_snapshots() {
10752
    hermetic();
10753
    let dir = tempfile::tempdir().unwrap();
10754
    let root = dir.path();
10755
    let mut repo = Repo::init(root).unwrap();
10756
    repo.config.max_new_file = 1024;
10757
    write(root, "small.txt", b"small\n");
10758
    write(root, "big.bin", &vec![0u8; 4096]);
10759
    let s = repo.snapshot("oxy status").unwrap();
10760
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
10761
    assert_eq!(paths, ["small.txt"]);
10762
    assert_eq!(repo.skipped_large(), vec![("big.bin".to_string(), 4096)]);
10763
    repo.commit("small", &[]).unwrap();
10764
10765
    // A tracked file may grow past the limit.
10766
    write(root, "small.txt", &vec![b'x'; 4096]);
10767
    let s = repo.snapshot("oxy status").unwrap();
10768
    assert!(s.statuses.iter().any(|p| p.path == "small.txt"));
10769
    // With no limit the big file is taken in, and stays once it is.
10770
    repo.config.max_new_file = 0;
10771
    let s = repo.snapshot("oxy status").unwrap();
10772
    assert!(s.statuses.iter().any(|p| p.path == "big.bin"));
10773
    repo.config.max_new_file = 1024;
10774
    let s = repo.snapshot("oxy status").unwrap();
10775
    assert!(
10776
        s.statuses.iter().any(|p| p.path == "big.bin"),
10777
        "already in the working copy"
10778
    );
10779
    assert!(repo.skipped_large().is_empty());
10780
}
10781
10782
/// oxygen#98: a file only a past working-copy snapshot held is pruned once
10783
/// snapshots expire, and kept while they have not.
10784
#[test]
10785
fn gc_prunes_what_only_expired_snapshots_held() {
10786
    hermetic();
10787
    let dir = tempfile::tempdir().unwrap();
10788
    let root = dir.path();
10789
    let mut repo = Repo::init(root).unwrap();
10790
    repo.config.gc_grace_days = 0;
10791
    write(root, "a.txt", b"a\n");
10792
    repo.commit("a", &[]).unwrap();
10793
    let image: Vec<u8> = (0..200_000u32).map(|i| (i % 7) as u8).collect();
10794
    write(root, "image.tar", &image);
10795
    repo.snapshot("oxy status").unwrap();
10796
    std::fs::remove_file(root.join("image.tar")).unwrap();
10797
    repo.snapshot("oxy status").unwrap();
10798
    let blob = Repo::blob_ref(&image);
10799
    assert!(repo.store().has(&blob));
10800
    repo.gc(true).unwrap();
10801
    assert!(repo.store().has(&blob), "a recent snapshot keeps it");
10802
    repo.config.snapshot_retention_days = 0;
10803
    repo.gc(true).unwrap();
10804
    assert!(!repo.store().has(&blob), "an expired snapshot does not");
10805
    assert_eq!(
10806
        repo.file_at("a.txt", None).unwrap(),
10807
        b"a\n",
10808
        "committed files stay"
10809
    );
10810
}
10811
10812
/// oxygen#100: uncommitted work byte-for-byte what the bookmark switched to
10813
/// already has is no conflict: the switch goes through, nothing is lost,
10814
/// and other carried work still comes along.
10815
#[test]
10816
fn carrying_work_the_target_already_has_is_no_conflict() {
10817
    hermetic();
10818
    let dir = tempfile::tempdir().unwrap();
10819
    let root = dir.path();
10820
    let mut repo = Repo::init(root).unwrap();
10821
    write(root, "a.txt", b"one\n");
10822
    write(root, "b.txt", b"b\n");
10823
    repo.commit("one", &[]).unwrap();
10824
    repo.bookmark_create("landed", None).unwrap();
10825
    // On landed, a.txt becomes "two" (as a proposal landing would).
10826
    repo.bookmark_switch("landed", false).unwrap();
10827
    write(root, "a.txt", b"two\n");
10828
    repo.commit("two", &[]).unwrap();
10829
    repo.bookmark_switch("main", false).unwrap();
10830
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"one\n");
10831
    // The same edit, uncommitted, on main; and another edit besides.
10832
    write(root, "a.txt", b"two\n");
10833
    write(root, "b.txt", b"b, edited\n");
10834
    let (_, carried) = repo.bookmark_switch_carry("landed").unwrap();
10835
    assert_eq!(
10836
        carried,
10837
        vec!["b.txt".to_string()],
10838
        "only the work landed lacks is carried"
10839
    );
10840
    assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"two\n");
10841
    assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"b, edited\n");
10842
    let s = repo.snapshot("oxy status").unwrap();
10843
    let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
10844
    assert_eq!(paths, ["b.txt"]);
10845
10846
    // A real difference is still refused.
10847
    repo.bookmark_switch("main", true).unwrap();
10848
    write(root, "a.txt", b"three\n");
10849
    let e = repo
10850
        .bookmark_switch_carry("landed")
10851
        .unwrap_err()
10852
        .to_string();
10853
    assert!(e.contains("a.txt") && e.contains("--discard"), "{e}");
10854
}
10855
10856
/// oxygen#103: a full change hash as `--json` prints it, without `#`,
10857
/// resolves, so JSON output feeds back into commands.
10858
#[test]
10859
fn a_full_hash_resolves_without_its_hash_sign() {
10860
    hermetic();
10861
    let dir = tempfile::tempdir().unwrap();
10862
    let root = dir.path();
10863
    let repo = Repo::init(root).unwrap();
10864
    write(root, "a.txt", b"a\n");
10865
    let h = repo.commit("a", &[]).unwrap();
10866
    assert_eq!(repo.resolve_change(&h.to_hex()).unwrap(), h);
10867
    assert_eq!(repo.resolve_change(&format!("#{}", h.to_hex())).unwrap(), h);
10868
    assert!(repo
10869
        .resolve_change(&"0".repeat(64))
10870
        .unwrap_err()
10871
        .to_string()
10872
        .contains("no change matches"));
10873
}
10874
10875
#[test]
10876
fn a_pin_change_moves_only_the_pin() {
10877
    hermetic();
10878
    let dir = tempfile::tempdir().unwrap();
10879
    let root = dir.path();
10880
    let _lib_origin = Repo::init(&root.join("lib-origin")).unwrap();
10881
    let lib_url = root.join("lib-origin").to_string_lossy().to_string();
10882
    let lib = Repo::clone(&lib_url, &root.join("lib"))
10883
        .unwrap()
10884
        .with_home(root.join("home"));
10885
    write(&root.join("lib"), "lib.txt", b"v1\n");
10886
    lib.commit("lib v1", &[]).unwrap();
10887
    assert!(lib.push("origin", false).unwrap()[0].ok);
10888
    let _app_origin = Repo::init(&root.join("app-origin")).unwrap();
10889
    let app_dir = root.join("app");
10890
    let app = Repo::clone(&root.join("app-origin").to_string_lossy(), &app_dir)
10891
        .unwrap()
10892
        .with_home(root.join("home"));
10893
    write(&app_dir, "main.txt", b"app\n");
10894
    let pin1 = app.submodule_add(&lib_url, "libs/lib", None).unwrap();
10895
    let a1 = app.commit("app with lib", &[]).unwrap();
10896
    // The library moves on.
10897
    write(&root.join("lib"), "more.txt", b"v2\n");
10898
    let l2 = lib.commit("lib v2", &[]).unwrap();
10899
    let crate::subrepo::Pin::Oxy { repo, bookmark, .. } = pin1 else {
10900
        panic!("an Oxygen pin")
10901
    };
10902
    let pin2 = crate::subrepo::Pin::Oxy {
10903
        repo,
10904
        heads: vec![l2],
10905
        bookmark,
10906
    };
10907
    let author = app.store().get_change(&a1).unwrap().author;
10908
    let change = app
10909
        .build_pin_change(&[a1], "libs/lib", &pin2, "Move lib to v2", author)
10910
        .unwrap();
10911
    let mut state = app.load_state(&[a1]).unwrap();
10912
    state.add(change).unwrap();
10913
    let files = state.materialize().files;
10914
    assert_eq!(files["libs/lib"].kind, NodeKind::Subrepo);
10915
    let FileContent::Opaque { blobs } = &files["libs/lib"].content else {
10916
        panic!("a pin is opaque")
10917
    };
10918
    let read = crate::subrepo::Pin::decode(&app.read_blob(&blobs[0]).unwrap()).unwrap();
10919
    assert_eq!(read, pin2, "the new pin");
10920
    assert!(
10921
        matches!(&files["main.txt"].content, FileContent::Text { bytes, .. } if bytes.as_slice() == b"app\n"),
10922
        "nothing else changes"
10923
    );
10924
    // Only a subrepo's pin can be moved this way.
10925
    let e = app.build_pin_change(&[a1], "main.txt", &pin2, "x", author);
10926
    assert!(format!("{:?}", e.unwrap_err()).contains("not a subrepo"));
10927
    let e = app.build_pin_change(&[a1], "libs/none", &pin2, "x", author);
10928
    assert!(format!("{:?}", e.unwrap_err()).contains("does not exist"));
10929
}
10930
10931
/// oxygenhub#249: a handle reads the operation head once and keeps it,
10932
/// so one command or request never mixes two heads; another handle's
10933
/// operation shows only after `refresh`. Its own operations move it, and
10934
/// one recorded from the head it kept merges with what landed since, as
10935
/// any concurrent operation does.
10936
#[test]
10937
fn one_handle_keeps_one_head_until_it_refreshes() {
10938
    hermetic();
10939
    let dir = tempfile::tempdir().unwrap();
10940
    let root = dir.path();
10941
    let writer = Repo::init(root).unwrap();
10942
    write(root, "a.txt", b"one\n");
10943
    let h1 = writer.commit("one", &[]).unwrap();
10944
    let reader = Repo::open(root).unwrap();
10945
    let before = reader.view().unwrap();
10946
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
10947
    write(root, "a.txt", b"two\n");
10948
    let h2 = writer.commit("two", &[]).unwrap();
10949
    assert_eq!(
10950
        writer.bookmark_heads().unwrap(),
10951
        vec![h2],
10952
        "its own operation"
10953
    );
10954
    assert_eq!(reader.view().unwrap(), before, "the head it read first");
10955
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h1]);
10956
    reader.refresh().unwrap();
10957
    assert_eq!(reader.bookmark_heads().unwrap(), vec![h2]);
10958
10959
    // A handle recording from an older head merges with the newer one.
10960
    let stale = Repo::open(root).unwrap();
10961
    assert_eq!(stale.bookmark_heads().unwrap(), vec![h2]);
10962
    write(root, "a.txt", b"three\n");
10963
    let h3 = writer.commit("three", &[]).unwrap();
10964
    stale.bookmark_create("feature", Some(&[h1])).unwrap();
10965
    let view = stale.view().unwrap();
10966
    assert!(view.bookmarks.contains_key("feature"));
10967
    assert_eq!(
10968
        stale.bookmark_heads().unwrap(),
10969
        vec![h3],
10970
        "merged, not lost"
10971
    );
10972
    let fresh = Repo::open(root).unwrap();
10973
    assert_eq!(fresh.view().unwrap(), view);
10974
}
10975
10976
/// oxygenhub#249 over a store (a bucket's compare-and-swap): the same.
10977
#[test]
10978
fn over_a_store_one_handle_keeps_one_head() {
10979
    hermetic();
10980
    let backend = std::sync::Arc::new(crate::strata::MemoryStore::new());
10981
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(backend.clone()));
10982
    let dir = tempfile::tempdir().unwrap();
10983
    let a = Repo::init(dir.path()).unwrap();
10984
    let (h0, _) = a.head_op().unwrap();
10985
    let b = Repo::open(dir.path()).unwrap();
10986
    assert_eq!(b.head_op().unwrap().0, h0);
10987
    let state = a.store.put_state(&StateObject::new(vec![])).unwrap();
10988
    let mut view = a.view().unwrap();
10989
    view.bookmarks.insert("x".into(), state);
10990
    let r = a.record_op(&[h0], "bookmark x", view).unwrap();
10991
    assert_eq!(a.head_op().unwrap().0, r);
10992
    assert_eq!(b.head_op().unwrap().0, h0, "b keeps its head");
10993
    b.refresh().unwrap();
10994
    assert_eq!(b.head_op().unwrap().0, r);
10995
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
10996
}
10997
10998
/// oxygenhub#249: gc retires what it repacks rather than deleting it; a
10999
/// reader opened before reads on, then and after the next gc deletes the
11000
/// retired files once their hour is up. Younger ones are kept.
11001
#[test]
11002
fn gc_retires_and_a_later_gc_deletes_after_the_hour() {
11003
    hermetic();
11004
    let dir = tempfile::tempdir().unwrap();
11005
    let root = dir.path();
11006
    let repo = Repo::init(root).unwrap();
11007
    let mut heads = Vec::new();
11008
    for i in 0..4 {
11009
        write(root, &format!("f{i}.txt"), format!("{i}\n").as_bytes());
11010
        heads.push(repo.commit(&format!("c{i}"), &[]).unwrap());
11011
    }
11012
    let reader = Repo::open(root).unwrap();
11013
    assert_eq!(reader.log().unwrap().len(), 5);
11014
    let r = repo.gc(true).unwrap();
11015
    assert_eq!(r.retired, crate::store::RetiredReport::default());
11016
    assert_eq!(repo.store().loose_count().unwrap(), 0);
11017
    assert_eq!(reader.log().unwrap().len(), 5, "read on from what it had");
11018
    // Nothing is an hour old yet: a gc keeps it all.
11019
    let r = repo.gc(true).unwrap();
11020
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
11021
    assert!(r.retired.kept > 0, "{r:?}");
11022
    write(root, "f9.txt", b"9\n");
11023
    heads.push(repo.commit("c9", &[]).unwrap());
11024
    crate::store::reader_tests::age_retired(
11025
        repo.store(),
11026
        crate::store::RETIRED_FOR + std::time::Duration::from_secs(60),
11027
    );
11028
    let r = repo.gc(true).unwrap();
11029
    assert!(r.retired.packs >= 1 && r.retired.loose > 0, "{r:?}");
11030
    assert_eq!(r.retired.kept, 0, "{r:?}");
11031
    let r = repo.gc(true).unwrap();
11032
    assert_eq!((r.retired.packs, r.retired.loose), (0, 0));
11033
    assert!(r.retired.kept > 0, "what the last gc retired is young");
11034
    // The reader opened before all of it still reads everything, from
11035
    // the packs it finds when what it loaded is gone.
11036
    assert_eq!(reader.log().unwrap().len(), 5);
11037
    for h in &heads[..4] {
11038
        reader.store().get_change(h).unwrap();
11039
    }
11040
    reader.refresh().unwrap();
11041
    assert_eq!(reader.log().unwrap().len(), 6);
11042
    let fresh = Repo::open(root).unwrap();
11043
    assert_eq!(
11044
        fresh.store().pack_count(),
11045
        1,
11046
        "retired packs are not loaded"
11047
    );
11048
}
11049
11050
/// oxygenhub#249: a repository opens when its store's pack listing names
11051
/// an index that is not there (deleted between the listing and the read).
11052
#[test]
11053
fn a_repository_opens_when_a_listed_index_is_gone() {
11054
    hermetic();
11055
    let backend = crate::store::reader_tests::racing(true);
11056
    let dyn_backend: std::sync::Arc<crate::store::Backend> = backend.clone();
11057
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = Some(dyn_backend));
11058
    let dir = tempfile::tempdir().unwrap();
11059
    let repo = Repo::init(dir.path()).unwrap();
11060
    write(dir.path(), "a.txt", b"a\n");
11061
    let h = repo.commit("a", &[]).unwrap();
11062
    repo.gc(true).unwrap();
11063
    let again = Repo::open(dir.path()).unwrap();
11064
    assert_eq!(again.store().pack_count(), 1);
11065
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
11066
    // And when one is deleted between the listing and the read: a copy of
11067
    // the live pack, whose index goes as the store opens.
11068
    use crate::strata::Store as _;
11069
    let idx = backend
11070
        .list("pack-")
11071
        .unwrap()
11072
        .into_iter()
11073
        .map(|e| e.key)
11074
        .find(|k| k.ends_with(".idx") && k != "pack-0000.idx")
11075
        .unwrap();
11076
    let stem = idx.trim_end_matches(".idx");
11077
    for ext in ["pack", "idx"] {
11078
        let bytes = backend.get(&format!("{stem}.{ext}")).unwrap();
11079
        backend
11080
            .put_new(&format!("pack-copy.{ext}"), &bytes)
11081
            .unwrap();
11082
    }
11083
    *backend.doomed.lock().unwrap() = Some("pack-copy.idx".into());
11084
    let again = Repo::open(dir.path()).unwrap();
11085
    assert_eq!(again.store().pack_count(), 1);
11086
    assert_eq!(again.bookmark_heads().unwrap(), vec![h]);
11087
    assert!(!backend.has("pack-copy.idx").unwrap());
11088
    crate::store::TEST_BACKEND.with(|t| *t.borrow_mut() = None);
11089
}
11090
11091
/// oxygen#82: a home with `author.for` authors as the identity its hub
11092
/// last named (kept in `keys/author.for`), not its stale `author.key`; a
11093
/// repository's own `author.key` pin still wins, and without `author.for`
11094
/// the note is ignored.
11095
#[test]
11096
fn author_for_follows_the_key_the_hub_named() {
11097
    let dir = tempfile::tempdir().unwrap();
11098
    let home = dir.path().join("home");
11099
    fs::create_dir_all(home.join("keys")).unwrap();
11100
    let user = home.join("config.toml");
11101
    let repo_cfg = dir.path().join("config");
11102
    let (old, new, pin) = (
11103
        KeyId::from_hex(&"a".repeat(64)).unwrap(),
11104
        KeyId::from_hex(&"b".repeat(64)).unwrap(),
11105
        KeyId::from_hex(&"c".repeat(64)).unwrap(),
11106
    );
11107
    fs::write(&user, format!("author.key = \"{}\"\n", old.to_hex())).unwrap();
11108
    fs::write(
11109
        home.join("keys").join(super::config::AUTHOR_FOR_FILE),
11110
        format!("{}\n", new.to_hex()),
11111
    )
11112
    .unwrap();
11113
    fs::write(&repo_cfg, "").unwrap();
11114
    assert_eq!(
11115
        Config::load(Some(&user), &repo_cfg).unwrap().author_key,
11116
        Some(old),
11117
        "no author.for: the note is ignored"
11118
    );
11119
    fs::write(
11120
        &user,
11121
        format!(
11122
            "author.key = \"{}\"\nauthor.for = \"andymccall\"\n",
11123
            old.to_hex()
11124
        ),
11125
    )
11126
    .unwrap();
11127
    assert_eq!(
11128
        Config::load(Some(&user), &repo_cfg).unwrap().author_key,
11129
        Some(new)
11130
    );
11131
    fs::write(&repo_cfg, format!("author.key = \"{}\"\n", pin.to_hex())).unwrap();
11132
    assert_eq!(
11133
        Config::load(Some(&user), &repo_cfg).unwrap().author_key,
11134
        Some(pin),
11135
        "a repository's pin wins"
11136
    );
11137
}